{"TotalCount":54,"Files":[{"Ident":"mrtn.golfkit","Path":"Code/GolfBarbedWire.cs","FileName":"GolfBarbedWire.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":440545,"IsPrivate":false,"Code":"using Sandbox;\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\n\r\n/// \u003Csummary\u003E\r\n/// Barbed wire: a trigger volume on the wire model. A player in it walks at a fraction of their\r\n/// speed and is scraped for a share of their health every so often, playing and finished players\r\n/// alike, with a scrape sound; a player who hasn\u0027t finished the hole is never killed by it (the\r\n/// scrape stops at 1 hp for them). A ball in it is dragged down towards a fraction of its speed\r\n/// while it stays in, without being blocked. The host decides everything from what the trigger\r\n/// is touching each physics step: who is inside, when a scrape is due and the ball drag. Players\r\n/// are the bodies tagged \u0022player\u0022; the damage and the slow are the game\u0027s, told through\r\n/// \u003Csee cref=\u0022IGolfCourseEvents\u0022/\u003E (entered, left, scrape). The scrape sound is played from here\r\n/// when the game asks (\u003Csee cref=\u0022PlayScrape\u0022/\u003E).\r\n/// \u003C/summary\u003E\r\n[Title( \u0022Golf Barbed Wire\u0022 ), Icon( \u0022fence\u0022 )]\r\npublic sealed class GolfBarbedWire : Component\r\n{\r\n\t/// \u003Csummary\u003EDamage tag of a scrape, so the golf damage rules let it through.\u003C/summary\u003E\r\n\tpublic const string DamageTag = \u0022barbedwire\u0022;\r\n\r\n\t/// \u003Csummary\u003EMove speed in the wire as a fraction of normal: 0.5 is half speed.\u003C/summary\u003E\r\n\t[Property, Title( \u0022Slow Factor\u0022 ), Range( 0.1f, 1f )]\r\n\tpublic float SlowFactor { get; set; } = 0.5f;\r\n\r\n\t/// \u003Csummary\u003EHealth taken per scrape, as a percentage of max health.\u003C/summary\u003E\r\n\t[Property, Title( \u0022Damage Percent\u0022 ), Range( 0f, 100f )]\r\n\tpublic float DamagePercent { get; set; } = 10f;\r\n\r\n\t/// \u003Csummary\u003ESeconds between scrapes while a player stays in the wire. The first scrape is on entry.\u003C/summary\u003E\r\n\t[Property, Title( \u0022Damage Interval\u0022 ), Range( 0.25f, 10f )]\r\n\tpublic float DamageInterval { get; set; } = 2f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// How fast a ball in the wire loses speed, per second, towards \u003Csee cref=\u0022SlowFactor\u0022/\u003E of the\r\n\t/// fastest it has gone since it came in. 6 takes it most of the way in a third of a second.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, Title( \u0022Ball Drag\u0022 ), Range( 0.1f, 20f )]\r\n\tpublic float BallDrag { get; set; } = 6f;\r\n\r\n\t/// \u003Csummary\u003EThe scrape, played at the player for everyone nearby. Empty: a metal scrape from the engine.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Sound\u0022 )]\r\n\tpublic SoundEvent ScrapeSound { get; set; }\r\n\r\n\t[Property, Group( \u0022Sound\u0022 ), Range( 0f, 3f )]\r\n\tpublic float ScrapeVolume { get; set; } = 0.6f;\r\n\r\n\t[Property, Group( \u0022Sound\u0022 ), Range( 0.3f, 2f )]\r\n\tpublic float ScrapePitch { get; set; } = 0.8f;\r\n\r\n\tconst string DefaultScrape = \u0022sounds/impacts/melee/impact-melee-metal.sound\u0022;\r\n\r\n\t/// \u003Csummary\u003EThe tag on a player\u0027s body; the object carrying it (not a child that inherits it) is the walker.\u003C/summary\u003E\r\n\tpublic const string WalkerTag = \u0022player\u0022;\r\n\r\n\t// Host: which bodies are in this wire and how long since their last scrape; which balls are in\r\n\t// it and the fastest each has gone since it came in.\r\n\treadonly Dictionary\u003CGameObject, RealTimeSince\u003E _walkers = new();\r\n\treadonly Dictionary\u003CIGolfCourseBall, float\u003E _balls = new();\r\n\treadonly HashSet\u003CGameObject\u003E _walkersNow = new();\r\n\treadonly HashSet\u003CIGolfCourseBall\u003E _ballsNow = new();\r\n\r\n\tCollider _trigger;\r\n\r\n\tprotected override void OnStart()\r\n\t{\r\n\t\t_trigger = GetComponent\u003CCollider\u003E();\r\n\t\tif ( !_trigger.IsValid() || !_trigger.IsTrigger )\r\n\t\t\tLog.Warning( $\u0022GolfBarbedWire: {GameObject.Name} has no trigger collider; the wire does nothing\u0022 );\r\n\t}\r\n\r\n\tprotected override void OnDisabled()\r\n\t{\r\n\t\tif ( !Networking.IsHost ) return;\r\n\t\tforeach ( var walker in _walkers.Keys.ToList() )\r\n\t\t\tLeave( walker, \u0022wire disabled\u0022 );\r\n\t\t_walkers.Clear();\r\n\t\t_balls.Clear();\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EThe walker a touched collider belongs to: the nearest object up the chain that carries the tag itself.\u003C/summary\u003E\r\n\tstatic GameObject WalkerOf( GameObject touched )\r\n\t{\r\n\t\tfor ( var go = touched; go.IsValid() \u0026\u0026 go is not global::Sandbox.Scene; go = go.Parent )\r\n\t\t\tif ( go.Tags.Has( WalkerTag, false ) ) return go;\r\n\t\treturn null;\r\n\t}\r\n\r\n\tprotected override void OnFixedUpdate()\r\n\t{\r\n\t\tif ( !Networking.IsHost || !_trigger.IsValid() ) return;\r\n\r\n\t\t// What the trigger overlaps right now, from the physics itself: no enter or exit event to miss.\r\n\t\t_walkersNow.Clear();\r\n\t\t_ballsNow.Clear();\r\n\t\tforeach ( var other in _trigger.Touching )\r\n\t\t{\r\n\t\t\tif ( !other.IsValid() || !other.GameObject.IsValid() ) continue;\r\n\t\t\tvar walker = WalkerOf( other.GameObject );\r\n\t\t\tif ( walker.IsValid() ) { _walkersNow.Add( walker ); continue; }\r\n\t\t\tvar ball = other.GameObject.GetComponentInParent\u003CIGolfCourseBall\u003E();\r\n\t\t\tif ( ball is not null \u0026\u0026 ball.GameObject.IsValid() ) _ballsNow.Add( ball );\r\n\t\t}\r\n\r\n\t\t// Walkers: newcomers are reported and scraped at once, stayers on the interval, leavers released.\r\n\t\tforeach ( var walker in _walkers.Keys.ToList() )\r\n\t\t{\r\n\t\t\tif ( walker.IsValid() \u0026\u0026 _walkersNow.Contains( walker ) ) continue;\r\n\t\t\tLeave( walker, walker.IsValid() ? \u0022left\u0022 : \u0022gone\u0022 );\r\n\t\t\t_walkers.Remove( walker );\r\n\t\t}\r\n\t\tforeach ( var walker in _walkersNow )\r\n\t\t{\r\n\t\t\tif ( !_walkers.ContainsKey( walker ) )\r\n\t\t\t{\r\n\t\t\t\t_walkers[walker] = 0f;\r\n\t\t\t\tLog.Info( $\u0022GolfBarbedWire: {walker.Name} entered the wire at {GameObject.Name}\u0022 );\r\n\t\t\t\tIGolfCourseEvents.Post( x =\u003E x.OnWireEntered( this, walker ) );\r\n\t\t\t\tIGolfCourseEvents.Post( x =\u003E x.OnWireScrape( this, walker ) );\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\tif ( _walkers[walker] \u003C DamageInterval ) continue;\r\n\t\t\t_walkers[walker] = 0f;\r\n\t\t\tIGolfCourseEvents.Post( x =\u003E x.OnWireScrape( this, walker ) );\r\n\t\t}\r\n\r\n\t\t// Balls: dragged towards the slow factor of the fastest they\u0027ve gone in here.\r\n\t\tforeach ( var ball in _balls.Keys.ToList() )\r\n\t\t{\r\n\t\t\tvar alive = ball.GameObject.IsValid();\r\n\t\t\tif ( alive \u0026\u0026 _ballsNow.Contains( ball ) ) continue;\r\n\t\t\tLog.Info( $\u0022GolfBarbedWire: {( alive ? ball.OwnerName : \u0022?\u0022 )}\u0027s ball left the wire at {GameObject.Name}, speed {( alive \u0026\u0026 ball.Rigidbody.IsValid() ? ball.Rigidbody.Velocity.Length : 0f ):0}\u0022 );\r\n\t\t\t_balls.Remove( ball );\r\n\t\t}\r\n\t\tforeach ( var ball in _ballsNow )\r\n\t\t{\r\n\t\t\tif ( !ball.Rigidbody.IsValid() ) continue;\r\n\t\t\tvar body = ball.Rigidbody;\r\n\t\t\tvar velocity = body.Velocity;\r\n\t\t\tvar speed = velocity.Length;\r\n\r\n\t\t\tif ( !_balls.ContainsKey( ball ) )\r\n\t\t\t{\r\n\t\t\t\t_balls[ball] = speed;\r\n\t\t\t\tLog.Info( $\u0022GolfBarbedWire: {ball.OwnerName}\u0027s ball entered the wire at {GameObject.Name}, speed {speed:0}\u0022 );\r\n\t\t\t}\r\n\t\t\tif ( ball.IsHoled ) continue;\r\n\r\n\t\t\tvar top = Math.Max( _balls[ball], speed );\r\n\t\t\t_balls[ball] = top;\r\n\r\n\t\t\tvar target = top * SlowFactor;\r\n\t\t\tif ( speed \u003C= target || speed \u003C 1f ) continue;\r\n\r\n\t\t\tvar slowed = MathX.Lerp( speed, target, Math.Clamp( BallDrag * Time.Delta, 0f, 1f ) );\r\n\t\t\tbody.Velocity = velocity * (slowed / speed);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid Leave( GameObject walker, string why )\r\n\t{\r\n\t\tLog.Info( $\u0022GolfBarbedWire: {( walker.IsValid() ? walker.Name : \u0022a body\u0022 )} {why} the wire at {GameObject.Name}\u0022 );\r\n\t\tIGolfCourseEvents.Post( x =\u003E x.OnWireLeft( this, walker ) );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EThe scrape sound at a position, for everyone nearby. The game calls this when a scrape did damage.\u003C/summary\u003E\r\n\tpublic void PlayScrape( Vector3 position )\r\n\t{\r\n\t\tScrapeRpc( position, ScrapeSound?.ResourcePath ?? DefaultScrape, ScrapeVolume, ScrapePitch );\r\n\t}\r\n\r\n\t[Rpc.Broadcast]\r\n\tstatic void ScrapeRpc( Vector3 position, string path, float volume, float pitch )\r\n\t{\r\n\t\tvar sound = ResourceLibrary.Get\u003CSoundEvent\u003E( string.IsNullOrEmpty( path ) ? DefaultScrape : path );\r\n\t\tif ( sound is null || volume \u003C= 0f ) return;\r\n\t\tvar handle = Sound.Play( sound, position );\r\n\t\tif ( !handle.IsValid() ) return;\r\n\t\thandle.Volume = volume;\r\n\t\thandle.Pitch = pitch;\r\n\t}\r\n}\r\n"},{"Ident":"mrtn.golfkit","Path":"GolfRotator.cs","FileName":"GolfRotator.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":440545,"IsPrivate":false,"Code":"using Sandbox;\r\nusing System;\r\nusing System.Linq;\r\n\r\n/// \u003Csummary\u003E\r\n/// Spins the object it sits on round one of its own axes at a steady rate, on every machine and\r\n/// in the editor too (nothing is networked: every machine turns it the same way from the same\r\n/// start, and a prop that is a little out of step between machines does not matter). Made for\r\n/// the windmill\u0027s blades, whose axle is their local Y.\r\n///\r\n/// With a Rigidbody on the same object (motion off, so the body is keyframed in play) the turn\r\n/// goes through the physics body with a matching angular velocity, and on the host the box\r\n/// colliders on the object also push golf balls by hand: a ball inside the sweep is kept awake,\r\n/// and a ball an arm box overlaps is given the arm\u0027s surface speed at the contact point, so\r\n/// resting balls get swatted instead of being passed through.\r\n/// \u003C/summary\u003E\r\n[Title( \u0022Golf Rotator\u0022 ), Icon( \u0022sync\u0022 ), Category( \u0022Golf\u0022 )]\r\npublic sealed class GolfRotator : Component, Component.ExecuteInEditor\r\n{\r\n\t/// \u003Csummary\u003EThe local axis to turn round. The windmill blades turn round their local Y.\u003C/summary\u003E\r\n\t[Property]\r\n\tpublic Vector3 Axis { get; set; } = new Vector3( 0f, 1f, 0f );\r\n\r\n\t/// \u003Csummary\u003ETurning speed in degrees per second; negative turns the other way.\u003C/summary\u003E\r\n\t[Property, Title( \u0022Degrees Per Second\u0022 ), Range( -360f, 360f )]\r\n\tpublic float DegreesPerSecond { get; set; } = 30f;\r\n\r\n\tRigidbody _body;\r\n\tBoxCollider[] _arms = Array.Empty\u003CBoxCollider\u003E();\r\n\tfloat _reach;\r\n\tbool _loggedContact;\r\n\r\n\tprotected override void OnStart()\r\n\t{\r\n\t\t_body = GetComponent\u003CRigidbody\u003E( true );\r\n\t\t_arms = GetComponents\u003CBoxCollider\u003E( true ).ToArray();\r\n\t\t_reach = _arms.Length == 0 ? 0f : _arms.Max( a =\u003E a.Center.Length \u002B a.Scale.Length * 0.5f );\r\n\t}\r\n\r\n\tprotected override void OnUpdate()\r\n\t{\r\n\t\t// In play with a physics body the fixed step below does the turning.\r\n\t\tif ( !Scene.IsEditor \u0026\u0026 _body.IsValid() ) return;\r\n\t\tTurn( Time.Delta );\r\n\t}\r\n\r\n\tprotected override void OnFixedUpdate()\r\n\t{\r\n\t\tif ( Scene.IsEditor || !_body.IsValid() ) return;\r\n\t\tvar next = Turn( Time.Delta );\r\n\t\tif ( next is null ) return;\r\n\r\n\t\t// The keyframed body is rotated with the velocity that gets it there this step, so a ball\r\n\t\t// in the blade\u0027s path is pushed rather than finding the blade somewhere else next step.\r\n\t\t_body.SmoothRotate( next.Value, Time.Delta, Time.Delta );\r\n\r\n\t\tif ( Networking.IsHost ) PushBalls();\r\n\t}\r\n\r\n\t/// \u003Csummary\u003ETurns the object by one step and returns the new world rotation, or null when there is nothing to do.\u003C/summary\u003E\r\n\tRotation? Turn( float seconds )\r\n\t{\r\n\t\tvar axis = Axis;\r\n\t\tif ( axis.IsNearlyZero() || DegreesPerSecond == 0f || seconds \u003C= 0f ) return null;\r\n\t\tLocalRotation *= Rotation.FromAxis( axis.Normal, DegreesPerSecond * seconds );\r\n\t\treturn WorldRotation;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Host only. Every ball within the sweep is kept awake (a sleeping ball ignores a keyframed\r\n\t/// body sliding into it), and a ball that an arm box overlaps gets at least the arm\u0027s surface\r\n\t/// velocity along the contact normal and is lifted out of the box.\r\n\t/// \u003C/summary\u003E\r\n\tvoid PushBalls()\r\n\t{\r\n\t\tif ( _arms.Length == 0 || DegreesPerSecond == 0f ) return;\r\n\r\n\t\tvar hub = WorldPosition;\r\n\t\tvar omega = WorldRotation * Axis.Normal * DegreesPerSecond.DegreeToRadian();\r\n\t\tvar transform = WorldTransform;\r\n\r\n\t\tforeach ( var ball in Scene.GetAllComponents\u003CIGolfCourseBall\u003E() )\r\n\t\t{\r\n\t\t\tif ( !ball.GameObject.IsValid() || ball.IsHoled || !ball.Rigidbody.IsValid() ) continue;\r\n\r\n\t\t\tvar pos = ball.WorldPosition;\r\n\t\t\tif ( pos.Distance( hub ) \u003E _reach \u002B ball.Radius \u002B 4f ) continue;\r\n\r\n\t\t\tball.Rigidbody.Sleeping = false;\r\n\r\n\t\t\tforeach ( var arm in _arms )\r\n\t\t\t{\r\n\t\t\t\tif ( !arm.IsValid() || !arm.Enabled ) continue;\r\n\r\n\t\t\t\t// Closest point of the arm box to the ball\u0027s centre, in the box\u0027s own frame.\r\n\t\t\t\tvar local = transform.PointToLocal( pos ) - arm.Center;\r\n\t\t\t\tvar half = arm.Scale * 0.5f;\r\n\t\t\t\tvar clamped = new Vector3( Math.Clamp( local.x, -half.x, half.x ), Math.Clamp( local.y, -half.y, half.y ), Math.Clamp( local.z, -half.z, half.z ) );\r\n\t\t\t\tvar closest = transform.PointToWorld( clamped \u002B arm.Center );\r\n\t\t\t\tvar gap = pos - closest;\r\n\t\t\t\tvar dist = gap.Length;\r\n\t\t\t\tif ( dist \u003E ball.Radius ) continue;\r\n\r\n\t\t\t\tvar surface = Vector3.Cross( omega, closest - hub );\r\n\t\t\t\tvar normal = dist \u003E 0.05f ? gap.Normal : surface.Normal;\r\n\t\t\t\tif ( normal.IsNearlyZero() ) continue;\r\n\r\n\t\t\t\t// Match the arm\u0027s speed into the ball; a ball already moving away is left alone.\r\n\t\t\t\tvar velocity = ball.Rigidbody.Velocity;\r\n\t\t\t\tvar relative = (velocity - surface).Dot( normal );\r\n\t\t\t\tif ( relative \u003C 0f ) ball.Rigidbody.Velocity = velocity - normal * relative;\r\n\r\n\t\t\t\t// Lift it out of the box so the next step starts from a clean contact.\r\n\t\t\t\tif ( dist \u003C ball.Radius - 0.1f ) ball.WorldPosition = pos \u002B normal * (ball.Radius - dist);\r\n\r\n\t\t\t\tif ( !_loggedContact )\r\n\t\t\t\t{\r\n\t\t\t\t\t_loggedContact = true;\r\n\t\t\t\t\tLog.Info( $\u0022GolfRotator: {GameObject.Name} first touched {ball.OwnerName}\u0027s ball at {closest}, arm surface speed {surface.Length:0}, ball {velocity.Length:0} -\u003E {ball.Rigidbody.Velocity.Length:0} u/s\u0022 );\r\n\t\t\t\t}\r\n\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n"},{"Ident":"mrtn.golfkit","Path":"TrenchFire.cs","FileName":"TrenchFire.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":440545,"IsPrivate":false,"Code":"using Sandbox;\r\nusing System;\r\n\r\n/// \u003Csummary\u003E\r\n/// Decorative machine-gun fire for the trench map: bursts of glowing tracers fly from a random\r\n/// point on the Start line to a random point on the End line, with a muzzle flash where they leave\r\n/// and a dust puff where they land, and a distant, softened shot sound for every round. Purely a\r\n/// show: nothing is traced against players or balls, nothing takes damage, nothing is networked.\r\n/// Every machine runs its own with its own random timing.\r\n///\r\n/// The two lines are each two child objects (Start A/B, End A/B) that you move with the normal\r\n/// move gizmo; they are created the first time the component is seen in the editor if missing.\r\n/// The lines and the handles are drawn as gizmos. The component\u0027s own Enabled checkbox turns the\r\n/// gun off. Small pool of tracers and flash lights, nothing allocated per shot but the engine\u0027s\r\n/// own sound handle and the surface\u0027s impact particle.\r\n/// \u003C/summary\u003E\r\n[Title( \u0022Trench Fire\u0022 ), Category( \u0022Golf\u0022 ), Icon( \u0022whatshot\u0022 )]\r\npublic sealed class TrenchFire : Component\r\n{\r\n\t/// \u003Csummary\u003EOne end of the line the tracers leave from.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Lines\u0022 ), Title( \u0022Start A\u0022 )]\r\n\tpublic GameObject StartA { get; set; }\r\n\r\n\t/// \u003Csummary\u003EThe other end of the line the tracers leave from.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Lines\u0022 ), Title( \u0022Start B\u0022 )]\r\n\tpublic GameObject StartB { get; set; }\r\n\r\n\t/// \u003Csummary\u003EOne end of the line the tracers land on.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Lines\u0022 ), Title( \u0022End A\u0022 )]\r\n\tpublic GameObject EndA { get; set; }\r\n\r\n\t/// \u003Csummary\u003EThe other end of the line the tracers land on.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Lines\u0022 ), Title( \u0022End B\u0022 )]\r\n\tpublic GameObject EndB { get; set; }\r\n\r\n\t/// \u003Csummary\u003ERandom scatter around the landing point, in units.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Lines\u0022 ), Range( 0f, 300f )]\r\n\tpublic float Spread { get; set; } = 40f;\r\n\r\n\t/// \u003Csummary\u003EBursts per minute.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Timing\u0022 ), Range( 0.1f, 60f ), Title( \u0022Rate (bursts per minute)\u0022 )]\r\n\tpublic float Rate { get; set; } = 6f;\r\n\r\n\t/// \u003Csummary\u003EFewest shots in a burst.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Timing\u0022 ), Range( 1, 60 ), Title( \u0022Burst Length Min\u0022 )]\r\n\tpublic int BurstMin { get; set; } = 8;\r\n\r\n\t/// \u003Csummary\u003EMost shots in a burst.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Timing\u0022 ), Range( 1, 60 ), Title( \u0022Burst Length Max\u0022 )]\r\n\tpublic int BurstMax { get; set; } = 15;\r\n\r\n\t/// \u003Csummary\u003EShots per second inside a burst.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Timing\u0022 ), Range( 1f, 30f )]\r\n\tpublic float ShotsPerSecond { get; set; } = 12f;\r\n\r\n\t/// \u003Csummary\u003EHow much the pause between bursts varies, 0 for a metronome, 1 for anything from no pause to double.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Timing\u0022 ), Range( 0f, 1f )]\r\n\tpublic float PauseVariance { get; set; } = 0.5f;\r\n\r\n\t/// \u003Csummary\u003EHow fast a tracer flies, units per second.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Tracer\u0022 ), Range( 500f, 20000f )]\r\n\tpublic float TracerSpeed { get; set; } = 6000f;\r\n\r\n\t/// \u003Csummary\u003EColour of the tracer streak, the flash and its light.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Tracer\u0022 )]\r\n\tpublic Color TracerColour { get; set; } = new Color( 1f, 0.55f, 0.15f );\r\n\r\n\t/// \u003Csummary\u003ELength of the streak, in units.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Tracer\u0022 ), Range( 10f, 1000f )]\r\n\tpublic float TracerLength { get; set; } = 160f;\r\n\r\n\t/// \u003Csummary\u003EWidth of the streak at its bright end, in units.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Tracer\u0022 ), Range( 0.5f, 10f )]\r\n\tpublic float TracerWidth { get; set; } = 2.5f;\r\n\r\n\t/// \u003Csummary\u003EHow much brighter than the colour the streak glows.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Tracer\u0022 ), Range( 1f, 8f )]\r\n\tpublic float Glow { get; set; } = 3f;\r\n\r\n\t/// \u003Csummary\u003EA short flash of light at the start point for every shot.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Effects\u0022 )]\r\n\tpublic bool MuzzleFlash { get; set; } = true;\r\n\r\n\t/// \u003Csummary\u003EThe surface\u0027s bullet impact particle where a tracer lands.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Effects\u0022 )]\r\n\tpublic bool DustPuff { get; set; } = true;\r\n\r\n\t/// \u003Csummary\u003EThe distant shot, played at the start point for every round. Empty uses sounds/trench_fire.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Sound\u0022 )]\r\n\tpublic SoundEvent ShotSound { get; set; }\r\n\r\n\t/// \u003Csummary\u003EVolume of the shots, 0 to 1.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Sound\u0022 ), Range( 0f, 1f )]\r\n\tpublic float Volume { get; set; } = 0.35f;\r\n\r\n\tconst string DefaultSound = \u0022sounds/trench_fire.sound\u0022;\r\n\tconst float FlashSeconds = 0.05f;\r\n\tconst float FlashRadius = 160f;\r\n\r\n\tstruct Landing\r\n\t{\r\n\t\tpublic float At;        // Time.Now the tracer arrives; 0 for none pending\r\n\t\tpublic Vector3 Position;\r\n\t\tpublic Vector3 Normal;\r\n\t\tpublic Surface Surface;\r\n\t}\r\n\r\n\tTracerEffect[] _tracers = Array.Empty\u003CTracerEffect\u003E();\r\n\tLanding[] _landings = Array.Empty\u003CLanding\u003E();\r\n\tPointLight[] _flashes = Array.Empty\u003CPointLight\u003E();\r\n\tfloat[] _flashOff = Array.Empty\u003Cfloat\u003E();\r\n\tint _nextTracer;\r\n\tint _nextFlash;\r\n\tSurface _defaultSurface;\r\n\tColor _builtColour;\r\n\tfloat _builtWidth;\r\n\r\n\tfloat _nextBurstAt;\r\n\tfloat _nextShotAt;\r\n\tint _shotsLeft;\r\n\r\n\tprotected override void OnStart()\r\n\t{\r\n\t\tEnsureHandles();\r\n\t\tShotSound ??= ResourceLibrary.Get\u003CSoundEvent\u003E( DefaultSound );\r\n\t\t_defaultSurface = Surface.FindByName( \u0022default\u0022 );\r\n\t\tBuildPool();\r\n\t\t_nextBurstAt = Time.Now \u002B NextPause() * Game.Random.Float( 0f, 1f );\r\n\t}\r\n\r\n\tprotected override void OnDisabled()\r\n\t{\r\n\t\t_shotsLeft = 0;\r\n\t\tfor ( var i = 0; i \u003C _landings.Length; i\u002B\u002B ) _landings[i].At = 0f;\r\n\t\tforeach ( var flash in _flashes ) if ( flash.IsValid() ) flash.Enabled = false;\r\n\t}\r\n\r\n\tprotected override void OnUpdate()\r\n\t{\r\n\t\tif ( Scene.IsEditor ) return;\r\n\t\tif ( _tracers.Length == 0 ) return;\r\n\r\n\t\tvar now = Time.Now;\r\n\r\n\t\t// Flashes go out, landings puff.\r\n\t\tfor ( var i = 0; i \u003C _flashes.Length; i\u002B\u002B )\r\n\t\t{\r\n\t\t\tif ( _flashOff[i] \u003E 0f \u0026\u0026 now \u003E= _flashOff[i] )\r\n\t\t\t{\r\n\t\t\t\t_flashOff[i] = 0f;\r\n\t\t\t\tif ( _flashes[i].IsValid() ) _flashes[i].Enabled = false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfor ( var i = 0; i \u003C _landings.Length; i\u002B\u002B )\r\n\t\t{\r\n\t\t\tif ( _landings[i].At \u003C= 0f || now \u003C _landings[i].At ) continue;\r\n\t\t\t_landings[i].At = 0f;\r\n\t\t\tif ( DustPuff )\r\n\t\t\t\tBaseCombatWeapon.ImpactPrefab( null, _landings[i].Surface, _landings[i].Position, _landings[i].Normal );\r\n\t\t}\r\n\r\n\t\t// Bursts.\r\n\t\tif ( _shotsLeft \u003C= 0 )\r\n\t\t{\r\n\t\t\tif ( now \u003C _nextBurstAt ) return;\r\n\t\t\t_shotsLeft = Game.Random.Int( Math.Min( BurstMin, BurstMax ), Math.Max( BurstMin, BurstMax ) );\r\n\t\t\t_nextShotAt = now;\r\n\t\t\t_nextBurstAt = now \u002B NextPause();\r\n\t\t}\r\n\r\n\t\tif ( now \u003C _nextShotAt ) return;\r\n\t\t_nextShotAt = now \u002B 1f / Math.Max( 1f, ShotsPerSecond );\r\n\t\t_shotsLeft--;\r\n\t\tFire();\r\n\t}\r\n\r\n\tfloat NextPause()\r\n\t{\r\n\t\tvar mean = 60f / Math.Max( 0.1f, Rate );\r\n\t\treturn mean * (1f \u002B Game.Random.Float( -PauseVariance, PauseVariance ));\r\n\t}\r\n\r\n\tvoid Fire()\r\n\t{\r\n\t\tif ( !StartA.IsValid() || !StartB.IsValid() || !EndA.IsValid() || !EndB.IsValid() ) return;\r\n\r\n\t\tvar start = Vector3.Lerp( StartA.WorldPosition, StartB.WorldPosition, Game.Random.Float( 0f, 1f ) );\r\n\t\tvar end = Vector3.Lerp( EndA.WorldPosition, EndB.WorldPosition, Game.Random.Float( 0f, 1f ) )\r\n\t\t\t\u002B Vector3.Random * Spread;\r\n\r\n\t\t// Where it lands: the ground near the end point, for the puff\u0027s surface and facing.\r\n\t\tvar landing = new Landing { Position = end, Normal = Vector3.Up, Surface = _defaultSurface };\r\n\t\tvar trace = Scene.Trace.Ray( end \u002B Vector3.Up * 48f, end \u002B Vector3.Down * 96f ).WithoutTags( \u0022player\u0022, \u0022golfball\u0022 ).Run();\r\n\t\tif ( trace.Hit )\r\n\t\t{\r\n\t\t\tlanding.Position = trace.HitPosition;\r\n\t\t\tlanding.Normal = trace.Normal;\r\n\t\t\tlanding.Surface = trace.Surface ?? _defaultSurface;\r\n\t\t}\r\n\r\n\t\tvar distance = start.Distance( end );\r\n\t\tlanding.At = Time.Now \u002B distance / Math.Max( 1f, TracerSpeed );\r\n\r\n\t\t// Tracer: the pool\u0027s oldest one restarts from the new start point.\r\n\t\tvar i = _nextTracer;\r\n\t\t_nextTracer = (_nextTracer \u002B 1) % _tracers.Length;\r\n\t\tvar tracer = _tracers[i];\r\n\t\tif ( tracer.IsValid() )\r\n\t\t{\r\n\t\t\tif ( _builtColour != TracerColour || _builtWidth != TracerWidth ) BuildLook();\r\n\t\t\ttracer.Enabled = false;\r\n\t\t\ttracer.WorldPosition = start;\r\n\t\t\ttracer.EndPoint = end;\r\n\t\t\ttracer.DistancePerSecond = TracerSpeed;\r\n\t\t\ttracer.Length = TracerLength;\r\n\t\t\ttracer.Enabled = true;\r\n\t\t}\r\n\t\t_landings[i] = landing;\r\n\r\n\t\t// Muzzle flash.\r\n\t\tif ( MuzzleFlash \u0026\u0026 _flashes.Length \u003E 0 )\r\n\t\t{\r\n\t\t\tvar f = _nextFlash;\r\n\t\t\t_nextFlash = (_nextFlash \u002B 1) % _flashes.Length;\r\n\t\t\tvar flash = _flashes[f];\r\n\t\t\tif ( flash.IsValid() )\r\n\t\t\t{\r\n\t\t\t\tflash.WorldPosition = start \u002B (end - start).Normal * 12f;\r\n\t\t\t\tflash.LightColor = TracerColour * Glow;\r\n\t\t\t\tflash.Radius = FlashRadius;\r\n\t\t\t\tflash.Enabled = true;\r\n\t\t\t\t_flashOff[f] = Time.Now \u002B FlashSeconds;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// The distant shot.\r\n\t\tif ( ShotSound is not null \u0026\u0026 Volume \u003E 0f )\r\n\t\t{\r\n\t\t\tvar handle = Sound.Play( ShotSound, start );\r\n\t\t\tif ( handle.IsValid() ) handle.Volume = Volume;\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Enough tracers to cover the longest flight at the burst rate, and a couple of flash lights.\r\n\t/// Pool objects are hidden children that are never saved or networked.\r\n\t/// \u003C/summary\u003E\r\n\tvoid BuildPool()\r\n\t{\r\n\t\tvar longest = 0f;\r\n\t\tif ( StartA.IsValid() \u0026\u0026 StartB.IsValid() \u0026\u0026 EndA.IsValid() \u0026\u0026 EndB.IsValid() )\r\n\t\t{\r\n\t\t\tlongest = Math.Max( Math.Max( StartA.WorldPosition.Distance( EndA.WorldPosition ), StartA.WorldPosition.Distance( EndB.WorldPosition ) ),\r\n\t\t\t\tMath.Max( StartB.WorldPosition.Distance( EndA.WorldPosition ), StartB.WorldPosition.Distance( EndB.WorldPosition ) ) );\r\n\t\t}\r\n\t\tvar flight = (longest \u002B Spread \u002B TracerLength) / Math.Max( 1f, TracerSpeed );\r\n\t\tvar count = Math.Clamp( (int)MathF.Ceiling( flight * ShotsPerSecond ) \u002B 2, 4, 32 );\r\n\r\n\t\t_tracers = new TracerEffect[count];\r\n\t\t_landings = new Landing[count];\r\n\t\tfor ( var i = 0; i \u003C count; i\u002B\u002B )\r\n\t\t{\r\n\t\t\tvar go = new GameObject( GameObject, false, $\u0022tracer {i}\u0022 );\r\n\t\t\tgo.Flags |= GameObjectFlags.NotSaved | GameObjectFlags.NotNetworked | GameObjectFlags.Hidden;\r\n\t\t\tvar tracer = go.AddComponent\u003CTracerEffect\u003E( false );\r\n\t\t\ttracer.StartDistance = 0f;\r\n\t\t\ttracer.Opaque = false;\r\n\t\t\ttracer.CastShadows = false;\r\n\t\t\ttracer.EnableLight = false;\r\n\t\t\t_tracers[i] = tracer;\r\n\t\t\tgo.Enabled = true;\r\n\t\t}\r\n\t\tBuildLook();\r\n\r\n\t\t_flashes = new PointLight[2];\r\n\t\t_flashOff = new float[2];\r\n\t\tfor ( var i = 0; i \u003C _flashes.Length; i\u002B\u002B )\r\n\t\t{\r\n\t\t\tvar go = new GameObject( GameObject, false, $\u0022flash {i}\u0022 );\r\n\t\t\tgo.Flags |= GameObjectFlags.NotSaved | GameObjectFlags.NotNetworked | GameObjectFlags.Hidden;\r\n\t\t\tvar light = go.AddComponent\u003CPointLight\u003E( false );\r\n\t\t\tlight.Shadows = false;\r\n\t\t\tlight.Radius = FlashRadius;\r\n\t\t\tlight.Attenuation = 2f;\r\n\t\t\t_flashes[i] = light;\r\n\t\t\tgo.Enabled = true;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid BuildLook()\r\n\t{\r\n\t\t_builtColour = TracerColour;\r\n\t\t_builtWidth = TracerWidth;\r\n\t\tvar head = TracerColour * Glow;\r\n\t\thead.a = 1f;\r\n\t\tvar colour = new Gradient( new Gradient.ColorFrame( 0f, head ), new Gradient.ColorFrame( 0.35f, TracerColour ), new Gradient.ColorFrame( 1f, TracerColour.WithAlpha( 0f ) ) );\r\n\t\tvar width = new Curve( new Curve.Frame( 0f, TracerWidth ), new Curve.Frame( 1f, 0f ) );\r\n\t\tforeach ( var tracer in _tracers )\r\n\t\t{\r\n\t\t\tif ( !tracer.IsValid() ) continue;\r\n\t\t\ttracer.LineColor = colour;\r\n\t\t\ttracer.LineWidth = width;\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The four handle objects: found by name under this object, or made with default spots.\r\n\t/// \u003C/summary\u003E\r\n\tvoid EnsureHandles()\r\n\t{\r\n\t\tStartA = Handle( StartA, \u0022Start A\u0022, new Vector3( 0f, -150f, 40f ) );\r\n\t\tStartB = Handle( StartB, \u0022Start B\u0022, new Vector3( 0f, 150f, 40f ) );\r\n\t\tEndA = Handle( EndA, \u0022End A\u0022, new Vector3( 1200f, -250f, 0f ) );\r\n\t\tEndB = Handle( EndB, \u0022End B\u0022, new Vector3( 1200f, 250f, 0f ) );\r\n\t}\r\n\r\n\tGameObject Handle( GameObject current, string name, Vector3 localPosition )\r\n\t{\r\n\t\tif ( current.IsValid() ) return current;\r\n\r\n\t\tforeach ( var child in GameObject.Children )\r\n\t\t\tif ( child.IsValid() \u0026\u0026 child.Name == name ) return child;\r\n\r\n\t\tvar go = new GameObject( GameObject, true, name );\r\n\t\tgo.LocalPosition = localPosition;\r\n\t\treturn go;\r\n\t}\r\n\r\n\tprotected override void DrawGizmos()\r\n\t{\r\n\t\tEnsureHandles();\r\n\t\tif ( !StartA.IsValid() || !StartB.IsValid() || !EndA.IsValid() || !EndB.IsValid() ) return;\r\n\r\n\t\tvar alpha = Gizmo.IsSelected ? 1f : (Gizmo.IsHovered ? 0.6f : 0.3f);\r\n\t\tvar local = WorldTransform;\r\n\t\tvar sa = local.PointToLocal( StartA.WorldPosition );\r\n\t\tvar sb = local.PointToLocal( StartB.WorldPosition );\r\n\t\tvar ea = local.PointToLocal( EndA.WorldPosition );\r\n\t\tvar eb = local.PointToLocal( EndB.WorldPosition );\r\n\r\n\t\tGizmo.Draw.LineThickness = Gizmo.IsSelected ? 3f : 2f;\r\n\t\tGizmo.Draw.Color = TracerColour.WithAlpha( alpha );\r\n\t\tGizmo.Draw.Line( sa, sb );\r\n\t\tGizmo.Draw.LineSphere( new Sphere( sa, 8f ), 8 );\r\n\t\tGizmo.Draw.LineSphere( new Sphere( sb, 8f ), 8 );\r\n\r\n\t\tGizmo.Draw.Color = Color.Red.WithAlpha( alpha );\r\n\t\tGizmo.Draw.Line( ea, eb );\r\n\t\tGizmo.Draw.LineSphere( new Sphere( ea, 8f ), 8 );\r\n\t\tGizmo.Draw.LineSphere( new Sphere( eb, 8f ), 8 );\r\n\r\n\t\tGizmo.Draw.LineThickness = 1f;\r\n\t\tGizmo.Draw.Color = Color.White.WithAlpha( alpha * 0.7f );\r\n\t\tGizmo.Draw.Arrow( (sa \u002B sb) * 0.5f, (ea \u002B eb) * 0.5f, 24f, 8f );\r\n\t}\r\n}\r\n"},{"Ident":"mrtn.golfkit","Path":"Code/GolfPreviewNote.razor.scss","FileName":"GolfPreviewNote.razor.scss","PackageType":"library","CodeKind":"Game","AssetVersionId":440545,"IsPrivate":false,"Code":"GolfPreviewNote\n{\n\tposition: absolute;\n\tleft: 0;\n\tright: 0;\n\tbottom: 24px;\n\talign-items: center;\n\tjustify-content: center;\n\tpointer-events: none;\n\n\t.note\n\t{\n\t\tflex-direction: column;\n\t\tmax-width: 640px;\n\t\tpadding: 10px 16px;\n\t\tborder-radius: 8px;\n\t\tbackground-color: #0d1117cc;\n\t\tcolor: #ffffff;\n\t\tfont-family: Poppins, sans-serif;\n\n\t\t.title { font-size: 15px; font-weight: 700; margin-bottom: 2px; }\n\t\t.line { font-size: 13px; opacity: 0.85; white-space: normal; }\n\t}\n}\n"},{"Ident":"mrtn.golfkit","Path":"Code/Hole.cs","FileName":"Hole.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":440545,"IsPrivate":false,"Code":"using Sandbox;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\n/// \u003Csummary\u003E\n/// One hole of the course, on the hole\u0027s group object: the title and par, and the size of the\n/// scoring trigger at the bottom of its cup. Everything else is found under the group: the cup\n/// (the object with a \u003Csee cref=\u0022GolfCup\u0022/\u003E, the kit\u0027s cup prefab), the tee (a \u003Csee cref=\u0022GolfTee\u0022/\u003E,\n/// the kit\u0027s tee prefab) and the pieces, whose renderers give the playable area. Nothing needs\n/// wiring or naming: a group with this component, a cup, a tee and some floor is a hole, and the\n/// game plays the groups in the order they stand in the scene.\n///\n/// The group\u0027s Golf Hole Collision (one welded collider for all the pieces) is added here when it\n/// is missing, so the group never needs a second component by hand.\n/// \u003C/summary\u003E\n[Title( \u0022Golf Hole\u0022 ), Icon( \u0022golf_course\u0022 )]\npublic sealed class Hole : Component, Component.ExecuteInEditor\n{\n\t/// \u003Csummary\u003EName shown on the HUD.\u003C/summary\u003E\n\t[Property]\n\tpublic string Title { get; set; } = \u0022\u0022;\n\n\t/// \u003Csummary\u003EExpected number of shots.\u003C/summary\u003E\n\t[Property, Range( 1, 10 )]\n\tpublic int Par { get; set; } = 3;\n\n\t/// \u003Csummary\u003E\n\t/// Radius of the scoring trigger at the bottom of the cup, in units: a ball whose centre gets\n\t/// this close to the cup\u0027s axis, down in the cup, is holed. 4 matches the kit\u0027s cups.\n\t/// \u003C/summary\u003E\n\t[Property, Title( \u0022Cup Radius\u0022 ), Range( 1f, 30f )]\n\tpublic float CupRadius { get; set; } = 4f;\n\n\t/// \u003Csummary\u003E\n\t/// How far below the cup object the trigger sits, in units. 40 is the kit\u0027s straight cup; the\n\t/// curved and trench cups are 52 deep.\n\t/// \u003C/summary\u003E\n\t[Property, Title( \u0022Cup Depth\u0022 ), Range( 0f, 200f )]\n\tpublic float CupDepth { get; set; } = 40f;\n\n\t/// \u003Csummary\u003ERoom left round the pieces on each side in X and Y, in units; 120 below the lowest piece and 800 above the highest.\u003C/summary\u003E\n\tpublic const float BoundsMargin = 200f;\n\tpublic const float BoundsBelow = 120f;\n\tpublic const float BoundsAbove = 800f;\n\n\t/// \u003Csummary\u003EThe cup under this group: the first enabled \u003Csee cref=\u0022GolfCup\u0022/\u003E, or null.\u003C/summary\u003E\n\tpublic GolfCup Cup =\u003E GameObject.GetComponentInChildren\u003CGolfCup\u003E( false );\n\n\t/// \u003Csummary\u003EThe tee under this group: the first enabled \u003Csee cref=\u0022GolfTee\u0022/\u003E, or null.\u003C/summary\u003E\n\tpublic GolfTee Tee =\u003E GameObject.GetComponentInChildren\u003CGolfTee\u003E( false );\n\n\t/// \u003Csummary\u003EWhere the cup is: the cup object\u0027s position, or the group\u0027s own when there is no cup.\u003C/summary\u003E\n\tpublic Vector3 CupPosition\n\t{\n\t\tget\n\t\t{\n\t\t\tvar cup = Cup;\n\t\t\treturn cup.IsValid() ? cup.WorldPosition : WorldPosition;\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003EWhere the balls start: the tee, or the cup when there is no tee.\u003C/summary\u003E\n\tpublic Vector3 TeePosition\n\t{\n\t\tget\n\t\t{\n\t\t\tvar tee = Tee;\n\t\t\treturn tee.IsValid() ? tee.WorldPosition : CupPosition;\n\t\t}\n\t}\n\n\tBBox _bounds;\n\tint _boundsHash;\n\tbool _boundsKnown;\n\n\t/// \u003Csummary\u003E\n\t/// The playable area, in world space: every renderer under the group, plus the margins. A ball\n\t/// outside it is out of bounds. Computed from the pieces when first asked and again when the\n\t/// set of pieces changes (a piece added or removed in the editor); moving the whole group moves\n\t/// it along.\n\t/// \u003C/summary\u003E\n\tpublic BBox Bounds\n\t{\n\t\tget\n\t\t{\n\t\t\tvar renderers = GameObject.GetComponentsInChildren\u003CModelRenderer\u003E( true ).ToList();\n\t\t\tvar hash = new HashCode();\n\t\t\thash.Add( renderers.Count );\n\t\t\thash.Add( (int)MathF.Round( WorldPosition.x ) ); hash.Add( (int)MathF.Round( WorldPosition.y ) ); hash.Add( (int)MathF.Round( WorldPosition.z ) );\n\t\t\tvar code = hash.ToHashCode();\n\t\t\tif ( _boundsKnown \u0026\u0026 code == _boundsHash \u0026\u0026 Game.IsPlaying ) return _bounds;\n\n\t\t\tBBox? box = null;\n\t\t\tforeach ( var renderer in renderers )\n\t\t\t{\n\t\t\t\tif ( !renderer.IsValid() ) continue;\n\t\t\t\tvar b = renderer.Bounds;\n\t\t\t\tif ( b.Size.Length \u003C 0.01f ) continue;\n\t\t\t\tbox = box is null ? b : box.Value.AddBBox( b );\n\t\t\t}\n\t\t\tvar centre = CupPosition;\n\t\t\tvar inner = box ?? new BBox( centre - new Vector3( 640f, 640f, 0f ), centre \u002B new Vector3( 640f, 640f, 0f ) );\n\t\t\t_bounds = new BBox( inner.Mins \u002B new Vector3( -BoundsMargin, -BoundsMargin, -BoundsBelow ), inner.Maxs \u002B new Vector3( BoundsMargin, BoundsMargin, BoundsAbove ) );\n\t\t\t_boundsHash = code;\n\t\t\t_boundsKnown = true;\n\t\t\treturn _bounds;\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003ETrue if a world position is inside the playable area.\u003C/summary\u003E\n\tpublic bool Contains( Vector3 position )\n\t{\n\t\tvar box = Bounds;\n\t\treturn position.x \u003E= box.Mins.x \u0026\u0026 position.x \u003C= box.Maxs.x\n\t\t\t\u0026\u0026 position.y \u003E= box.Mins.y \u0026\u0026 position.y \u003C= box.Maxs.y\n\t\t\t\u0026\u0026 position.z \u003E= box.Mins.z \u0026\u0026 position.z \u003C= box.Maxs.z;\n\t}\n\n\tprotected override void OnEnabled()\n\t{\n\t\t_boundsKnown = false;\n\t\t// The group\u0027s merged collider, added here so a hole never needs it added by hand. Only in\n\t\t// the editor: in play a hole without one stays as its author saved it.\n\t\tif ( !Game.IsPlaying \u0026\u0026 !IsOldLayout \u0026\u0026 Components.Get\u003CGolfHoleCollision\u003E( true ) is null )\n\t\t\tComponents.Create\u003CGolfHoleCollision\u003E();\n\t}\n\n\t// ---------------------------------------------------------------- the old layout\n\n\t/// \u003Csummary\u003E\n\t/// A hole saved by an older kit: the component sat on the cup object (with a Model Renderer)\n\t/// under a \u0022Hole N\u0022 group, with Title and Par there and a Golf Cup Shape beside it.\n\t/// \u003C/summary\u003E\n\tpublic bool IsOldLayout =\u003E GameObject.GetComponent\u003CModelRenderer\u003E( true ) is not null;\n\n\t/// \u003Csummary\u003E\n\t/// Brings every old-layout hole in a scene to this layout: the parent group (the nearest\n\t/// ancestor named \u0022Hole N\u0022, else the parent) gets a Golf Hole with the cup\u0027s title and par,\n\t/// the cup object gets a \u003Csee cref=\u0022GolfCup\u0022/\u003E, and the old component is switched off. Safe\n\t/// to call more than once. Returns how many holes were moved.\n\t/// \u003C/summary\u003E\n\tpublic static int MigrateOldLayout( Scene scene )\n\t{\n\t\tif ( scene is null ) return 0;\n\t\tvar moved = 0;\n\t\tforeach ( var old in scene.GetAllComponents\u003CHole\u003E().ToList() )\n\t\t{\n\t\t\tif ( !old.IsValid() || !old.IsOldLayout ) continue;\n\t\t\tvar cupObject = old.GameObject;\n\t\t\tvar group = GroupOf( cupObject );\n\t\t\tif ( !group.IsValid() ) continue;\n\n\t\t\tvar hole = group.GetComponent\u003CHole\u003E( true );\n\t\t\tif ( hole is null || hole == old )\n\t\t\t{\n\t\t\t\thole = group.Components.Create\u003CHole\u003E();\n\t\t\t\thole.Title = old.Title;\n\t\t\t\thole.Par = old.Par;\n\t\t\t\thole.CupRadius = old.CupRadius;\n\t\t\t\thole.CupDepth = GuessDepth( cupObject, old.CupDepth );\n\t\t\t}\n\t\t\tif ( cupObject.GetComponent\u003CGolfCup\u003E( true ) is null ) cupObject.Components.Create\u003CGolfCup\u003E();\n\t\t\told.Enabled = false;\n\t\t\tmoved\u002B\u002B;\n\t\t\tLog.Info( $\u0022Golf Hole: {group.Name} brought to the current layout (title \\\u0022{hole.Title}\\\u0022, par {hole.Par}; the hole was on its cup {cupObject.Name})\u0022 );\n\t\t}\n\t\treturn moved;\n\t}\n\n\t/// \u003Csummary\u003EThe hole group of an object in the old layout: the nearest ancestor named \u0022Hole N\u0022, else the parent.\u003C/summary\u003E\n\tstatic GameObject GroupOf( GameObject cup )\n\t{\n\t\tGameObject fallback = null;\n\t\tfor ( var go = cup.Parent; go.IsValid() \u0026\u0026 go is not Sandbox.Scene; go = go.Parent )\n\t\t{\n\t\t\tfallback ??= go;\n\t\t\tif ( System.Text.RegularExpressions.Regex.IsMatch( go.Name ?? \u0022\u0022, @\u0022^\\s*Hole\\s\u002B\\d\u002B\u0022 ) ) return go;\n\t\t}\n\t\treturn fallback;\n\t}\n\n\t/// \u003Csummary\u003EThe trigger depth for a cup by its model: the curved and trench cups are 52 deep, the straight cup 40.\u003C/summary\u003E\n\tpublic static float GuessDepth( GameObject cup, float fallback )\n\t{\n\t\tvar name = cup.GetComponent\u003CModelRenderer\u003E( true )?.Model?.Name ?? \u0022\u0022;\n\t\tif ( name.Contains( \u0022curved\u0022, StringComparison.OrdinalIgnoreCase ) || name.Contains( \u0022trench\u0022, StringComparison.OrdinalIgnoreCase ) ) return 52f;\n\t\tif ( name.Contains( \u0022straight\u0022, StringComparison.OrdinalIgnoreCase ) ) return 40f;\n\t\treturn fallback;\n\t}\n\n\t// ---------------------------------------------------------------- editor gizmo\n\n\t/// \u003Csummary\u003EEditor: the playable area as a red wireframe while the group is selected, and a line from tee to cup.\u003C/summary\u003E\n\tprotected override void DrawGizmos()\n\t{\n\t\tif ( !Gizmo.IsSelected ) return;\n\t\tusing var scope = Gizmo.Scope( \u0022hole\u0022 );\n\t\tGizmo.Transform = global::Transform.Zero;\n\t\tvar box = Bounds;\n\t\tGizmo.Draw.IgnoreDepth = false;\n\t\tGizmo.Draw.LineThickness = 2f;\n\t\tGizmo.Draw.Color = Color.Red.WithAlpha( 0.5f );\n\t\tGizmo.Draw.LineBBox( box );\n\t\tGizmo.Draw.Color = Color.Yellow.WithAlpha( 0.8f );\n\t\tGizmo.Draw.Line( TeePosition, CupPosition );\n\t}\n}\n"},{"Ident":"mrtn.golfkit","Path":"GolfHoleCollision.cs","FileName":"GolfHoleCollision.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":440545,"IsPrivate":false,"Code":"using Sandbox;\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Diagnostics;\r\nusing System.Linq;\r\n\r\n/// \u003Csummary\u003E\r\n/// One welded collision mesh for a whole hole. Lives on the hole\u0027s group, where the Golf Hole\r\n/// adds it on its own: collects every enabled piece under the group, takes their collision geometry in hole\r\n/// space, welds shared vertices across the pieces and builds a single static mesh collider with the\r\n/// golf surface. The pieces\u0027 own colliders are switched off, their visible meshes stay as they are.\r\n/// A ball rolling over a seam between two pieces then never meets an edge, so it never hops.\r\n///\r\n/// Runs in the editor too and rebuilds itself whenever a piece is added, moved, changed or removed,\r\n/// so a hole is built with pieces and this never needs touching. Nothing is networked: every machine\r\n/// builds the same mesh from the same scene (the piece set and their transforms come from the scene\r\n/// file, and welding is position based, so the result does not depend on order or on who is host).\r\n/// \u003C/summary\u003E\r\npublic sealed class GolfHoleCollision : Component, Component.ExecuteInEditor\r\n{\r\n\t/// \u003Csummary\u003EPhysics surface for the whole hole (Assets/surface/golf_green.surface).\u003C/summary\u003E\r\n\tpublic const string SurfaceName = \u0022golf_green\u0022;\r\n\r\n\t/// \u003Csummary\u003EVertices closer than 1/16 unit are the same vertex. Rotated pieces (walls, corners,\r\n\t/// bumpers) land a hair off the grid, this snaps them back onto their neighbours.\u003C/summary\u003E\r\n\tconst float WeldGrid = 16f;\r\n\r\n\t/// \u003Csummary\u003EHow often the pieces are checked for changes, in seconds.\u003C/summary\u003E\r\n\tconst float CheckInterval = 0.25f;\r\n\r\n\t/// \u003Csummary\u003EPieces and welded vertices of the last build; only the triangle count is shown.\u003C/summary\u003E\r\n\tpublic int Pieces { get; private set; }\r\n\tpublic int Vertices { get; private set; }\r\n\t[Property, ReadOnly] public int Triangles { get; private set; }\r\n\r\n\t/// \u003Csummary\u003EHow many hole colliders have been rebuilt since load (see golf_perf).\u003C/summary\u003E\r\n\tpublic static int RebuildCount;\r\n\r\n\tbool _dirty = true;\r\n\tint _lastHash;\r\n\tTimeSince _sinceCheck;\r\n\tModelCollider _collider;\r\n\r\n\t/// \u003Csummary\u003EA piece under this hole changed: rebuild on the next update.\u003C/summary\u003E\r\n\tpublic void MarkDirty() =\u003E _dirty = true;\r\n\r\n\tprotected override void OnEnabled()\r\n\t{\r\n\t\t_dirty = true;\r\n\t}\r\n\r\n\tprotected override void OnDisabled()\r\n\t{\r\n\t\tif ( _collider.IsValid() ) _collider.Enabled = false;\r\n\t}\r\n\r\n\tprotected override void OnUpdate()\r\n\t{\r\n\t\tif ( !_dirty )\r\n\t\t{\r\n\t\t\t// Polling for moved or edited pieces is for the editor. In play nothing moves a piece\r\n\t\t\t// except code, and that calls MarkDirty; every rebuild there cooks a physics mesh.\r\n\t\t\tif ( Game.IsPlaying ) return;\r\n\t\t\tif ( _sinceCheck \u003C CheckInterval ) return;\r\n\t\t\t_sinceCheck = 0;\r\n\t\t\tif ( ComputeHash() == _lastHash ) return;\r\n\t\t}\r\n\r\n\t\tRebuild();\r\n\t}\r\n\r\n\tIEnumerable\u003CKitShape\u003E PiecesBelow() =\u003E Components.GetAll\u003CKitShape\u003E( FindMode.EnabledInSelfAndDescendants );\r\n\r\n\t/// \u003Csummary\u003EModel pieces below (a Model Collider with a model, on an object that is not a Kit Shape): the Blender-made kit pieces.\u003C/summary\u003E\r\n\t// Disabled colliders count too: the merge switches a piece\u0027s own collider off, and a saved scene\r\n\t// keeps it off, so the piece must still be found on the next load.\r\n\tIEnumerable\u003CModelCollider\u003E ModelPiecesBelow() =\u003E Components.GetAll\u003CModelCollider\u003E( FindMode.EverythingInSelfAndDescendants )\r\n\t\t.Where( c =\u003E c.IsValid() \u0026\u0026 c.GameObject != GameObject \u0026\u0026 c.GameObject.Enabled \u0026\u0026 c.Model is not null \u0026\u0026 c.GetComponent\u003CKitShape\u003E() is null );\r\n\r\n\t/// \u003Csummary\u003ECheap fingerprint of every piece\u0027s transform and settings, for the change check.\u003C/summary\u003E\r\n\tint ComputeHash()\r\n\t{\r\n\t\tvar hash = new HashCode();\r\n\t\thash.Add( 2 ); // bump to force a rebuild after a code change\r\n\t\tvar hole = WorldTransform;\r\n\t\tforeach ( var piece in PiecesBelow() )\r\n\t\t{\r\n\t\t\t// Pieces without collision (flags, tee pads) never change the collider: the swaying flag\r\n\t\t\t// must not count as a change.\r\n\t\t\thash.Add( piece.Collision );\r\n\t\t\tif ( !piece.Collision ) continue;\r\n\t\t\tvar t = hole.ToLocal( piece.WorldTransform );\r\n\t\t\thash.Add( piece.Kind );\r\n\t\t\thash.Add( (int)MathF.Round( piece.Length * WeldGrid ) );\r\n\t\t\thash.Add( (int)MathF.Round( piece.Rise * WeldGrid ) );\r\n\t\t\thash.Add( (int)MathF.Round( t.Position.x * WeldGrid ) );\r\n\t\t\thash.Add( (int)MathF.Round( t.Position.y * WeldGrid ) );\r\n\t\t\thash.Add( (int)MathF.Round( t.Position.z * WeldGrid ) );\r\n\t\t\thash.Add( (int)MathF.Round( t.Rotation.x * 10000f ) );\r\n\t\t\thash.Add( (int)MathF.Round( t.Rotation.y * 10000f ) );\r\n\t\t\thash.Add( (int)MathF.Round( t.Rotation.z * 10000f ) );\r\n\t\t\thash.Add( (int)MathF.Round( t.Rotation.w * 10000f ) );\r\n\t\t\thash.Add( (int)MathF.Round( t.Scale.x * 1000f ) );\r\n\t\t\thash.Add( (int)MathF.Round( t.Scale.y * 1000f ) );\r\n\t\t\thash.Add( (int)MathF.Round( t.Scale.z * 1000f ) );\r\n\t\t\thash.Add( piece.CollisionIndices.Count );\r\n\t\t}\r\n\t\tforeach ( var piece in ModelPiecesBelow() )\r\n\t\t{\r\n\t\t\tvar t = hole.ToLocal( piece.WorldTransform );\r\n\t\t\thash.Add( piece.Model.Name );\r\n\t\t\thash.Add( (int)MathF.Round( piece.Model.Bounds.Mins.z * WeldGrid ) );\r\n\t\t\thash.Add( (int)MathF.Round( piece.Model.Bounds.Maxs.x * WeldGrid ) );\r\n\t\t\thash.Add( (int)MathF.Round( piece.Model.Bounds.Maxs.y * WeldGrid ) );\r\n\t\t\thash.Add( (int)MathF.Round( t.Position.x * WeldGrid ) );\r\n\t\t\thash.Add( (int)MathF.Round( t.Position.y * WeldGrid ) );\r\n\t\t\thash.Add( (int)MathF.Round( t.Position.z * WeldGrid ) );\r\n\t\t\thash.Add( (int)MathF.Round( t.Rotation.x * 10000f ) );\r\n\t\t\thash.Add( (int)MathF.Round( t.Rotation.y * 10000f ) );\r\n\t\t\thash.Add( (int)MathF.Round( t.Rotation.z * 10000f ) );\r\n\t\t\thash.Add( (int)MathF.Round( t.Rotation.w * 10000f ) );\r\n\t\t\thash.Add( (int)MathF.Round( t.Scale.x * 1000f ) );\r\n\t\t}\r\n\t\treturn hash.ToHashCode();\r\n\t}\r\n\r\n\tvoid Rebuild()\r\n\t{\r\n\t\tvar watch = Stopwatch.StartNew();\r\n\t\tRebuildCount\u002B\u002B;\r\n\t\t_dirty = false;\r\n\t\t_lastHash = ComputeHash();\r\n\r\n\t\tvar hole = WorldTransform;\r\n\t\tvar positions = new List\u003CVector3\u003E();\r\n\t\tvar indices = new List\u003Cint\u003E();\r\n\t\tvar lookup = new Dictionary\u003C(int, int, int), int\u003E();\r\n\t\tvar pieces = 0;\r\n\t\tvar found = 0;\r\n\r\n\t\tforeach ( var piece in PiecesBelow() )\r\n\t\t{\r\n\t\t\tfound\u002B\u002B;\r\n\t\t\t// The piece keeps its own collider only when it is not part of a hole.\r\n\t\t\tvar own = piece.GetComponent\u003CModelCollider\u003E();\r\n\t\t\tif ( own.IsValid() \u0026\u0026 own.Enabled ) own.Enabled = false;\r\n\r\n\t\t\tpiece.EnsureBuilt();\r\n\t\t\tif ( !piece.Collision || piece.CollisionIndices.Count == 0 ) continue;\r\n\t\t\tpieces\u002B\u002B;\r\n\r\n\t\t\tvar local = hole.ToLocal( piece.WorldTransform );\r\n\t\t\tvar source = piece.CollisionPositions;\r\n\t\t\tvar map = new int[source.Count];\r\n\t\t\tfor ( var i = 0; i \u003C source.Count; i\u002B\u002B )\r\n\t\t\t{\r\n\t\t\t\tvar p = local.PointToWorld( source[i] );\r\n\t\t\t\tvar key = ((int)MathF.Round( p.x * WeldGrid ), (int)MathF.Round( p.y * WeldGrid ), (int)MathF.Round( p.z * WeldGrid ));\r\n\t\t\t\tif ( !lookup.TryGetValue( key, out var index ) )\r\n\t\t\t\t{\r\n\t\t\t\t\tindex = positions.Count;\r\n\t\t\t\t\tpositions.Add( new Vector3( key.Item1 / WeldGrid, key.Item2 / WeldGrid, key.Item3 / WeldGrid ) );\r\n\t\t\t\t\tlookup[key] = index;\r\n\t\t\t\t}\r\n\t\t\t\tmap[i] = index;\r\n\t\t\t}\r\n\r\n\t\t\tvar tris = piece.CollisionIndices;\r\n\t\t\tfor ( var i = 0; i \u002B 2 \u003C tris.Count; i \u002B= 3 )\r\n\t\t\t{\r\n\t\t\t\tint a = map[tris[i]], b = map[tris[i \u002B 1]], c = map[tris[i \u002B 2]];\r\n\t\t\t\tif ( a == b || b == c || a == c ) continue; // collapsed by the weld\r\n\t\t\t\tindices.Add( a ); indices.Add( b ); indices.Add( c );\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Blender-made pieces: their model\u0027s mesh, welded in the same way; their own collider goes off.\r\n\t\tvar modelPieces = 0;\r\n\t\tforeach ( var piece in ModelPiecesBelow().ToList() )\r\n\t\t{\r\n\t\t\tfound\u002B\u002B;\r\n\t\t\tvar model = piece.Model;\r\n\t\t\tvar source = model.GetVertices();\r\n\t\t\tvar tris = model.GetIndices();\r\n\t\t\tif ( source is null || tris is null || source.Length == 0 || tris.Length \u003C 3 ) continue;\r\n\t\t\tif ( piece.Enabled ) piece.Enabled = false;\r\n\t\t\tmodelPieces\u002B\u002B;\r\n\t\t\tpieces\u002B\u002B;\r\n\r\n\t\t\tvar local = hole.ToLocal( piece.WorldTransform );\r\n\t\t\tvar map = new int[source.Length];\r\n\t\t\tfor ( var i = 0; i \u003C source.Length; i\u002B\u002B )\r\n\t\t\t{\r\n\t\t\t\tvar p = local.PointToWorld( source[i].Position );\r\n\t\t\t\tvar key = ((int)MathF.Round( p.x * WeldGrid ), (int)MathF.Round( p.y * WeldGrid ), (int)MathF.Round( p.z * WeldGrid ));\r\n\t\t\t\tif ( !lookup.TryGetValue( key, out var index ) )\r\n\t\t\t\t{\r\n\t\t\t\t\tindex = positions.Count;\r\n\t\t\t\t\tpositions.Add( new Vector3( key.Item1 / WeldGrid, key.Item2 / WeldGrid, key.Item3 / WeldGrid ) );\r\n\t\t\t\t\tlookup[key] = index;\r\n\t\t\t\t}\r\n\t\t\t\tmap[i] = index;\r\n\t\t\t}\r\n\t\t\tfor ( var i = 0; i \u002B 2 \u003C tris.Length; i \u002B= 3 )\r\n\t\t\t{\r\n\t\t\t\tint a = map[tris[i]], b = map[tris[i \u002B 1]], c = map[tris[i \u002B 2]];\r\n\t\t\t\tif ( a == b || b == c || a == c ) continue;\r\n\t\t\t\tindices.Add( a ); indices.Add( b ); indices.Add( c );\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tPieces = pieces;\r\n\t\tVertices = positions.Count;\r\n\t\tTriangles = indices.Count / 3;\r\n\r\n\t\tif ( !_collider.IsValid() )\r\n\t\t{\r\n\t\t\t_collider = Components.GetOrCreate\u003CModelCollider\u003E( FindMode.EverythingInSelf );\r\n\t\t\t_collider.Flags |= ComponentFlags.NotSaved; // rebuilt on load, never written to the scene file\r\n\t\t}\r\n\r\n\t\tif ( Triangles == 0 )\r\n\t\t{\r\n\t\t\t_collider.Enabled = false;\r\n\t\t\tLog.Info( $\u0022GolfHoleCollision: {GameObject.Name} has no collision: {found} pieces found, {Pieces} with collision data\u0022 );\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t_collider.Model = Model.Builder.AddCollisionMesh( positions, indices ).Create();\r\n\t\t_collider.Static = true;\r\n\t\t_collider.Surface = Surface.FindByName( SurfaceName ) ?? _collider.Surface;\r\n\t\t_collider.Enabled = true;\r\n\r\n\t\tLog.Info( $\u0022GolfHoleCollision: {GameObject.Name} built {Triangles} triangles from {Pieces} of {found} pieces, {modelPieces} of them models ({Vertices} welded vertices) in {watch.ElapsedMilliseconds} ms\u0022 );\r\n\t}\r\n}\r\n"},{"Ident":"mrtn.golfkit","Path":"Editor/CourseWallBuilderTool.Preview.cs","FileName":"CourseWallBuilderTool.Preview.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":440545,"IsPrivate":false,"Code":"using Sandbox;\r\nusing Editor;\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\n\r\n/// \u003Csummary\u003E\r\n/// The preview: the snap\u0027s blue feedback, and a ghost of exactly what the next click (or the drag\u0027s\r\n/// release) would place, drawn from a clone of the wall graph given the same operation and laid out\r\n/// by the same functions the sync uses. Redrawn every frame.\r\n/// \u003C/summary\u003E\r\npublic sealed partial class CourseWallBuilderTool\r\n{\r\n\t/// \u003Csummary\u003EEvery snap\u0027s feedback (the post outline, the grid and tile markers, the guide lines): light blue, semi-transparent.\u003C/summary\u003E\r\n\tstatic readonly Color SnapColor = new( 80f / 255f, 170f / 255f, 255f / 255f, 0.7f );\r\n\r\n\tstatic readonly Color GhostColor = Color.White.WithAlpha( 0.45f );\r\n\r\n\t/// \u003Csummary\u003EThe whole preview of a frame with the cursor on a surface: the snap\u0027s feedback, then the ghost of the pending click.\u003C/summary\u003E\r\n\tvoid DrawPreview( WallGraph graph, SnapResult snap )\r\n\t{\r\n\t\tDrawSnapFeedback( snap );\r\n\r\n\t\tvar preview = graph.Clone();\r\n\t\tvar joined = PendingClick( preview, snap, out var joinPost );\r\n\t\tDrawGhosts( preview );\r\n\r\n\t\tif ( !joined ) return;\r\n\r\n\t\t// A click on an existing post places nothing there; the post is outlined instead, and with no\r\n\t\t// run open a NuWall post shows the inside the new rails would inherit.\r\n\t\tif ( !Continuing \u0026\u0026 Style == WallStyle.NuWall )\r\n\t\t\tforeach ( var inside in InsidesAt( graph, joinPost ).Take( 1 ) )\r\n\t\t\t{\r\n\t\t\t\tGizmo.Draw.Color = SnapColor;\r\n\t\t\t\tGizmo.Draw.LineThickness = 3f;\r\n\t\t\t\tGizmo.Draw.Line( joinPost.Point \u002B Vector3.Up, joinPost.Point \u002B Vector3.Up \u002B inside * 40f );\r\n\t\t\t}\r\n\t\tvar postModel = Style == WallStyle.NuWall ? NuWallCornerModel : KitPostModel;\r\n\t\tvar postBox = postModel is null\r\n\t\t\t? new BBox( new Vector3( -PostSize / 2f, -PostSize / 2f, 0f ), new Vector3( PostSize / 2f, PostSize / 2f, KitShape.WallHeight ) )\r\n\t\t\t: new BBox( postModel.Bounds.Mins - WallPieces.StandOffset( postModel.Bounds ), postModel.Bounds.Maxs - WallPieces.StandOffset( postModel.Bounds ) );\r\n\t\tGizmo.Draw.Color = SnapColor;\r\n\t\tGizmo.Draw.LineThickness = 3f;\r\n\t\tusing ( Gizmo.Scope( \u0022coursewall-snap\u0022, new Transform( joinPost.Point, Rotation.Identity ) ) )\r\n\t\t\tGizmo.Draw.LineBBox( postBox );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Applies to a graph what a click at the snap would do: the loop close lays the last rail to the\r\n\t/// first post; a snap on a post joins it (with a rail while the run is open, as the run\u0027s start\r\n\t/// otherwise); anything else adds a post there and, with the run open, the rail to it. Returns\r\n\t/// true when an existing post is joined rather than a post placed, with that post.\r\n\t/// \u003C/summary\u003E\r\n\tbool PendingClick( WallGraph graph, SnapResult snap, out WallPost joined )\r\n\t{\r\n\t\tjoined = null;\r\n\t\tif ( snap.Kind == SnapKind.LoopClose )\r\n\t\t{\r\n\t\t\tvar first = graph.PostAt( _run.First );\r\n\t\t\tvar last = graph.PostAt( _run.Last );\r\n\t\t\tif ( first is not null \u0026\u0026 last is not null ) graph.AddRail( last, first, Style, RailInside( _run.Last, _run.First ) );\r\n\t\t\tjoined = first;\r\n\t\t\treturn first is not null;\r\n\t\t}\r\n\t\tif ( snap.Kind == SnapKind.Post \u0026\u0026 graph.PostAt( snap.Point ) is { } existing )\r\n\t\t{\r\n\t\t\tjoined = existing;\r\n\t\t\tif ( Continuing \u0026\u0026 graph.PostAt( _run.Last ) is { } from \u0026\u0026 from != existing ) graph.AddRail( from, existing, Style, RailInside( _run.Last, existing.Point ) );\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif ( Continuing \u0026\u0026 _run.Last.Distance( snap.Point ) \u003C= PostSize ) { joined = graph.PostAt( _run.Last ); return joined is not null; }\r\n\t\tvar post = graph.AddPost( snap.Point );\r\n\t\tif ( Continuing \u0026\u0026 graph.PostAt( _run.Last ) is { } last2 \u0026\u0026 last2 != post ) graph.AddRail( last2, post, Style, RailInside( _run.Last, post.Point ) );\r\n\t\treturn false;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EThe ghosts of everything a graph would build when applied: a post for every post node without an object, the pieces of every rail without pieces.\u003C/summary\u003E\r\n\tvoid DrawGhosts( WallGraph graph )\r\n\t{\r\n\t\tforeach ( var post in graph.Posts.Where( p =\u003E !p.Object.IsValid() ) )\r\n\t\t{\r\n\t\t\tif ( Style == WallStyle.NuWall )\r\n\t\t\t{\r\n\t\t\t\tif ( NuWallCornerModel is { } corner ) DrawGhost( corner, NuWallCornerTransform( post.Point, graph.RailInfo( post ) ), GhostColor );\r\n\t\t\t}\r\n\t\t\telse if ( KitPostModel is { } model )\r\n\t\t\t\tDrawGhost( model, new Transform( post.Point - WallPieces.StandOffset( model.Bounds ), Rotation.Identity ), GhostColor );\r\n\t\t}\r\n\t\tforeach ( var rail in graph.Rails.Where( r =\u003E r.Pieces.Count == 0 \u0026\u0026 r.Length \u003E= 1f ) )\r\n\t\t{\r\n\t\t\tif ( rail.Style == WallStyle.NuWall )\r\n\t\t\t{\r\n\t\t\t\tif ( NuWallEdgeModel is { } edge )\r\n\t\t\t\t\tforeach ( var transform in NuWallEdgeTransforms( rail.A.Point, rail.B.Point, RailHand( rail ) ) ) DrawGhost( edge, transform, GhostColor );\r\n\t\t\t}\r\n\t\t\telse if ( KitWallModel is { } wall )\r\n\t\t\t\tDrawGhost( wall, HolekitRailTransform( wall, rail.A.Point, rail.B.Point ), GhostColor );\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EOne ghost piece: the model drawn at the transform with a translucent tint.\u003C/summary\u003E\r\n\tstatic void DrawGhost( Model model, Transform transform, Color tint )\r\n\t{\r\n\t\tGizmo.Draw.Color = tint;\r\n\t\tvar sceneModel = Gizmo.Draw.Model( model, transform );\r\n\t\tif ( sceneModel is not null ) sceneModel.ColorTint = tint;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The snap\u0027s blue feedback: a snapped edge or grid line drawn itself, a direction or axis from\r\n\t/// the post through the point and a little beyond, the alignment from the first post; and a\r\n\t/// marker on the ground at the point for every point snap but a post (a dot for an edge midpoint,\r\n\t/// a ring for a tile centre, a cross for a grid or axis point and a line snap\u0027s foot, a diamond\r\n\t/// for a tile corner).\r\n\t/// \u003C/summary\u003E\r\n\tstatic void DrawSnapFeedback( SnapResult snap )\r\n\t{\r\n\t\tvar kind = snap.Kind;\r\n\t\tforeach ( var (lineFrom, lineTo) in snap.Lines )\r\n\t\t{\r\n\t\t\tvar along = (lineTo - lineFrom).WithZ( 0f );\r\n\t\t\tvar end = IsLineKind( kind ) ? lineTo : along.Length \u003E 1f ? lineTo \u002B along.Normal * KitShape.Tile : lineTo;\r\n\t\t\tGizmo.Draw.Color = SnapColor;\r\n\t\t\tGizmo.Draw.LineThickness = IsLineKind( kind ) ? 2f : 1f;\r\n\t\t\tGizmo.Draw.Line( lineFrom \u002B Vector3.Up, end \u002B Vector3.Up );\r\n\t\t}\r\n\r\n\t\tif ( kind is SnapKind.None or SnapKind.Direction or SnapKind.Post or SnapKind.LoopClose ) return;\r\n\t\tGizmo.Draw.Color = SnapColor;\r\n\t\tGizmo.Draw.LineThickness = 2f;\r\n\t\tvar at = snap.Point \u002B Vector3.Up;\r\n\t\tconst float arm = 15f;\r\n\t\tswitch ( kind )\r\n\t\t{\r\n\t\t\tcase SnapKind.TileMid:\r\n\t\t\t\tGizmo.Draw.SolidBox( BBox.FromPositionAndSize( at, 6f ) );\r\n\t\t\t\tbreak;\r\n\t\t\tcase SnapKind.TileCentre:\r\n\t\t\t\tconst int segments = 16;\r\n\t\t\t\tfor ( var i = 0; i \u003C segments; i\u002B\u002B )\r\n\t\t\t\t{\r\n\t\t\t\t\tvar a0 = MathF.Tau * i / segments;\r\n\t\t\t\t\tvar a1 = MathF.Tau * (i \u002B 1) / segments;\r\n\t\t\t\t\tGizmo.Draw.Line( at \u002B new Vector3( MathF.Cos( a0 ), MathF.Sin( a0 ), 0f ) * 10f, at \u002B new Vector3( MathF.Cos( a1 ), MathF.Sin( a1 ), 0f ) * 10f );\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase SnapKind.TileCorner:\r\n\t\t\t\tvar n = at \u002B Vector3.Forward * arm;\r\n\t\t\t\tvar s = at - Vector3.Forward * arm;\r\n\t\t\t\tvar w = at \u002B Vector3.Left * arm;\r\n\t\t\t\tvar e = at - Vector3.Left * arm;\r\n\t\t\t\tGizmo.Draw.Line( n, w ); Gizmo.Draw.Line( w, s ); Gizmo.Draw.Line( s, e ); Gizmo.Draw.Line( e, n );\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tGizmo.Draw.Line( at \u002B Vector3.Left * arm, at - Vector3.Left * arm );\r\n\t\t\t\tGizmo.Draw.Line( at \u002B Vector3.Forward * arm, at - Vector3.Forward * arm );\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EThe outline of a piece\u0027s render bounds: the hover highlight, or the stronger selection outline.\u003C/summary\u003E\r\n\tstatic void DrawPieceOutline( GameObject go, bool selected )\r\n\t{\r\n\t\tvar renderer = go.GetComponent\u003CModelRenderer\u003E( true );\r\n\t\tif ( renderer is null ) return;\r\n\t\tGizmo.Draw.Color = selected ? SnapColor.WithAlpha( 1f ) : SnapColor;\r\n\t\tGizmo.Draw.LineThickness = selected ? 3f : 1.5f;\r\n\t\tGizmo.Draw.LineBBox( renderer.Bounds );\r\n\t}\r\n}\r\n"},{"Ident":"mrtn.golfkit","Path":"Code/GolfRotator.cs","FileName":"GolfRotator.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":440545,"IsPrivate":false,"Code":"using Sandbox;\r\nusing System;\r\nusing System.Linq;\r\n\r\n/// \u003Csummary\u003E\r\n/// Spins the object it sits on round one of its own axes at a steady rate, on every machine and\r\n/// in the editor too (nothing is networked: every machine turns it the same way from the same\r\n/// start, and a prop that is a little out of step between machines does not matter). Made for\r\n/// the windmill\u0027s blades, whose axle is their local Y.\r\n///\r\n/// With a Rigidbody on the same object (motion off, so the body is keyframed in play) the turn\r\n/// goes through the physics body with a matching angular velocity, and on the host the box\r\n/// colliders on the object also push golf balls by hand: a ball inside the sweep is kept awake,\r\n/// and a ball an arm box overlaps is given the arm\u0027s surface speed at the contact point, so\r\n/// resting balls get swatted instead of being passed through.\r\n/// \u003C/summary\u003E\r\n[Title( \u0022Golf Rotator\u0022 ), Icon( \u0022sync\u0022 ), Category( \u0022Golf\u0022 )]\r\npublic sealed class GolfRotator : Component, Component.ExecuteInEditor\r\n{\r\n\t/// \u003Csummary\u003EThe local axis to turn round. The windmill blades turn round their local Y.\u003C/summary\u003E\r\n\t[Property]\r\n\tpublic Vector3 Axis { get; set; } = new Vector3( 0f, 1f, 0f );\r\n\r\n\t/// \u003Csummary\u003ETurning speed in degrees per second; negative turns the other way.\u003C/summary\u003E\r\n\t[Property, Title( \u0022Degrees Per Second\u0022 ), Range( -360f, 360f )]\r\n\tpublic float DegreesPerSecond { get; set; } = 30f;\r\n\r\n\tRigidbody _body;\r\n\tBoxCollider[] _arms = Array.Empty\u003CBoxCollider\u003E();\r\n\tfloat _reach;\r\n\tbool _loggedContact;\r\n\r\n\tprotected override void OnStart()\r\n\t{\r\n\t\t_body = GetComponent\u003CRigidbody\u003E( true );\r\n\t\t_arms = GetComponents\u003CBoxCollider\u003E( true ).ToArray();\r\n\t\t_reach = _arms.Length == 0 ? 0f : _arms.Max( a =\u003E a.Center.Length \u002B a.Scale.Length * 0.5f );\r\n\t}\r\n\r\n\tprotected override void OnUpdate()\r\n\t{\r\n\t\t// In play with a physics body the fixed step below does the turning.\r\n\t\tif ( !Scene.IsEditor \u0026\u0026 _body.IsValid() ) return;\r\n\t\tTurn( Time.Delta );\r\n\t}\r\n\r\n\tprotected override void OnFixedUpdate()\r\n\t{\r\n\t\tif ( Scene.IsEditor || !_body.IsValid() ) return;\r\n\t\tvar next = Turn( Time.Delta );\r\n\t\tif ( next is null ) return;\r\n\r\n\t\t// The keyframed body is rotated with the velocity that gets it there this step, so a ball\r\n\t\t// in the blade\u0027s path is pushed rather than finding the blade somewhere else next step.\r\n\t\t_body.SmoothRotate( next.Value, Time.Delta, Time.Delta );\r\n\r\n\t\tif ( Networking.IsHost ) PushBalls();\r\n\t}\r\n\r\n\t/// \u003Csummary\u003ETurns the object by one step and returns the new world rotation, or null when there is nothing to do.\u003C/summary\u003E\r\n\tRotation? Turn( float seconds )\r\n\t{\r\n\t\tvar axis = Axis;\r\n\t\tif ( axis.IsNearlyZero() || DegreesPerSecond == 0f || seconds \u003C= 0f ) return null;\r\n\t\tLocalRotation *= Rotation.FromAxis( axis.Normal, DegreesPerSecond * seconds );\r\n\t\treturn WorldRotation;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Host only. Every ball within the sweep is kept awake (a sleeping ball ignores a keyframed\r\n\t/// body sliding into it), and a ball that an arm box overlaps gets at least the arm\u0027s surface\r\n\t/// velocity along the contact normal and is lifted out of the box.\r\n\t/// \u003C/summary\u003E\r\n\tvoid PushBalls()\r\n\t{\r\n\t\tif ( _arms.Length == 0 || DegreesPerSecond == 0f ) return;\r\n\r\n\t\tvar hub = WorldPosition;\r\n\t\tvar omega = WorldRotation * Axis.Normal * DegreesPerSecond.DegreeToRadian();\r\n\t\tvar transform = WorldTransform;\r\n\r\n\t\tforeach ( var ball in Scene.GetAllComponents\u003CIGolfCourseBall\u003E() )\r\n\t\t{\r\n\t\t\tif ( !ball.GameObject.IsValid() || ball.IsHoled || !ball.Rigidbody.IsValid() ) continue;\r\n\r\n\t\t\tvar pos = ball.WorldPosition;\r\n\t\t\tif ( pos.Distance( hub ) \u003E _reach \u002B ball.Radius \u002B 4f ) continue;\r\n\r\n\t\t\tball.Rigidbody.Sleeping = false;\r\n\r\n\t\t\tforeach ( var arm in _arms )\r\n\t\t\t{\r\n\t\t\t\tif ( !arm.IsValid() || !arm.Enabled ) continue;\r\n\r\n\t\t\t\t// Closest point of the arm box to the ball\u0027s centre, in the box\u0027s own frame.\r\n\t\t\t\tvar local = transform.PointToLocal( pos ) - arm.Center;\r\n\t\t\t\tvar half = arm.Scale * 0.5f;\r\n\t\t\t\tvar clamped = new Vector3( Math.Clamp( local.x, -half.x, half.x ), Math.Clamp( local.y, -half.y, half.y ), Math.Clamp( local.z, -half.z, half.z ) );\r\n\t\t\t\tvar closest = transform.PointToWorld( clamped \u002B arm.Center );\r\n\t\t\t\tvar gap = pos - closest;\r\n\t\t\t\tvar dist = gap.Length;\r\n\t\t\t\tif ( dist \u003E ball.Radius ) continue;\r\n\r\n\t\t\t\tvar surface = Vector3.Cross( omega, closest - hub );\r\n\t\t\t\tvar normal = dist \u003E 0.05f ? gap.Normal : surface.Normal;\r\n\t\t\t\tif ( normal.IsNearlyZero() ) continue;\r\n\r\n\t\t\t\t// Match the arm\u0027s speed into the ball; a ball already moving away is left alone.\r\n\t\t\t\tvar velocity = ball.Rigidbody.Velocity;\r\n\t\t\t\tvar relative = (velocity - surface).Dot( normal );\r\n\t\t\t\tif ( relative \u003C 0f ) ball.Rigidbody.Velocity = velocity - normal * relative;\r\n\r\n\t\t\t\t// Lift it out of the box so the next step starts from a clean contact.\r\n\t\t\t\tif ( dist \u003C ball.Radius - 0.1f ) ball.WorldPosition = pos \u002B normal * (ball.Radius - dist);\r\n\r\n\t\t\t\tif ( !_loggedContact )\r\n\t\t\t\t{\r\n\t\t\t\t\t_loggedContact = true;\r\n\t\t\t\t\tLog.Info( $\u0022GolfRotator: {GameObject.Name} first touched {ball.OwnerName}\u0027s ball at {closest}, arm surface speed {surface.Length:0}, ball {velocity.Length:0} -\u003E {ball.Rigidbody.Velocity.Length:0} u/s\u0022 );\r\n\t\t\t\t}\r\n\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n"},{"Ident":"mrtn.golfkit","Path":"Editor/GolfCourseProjectMeta.cs","FileName":"GolfCourseProjectMeta.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":440545,"IsPrivate":false,"Code":"using Sandbox;\nusing Editor;\nusing System;\nusing System.IO;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing System.Collections.Generic;\n\n/// \u003Csummary\u003E\n/// Keeps a course project\u0027s package metadata right so a mapper never edits the .sbproj by hand,\n/// and publishes the course the way the backend expects a map.\n///\n/// While editing the project is an \u0022addon\u0022 with no ParentPackage and PrimaryAsset the scene with\n/// the course in it. A project with a parent package makes the editor fetch and reference that\n/// game at compile time, and a map-typed project does not compile its local libraries at all;\n/// either way a mapper whose editor cannot load the game loses every kit component. This state\n/// is restored when the editor comes up, after a code reload and after every scene save, which\n/// also repairs a project an older kit left as a map.\n///\n/// Publishing goes through the course scene\u0027s own publish settings (Golf Kit \u0026gt; Publish\n/// course.., \u003Csee cref=\u0022PublishCourse\u0022/\u003E): the scene asset is published as a \u0022map\u0022 package of the\n/// game, through a temporary project the way the Inspector\u0027s Publish button publishes a scene.\n/// That is the only form of map the backend indexes: a whole project uploaded with Type \u0022map\u0022\n/// gets a package record, but it never appears under \u0022type:map\u0022 or \u0022target:\u0022 (checked\n/// 2026-10-28: all 100 newest indexed maps carry the asset publish\u0027s AssetType metadata, and a\n/// project-published map with the same ParentPackage was missing from every listing), so the\n/// game\u0027s course screen never sees it.\n///\n/// Only the editor\u0027s active project is touched, only when it holds golf objects (a Golf Course\n/// Info or a Hole) and is neither the game nor the kit. Everything goes through the live\n/// \u003Csee cref=\u0022Project.Config\u0022/\u003E and the editor\u0027s own project save: the editor writes the .sbproj\n/// from that config on close, so a file edited behind its back would be overwritten.\n/// \u003C/summary\u003E\npublic static class GolfCourseProjectMeta\n{\n\tpublic const string GameIdent = \u0022mrtn.golfwithyourguns\u0022;\n\tpublic const string KitIdent = \u0022mrtn.golfkit\u0022;\n\tpublic const string MapType = \u0022map\u0022;\n\tpublic const string EditType = \u0022addon\u0022;\n\n\t/// \u003Csummary\u003EMarker in a scene\u0027s publish settings: the kit filled them in once, the mapper\u0027s later edits stand.\u003C/summary\u003E\n\tconst string CourseMetaKey = \u0022GolfCourse\u0022;\n\n\tstatic readonly System.Collections.Generic.HashSet\u003Cstring\u003E _skipped = new( StringComparer.OrdinalIgnoreCase );\n\n\t// The editor\u0027s own handlers take these arguments (EditorMainWindow, Scene); the event system\n\t// refuses a handler whose parameter count differs.\n\t[Event( \u0022editor.created\u0022 )]\n\tstatic void OnEditorCreated( EditorMainWindow window ) =\u003E Apply( \u0022editor start\u0022, null );\n\n\t[EditorEvent.Hotload]\n\tstatic void OnHotload() =\u003E Apply( \u0022code reload\u0022, null );\n\n\t[Event( \u0022scene.saved\u0022 )]\n\tstatic void OnSceneSaved( Scene scene ) =\u003E Apply( \u0022scene save\u0022, scene?.Source?.ResourcePath );\n\n\t/// \u003Csummary\u003EHow often the editor events above have fired, and the last reason: a check that the hooks are wired.\u003C/summary\u003E\n\tpublic static int Fired { get; private set; }\n\tpublic static string LastReason { get; private set; }\n\n\tstatic void Apply( string reason, string savedScene )\n\t{\n\t\tFired\u002B\u002B;\n\t\tLastReason = reason;\n\t\ttry\n\t\t{\n\t\t\tApply( Project.Current, savedScene ?? SceneEditorSession.Active?.Scene?.Source?.ResourcePath, reason );\n\t\t}\n\t\tcatch ( Exception e )\n\t\t{\n\t\t\tLog.Warning( e, $\u0022Golf Kit: course metadata ({reason}) failed\u0022 );\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Puts the project in the editing state (Type addon, no ParentPackage, PrimaryAsset the course\n\t/// scene) when it is not there already, saves the project through the editor and reads the\n\t/// config back. Returns true when something changed. A project with no golf objects is left\n\t/// alone; so are the game and the kit, and game or library projects.\n\t/// \u003C/summary\u003E\n\tpublic static bool Apply( Project project, string openScene, string reason )\n\t{\n\t\tif ( !IsCourseProject( project, out var config, out var ident ) ) return false;\n\n\t\tvar scenes = CourseScenes( project );\n\t\tif ( scenes.Count == 0 ) return false;\n\n\t\tvar scene = Choose( scenes, openScene, ident );\n\n\t\tvar currentType = config.Type ?? \u0022\u0022;\n\t\tvar currentParent = config.GetMetaOrDefault\u003Cstring\u003E( \u0022ParentPackage\u0022, null ) ?? \u0022\u0022;\n\t\tvar currentPrimary = config.GetMetaOrDefault\u003Cstring\u003E( \u0022PrimaryAsset\u0022, null ) ?? \u0022\u0022;\n\t\tvar typeOk = string.Equals( currentType, EditType, StringComparison.OrdinalIgnoreCase );\n\t\tif ( typeOk \u0026\u0026 currentParent.Length == 0 \u0026\u0026 string.Equals( currentPrimary, scene, StringComparison.OrdinalIgnoreCase ) )\n\t\t\treturn false;\n\n\t\tconfig.Type = EditType;\n\t\tconfig.Metadata?.Remove( \u0022ParentPackage\u0022 );\n\t\tconfig.SetMeta( \u0022PrimaryAsset\u0022, scene );\n\t\tvar wasMap = string.Equals( currentType, MapType, StringComparison.OrdinalIgnoreCase ) || string.Equals( currentType, \u0022content\u0022, StringComparison.OrdinalIgnoreCase );\n\t\tLog.Info( $\u0022Golf Kit: {ident} ({reason}): Type {Show( currentType )} -\u003E {EditType}, ParentPackage {Show( currentParent )} -\u003E (none), PrimaryAsset {Show( currentPrimary )} -\u003E {scene}\u0022\n\t\t\t\u002B ( wasMap ? \u0022; the course is published as a map package of the game through Golf Kit \u003E Publish course..\u0022 : \u0022\u0022 ) );\n\n\t\tSave( project );\n\t\tVerify( project, scene );\n\t\treturn true;\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Golf Kit \u0026gt; Publish course..: fills in the course scene\u0027s publish settings (a \u0022map\u0022 package\n\t/// of the game: ParentPackage and GameSupport the game, PrimaryAsset the scene; on the first\n\t/// run the project\u0027s org, ident and title, so a course keeps the ident it had), saves them to\n\t/// the scene\u0027s .meta, and opens the editor\u0027s Publisher on the temporary project the editor\n\t/// builds for a published asset. The mapper\u0027s own project is left in the editing state.\n\t/// \u003C/summary\u003E\n\t[Menu( \u0022Editor\u0022, \u0022Golf Kit/Publish course..\u0022, \u0022upload_file\u0022 )]\n\tpublic static void PublishCourse()\n\t{\n\t\ttry\n\t\t{\n\t\t\tvar project = Project.Current;\n\t\t\tif ( !IsCourseProject( project, out var projectConfig, out var ident ) )\n\t\t\t{\n\t\t\t\tLog.Warning( $\u0022Golf Kit: {Show( project?.Config?.FullIdent )} is not a course project (the game, the kit, a game or library project, or no project); nothing to publish\u0022 );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tvar scenes = CourseScenes( project );\n\t\t\tif ( scenes.Count == 0 )\n\t\t\t{\n\t\t\t\tLog.Warning( $\u0022Golf Kit: {ident} has no scene with a Golf Course Info or a Hole; nothing to publish\u0022 );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tvar scene = Choose( scenes, SceneEditorSession.Active?.Scene?.Source?.ResourcePath, ident );\n\t\t\tApply( project, scene, \u0022publish\u0022 );\n\n\t\t\tvar asset = AssetSystem.FindByPath( Path.Combine( project.GetAssetsPath(), scene ) ) ?? AssetSystem.FindByPath( scene );\n\t\t\tif ( asset is null )\n\t\t\t{\n\t\t\t\tLog.Warning( $\u0022Golf Kit: the course scene {scene} of {ident} is not in the asset system (is it saved?); nothing to publish\u0022 );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tvar publishing = asset.Publishing;\n\t\t\tvar config = publishing.ProjectConfig;\n\t\t\tvar fresh = !config.TryGetMeta\u003Cbool\u003E( CourseMetaKey, out var marked ) || !marked;\n\t\t\tpublishing.Enabled = true;\n\t\t\tconfig.Type = MapType;\n\t\t\tif ( fresh || string.IsNullOrEmpty( config.Org ) || string.Equals( config.Org, \u0022local\u0022, StringComparison.OrdinalIgnoreCase ) )\n\t\t\t\tconfig.Org = projectConfig.Org;\n\t\t\tif ( fresh || string.IsNullOrEmpty( config.Ident ) )\n\t\t\t\tconfig.Ident = projectConfig.Ident;\n\t\t\tif ( fresh || string.IsNullOrEmpty( config.Title ) )\n\t\t\t\tconfig.Title = string.IsNullOrEmpty( projectConfig.Title ) ? config.Ident : projectConfig.Title;\n\t\t\tconfig.SetMeta( \u0022ParentPackage\u0022, GameIdent );\n\t\t\tconfig.SetMeta( \u0022GameSupport\u0022, new System.Collections.Generic.List\u003Cstring\u003E { GameIdent } );\n\t\t\tconfig.SetMeta( \u0022PrimaryAsset\u0022, scene );\n\t\t\tconfig.SetMeta( CourseMetaKey, true );\n\t\t\tpublishing.Save();\n\t\t\tLog.Info( $\u0022Golf Kit: {ident} (publish): the scene {scene} is published as {config.FullIdent}, a {MapType} package of {GameIdent}{( fresh ? \u0022 (publish settings filled in from the project; change them on the Publisher\u0027s first page)\u0022 : \u0022\u0022 )}\u0022 );\n\n\t\t\tvar context = publishing.BuildPublishContext();\n\t\t\tif ( !context.PublishingEnabled )\n\t\t\t{\n\t\t\t\tLog.Warning( $\u0022Golf Kit: the scene {scene} cannot be published: {context.ReasonForDisabling}\u0022 );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tvar thumbnail = CaptureThumbnail( project, scene );\n\n\t\t\tvar temporary = publishing.CreateTemporaryProject( context.IncludeCode ? project.RootDirectory : null );\n\t\t\tif ( temporary is null )\n\t\t\t{\n\t\t\t\tLog.Warning( $\u0022Golf Kit: the editor would not build a publish project for {scene}; publish the scene from its Inspector\u0027s Publish button instead\u0022 );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tvar wizard = OpenPublisher( temporary, context );\n\t\t\tif ( wizard is null )\n\t\t\t\tLog.Warning( $\u0022Golf Kit: the editor\u0027s Publisher could not be opened from here; select {scene} in the Asset Browser and press the Inspector\u0027s Publish button, the settings are filled in\u0022 );\n\t\t\telse\n\t\t\t\t_ownWizards.Add( wizard );\n\n\t\t\tif ( wizard is not null \u0026\u0026 thumbnail is not null )\n\t\t\t\t_pendingThumbnail = (wizard, thumbnail, RealTime.Now);\n\t\t\telse\n\t\t\t\t_ = RemindAboutThumbnailAsync( config.FullIdent );\n\t\t}\n\t\tcatch ( Exception e )\n\t\t{\n\t\t\tLog.Warning( e, \u0022Golf Kit: Publish course failed\u0022 );\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// sbox.game lists a map (and a game) only when it has a thumbnail; the backend\u0027s generated\n\t/// placeholder logo does not count (checked 2026-10-28: none of the 30 newest listed maps had\n\t/// one, and a course with one was missing from every map listing and from \u0022target:\u0022). The\n\t/// Publisher uploads a thumbnail only when one is picked on its first page, and when the\n\t/// package already exists it shows the placeholder there as if it were one. So the mapper is\n\t/// told, in the console and in a dialog, to pick an image; with the package\u0027s current state\n\t/// when the backend answers.\n\t/// \u003C/summary\u003E\n\tstatic async System.Threading.Tasks.Task RemindAboutThumbnailAsync( string fullIdent )\n\t{\n\t\tvar state = \u0022\u0022;\n\t\ttry\n\t\t{\n\t\t\tvar package = await Package.FetchAsync( fullIdent, false, false );\n\t\t\tif ( package is null ) state = $\u0022{fullIdent} is not on sbox.game yet, so it has no thumbnail. \u0022;\n\t\t\telse if ( string.IsNullOrEmpty( package.Thumb ) || package.Thumb.Contains( \u0022generated\u0022, StringComparison.OrdinalIgnoreCase ) ) state = $\u0022{fullIdent} has only the placeholder logo on sbox.game, which is why the game\u0027s course list does not show it. \u0022;\n\t\t\telse return;\n\t\t}\n\t\tcatch ( Exception e )\n\t\t{\n\t\t\tLog.Info( $\u0022Golf Kit: could not look up {fullIdent} on sbox.game ({e.Message}); the thumbnail reminder stands\u0022 );\n\t\t}\n\n\t\tvar message = state \u002B \u0022sbox.game lists a map only when it has a thumbnail, and the Publisher uploads one only if you pick it: click the square image on its first page and choose a PNG or JPG before you publish.\u0022;\n\t\tLog.Warning( $\u0022Golf Kit: {message}\u0022 );\n\t\ttry { Dialog.AskConfirm( () =\u003E { }, message, \u0022Golf Kit: pick a thumbnail\u0022, \u0022OK\u0022, \u0022Later\u0022 ); }\n\t\tcatch ( Exception e ) { Log.Info( $\u0022Golf Kit: the thumbnail dialog could not be shown ({e.Message})\u0022 ); }\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// The editor\u0027s publish wizard (Editor.Wizards.PublishWizard in the editor\u0027s tools addon, not\n\t/// public), opened the way the Inspector\u0027s Publish button opens it for an asset: with the\n\t/// asset\u0027s temporary project and its publish context. False when this editor build has no\n\t/// such wizard.\n\t/// \u003C/summary\u003E\n\tstatic object OpenPublisher( Project project, ResourcePublishContext context )\n\t{\n\t\tvar wizardType = AppDomain.CurrentDomain.GetAssemblies()\n\t\t\t.Select( a =\u003E { try { return a.GetType( \u0022Editor.Wizards.PublishWizard\u0022, false ); } catch { return null; } } )\n\t\t\t.FirstOrDefault( t =\u003E t is not null );\n\t\tvar open = wizardType?.GetMethods( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static )\n\t\t\t.FirstOrDefault( m =\u003E m.Name == \u0022Open\u0022 \u0026\u0026 m.GetParameters().Length \u003E= 1 \u0026\u0026 m.GetParameters()[0].ParameterType == typeof( Project ) );\n\t\tif ( open is null ) return null;\n\n\t\tvar parameters = open.GetParameters();\n\t\tvar args = new object[parameters.Length];\n\t\targs[0] = project;\n\t\tfor ( var i = 1; i \u003C parameters.Length; i\u002B\u002B )\n\t\t{\n\t\t\tvar type = parameters[i].ParameterType;\n\t\t\targs[i] = type.IsInstanceOfType( context ) ? context : type.IsValueType ? Activator.CreateInstance( type ) : null;\n\t\t}\n\n\t\treturn open.Invoke( null, args );\n\t}\n\n\t// ---------------------------------------------------------------- the thumbnail\n\n\t/// \u003Csummary\u003EWhere the captured thumbnail is written: the project\u0027s .sbox folder, which is never published or committed.\u003C/summary\u003E\n\tconst string ThumbnailFile = \u0022golfkit_thumbnail.png\u0022;\n\tconst int ThumbnailSize = 512;\n\n\t/// \u003Csummary\u003E\n\t/// Renders the course from the Golf Menu Camera (or the first camera in the scene) to a square\n\t/// PNG for the Publisher\u0027s thumbnail. Needs the course scene to be the open scene. Null when\n\t/// nothing could be rendered; the reminder dialog then stands in.\n\t/// \u003C/summary\u003E\n\tstatic string CaptureThumbnail( Project project, string scenePath )\n\t{\n\t\ttry\n\t\t{\n\t\t\tvar scene = SceneEditorSession.Active?.Scene;\n\t\t\tvar openPath = (scene?.Source?.ResourcePath ?? \u0022\u0022).Replace( \u0027\\\\\u0027, \u0027/\u0027 ).TrimStart( \u0027/\u0027 );\n\t\t\tif ( scene is null || !string.Equals( openPath, scenePath, StringComparison.OrdinalIgnoreCase ) )\n\t\t\t{\n\t\t\t\tLog.Info( $\u0022Golf Kit: no thumbnail captured, the open scene is {Show( openPath )} and the course scene is {scenePath}\u0022 );\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tusing var sceneScope = scene.Push();\n\n\t\t\tTransform view;\n\t\t\tvar fov = 70f;\n\t\t\tvar menu = scene.GetAllComponents\u003CGolfMenuCamera\u003E().FirstOrDefault( m =\u003E m.IsValid() );\n\t\t\tif ( menu is not null \u0026\u0026 menu.HasValidView )\n\t\t\t{\n\t\t\t\tview = menu.ViewAt( 0f );\n\t\t\t\tfov = menu.FieldOfView;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tvar camera = scene.GetAllComponents\u003CCameraComponent\u003E().FirstOrDefault( c =\u003E c.IsValid() );\n\t\t\t\tif ( camera is null ) { Log.Info( \u0022Golf Kit: no thumbnail captured, the scene has no Golf Menu Camera and no camera\u0022 ); return null; }\n\t\t\t\tview = camera.WorldTransform;\n\t\t\t\tfov = camera.FieldOfView;\n\t\t\t}\n\n\t\t\tvar target = Texture.CreateRenderTarget( \u0022golfkit-thumbnail\u0022, ImageFormat.RGBA8888, new Vector2( ThumbnailSize, ThumbnailSize ) );\n\t\t\tvar sceneCamera = new SceneCamera\n\t\t\t{\n\t\t\t\tWorld = scene.SceneWorld,\n\t\t\t\tPosition = view.Position,\n\t\t\t\tRotation = view.Rotation,\n\t\t\t\tFieldOfView = fov,\n\t\t\t\tZNear = 5f,\n\t\t\t\tZFar = 60000f,\n\t\t\t\tSize = new Vector2( ThumbnailSize, ThumbnailSize ),\n\t\t\t\tBackgroundColor = Color.Black,\n\t\t\t};\n\t\t\tGraphics.RenderToTexture( sceneCamera, target );\n\t\t\tvar bitmap = target.GetBitmap( 0 );\n\t\t\tif ( bitmap is null ) { Log.Info( \u0022Golf Kit: no thumbnail captured, the render could not be read back\u0022 ); return null; }\n\t\t\tvar png = bitmap.ToPng();\n\t\t\tif ( png is null || png.Length \u003C 1024 ) { Log.Info( \u0022Golf Kit: no thumbnail captured, the render came back empty\u0022 ); return null; }\n\n\t\t\tvar folder = Path.Combine( project.RootDirectory.FullName, \u0022.sbox\u0022 );\n\t\t\tDirectory.CreateDirectory( folder );\n\t\t\tvar path = Path.Combine( folder, ThumbnailFile );\n\t\t\tFile.WriteAllBytes( path, png );\n\t\t\tLog.Info( $\u0022Golf Kit: thumbnail captured from {( menu is not null ? \u0022the Golf Menu Camera\u0022 : \u0022the first camera\u0022 )} ({ThumbnailSize}x{ThumbnailSize}) to {path}\u0022 );\n\t\t\treturn path;\n\t\t}\n\t\tcatch ( Exception e )\n\t\t{\n\t\t\tLog.Info( $\u0022Golf Kit: no thumbnail captured ({e.Message}); pick one on the Publisher\u0027s first page\u0022 );\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t// The wizard that still needs the captured thumbnail: it makes its Workshop choices when its\n\t// first page shows, so the thumbnail is handed over from the frame event once they exist.\n\tstatic (object Wizard, string Path, float Since)? _pendingThumbnail;\n\n\t/// \u003Csummary\u003ESets the captured file as the wizard\u0027s picked thumbnail (what its upload sends to the Workshop). True once done or given up.\u003C/summary\u003E\n\tstatic bool HandOverThumbnail()\n\t{\n\t\tif ( _pendingThumbnail is not { } pending ) return true;\n\t\ttry\n\t\t{\n\t\t\tvar wizard = pending.Wizard;\n\t\t\tif ( wizard is Widget w \u0026\u0026 !w.IsValid() ) { _pendingThumbnail = null; return true; }\n\t\t\tvar flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic;\n\t\t\tvar config = wizard.GetType().GetField( \u0022Config\u0022, flags )?.GetValue( wizard );\n\t\t\tvar workshop = config?.GetType().GetProperty( \u0022Workshop\u0022, flags )?.GetValue( config );\n\t\t\tif ( workshop is null )\n\t\t\t{\n\t\t\t\tif ( RealTime.Now - pending.Since \u003E 20f ) { Log.Info( \u0022Golf Kit: the Publisher made no Workshop choices (not a Workshop upload?); pick the thumbnail by hand if it asks for one\u0022 ); _pendingThumbnail = null; return true; }\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tvar picked = workshop.GetType().GetProperty( \u0022PickedThumbnail\u0022, flags );\n\t\t\tif ( picked is null || !picked.CanWrite ) { Log.Info( \u0022Golf Kit: this editor\u0027s Publisher takes no picked thumbnail from here; pick one on its first page\u0022 ); _pendingThumbnail = null; return true; }\n\t\t\tpicked.SetValue( workshop, pending.Path );\n\t\t\tvar preview = workshop.GetType().GetProperty( \u0022Preview\u0022, flags );\n\t\t\tif ( preview is not null \u0026\u0026 preview.CanWrite )\n\t\t\t{\n\t\t\t\ttry { preview.SetValue( workshop, Pixmap.FromFile( pending.Path ) ); } catch { }\n\t\t\t}\n\t\t\t_pendingThumbnail = null;\n\t\t\tLog.Info( \u0022Golf Kit: the captured thumbnail is set on the Publisher; replace it on the first page if you want another\u0022 );\n\t\t\treturn true;\n\t\t}\n\t\tcatch ( Exception e )\n\t\t{\n\t\t\tLog.Info( $\u0022Golf Kit: the thumbnail could not be handed to the Publisher ({e.Message}); pick one on its first page\u0022 );\n\t\t\t_pendingThumbnail = null;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t// ---------------------------------------------------------------- the project\u0027s own Publish..\n\n\t// The wizards this class opened (for the temporary projects), so a Publisher for the mapper\u0027s\n\t// own project can be told apart from them.\n\tstatic readonly HashSet\u003Cobject\u003E _ownWizards = new();\n\tstatic readonly HashSet\u003Cobject\u003E _seenWizards = new();\n\tstatic TimeSince _sinceWatch;\n\n\t/// \u003Csummary\u003E\n\t/// Every frame: hands a pending thumbnail over, and watches for the editor\u0027s Publisher opened on\n\t/// the course project itself (the project name\u0027s Publish..). That upload would be a plain addon\n\t/// the game cannot find, so the window is closed and Publish course takes over. The window is\n\t/// found through the editor\u0027s focus, the only handle the editor gives.\n\t/// \u003C/summary\u003E\n\t[EditorEvent.Frame]\n\tstatic void OnFrame()\n\t{\n\t\tHandOverThumbnail();\n\n\t\tif ( _sinceWatch \u003C 0.25f ) return;\n\t\t_sinceWatch = 0;\n\t\ttry\n\t\t{\n\t\t\tfor ( var w = Editor.Application.FocusWidget; w is not null \u0026\u0026 w.IsValid(); w = w.Parent )\n\t\t\t{\n\t\t\t\tif ( w.GetType().Name != \u0022PublishWizard\u0022 ) continue;\n\t\t\t\tif ( _ownWizards.Contains( w ) || _seenWizards.Contains( w ) ) return;\n\t\t\t\t_seenWizards.Add( w );\n\t\t\t\tvar wizardProject = w.GetType().GetField( \u0022Project\u0022 )?.GetValue( w ) as Project;\n\t\t\t\tif ( wizardProject is null || wizardProject != Project.Current ) return;\n\t\t\t\tif ( !IsCourseProject( wizardProject, out _, out var ident ) || CourseScenes( wizardProject ).Count == 0 ) return;\n\n\t\t\t\tw.Destroy();\n\t\t\t\tLog.Warning( $\u0022Golf Kit: the project\u0027s own Publish.. would upload {ident} as a plain addon the game\u0027s course list cannot find; Publish course opens instead\u0022 );\n\t\t\t\tPublishCourse();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tcatch ( Exception e )\n\t\t{\n\t\t\tLog.Info( $\u0022Golf Kit: the Publisher watch failed ({e.Message})\u0022 );\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003EThe active project when it is a mapper\u0027s course project: not built in, not the game or the kit, not a game or library project.\u003C/summary\u003E\n\tstatic bool IsCourseProject( Project project, out Sandbox.DataModel.ProjectConfig config, out string ident )\n\t{\n\t\tconfig = project?.Config;\n\t\tident = config?.FullIdent ?? \u0022\u0022;\n\t\tif ( project is null || config is null || project.IsBuiltIn ) return false;\n\n\t\tif ( string.Equals( ident, GameIdent, StringComparison.OrdinalIgnoreCase ) || string.Equals( ident, KitIdent, StringComparison.OrdinalIgnoreCase ) )\n\t\t\treturn false;\n\t\tif ( string.Equals( config.Type, \u0022game\u0022, StringComparison.OrdinalIgnoreCase ) || string.Equals( config.Type, \u0022library\u0022, StringComparison.OrdinalIgnoreCase ) )\n\t\t{\n\t\t\tif ( _skipped.Add( ident ) ) Log.Info( $\u0022Golf Kit: {ident} is a {config.Type} project, its metadata is left alone\u0022 );\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tstatic string Show( string value ) =\u003E string.IsNullOrEmpty( value ) ? \u0022(none)\u0022 : value;\n\n\t/// \u003Csummary\u003E\n\t/// The editor\u0027s own project save (Project.Save, not public), which writes the live config to the\n\t/// .sbproj; then its package record is brought up to date so the local course list sees the\n\t/// primary scene without a restart. If the save method is ever gone, the config\u0027s own JSON is\n\t/// written to the project\u0027s config path, which is what the editor itself writes.\n\t/// \u003C/summary\u003E\n\tstatic void Save( Project project )\n\t{\n\t\tvar flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic;\n\t\tvar save = typeof( Project ).GetMethod( \u0022Save\u0022, flags, Type.EmptyTypes );\n\t\tif ( save is not null )\n\t\t{\n\t\t\tsave.Invoke( project, null );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tLog.Warning( \u0022Golf Kit: Project.Save not found in this editor build; writing the config JSON to the project file instead\u0022 );\n\t\t\tFile.WriteAllText( project.ConfigFilePath, project.Config.ToJson() );\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\tvar sync = typeof( Project ).GetMethod( \u0022SyncWithPackageManager\u0022, flags );\n\t\t\tif ( sync is not null ) sync.Invoke( sync.IsStatic ? null : project, sync.GetParameters().Length == 0 ? null : new object[] { project } );\n\t\t\tvar mock = typeof( Project ).GetMethod( \u0022UpdateMockPackage\u0022, flags );\n\t\t\tif ( mock is not null \u0026\u0026 mock.GetParameters().Length == 0 ) mock.Invoke( mock.IsStatic ? null : project, null );\n\t\t}\n\t\tcatch ( Exception e )\n\t\t{\n\t\t\tLog.Info( $\u0022Golf Kit: the package record of {project.Config?.FullIdent} could not be refreshed ({e.GetBaseException().Message}); it is read again when the editor opens\u0022 );\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003EWhat the editor holds and what is on disk, after the save, against the editing state; a mismatch is a warning.\u003C/summary\u003E\n\tstatic void Verify( Project project, string scene )\n\t{\n\t\tvar config = project.Config;\n\t\tvar liveOk = string.Equals( config.Type, EditType, StringComparison.OrdinalIgnoreCase )\n\t\t\t\u0026\u0026 string.IsNullOrEmpty( config.GetMetaOrDefault\u003Cstring\u003E( \u0022ParentPackage\u0022, null ) )\n\t\t\t\u0026\u0026 string.Equals( config.GetMetaOrDefault\u003Cstring\u003E( \u0022PrimaryAsset\u0022, null ), scene, StringComparison.OrdinalIgnoreCase );\n\n\t\tvar fileOk = false;\n\t\tvar fileType = \u0022(unreadable)\u0022;\n\t\ttry\n\t\t{\n\t\t\tvar json = File.ReadAllText( project.ConfigFilePath );\n\t\t\tusing var doc = System.Text.Json.JsonDocument.Parse( json );\n\t\t\tvar root = doc.RootElement;\n\t\t\tfileType = root.TryGetProperty( \u0022Type\u0022, out var t ) ? t.GetString() : \u0022(none)\u0022;\n\t\t\tstring fileParent = null, filePrimary = null;\n\t\t\tif ( root.TryGetProperty( \u0022Metadata\u0022, out var meta ) \u0026\u0026 meta.ValueKind == System.Text.Json.JsonValueKind.Object )\n\t\t\t{\n\t\t\t\tfileParent = meta.TryGetProperty( \u0022ParentPackage\u0022, out var p ) \u0026\u0026 p.ValueKind == System.Text.Json.JsonValueKind.String ? p.GetString() : null;\n\t\t\t\tfilePrimary = meta.TryGetProperty( \u0022PrimaryAsset\u0022, out var a ) \u0026\u0026 a.ValueKind == System.Text.Json.JsonValueKind.String ? a.GetString() : null;\n\t\t\t}\n\t\t\tfileOk = string.Equals( fileType, EditType, StringComparison.OrdinalIgnoreCase ) \u0026\u0026 string.IsNullOrEmpty( fileParent ) \u0026\u0026 string.Equals( filePrimary, scene, StringComparison.OrdinalIgnoreCase );\n\t\t}\n\t\tcatch ( Exception e )\n\t\t{\n\t\t\tfileType = $\u0022(unreadable: {e.Message})\u0022;\n\t\t}\n\n\t\tif ( liveOk \u0026\u0026 fileOk )\n\t\t\tLog.Info( $\u0022Golf Kit: {config.FullIdent} ready for editing: an {fileType} project, no parent game, primary scene {scene} ({Path.GetFileName( project.ConfigFilePath )} read back OK)\u0022 );\n\t\telse\n\t\t\tLog.Warning( $\u0022Golf Kit: {config.FullIdent} metadata did not stick (live config {( liveOk ? \u0022OK\u0022 : \u0022wrong\u0022 )}, {Path.GetFileName( project.ConfigFilePath )} {( fileOk ? \u0022OK\u0022 : \u0022wrong\u0022 )}, file Type {fileType}). Expected Type {EditType}, no ParentPackage, PrimaryAsset {scene}; set them in the project settings by hand.\u0022 );\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Every scene under the project\u0027s Assets folder that holds a course: a Golf Course Info or Hole\n\t/// component, or an object named \u0022Hole N\u0022. Paths are relative to Assets with forward slashes.\n\t/// Dot folders (parked sources) are skipped.\n\t/// \u003C/summary\u003E\n\tpublic static System.Collections.Generic.List\u003Cstring\u003E CourseScenes( Project project )\n\t{\n\t\tvar result = new System.Collections.Generic.List\u003Cstring\u003E();\n\t\tif ( !project.HasAssetsPath() ) return result;\n\t\tvar assets = project.GetAssetsPath();\n\t\tif ( string.IsNullOrEmpty( assets ) || !Directory.Exists( assets ) ) return result;\n\n\t\tvar golf = new Regex( \u0022\\\u0022__type\\\u0022:\\\\s*\\\u0022(GolfCourseInfo|Hole)\\\u0022|\\\u0022Name\\\u0022:\\\\s*\\\u0022Hole\\\\s\u002B\\\\d\u002B\u0022, RegexOptions.Compiled );\n\t\tforeach ( var file in Directory.EnumerateFiles( assets, \u0022*.scene\u0022, SearchOption.AllDirectories ) )\n\t\t{\n\t\t\tvar relative = Path.GetRelativePath( assets, file ).Replace( \u0027\\\\\u0027, \u0027/\u0027 );\n\t\t\tif ( relative.Split( \u0027/\u0027 ).Any( part =\u003E part.StartsWith( \u0027.\u0027 ) ) ) continue;\n\t\t\tstring text;\n\t\t\ttry { text = File.ReadAllText( file ); }\n\t\t\tcatch { continue; }\n\t\t\tif ( golf.IsMatch( text ) ) result.Add( relative );\n\t\t}\n\t\tresult.Sort( StringComparer.OrdinalIgnoreCase );\n\t\treturn result;\n\t}\n\n\t/// \u003Csummary\u003EThe open scene when it is one of the course scenes, else the first; the choice is logged when there is one to make.\u003C/summary\u003E\n\tstatic string Choose( System.Collections.Generic.List\u003Cstring\u003E scenes, string openScene, string ident )\n\t{\n\t\tif ( scenes.Count == 1 ) return scenes[0];\n\t\tvar open = (openScene ?? \u0022\u0022).Replace( \u0027\\\\\u0027, \u0027/\u0027 ).TrimStart( \u0027/\u0027 );\n\t\tvar match = scenes.FirstOrDefault( s =\u003E string.Equals( s, open, StringComparison.OrdinalIgnoreCase ) );\n\t\tvar chosen = match ?? scenes[0];\n\t\tLog.Info( $\u0022Golf Kit: {ident} has {scenes.Count} course scenes ({string.Join( \u0022, \u0022, scenes )}); {( match is null ? \u0022the first is\u0022 : \u0022the open one is\u0022 )} the primary scene: {chosen}\u0022 );\n\t\treturn chosen;\n\t}\n}\n"},{"Ident":"mrtn.golfkit","Path":"Code/GolfCourseInfo.cs","FileName":"GolfCourseInfo.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":440545,"IsPrivate":false,"Code":"using Sandbox;\r\nusing System.Linq;\r\n\r\n/// \u003Csummary\u003E\r\n/// What a course scene says about itself, on one object at the scene root. The game reads it:\r\n/// the name, the ambience loop played while the scene is loaded, how far the sun\u0027s shadows reach\r\n/// (0 leaves the engine\u0027s own distance), and which wall set Add bounds builds around the holes.\r\n/// \u003C/summary\u003E\r\n[Title( \u0022Golf Course Info\u0022 ), Category( \u0022Golf\u0022 ), Icon( \u0022flag\u0022 )]\r\npublic sealed class GolfCourseInfo : Component\r\n{\r\n\t/// \u003Csummary\u003E\r\n\t/// The wall set the Add bounds button on Golf Hole Collision builds around a hole\u0027s tile boundary:\r\n\t/// the Blender kit rail (wall_100 and post_10), the Minigolf hedge set, or the trench wall set. The\r\n\t/// Course Wall Builder\u0027s low rails are not affected; that tool has its own style dropdown.\r\n\t/// \u003C/summary\u003E\r\n\tpublic enum KitWallStyle\r\n\t{\r\n\t\tKit,\r\n\t\tMinigolf,\r\n\t\tTrench,\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EThe course\u0027s name, as shown to the players.\u003C/summary\u003E\r\n\t[Property, Title( \u0022Course Name\u0022 )]\r\n\tpublic string CourseName { get; set; } = \u0022\u0022;\r\n\r\n\t/// \u003Csummary\u003EA 2D loop every machine plays while this scene is loaded. None for a silent course.\u003C/summary\u003E\r\n\t[Property]\r\n\tpublic SoundEvent Ambience { get; set; }\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// How far from the camera the sun\u0027s shadow cascades reach, in units, while this course is\r\n\t/// loaded. A small course gets crisp shadows from a short distance; 0 keeps the engine default.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, Title( \u0022Shadow Distance\u0022 ), Range( 0f, 20000f )]\r\n\tpublic float ShadowDistance { get; set; } = 0f;\r\n\r\n\t/// \u003Csummary\u003EWhich wall set Add bounds builds around this course\u0027s holes.\u003C/summary\u003E\r\n\t[Property, Title( \u0022Wall Style\u0022 )]\r\n\tpublic KitWallStyle WallStyle { get; set; } = KitWallStyle.Kit;\r\n\r\n\t/// \u003Csummary\u003EThe course info in a scene, or null when it has none.\u003C/summary\u003E\r\n\tpublic static GolfCourseInfo Find( Scene scene )\r\n\t{\r\n\t\treturn scene?.GetAllComponents\u003CGolfCourseInfo\u003E().FirstOrDefault();\r\n\t}\r\n}\r\n"},{"Ident":"mrtn.golfkit","Path":"Editor/CourseWallBuilderTool.Edit.cs","FileName":"CourseWallBuilderTool.Edit.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":440545,"IsPrivate":false,"Code":"using Sandbox;\r\nusing Editor;\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\n\r\n/// \u003Csummary\u003E\r\n/// Editing the walls that stand: the tool\u0027s own selection, the move gizmo and its drag (with the\r\n/// merge when a post is released on another), Delete, the style swap and the rail flip. Each is one\r\n/// graph operation applied as one undo step.\r\n/// \u003C/summary\u003E\r\npublic sealed partial class CourseWallBuilderTool\r\n{\r\n\t/// \u003Csummary\u003EThe gizmo stays on the post it was last shown on while the cursor is within this (units, ground plane) of the post\u0027s foot, so its arrows can be reached.\u003C/summary\u003E\r\n\tconst float GizmoStickDistance = 120f;\r\n\r\n\t/// \u003Csummary\u003EThe tool\u0027s own selection of posts and rail pieces (not the editor\u0027s).\u003C/summary\u003E\r\n\treadonly List\u003CGameObject\u003E _selection = new();\r\n\r\n\t/// \u003Csummary\u003EThe piece under the cursor this frame, or null.\u003C/summary\u003E\r\n\tGameObject _hovered;\r\n\r\n\t/// \u003Csummary\u003EThe post the move gizmo was last shown on.\u003C/summary\u003E\r\n\tGameObject _gizmoPost;\r\n\r\n\t/// \u003Csummary\u003EA post being dragged by the gizmo: its object and group, where it started, where it is, and whether the Z arrow has been used.\u003C/summary\u003E\r\n\tsealed class DragState\r\n\t{\r\n\t\tpublic GameObject Object;\r\n\t\tpublic GameObject Group;\r\n\t\tpublic Transform Original;\r\n\t\tpublic Vector3 From;\r\n\t\tpublic Vector3 Point;\r\n\t\tpublic Vector3 Delta;\r\n\t\tpublic bool ZUsed;\r\n\t\tpublic bool Sloped;\r\n\t}\r\n\tDragState _drag;\r\n\r\n\t// ---------------------------------------------------------------- selection\r\n\r\n\t/// \u003Csummary\u003ESelect a piece: a rail piece brings its whole rail. Shift adds, or removes an already selected piece.\u003C/summary\u003E\r\n\tvoid Select( WallGraph graph, GameObject piece, bool add )\r\n\t{\r\n\t\tvar pieces = new List\u003CGameObject\u003E { piece };\r\n\t\tif ( IsRailPiece( piece ) )\r\n\t\t{\r\n\t\t\tvar g = graph.Group == GroupOf( piece ) ? graph : ReadGraph( GroupOf( piece ) );\r\n\t\t\tif ( g.RailOf( piece ) is { } rail ) pieces = rail.Pieces.ToList();\r\n\t\t}\r\n\t\tif ( !add ) _selection.Clear();\r\n\t\telse if ( pieces.All( _selection.Contains ) )\r\n\t\t{\r\n\t\t\tforeach ( var p in pieces ) _selection.Remove( p );\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tforeach ( var p in pieces ) if ( !_selection.Contains( p ) ) _selection.Add( p );\r\n\t}\r\n\r\n\tvoid DrawSelection()\r\n\t{\r\n\t\t_selection.RemoveAll( go =\u003E !go.IsValid() );\r\n\t\tforeach ( var go in _selection ) DrawPieceOutline( go, true );\r\n\t}\r\n\r\n\t// ---------------------------------------------------------------- the move gizmo\r\n\r\n\t/// \u003Csummary\u003EThe post the move gizmo stands on this frame: the one being dragged, else the selected one, else the hovered one, else the last one while the cursor stays near it; null for none.\u003C/summary\u003E\r\n\tGameObject GizmoPost( GameObject hovered, SceneTraceResult trace )\r\n\t{\r\n\t\tvar post = _drag?.Object;\r\n\t\tif ( !post.IsValid() ) post = _selection.FirstOrDefault( IsPost );\r\n\t\tif ( !post.IsValid() \u0026\u0026 IsPost( hovered ) ) post = hovered;\r\n\t\tif ( !post.IsValid() \u0026\u0026 _gizmoPost.IsValid() \u0026\u0026 (!trace.Hit || trace.HitPosition.WithZ( 0f ).Distance( PostPoint( _gizmoPost ).WithZ( 0f ) ) \u003C= GizmoStickDistance) ) post = _gizmoPost;\r\n\t\t_gizmoPost = post.IsValid() ? post : null;\r\n\t\treturn _gizmoPost;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The editor\u0027s arrow gizmo on a post: X and Y arrows always, a Z arrow when the floor under the\r\n\t/// post is a ramp. Dragging an arrow moves the post by the arrow\u0027s travel each frame, the new foot\r\n\t/// going through the snap pass (Ctrl for none) and, unless the Z arrow was used, onto the floor\r\n\t/// under its new X and Y (its original height where no tile is). The post itself follows live;\r\n\t/// its rails, and whatever the move would split or merge, show as ghosts from a preview of the\r\n\t/// move. Releasing the arrow commits the move as one undo step. Returns true while an arrow is\r\n\t/// hovered or dragged, so the rest of the frame leaves the mouse alone.\r\n\t/// \u003C/summary\u003E\r\n\tbool UpdateMoveGizmo( WallGraph graph, GameObject parent, GameObject post )\r\n\t{\r\n\t\tvar foot = _drag?.Point ?? PostPoint( post );\r\n\t\tvar sloped = _drag?.Sloped ?? FloorIsSloped( graph.Group, foot );\r\n\t\tvar delta = Vector3.Zero;\r\n\t\tvar moved = false;\r\n\t\tvar zMoved = false;\r\n\t\tbool hovered;\r\n\r\n\t\t// The arrows sit on top of the post and start outside its log: at the foot they would lie in the floor plane and inside the model, drawn but never seen.\r\n\t\tvar renderer = post.GetComponent\u003CModelRenderer\u003E( true );\r\n\t\tvar top = renderer is null ? foot \u002B Vector3.Up * KitShape.WallHeight : foot.WithZ( renderer.Bounds.Maxs.z \u002B 2f );\r\n\t\tvar reach = NuWallCornerRadius \u002B 2f;\r\n\t\tusing ( Gizmo.Scope( \u0022coursewall-move\u0022, new Transform( top ) ) )\r\n\t\t{\r\n\t\t\tGizmo.Hitbox.DepthBias = 0.01f;\r\n\t\t\tGizmo.Draw.Color = Gizmo.Colors.Red;\r\n\t\t\tif ( Gizmo.Control.Arrow( \u0022move-x\u0022, Vector3.Forward, out var dx, length: 36f, axisOffset: reach, cullAngle: 0f ) ) { delta \u002B= Vector3.Forward * dx; moved = true; }\r\n\t\t\tGizmo.Draw.Color = Gizmo.Colors.Green;\r\n\t\t\tif ( Gizmo.Control.Arrow( \u0022move-y\u0022, Vector3.Left, out var dy, length: 36f, axisOffset: reach, cullAngle: 0f ) ) { delta \u002B= Vector3.Left * dy; moved = true; }\r\n\t\t\tif ( sloped )\r\n\t\t\t{\r\n\t\t\t\tGizmo.Draw.Color = Gizmo.Colors.Blue;\r\n\t\t\t\tif ( Gizmo.Control.Arrow( \u0022move-z\u0022, Vector3.Up, out var dz, length: 36f, axisOffset: 2f, cullAngle: 0f ) ) { delta \u002B= Vector3.Up * dz; moved = true; zMoved = MathF.Abs( dz ) \u003E 0.001f; }\r\n\t\t\t}\r\n\t\t\thovered = Gizmo.HasHovered || Gizmo.Pressed.Any;\r\n\t\t}\r\n\r\n\t\tif ( _drag is null )\r\n\t\t{\r\n\t\t\tif ( !moved ) return hovered;\r\n\t\t\tBeginDrag( post );\r\n\t\t\t_drag.Sloped = sloped;\r\n\t\t\t// The graph of this frame was read before the drag began: read it again with the post at its start.\r\n\t\t\tgraph = ReadGraph( graph.Group, (post, _drag.From) );\r\n\t\t}\r\n\t\tvar drag = _drag;\r\n\t\tvar moving = graph.PostOf( drag.Object );\r\n\t\tif ( !drag.Object.IsValid() || moving is null ) { _drag = null; return false; }\r\n\r\n\t\tdrag.Delta \u002B= delta;\r\n\t\tif ( zMoved ) drag.ZUsed = true;\r\n\t\tvar target = drag.From \u002B drag.Delta;\r\n\t\tif ( !Gizmo.IsCtrlPressed ) target = Resolve( graph, parent, target, Gizmo.IsShiftPressed, false, moving ).Point.WithZ( target.z );\r\n\t\tif ( !drag.ZUsed ) target = target.WithZ( FloorUnder( FloorScope( graph.Group ), target, drag.From.z ) is { } floor ? floor.point.z : drag.From.z );\r\n\t\tdrag.Point = target;\r\n\r\n\t\t// The post follows live; everything else the move does is a ghost from a preview of it.\r\n\t\tvar preview = graph.Clone();\r\n\t\tvar previewPost = preview.PostOf( drag.Object );\r\n\t\tpreview.MovePost( previewPost, target );\r\n\t\tvar standing = preview.Posts.Contains( previewPost ) ? previewPost : preview.PostAt( target );\r\n\t\tdrag.Object.WorldTransform = PostTransform( drag.Object, target, standing is null ? Enumerable.Empty\u003C(Vector3 away, Vector3? inside)\u003E() : preview.RailInfo( standing ) );\r\n\t\tDrawPieceOutline( drag.Object, true );\r\n\t\tDrawGhosts( preview );\r\n\r\n\t\tif ( Gizmo.Pressed.Any ) return true;\r\n\t\tCommitDrag( graph );\r\n\t\treturn true;\r\n\t}\r\n\r\n\tvoid BeginDrag( GameObject post )\r\n\t{\r\n\t\tvar from = PostPoint( post );\r\n\t\t_drag = new DragState { Object = post, Group = GroupOf( post ), Original = post.WorldTransform, From = from, Point = from };\r\n\t\tif ( !_selection.Contains( post ) ) { _selection.Clear(); _selection.Add( post ); }\r\n\t\tif ( DebugLog ) Log.Info( $\u0022Course Wall Builder: drag start on the post at {from}\u0022 );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The release: the move as one undo step. The post goes back to where it started first, so the\r\n\t/// step records the whole move; then the graph moves it, which rebuilds its rails to the new\r\n\t/// point, splits what they now cross, and merges the post into one it was released on (its rails\r\n\t/// re-attach to the survivor, doubled rails go, the survivor\u0027s corner turns to them). The open\r\n\t/// run\u0027s points follow the post.\r\n\t/// \u003C/summary\u003E\r\n\tvoid CommitDrag( WallGraph graph )\r\n\t{\r\n\t\tvar drag = _drag;\r\n\t\t_drag = null;\r\n\t\tif ( !drag.Object.IsValid() ) return;\r\n\t\tdrag.Object.WorldTransform = drag.Original;\r\n\t\tif ( drag.Point.Distance( drag.From ) \u003C 0.5f ) return;\r\n\t\tvar post = graph.PostOf( drag.Object );\r\n\t\tif ( post is null ) return;\r\n\r\n\t\tgraph.MovePost( post, drag.Point );\r\n\t\tvar landed = graph.PostAt( drag.Point )?.Point ?? drag.Point;\r\n\t\tif ( _run is not null ) for ( var i = 0; i \u003C _run.Points.Count; i\u002B\u002B ) if ( _run.Points[i].Distance( drag.From ) \u003C= JoinDistance ) _run.Points[i] = landed;\r\n\t\tApply( graph, \u0022Move post\u0022 );\r\n\t\t_selection.RemoveAll( go =\u003E !go.IsValid() );\r\n\t\tLog.Info( $\u0022Course Wall Builder: post moved {drag.From} -\u003E {landed}{(drag.ZUsed ? \u0022 (Z arrow used)\u0022 : \u0022\u0022)}{(graph.Posts.Contains( post ) ? \u0022\u0022 : \u0022 and merged into the post there\u0022)}\u0022 );\r\n\t}\r\n\r\n\t// ---------------------------------------------------------------- delete, restyle and flip\r\n\r\n\t/// \u003Csummary\u003EDelete: the piece under the cursor when there is one (its whole rail, or the post with its rails), else the selection.\u003C/summary\u003E\r\n\tvoid DeleteHoveredOrSelection( WallGraph graph )\r\n\t{\r\n\t\tif ( _hovered.IsValid() ) Select( graph, _hovered, false );\r\n\t\tDeleteSelection( graph );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The selected rails go, a selected post goes with every rail ending at it, and a post left\r\n\t/// without any rail by this goes too. One undo step per group the selection spans (one, in\r\n\t/// practice).\r\n\t/// \u003C/summary\u003E\r\n\tvoid DeleteSelection( WallGraph graph )\r\n\t{\r\n\t\t_selection.RemoveAll( go =\u003E !go.IsValid() );\r\n\t\tif ( _selection.Count == 0 ) return;\r\n\t\tvar removed = 0;\r\n\t\tforeach ( var group in _selection.Select( GroupOf ).Distinct().ToList() )\r\n\t\t{\r\n\t\t\tvar g = group == graph.Group ? graph : ReadGraph( group );\r\n\t\t\tvar ends = new HashSet\u003CWallPost\u003E();\r\n\t\t\tforeach ( var piece in _selection.Where( s =\u003E GroupOf( s ) == group ) )\r\n\t\t\t{\r\n\t\t\t\tif ( IsPost( piece ) )\r\n\t\t\t\t{\r\n\t\t\t\t\tif ( g.PostOf( piece ) is not { } post ) continue;\r\n\t\t\t\t\tends.UnionWith( g.RailsAt( post ).Select( r =\u003E r.Other( post ) ) );\r\n\t\t\t\t\tg.RemovePost( post );\r\n\t\t\t\t\tremoved\u002B\u002B;\r\n\t\t\t\t}\r\n\t\t\t\telse if ( g.RailOf( piece ) is { } rail )\r\n\t\t\t\t{\r\n\t\t\t\t\tends.Add( rail.A );\r\n\t\t\t\t\tends.Add( rail.B );\r\n\t\t\t\t\tg.RemoveRail( rail );\r\n\t\t\t\t\tremoved\u002B\u002B;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tforeach ( var end in ends ) if ( g.Posts.Contains( end ) \u0026\u0026 !g.RailsAt( end ).Any() ) g.RemovePost( end );\r\n\t\t\tApply( g, \u0022Delete course walls\u0022 );\r\n\t\t}\r\n\t\t_selection.Clear();\r\n\t\tLog.Info( $\u0022Course Wall Builder: deleted {removed} piece(s) with what depended on them\u0022 );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EStyle changed with rails selected: each selected rail of another style is rebuilt in place in the new style between the same posts, keeping its inside (a rail without one takes the camera\u0027s side; a Holekit rail has none). One undo step.\u003C/summary\u003E\r\n\tvoid SwapSelectedStyle( WallGraph graph )\r\n\t{\r\n\t\t_selection.RemoveAll( go =\u003E !go.IsValid() );\r\n\t\tvar railPieces = _selection.Where( IsRailPiece ).ToList();\r\n\t\tif ( railPieces.Count == 0 ) return;\r\n\t\tvar swapped = 0;\r\n\t\tvar replaced = new List\u003CGameObject\u003E();\r\n\t\tforeach ( var group in railPieces.Select( GroupOf ).Distinct().ToList() )\r\n\t\t{\r\n\t\t\tvar g = group == graph.Group ? graph : ReadGraph( group );\r\n\t\t\tvar targets = g.Rails.Where( r =\u003E r.Style != Style \u0026\u0026 r.Pieces.Any( railPieces.Contains ) ).ToList();\r\n\t\t\tif ( targets.Count == 0 ) continue;\r\n\t\t\tvar camera = ViewPosition();\r\n\t\t\tforeach ( var rail in targets )\r\n\t\t\t\tg.Restyle( rail, Style, Style == WallStyle.NuWall ? rail.Inside ?? InsideFor( rail.A.Point, rail.B.Point, CameraHand( rail.A.Point, rail.B.Point, camera ) ) : null );\r\n\t\t\tApply( g, \u0022Swap wall style\u0022 );\r\n\t\t\treplaced.AddRange( targets.SelectMany( r =\u003E r.Pieces ) );\r\n\t\t\tswapped \u002B= targets.Count;\r\n\t\t}\r\n\t\tif ( swapped == 0 ) return;\r\n\t\t_selection.RemoveAll( go =\u003E !go.IsValid() );\r\n\t\tforeach ( var go in replaced ) if ( go.IsValid() \u0026\u0026 !_selection.Contains( go ) ) _selection.Add( go );\r\n\t\tLog.Info( $\u0022Course Wall Builder: {swapped} rail(s) rebuilt as {Style}\u0022 );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// F with rails selected and no run open: each selected NuWall rail is rebuilt with its inside on\r\n\t/// the other side (its slope swaps sides) between the same posts, and the corners at both ends are\r\n\t/// turned to the rails as they now stand; the hole\u0027s collision is rebuilt. A Holekit rail has no\r\n\t/// inside and is left alone. One undo step per group the selection spans. The selection keeps the\r\n\t/// rails through their new pieces.\r\n\t/// \u003C/summary\u003E\r\n\tvoid FlipSelectedRails( WallGraph graph )\r\n\t{\r\n\t\t_selection.RemoveAll( go =\u003E !go.IsValid() );\r\n\t\tvar railPieces = _selection.Where( IsRailPiece ).ToList();\r\n\t\tif ( railPieces.Count == 0 ) return;\r\n\t\tvar flipped = 0;\r\n\t\tvar replaced = new List\u003CGameObject\u003E();\r\n\t\tforeach ( var group in railPieces.Select( GroupOf ).Distinct().ToList() )\r\n\t\t{\r\n\t\t\tvar g = group == graph.Group ? graph : ReadGraph( group );\r\n\t\t\tvar targets = g.Rails.Where( r =\u003E r.Style == WallStyle.NuWall \u0026\u0026 r.Inside is { } inside \u0026\u0026 inside.WithZ( 0f ).Length \u003E 0.01f \u0026\u0026 r.Pieces.Any( railPieces.Contains ) ).ToList();\r\n\t\t\tif ( targets.Count == 0 ) continue;\r\n\t\t\tforeach ( var rail in targets ) g.Restyle( rail, rail.Style, -rail.Inside.Value );\r\n\t\t\tApply( g, \u0022Flip rail\u0022 );\r\n\t\t\treplaced.AddRange( targets.SelectMany( r =\u003E r.Pieces ) );\r\n\t\t\tflipped \u002B= targets.Count;\r\n\t\t}\r\n\t\tif ( flipped == 0 ) return;\r\n\t\t_selection.RemoveAll( go =\u003E !go.IsValid() );\r\n\t\tforeach ( var go in replaced ) if ( go.IsValid() \u0026\u0026 !_selection.Contains( go ) ) _selection.Add( go );\r\n\t\tLog.Info( $\u0022Course Wall Builder: {flipped} rail(s) flipped\u0022 );\r\n\t}\r\n}\r\n"},{"Ident":"mrtn.golfkit","Path":"Code/GolfAudioZone.cs","FileName":"GolfAudioZone.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":440545,"IsPrivate":false,"Code":"using Sandbox;\r\nusing Sandbox.Audio;\r\nusing System;\r\nusing System.Collections.Generic;\r\n\r\n/// \u003Csummary\u003E\r\n/// An underground audio zone: a box (the Box Collider on the same object, Is Trigger on, used only\r\n/// for its size) that muffles the world while the local player\u0027s camera is inside it. The music,\r\n/// ambience, golf sound and shelling mixers (\u003Csee cref=\u0022GolfMixers\u0022/\u003E) each get the engine\u0027s\r\n/// low-pass processor and a volume drop, faded in over Fade Time on entering and out again on\r\n/// leaving. The guns play on the default mixer and are untouched. Where zones overlap, the\r\n/// strongest wins per mixer: the lowest cutoff and the biggest drop among the zones the camera is\r\n/// in. The camera is tested against the box directly every frame, so it works for every camera,\r\n/// the player view, the fly-over, the free camera and the menu orbit; nothing is networked.\r\n///\r\n/// The engine\u0027s low-pass is a one-pole filter whose Cutoff is the per-sample smoothing factor,\r\n/// not a frequency, so Cutoff Hz is converted: alpha = 1 - exp( -2 pi f / sample rate ). A factor\r\n/// of 1 passes the sound through unchanged, which is what the fade starts from and returns to.\r\n/// Drawn in the editor as a translucent blue box.\r\n/// \u003C/summary\u003E\r\n[Title( \u0022Golf Audio Zone\u0022 ), Category( \u0022Golf\u0022 ), Icon( \u0022hearing\u0022 )]\r\npublic sealed class GolfAudioZone : Component\r\n{\r\n\t/// \u003Csummary\u003ELow-pass cutoff inside the zone, Hz. Lower is more muffled.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Filter\u0022 ), Range( 50f, 8000f ), Title( \u0022Cutoff Hz\u0022 )]\r\n\tpublic float CutoffHz { get; set; } = 600f;\r\n\r\n\t/// \u003Csummary\u003ESeconds the filter and the drop take to fade in or out.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Filter\u0022 ), Range( 0f, 5f ), Title( \u0022Fade Time\u0022 )]\r\n\tpublic float FadeTime { get; set; } = 0.6f;\r\n\r\n\t/// \u003Csummary\u003EHow much of the volume is taken away inside, 0 to 1; 0.2 leaves 80 percent.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Filter\u0022 ), Range( 0f, 1f ), Title( \u0022Volume Drop\u0022 )]\r\n\tpublic float VolumeDrop { get; set; } = 0.2f;\r\n\r\n\t[Property, Group( \u0022Mixers\u0022 ), Title( \u0022Music\u0022 )]\r\n\tpublic bool AffectMusic { get; set; } = true;\r\n\r\n\t[Property, Group( \u0022Mixers\u0022 ), Title( \u0022Ambience\u0022 )]\r\n\tpublic bool AffectAmbience { get; set; } = true;\r\n\r\n\t[Property, Group( \u0022Mixers\u0022 ), Title( \u0022Golf Sounds\u0022 )]\r\n\tpublic bool AffectSounds { get; set; } = true;\r\n\r\n\t[Property, Group( \u0022Mixers\u0022 ), Title( \u0022Shelling\u0022 )]\r\n\tpublic bool AffectShelling { get; set; } = true;\r\n\r\n\t// Every enabled zone; the first one drives the mixers for all of them.\r\n\tstatic readonly List\u003CGolfAudioZone\u003E Zones = new();\r\n\r\n\t// Per mixer: the processor, the current smoothing factor (1 = untouched) and volume (1 = full).\r\n\tsealed class Channel\r\n\t{\r\n\t\tpublic string Name;\r\n\t\tpublic LowPassProcessor Filter;\r\n\t\tpublic Mixer Mixer;\r\n\t\tpublic float Alpha = 1f;\r\n\t\tpublic float Volume = 1f;\r\n\t\t// Zones muffle this mixer; the default \u0022Game\u0022 mixer (guns, footsteps) is only muffled by an outside request.\r\n\t\tpublic bool ZoneControlled = true;\r\n\t}\r\n\r\n\tstatic readonly Channel[] Channels =\r\n\t{\r\n\t\tnew() { Name = GolfMixers.MusicName },\r\n\t\tnew() { Name = GolfMixers.AmbienceName },\r\n\t\tnew() { Name = GolfMixers.SoundsName },\r\n\t\tnew() { Name = GolfMixers.ShellingName },\r\n\t\tnew() { Name = \u0022Game\u0022, ZoneControlled = false },\r\n\t};\r\n\r\n\t// An outside request to muffle everything (the distraction hit): cutoff factor, volume and how\r\n\t// strong it is right now, 0 to 1. Made fresh every frame by the requester; it lapses by itself.\r\n\tstatic float _muffleAlpha = 1f, _muffleVolume = 1f, _muffleStrength;\r\n\tstatic float _muffleFrame = -1f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Muffle every mixer, the guns included, this frame: a low-pass at this cutoff and a volume\r\n\t/// drop, scaled by strength (0 none, 1 full). Call it every frame it should apply; the caller\r\n\t/// shapes the fade in and out through the strength. Overlapping audio zones still take the strongest.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static void SetMuffle( float cutoffHz, float volumeDrop, float strength )\r\n\t{\r\n\t\t_muffleAlpha = AlphaFor( cutoffHz );\r\n\t\t_muffleVolume = 1f - Math.Clamp( volumeDrop, 0f, 1f );\r\n\t\t_muffleStrength = Math.Clamp( strength, 0f, 1f );\r\n\t\t_muffleFrame = Time.Now;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Runs the mixer update when no zone is there to do it, so an outside muffle request works in\r\n\t/// scenes without audio zones. A zone that exists drives the mixers itself.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static void TickWithoutZones()\r\n\t{\r\n\t\tif ( Zones.Count \u003E 0 ) return;\r\n\t\tTick();\r\n\t}\r\n\r\n\tprotected override void OnEnabled()\r\n\t{\r\n\t\tif ( !Zones.Contains( this ) ) Zones.Add( this );\r\n\t}\r\n\r\n\tprotected override void OnDisabled()\r\n\t{\r\n\t\tZones.Remove( this );\r\n\t\tif ( Zones.Count == 0 ) ResetMixers();\r\n\t}\r\n\r\n\t/// \u003Csummary\u003ETrue when a world point is inside this zone\u0027s box.\u003C/summary\u003E\r\n\tpublic bool Contains( Vector3 worldPosition )\r\n\t{\r\n\t\tvar local = WorldTransform.PointToLocal( worldPosition );\r\n\t\treturn Box().Contains( local );\r\n\t}\r\n\r\n\tbool Affects( int channel ) =\u003E channel switch { 0 =\u003E AffectMusic, 1 =\u003E AffectAmbience, 2 =\u003E AffectSounds, _ =\u003E AffectShelling };\r\n\r\n\tBBox Box()\r\n\t{\r\n\t\tvar box = GetComponent\u003CBoxCollider\u003E( true );\r\n\t\treturn box is not null\r\n\t\t\t? BBox.FromPositionAndSize( box.Center, box.Scale )\r\n\t\t\t: BBox.FromPositionAndSize( new Vector3( 0f, 0f, 200f ), new Vector3( 400f, 400f, 400f ) );\r\n\t}\r\n\r\n\tprotected override void OnUpdate()\r\n\t{\r\n\t\tif ( Scene.IsEditor ) return;\r\n\t\t// One zone does the work for all of them, so overlapping zones blend into one answer.\r\n\t\tif ( Zones.Count == 0 || Zones[0] != this ) return;\r\n\t\tTick();\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// One update of every mixer: the strongest zone the camera is in per mixer, fading at that\r\n\t/// zone\u0027s Fade Time, and the outside muffle request on top, which follows its own strength at once.\r\n\t/// \u003C/summary\u003E\r\n\tstatic void Tick()\r\n\t{\r\n\t\tvar scene = Game.ActiveScene;\r\n\t\tvar camera = scene?.Camera;\r\n\t\tvar position = camera.IsValid() ? camera.WorldPosition : Vector3.Zero;\r\n\t\tvar muffling = _muffleFrame \u003E= Time.Now - 0.1f \u0026\u0026 _muffleStrength \u003E 0f;\r\n\r\n\t\tfor ( var i = 0; i \u003C Channels.Length; i\u002B\u002B )\r\n\t\t{\r\n\t\t\tvar channel = Channels[i];\r\n\r\n\t\t\t// The strongest zone the camera is in, per mixer.\r\n\t\t\tvar targetAlpha = 1f;\r\n\t\t\tvar targetVolume = 1f;\r\n\t\t\tvar fade = 0.6f;\r\n\t\t\tif ( channel.ZoneControlled )\r\n\t\t\t{\r\n\t\t\t\tforeach ( var zone in Zones )\r\n\t\t\t\t{\r\n\t\t\t\t\tif ( !zone.IsValid() || !zone.Affects( i ) ) continue;\r\n\t\t\t\t\tif ( !camera.IsValid() || !zone.Contains( position ) ) continue;\r\n\t\t\t\t\tvar alpha = AlphaFor( zone.CutoffHz );\r\n\t\t\t\t\tif ( alpha \u003C targetAlpha ) { targetAlpha = alpha; fade = zone.FadeTime; }\r\n\t\t\t\t\ttargetVolume = Math.Min( targetVolume, 1f - Math.Clamp( zone.VolumeDrop, 0f, 1f ) );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t// The outside request wins where it is stronger, and is followed at once: its caller shapes the fade.\r\n\t\t\tvar instant = false;\r\n\t\t\tif ( muffling )\r\n\t\t\t{\r\n\t\t\t\tvar alpha = MathX.Lerp( 1f, _muffleAlpha, _muffleStrength );\r\n\t\t\t\tvar volume = MathX.Lerp( 1f, _muffleVolume, _muffleStrength );\r\n\t\t\t\tif ( alpha \u003C targetAlpha ) { targetAlpha = alpha; instant = true; }\r\n\t\t\t\tif ( volume \u003C targetVolume ) { targetVolume = volume; instant = true; }\r\n\t\t\t}\r\n\t\t\telse if ( !channel.ZoneControlled || Zones.Count == 0 )\r\n\t\t\t{\r\n\t\t\t\tinstant = true;   // nothing asks for anything: straight back to clean\r\n\t\t\t}\r\n\r\n\t\t\tvar step = instant || fade \u003C= 0f ? 1f : Math.Clamp( Time.Delta / fade, 0f, 1f );\r\n\t\t\t// Linear in the smoothing factor sounds right: it sweeps the muffling smoothly.\r\n\t\t\tchannel.Alpha = MathX.Lerp( channel.Alpha, targetAlpha, step );\r\n\t\t\tchannel.Volume = MathX.Lerp( channel.Volume, targetVolume, step );\r\n\t\t\tif ( Math.Abs( channel.Alpha - targetAlpha ) \u003C 0.002f ) channel.Alpha = targetAlpha;\r\n\t\t\tif ( Math.Abs( channel.Volume - targetVolume ) \u003C 0.002f ) channel.Volume = targetVolume;\r\n\t\t\tApply( channel );\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EThe mixer\u0027s sample rate; the engine\u0027s own figure is not exposed to game code.\u003C/summary\u003E\r\n\tconst float SampleRate = 44100f;\r\n\r\n\t/// \u003Csummary\u003EThe one-pole smoothing factor that gives this cutoff at the mix sample rate.\u003C/summary\u003E\r\n\tstatic float AlphaFor( float hz )\r\n\t{\r\n\t\treturn Math.Clamp( 1f - MathF.Exp( -2f * MathF.PI * Math.Max( 10f, hz ) / SampleRate ), 0.001f, 1f );\r\n\t}\r\n\r\n\tstatic void Apply( Channel channel )\r\n\t{\r\n\t\tif ( channel.Mixer is null )\r\n\t\t{\r\n\t\t\tchannel.Mixer = GolfMixers.Get( channel.Name );\r\n\t\t\tif ( channel.Mixer is null ) return;\r\n\t\t}\r\n\r\n\t\tvar untouched = channel.Alpha \u003E= 0.999f;\r\n\t\tif ( channel.Filter is null )\r\n\t\t{\r\n\t\t\tif ( untouched ) { channel.Mixer.Volume = channel.Volume; return; }\r\n\t\t\tchannel.Filter = channel.Mixer.GetProcessor\u003CLowPassProcessor\u003E();\r\n\t\t\tif ( channel.Filter is null )\r\n\t\t\t{\r\n\t\t\t\tchannel.Filter = new LowPassProcessor { Cutoff = 1f };\r\n\t\t\t\tchannel.Mixer.AddProcessor( channel.Filter );\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tchannel.Filter.Cutoff = channel.Alpha;\r\n\t\tchannel.Filter.Enabled = !untouched;\r\n\t\tchannel.Mixer.Volume = channel.Volume;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003ENo zones left (scene change, all disabled): every mixer back to clean and full.\u003C/summary\u003E\r\n\tstatic void ResetMixers()\r\n\t{\r\n\t\tforeach ( var channel in Channels )\r\n\t\t{\r\n\t\t\tchannel.Alpha = 1f;\r\n\t\t\tchannel.Volume = 1f;\r\n\t\t\tif ( channel.Mixer is null ) continue;\r\n\t\t\tif ( channel.Filter is not null )\r\n\t\t\t{\r\n\t\t\t\tchannel.Filter.Cutoff = 1f;\r\n\t\t\t\tchannel.Filter.Enabled = false;\r\n\t\t\t}\r\n\t\t\tchannel.Mixer.Volume = 1f;\r\n\t\t}\r\n\t}\r\n\r\n\tprotected override void DrawGizmos()\r\n\t{\r\n\t\tvar bounds = Box();\r\n\t\tvar alpha = Gizmo.IsSelected ? 0.35f : (Gizmo.IsHovered ? 0.25f : 0.12f);\r\n\t\tvar blue = new Color( 0.25f, 0.55f, 1f );\r\n\t\tGizmo.Draw.Color = blue.WithAlpha( alpha );\r\n\t\tGizmo.Draw.SolidBox( bounds );\r\n\t\tGizmo.Draw.LineThickness = Gizmo.IsSelected ? 2f : 1f;\r\n\t\tGizmo.Draw.Color = blue.WithAlpha( Gizmo.IsSelected ? 0.9f : 0.5f );\r\n\t\tGizmo.Draw.LineBBox( bounds );\r\n\t}\r\n}\r\n"},{"Ident":"mrtn.golfkit","Path":"Code/GolfMenuCamera.cs","FileName":"GolfMenuCamera.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":440545,"IsPrivate":false,"Code":"using Sandbox;\r\nusing System;\r\nusing System.Linq;\r\n\r\n/// \u003Csummary\u003E\r\n/// Where the camera sits behind the main menu, the course settings and the lobby. Place one in a\r\n/// scene (the menu_camera prefab) and the fly-over\u0027s menu orbit is replaced by this view: the\r\n/// object\u0027s position and rotation with a gentle sway and a slight push-in. A child object named\r\n/// End makes it drift back and forth between the two points as well. Without one in the scene\r\n/// the old orbit round the start hole is used. Editor gizmo: the camera\u0027s frustum, and the path\r\n/// to End when there is one.\r\n/// \u003C/summary\u003E\r\n[Title( \u0022Golf Menu Camera\u0022 ), Icon( \u0022videocam\u0022 ), Category( \u0022Golf\u0022 )]\r\npublic sealed class GolfMenuCamera : Component\r\n{\r\n\t/// \u003Csummary\u003EThe menu camera in the loaded scene, or null.\u003C/summary\u003E\r\n\tpublic static GolfMenuCamera Current { get; private set; }\r\n\r\n\t/// \u003Csummary\u003EHow far the sway moves the camera sideways and up, in units. 0 holds it still.\u003C/summary\u003E\r\n\t[Property, Title( \u0022Drift Amount\u0022 ), Range( 0f, 200f )]\r\n\tpublic float DriftAmount { get; set; } = 24f;\r\n\r\n\t/// \u003Csummary\u003ESeconds for one full sway back and forth.\u003C/summary\u003E\r\n\t[Property, Title( \u0022Drift Period\u0022 ), Range( 2f, 60f )]\r\n\tpublic float DriftPeriod { get; set; } = 14f;\r\n\r\n\t/// \u003Csummary\u003EHow far the camera eases forward and back along its view, in units.\u003C/summary\u003E\r\n\t[Property, Title( \u0022Push In\u0022 ), Range( 0f, 400f )]\r\n\tpublic float PushIn { get; set; } = 40f;\r\n\r\n\t/// \u003Csummary\u003EDegrees of slow look-around that go with the sway. 0 keeps the rotation fixed.\u003C/summary\u003E\r\n\t[Property, Title( \u0022Sway Degrees\u0022 ), Range( 0f, 10f )]\r\n\tpublic float SwayDegrees { get; set; } = 1.5f;\r\n\r\n\t/// \u003Csummary\u003ESeconds for one trip from here to End and back, when a child named End exists.\u003C/summary\u003E\r\n\t[Property, Title( \u0022Loop Seconds\u0022 ), Range( 4f, 120f )]\r\n\tpublic float LoopSeconds { get; set; } = 30f;\r\n\r\n\t/// \u003Csummary\u003EVertical field of view of the menu view.\u003C/summary\u003E\r\n\t[Property, Title( \u0022Field Of View\u0022 ), Range( 30f, 110f )]\r\n\tpublic float FieldOfView { get; set; } = 70f;\r\n\r\n\tprotected override void OnEnabled()\r\n\t{\r\n\t\tCurrent = this;\r\n\t}\r\n\r\n\tprotected override void OnDisabled()\r\n\t{\r\n\t\tif ( Current == this ) Current = null;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EThe End child, if the camera loops between two points.\u003C/summary\u003E\r\n\tGameObject End =\u003E GameObject.Children.FirstOrDefault( c =\u003E c.IsValid() \u0026\u0026 string.Equals( c.Name, \u0022End\u0022, StringComparison.OrdinalIgnoreCase ) );\r\n\r\n\t/// \u003Csummary\u003ETrue when a child named End exists, so the view drifts between the two points.\u003C/summary\u003E\r\n\tpublic bool HasEnd =\u003E End.IsValid();\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// True when the view this camera gives is a usable transform (no NaN or infinite values, as a\r\n\t/// zero scale or a broken parent can produce). The fly-over falls back to its orbit otherwise.\r\n\t/// \u003C/summary\u003E\r\n\tpublic bool HasValidView\r\n\t{\r\n\t\tget\r\n\t\t{\r\n\t\t\tvar view = ViewAt( 0f );\r\n\t\t\treturn IsFinite( view.Position ) \u0026\u0026 IsFinite( view.Rotation.Forward ) \u0026\u0026 !view.Rotation.Forward.IsNearlyZero();\r\n\t\t}\r\n\t}\r\n\r\n\tstatic bool IsFinite( Vector3 v ) =\u003E float.IsFinite( v.x ) \u0026\u0026 float.IsFinite( v.y ) \u0026\u0026 float.IsFinite( v.z );\r\n\r\n\t/// \u003Csummary\u003EThe camera\u0027s position and rotation at a moment in time, drift and all.\u003C/summary\u003E\r\n\tpublic Transform ViewAt( float time )\r\n\t{\r\n\t\tvar start = WorldTransform;\r\n\t\tvar position = start.Position;\r\n\t\tvar rotation = start.Rotation;\r\n\r\n\t\t// Back and forth between here and End, easing at both ends.\r\n\t\tvar end = End;\r\n\t\tif ( end.IsValid() \u0026\u0026 LoopSeconds \u003E 0f )\r\n\t\t{\r\n\t\t\tvar phase = (time % LoopSeconds) / LoopSeconds;          // 0..1 over one round trip\r\n\t\t\tvar t = phase \u003C 0.5f ? phase * 2f : 2f - phase * 2f;      // 0 -\u003E 1 -\u003E 0\r\n\t\t\tt = t * t * (3f - 2f * t);                                // smoothstep\r\n\t\t\tposition = Vector3.Lerp( start.Position, end.WorldPosition, t );\r\n\t\t\trotation = Rotation.Slerp( start.Rotation, end.WorldRotation, t );\r\n\t\t}\r\n\r\n\t\t// The sway: a slow figure of eight sideways and up, with a push-in on a longer beat.\r\n\t\tvar period = MathF.Max( 2f, DriftPeriod );\r\n\t\tvar w = MathF.Tau * time / period;\r\n\t\tvar sideways = MathF.Sin( w ) * DriftAmount;\r\n\t\tvar upward = MathF.Sin( w * 0.5f \u002B 1.3f ) * DriftAmount * 0.5f;\r\n\t\tvar forward = (0.5f \u002B 0.5f * MathF.Sin( w * 0.25f )) * PushIn;\r\n\r\n\t\tvar swayed = rotation * Rotation.From( MathF.Sin( w * 0.5f ) * SwayDegrees * 0.5f, MathF.Sin( w ) * SwayDegrees, 0f );\r\n\t\tposition \u002B= rotation.Right * sideways \u002B rotation.Up * upward \u002B rotation.Forward * forward;\r\n\r\n\t\treturn new Transform( position, swayed );\r\n\t}\r\n\r\n\tprotected override void DrawGizmos()\r\n\t{\r\n\t\tvar selected = Gizmo.IsSelected || Gizmo.IsHovered;\r\n\t\tvar colour = new Color( 0.37f, 0.83f, 0.42f );\r\n\t\tGizmo.Draw.LineThickness = selected ? 2f : 1f;\r\n\t\tGizmo.Draw.Color = colour.WithAlpha( selected ? 0.95f : 0.55f );\r\n\r\n\t\t// The frustum in local space: the near and far rectangles of the field of view, joined up.\r\n\t\tvar aspect = 16f / 9f;\r\n\t\tvar near = 20f;\r\n\t\tvar far = selected ? 600f : 300f;\r\n\t\tvar tan = MathF.Tan( MathX.DegreeToRadian( FieldOfView ) * 0.5f );\r\n\t\tVector3[] Corners( float d )\r\n\t\t{\r\n\t\t\tvar h = tan * d;\r\n\t\t\tvar w = h * aspect;\r\n\t\t\treturn new[]\r\n\t\t\t{\r\n\t\t\t\tnew Vector3( d, -w, -h ), new Vector3( d, w, -h ),\r\n\t\t\t\tnew Vector3( d, w, h ), new Vector3( d, -w, h ),\r\n\t\t\t};\r\n\t\t}\r\n\t\tvar n = Corners( near );\r\n\t\tvar f = Corners( far );\r\n\t\tfor ( var i = 0; i \u003C 4; i\u002B\u002B )\r\n\t\t{\r\n\t\t\tGizmo.Draw.Line( n[i], n[(i \u002B 1) % 4] );\r\n\t\t\tGizmo.Draw.Line( f[i], f[(i \u002B 1) % 4] );\r\n\t\t\tGizmo.Draw.Line( Vector3.Zero, f[i] );\r\n\t\t}\r\n\r\n\t\t// A small body so it can be found and clicked.\r\n\t\tGizmo.Draw.LineBBox( new BBox( new Vector3( -14f, -8f, -8f ), new Vector3( 4f, 8f, 8f ) ) );\r\n\r\n\t\t// The loop path to End, in world space.\r\n\t\tvar end = End;\r\n\t\tif ( end.IsValid() )\r\n\t\t{\r\n\t\t\tvar local = WorldTransform.PointToLocal( end.WorldPosition );\r\n\t\t\tGizmo.Draw.Color = colour.WithAlpha( 0.8f );\r\n\t\t\tGizmo.Draw.Arrow( Vector3.Zero, local, 12f, 4f );\r\n\t\t}\r\n\t}\r\n}\r\n"},{"Ident":"mrtn.golfkit","Path":"Code/MudWaterRipple.cs","FileName":"MudWaterRipple.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":440545,"IsPrivate":false,"Code":"using Sandbox;\r\nusing System;\r\nusing System.Linq;\r\n\r\n/// \u003Csummary\u003E\r\n/// Ripples on a mud water plane. Every Interval (a random time between the min and max) a\r\n/// shockwave starts at a random point on the plane: a flat overlay quad carrying a ring texture\r\n/// (three concentric rings in its alpha and normal map, from Tools/make_mud_water.py) is placed on\r\n/// the surface, scaled up at Ring Speed until it reaches Max Radius, and fades to nothing on the\r\n/// way, about two seconds at the defaults. The overlay\u0027s fade is the renderer\u0027s Tint alpha; the\r\n/// complex shader has no attribute to drive a ripple inside the water material itself, so the\r\n/// overlay is the cheap route in this build. Nothing is networked, every machine ripples on its\r\n/// own; a small pool of overlays, no allocation per ripple. Put it on the object that renders the\r\n/// water plane: the plane\u0027s extent is that renderer\u0027s model bounds.\r\n///\r\n/// Between ripples the water also sways in place: the plane\u0027s material is copied at start and the\r\n/// copy\u0027s texture offset is moved round a tiny circle every frame (the complex shader has no\r\n/// wobble or animated normal option, only a straight scroll, so this is done from code). Nothing\r\n/// flows, the texture only drifts back and forth by a fraction of a texel.\r\n/// \u003C/summary\u003E\r\n[Title( \u0022Mud Water Ripple\u0022 ), Category( \u0022Golf\u0022 ), Icon( \u0022water\u0022 )]\r\npublic sealed class MudWaterRipple : Component\r\n{\r\n\t/// \u003Csummary\u003EShortest wait between ripples, seconds.\u003C/summary\u003E\r\n\t[Property, Range( 0.5f, 60f ), Title( \u0022Interval Min\u0022 )]\r\n\tpublic float IntervalMin { get; set; } = 5f;\r\n\r\n\t/// \u003Csummary\u003ELongest wait between ripples, seconds.\u003C/summary\u003E\r\n\t[Property, Range( 0.5f, 60f ), Title( \u0022Interval Max\u0022 )]\r\n\tpublic float IntervalMax { get; set; } = 15f;\r\n\r\n\t/// \u003Csummary\u003EHow fast the rings spread, units per second.\u003C/summary\u003E\r\n\t[Property, Range( 10f, 1000f ), Title( \u0022Ring Speed\u0022 )]\r\n\tpublic float RingSpeed { get; set; } = 100f;\r\n\r\n\t/// \u003Csummary\u003EHow visible the rings are when they start, 0 to 1.\u003C/summary\u003E\r\n\t[Property, Range( 0f, 1f ), Title( \u0022Ring Strength\u0022 )]\r\n\tpublic float RingStrength { get; set; } = 0.8f;\r\n\r\n\t/// \u003Csummary\u003ERadius the rings reach before they are gone, units.\u003C/summary\u003E\r\n\t[Property, Range( 20f, 2000f ), Title( \u0022Max Radius\u0022 )]\r\n\tpublic float MaxRadius { get; set; } = 200f;\r\n\r\n\t/// \u003Csummary\u003ERipples in flight at once; the pool size.\u003C/summary\u003E\r\n\t[Property, Range( 1, 8 )]\r\n\tpublic int MaxRipples { get; set; } = 3;\r\n\r\n\t/// \u003Csummary\u003ESway the water texture in place between ripples.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Wobble\u0022 )]\r\n\tpublic bool Wobble { get; set; } = true;\r\n\r\n\t/// \u003Csummary\u003EHow far the texture sways, in UV units; 0.002 is a fraction of a texel.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Wobble\u0022 ), Range( 0f, 0.02f ), Title( \u0022Wobble Radius\u0022 )]\r\n\tpublic float WobbleRadius { get; set; } = 0.002f;\r\n\r\n\t/// \u003Csummary\u003ESeconds for one full sway round the circle.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Wobble\u0022 ), Range( 1f, 30f ), Title( \u0022Wobble Period\u0022 )]\r\n\tpublic float WobblePeriod { get; set; } = 6f;\r\n\r\n\tconst string QuadModel = \u0022models/mud_water/ripple_quad.vmdl\u0022;\r\n\tconst string RingMaterial = \u0022textures/mud_water/ripple_ring.vmat\u0022;\r\n\tconst float Lift = 0.75f;   // the overlay floats this far above the water so it never z-fights\r\n\r\n\tModelRenderer[] _overlays = Array.Empty\u003CModelRenderer\u003E();\r\n\tfloat[] _born = Array.Empty\u003Cfloat\u003E();\r\n\tint _next;\r\n\tfloat _nextAt;\r\n\tModelRenderer _plane;\r\n\tMaterial _planeMaterial;   // what the plane had before the wobble copy, put back on disable\r\n\tMaterial _wobble;\r\n\r\n\tprotected override void OnStart()\r\n\t{\r\n\t\tvar model = Model.Load( QuadModel );\r\n\t\tvar material = Material.Load( RingMaterial );\r\n\t\tif ( model is null || material is null )\r\n\t\t{\r\n\t\t\tLog.Warning( $\u0022MudWaterRipple: missing {QuadModel} or {RingMaterial}\u0022 );\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tvar count = Math.Clamp( MaxRipples, 1, 8 );\r\n\t\t_overlays = new ModelRenderer[count];\r\n\t\t_born = new float[count];\r\n\t\tfor ( var i = 0; i \u003C count; i\u002B\u002B )\r\n\t\t{\r\n\t\t\tvar go = new GameObject( GameObject, false, $\u0022ripple {i}\u0022 );\r\n\t\t\tgo.Flags |= GameObjectFlags.NotSaved | GameObjectFlags.NotNetworked | GameObjectFlags.Hidden;\r\n\t\t\tvar renderer = go.AddComponent\u003CModelRenderer\u003E();\r\n\t\t\trenderer.Model = model;\r\n\t\t\trenderer.MaterialOverride = material;\r\n\t\t\t_overlays[i] = renderer;\r\n\t\t}\r\n\r\n\t\t_nextAt = Time.Now \u002B Wait();\r\n\r\n\t\t// The wobble works on a private copy of the plane\u0027s material, so the asset itself is untouched.\r\n\t\t_plane = GetComponent\u003CModelRenderer\u003E();\r\n\t\tvar source = _plane?.MaterialOverride ?? _plane?.Model?.Materials.FirstOrDefault();\r\n\t\tif ( Wobble \u0026\u0026 source is not null )\r\n\t\t{\r\n\t\t\t_planeMaterial = _plane.MaterialOverride;\r\n\t\t\t_wobble = source.CreateCopy( \u0022mud water wobble\u0022 );\r\n\t\t\t_plane.MaterialOverride = _wobble;\r\n\t\t}\r\n\t}\r\n\r\n\tprotected override void OnDisabled()\r\n\t{\r\n\t\tforeach ( var overlay in _overlays )\r\n\t\t\tif ( overlay.IsValid() ) overlay.GameObject.Enabled = false;\r\n\r\n\t\tif ( _wobble is not null \u0026\u0026 _plane.IsValid() \u0026\u0026 _plane.MaterialOverride == _wobble )\r\n\t\t\t_plane.MaterialOverride = _planeMaterial;\r\n\t\t_wobble = null;\r\n\t}\r\n\r\n\tprotected override void OnUpdate()\r\n\t{\r\n\t\tif ( Scene.IsEditor || _overlays.Length == 0 ) return;\r\n\r\n\t\tvar now = Time.Now;\r\n\r\n\t\tif ( _wobble is not null )\r\n\t\t{\r\n\t\t\tvar angle = now / Math.Max( 0.1f, WobblePeriod ) * MathF.PI * 2f;\r\n\t\t\tvar radius = Wobble ? WobbleRadius : 0f;\r\n\t\t\t_wobble.Set( \u0022g_vTexCoordOffset\u0022, new Vector2( MathF.Cos( angle ), MathF.Sin( angle ) ) * radius );\r\n\t\t}\r\n\t\tvar life = MaxRadius / Math.Max( 1f, RingSpeed );\r\n\r\n\t\tfor ( var i = 0; i \u003C _overlays.Length; i\u002B\u002B )\r\n\t\t{\r\n\t\t\tvar overlay = _overlays[i];\r\n\t\t\tif ( !overlay.IsValid() || !overlay.GameObject.Enabled ) continue;\r\n\r\n\t\t\tvar age = now - _born[i];\r\n\t\t\tif ( age \u003E= life )\r\n\t\t\t{\r\n\t\t\t\toverlay.GameObject.Enabled = false;\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\tvar t = age / life;\r\n\t\t\tvar radius = Math.Max( 1f, RingSpeed * age );\r\n\t\t\toverlay.GameObject.WorldScale = new Vector3( radius, radius, 1f );\r\n\t\t\toverlay.Tint = Color.White.WithAlpha( RingStrength * (1f - t) * (1f - t) );\r\n\t\t}\r\n\r\n\t\tif ( now \u003C _nextAt ) return;\r\n\t\t_nextAt = now \u002B Wait();\r\n\t\tSpawn();\r\n\t}\r\n\r\n\tfloat Wait()\r\n\t{\r\n\t\tvar min = Math.Min( IntervalMin, IntervalMax );\r\n\t\tvar max = Math.Max( IntervalMin, IntervalMax );\r\n\t\treturn Game.Random.Float( min, max );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EA ripple at a random point on the plane\u0027s top surface.\u003C/summary\u003E\r\n\tvoid Spawn()\r\n\t{\r\n\t\tvar i = _next;\r\n\t\t_next = (_next \u002B 1) % _overlays.Length;\r\n\t\tvar overlay = _overlays[i];\r\n\t\tif ( !overlay.IsValid() ) return;\r\n\r\n\t\tvar plane = GetComponent\u003CModelRenderer\u003E();\r\n\t\tvar bounds = plane?.Model?.Bounds ?? new BBox( new Vector3( -100f, -100f, 0f ), new Vector3( 100f, 100f, 0f ) );\r\n\t\tvar local = new Vector3(\r\n\t\t\tGame.Random.Float( bounds.Mins.x, bounds.Maxs.x ),\r\n\t\t\tGame.Random.Float( bounds.Mins.y, bounds.Maxs.y ),\r\n\t\t\tbounds.Maxs.z );\r\n\t\tvar position = WorldTransform.PointToWorld( local ) \u002B Vector3.Up * Lift;\r\n\r\n\t\toverlay.GameObject.WorldPosition = position;\r\n\t\toverlay.GameObject.WorldRotation = Rotation.FromYaw( Game.Random.Float( 0f, 360f ) );\r\n\t\toverlay.GameObject.WorldScale = new Vector3( 1f, 1f, 1f );\r\n\t\toverlay.Tint = Color.White.WithAlpha( RingStrength );\r\n\t\t_born[i] = Time.Now;\r\n\t\toverlay.GameObject.Enabled = true;\r\n\t}\r\n}\r\n"},{"Ident":"mrtn.golfkit","Path":"Code/TrenchShelling.cs","FileName":"TrenchShelling.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":440545,"IsPrivate":false,"Code":"using Sandbox;\r\nusing System;\r\n\r\n/// \u003Csummary\u003E\r\n/// Distant artillery for the trench map. Every Interval (a fresh random wait between the min and\r\n/// max, read from the Inspector each time a shell goes off) the host picks a shell: usually far\r\n/// off, a random yaw and a distance in the Far range; sometimes (Near Chance) a near one in the\r\n/// Near range. The host tells every machine the yaw, the distance and the kind, and each machine\r\n/// places the shell at that yaw and distance from its own camera, so every player gets the same\r\n/// near or far shell wherever they stand: an explosion sound in 3D at that spot (the far event is\r\n/// pitched down and softened, the near one is as it comes) and a camera shake sized by the\r\n/// distance, a soft rumble of about a second for a far one, a hard kick and a rolling two second\r\n/// decay plus a low rumble layer for a near one. No damage, nothing happens to balls, no particles.\r\n/// Runs from scene load, so the menu and the lobby hear it too. Place one anywhere; its position\r\n/// does not matter, and only one instance keeps the clock.\r\n///\r\n/// The shake is smooth noise, new every frame: layered sines on position (up to the shake\r\n/// strength in units) and on pitch, yaw and roll (up to Shake Angle, scaled by the strength), with\r\n/// a fast attack and an exponential decay. It reaches whichever camera is active. The engine\r\n/// composes each camera\u0027s view once per tick after Update, through the camera modifiers, and\r\n/// the shake is one of those (after the fly-over and the free camera). But the fly-over, the\r\n/// free camera and the menu orbit write the camera\u0027s transform in PreRender, after that\r\n/// composition, and the engine then renders from the raw transform and drops the composed view.\r\n/// So at the very end of the tick (the FinishUpdate stage, after every PreRender) the\r\n/// \u003Csee cref=\u0022TrenchShellingSystem\u0022/\u003E checks whether the active camera\u0027s transform changed after\r\n/// composition and, if it did, adds the same offset to the transform itself, undoing it again at\r\n/// the start of the next tick so nothing accumulates.\r\n/// \u003C/summary\u003E\r\n[Title( \u0022Trench Shelling\u0022 ), Category( \u0022Golf\u0022 ), Icon( \u0022flare\u0022 )]\r\npublic sealed class TrenchShelling : Component, ICameraModifier\r\n{\r\n\t/// \u003Csummary\u003EThe instance that keeps the clock and shakes the camera; the first enabled one.\u003C/summary\u003E\r\n\tpublic static TrenchShelling Current { get; private set; }\r\n\r\n\t/// \u003Csummary\u003EShortest wait between shells, seconds.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Timing\u0022 ), Range( 1f, 300f ), Title( \u0022Interval Min\u0022 )]\r\n\tpublic float IntervalMin { get; set; } = 20f;\r\n\r\n\t/// \u003Csummary\u003ELongest wait between shells, seconds.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Timing\u0022 ), Range( 1f, 300f ), Title( \u0022Interval Max\u0022 )]\r\n\tpublic float IntervalMax { get; set; } = 60f;\r\n\r\n\t/// \u003Csummary\u003EClosest a far shell lands, units from each player\u0027s camera.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Distance\u0022 ), Range( 500f, 20000f ), Title( \u0022Far Distance Min\u0022 )]\r\n\tpublic float FarMin { get; set; } = 2000f;\r\n\r\n\t/// \u003Csummary\u003EFurthest a far shell lands, units from each player\u0027s camera.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Distance\u0022 ), Range( 500f, 20000f ), Title( \u0022Far Distance Max\u0022 )]\r\n\tpublic float FarMax { get; set; } = 6000f;\r\n\r\n\t/// \u003Csummary\u003EChance a shell is a near one, 0 to 1.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Distance\u0022 ), Range( 0f, 1f ), Title( \u0022Near Chance\u0022 )]\r\n\tpublic float NearChance { get; set; } = 0.15f;\r\n\r\n\t/// \u003Csummary\u003EClosest a near shell lands, units from each player\u0027s camera.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Distance\u0022 ), Range( 50f, 5000f ), Title( \u0022Near Distance Min\u0022 )]\r\n\tpublic float NearMin { get; set; } = 300f;\r\n\r\n\t/// \u003Csummary\u003EFurthest a near shell lands, units from each player\u0027s camera.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Distance\u0022 ), Range( 50f, 5000f ), Title( \u0022Near Distance Max\u0022 )]\r\n\tpublic float NearMax { get; set; } = 800f;\r\n\r\n\t/// \u003Csummary\u003EThe far shell: pitched down and softened. Empty uses sounds/trench/shell_far.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Sound\u0022 ), Title( \u0022Far Sound\u0022 )]\r\n\tpublic SoundEvent FarSound { get; set; }\r\n\r\n\t/// \u003Csummary\u003EThe near shell. Empty uses sounds/trench/shell_near.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Sound\u0022 ), Title( \u0022Near Sound\u0022 )]\r\n\tpublic SoundEvent NearSound { get; set; }\r\n\r\n\t/// \u003Csummary\u003ELow rumble layered under a near shell. Empty uses sounds/trench/shell_rumble; None for none.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Sound\u0022 ), Title( \u0022Rumble Sound\u0022 )]\r\n\tpublic SoundEvent RumbleSound { get; set; }\r\n\r\n\t/// \u003Csummary\u003EVolume of every shell sound, 0 to 2.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Sound\u0022 ), Range( 0f, 2f )]\r\n\tpublic float Volume { get; set; } = 1f;\r\n\r\n\t/// \u003Csummary\u003EShake of a far shell for a camera right next to it, world units.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Shake\u0022 ), Range( 0f, 10f ), Title( \u0022Far Shake\u0022 )]\r\n\tpublic float FarShake { get; set; } = 1.2f;\r\n\r\n\t/// \u003Csummary\u003EHow long a far shell rumbles, seconds.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Shake\u0022 ), Range( 0f, 10f ), Title( \u0022Far Shake Time\u0022 )]\r\n\tpublic float FarShakeTime { get; set; } = 1f;\r\n\r\n\t/// \u003Csummary\u003EShake of a near shell for a camera right next to it, world units.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Shake\u0022 ), Range( 0f, 10f ), Title( \u0022Near Shake\u0022 )]\r\n\tpublic float NearShake { get; set; } = 6f;\r\n\r\n\t/// \u003Csummary\u003EHow long a near shell shakes, seconds.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Shake\u0022 ), Range( 0f, 10f ), Title( \u0022Near Shake Time\u0022 )]\r\n\tpublic float NearShakeTime { get; set; } = 2f;\r\n\r\n\t/// \u003Csummary\u003ESpeed of the shake noise, wobbles per second.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Shake\u0022 ), Range( 1f, 60f ), Title( \u0022Shake Frequency\u0022 )]\r\n\tpublic float ShakeFrequency { get; set; } = 9f;\r\n\r\n\t/// \u003Csummary\u003ETilt of the view at full Near Shake strength, degrees; smaller shakes tilt less in proportion.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Shake\u0022 ), Range( 0f, 10f ), Title( \u0022Shake Angle\u0022 )]\r\n\tpublic float ShakeAngle { get; set; } = 2f;\r\n\r\n\t/// \u003Csummary\u003EDistance from the camera at which a shell\u0027s shake has faded to nothing, units.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Shake\u0022 ), Range( 500f, 30000f ), Title( \u0022Shake Range\u0022 )]\r\n\tpublic float ShakeRange { get; set; } = 9000f;\r\n\r\n\tconst string FarSoundPath = \u0022sounds/trench/shell_far.sound\u0022;\r\n\tconst string NearSoundPath = \u0022sounds/trench/shell_near.sound\u0022;\r\n\tconst string RumbleSoundPath = \u0022sounds/trench/shell_rumble.sound\u0022;\r\n\r\n\t// The host\u0027s clock. A TimeUntil survives a hotload and counts in scene time.\r\n\tTimeUntil _nextShell;\r\n\tbool _scheduled;\r\n\r\n\t// The shake in progress.\r\n\tfloat _amplitude;        // units of position shake at the start\r\n\tfloat _started;          // Time.Now it began\r\n\tfloat _duration;\r\n\tbool _near;\r\n\tVector3 _kickDirection;  // the near shell\u0027s first hard knock\r\n\tint _shell;              // counts shells, so the camera line is logged once each\r\n\tint _loggedShell;\r\n\r\n\t// The camera the view was composed for this tick, and its raw transform at that moment.\r\n\tCameraComponent _composedCamera;\r\n\tVector3 _composedPosition;\r\n\tRotation _composedRotation;\r\n\tbool _composedThisTick;\r\n\r\n\t// An offset written into a camera\u0027s transform at the end of a tick, taken out again at the start of the next.\r\n\tCameraComponent _rawCamera;\r\n\tVector3 _rawOffset;\r\n\tRotation _rawTilt = Rotation.Identity;\r\n\tbool _rawApplied;\r\n\r\n\tprotected override void OnEnabled()\r\n\t{\r\n\t\tif ( !Current.IsValid() || Current.Scene != Scene ) Current = this;\r\n\t}\r\n\r\n\tprotected override void OnDisabled()\r\n\t{\r\n\t\tRestoreEarly();\r\n\t\tif ( Current == this ) Current = null;\r\n\t}\r\n\r\n\tprotected override void OnStart()\r\n\t{\r\n\t\tFarSound ??= ResourceLibrary.Get\u003CSoundEvent\u003E( FarSoundPath );\r\n\t\tNearSound ??= ResourceLibrary.Get\u003CSoundEvent\u003E( NearSoundPath );\r\n\t\tRumbleSound ??= ResourceLibrary.Get\u003CSoundEvent\u003E( RumbleSoundPath );\r\n\t}\r\n\r\n\tprotected override void OnUpdate()\r\n\t{\r\n\t\t// One instance keeps the clock, on the host; everyone else only hears what it sends.\r\n\t\tif ( Scene.IsEditor || Current != this || !Networking.IsHost ) return;\r\n\r\n\t\tif ( !_scheduled )\r\n\t\t{\r\n\t\t\tSchedule();\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif ( _nextShell \u003E 0f ) return;\r\n\t\tSchedule();\r\n\r\n\t\tvar near = Game.Random.Float( 0f, 1f ) \u003C NearChance;\r\n\t\tvar distance = near\r\n\t\t\t? Game.Random.Float( Math.Min( NearMin, NearMax ), Math.Max( NearMin, NearMax ) )\r\n\t\t\t: Game.Random.Float( Math.Min( FarMin, FarMax ), Math.Max( FarMin, FarMax ) );\r\n\t\tvar yaw = Game.Random.Float( 0f, 360f );\r\n\r\n\t\tShellRpc( yaw, distance, near );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EA fresh random wait, from the Inspector values as they are right now.\u003C/summary\u003E\r\n\tvoid Schedule()\r\n\t{\r\n\t\tvar min = Math.Min( IntervalMin, IntervalMax );\r\n\t\tvar max = Math.Max( IntervalMin, IntervalMax );\r\n\t\tvar wait = Game.Random.Float( min, max );\r\n\t\t_nextShell = wait;\r\n\t\t_scheduled = true;\r\n\t\tLog.Info( $\u0022TrenchShelling: next shell in {wait:0} s (interval {min:0} to {max:0})\u0022 );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EA shell lands at this yaw and distance from this machine\u0027s own camera: the sound there and a shake sized by the distance.\u003C/summary\u003E\r\n\t[Rpc.Broadcast]\r\n\tvoid ShellRpc( float yaw, float distance, bool near )\r\n\t{\r\n\t\tvar camera = Scene.Camera;\r\n\t\tvar origin = camera.IsValid() ? camera.WorldPosition : WorldPosition;\r\n\t\tvar position = origin \u002B Rotation.FromYaw( yaw ).Forward * distance;\r\n\r\n\t\tvar sound = near ? NearSound : FarSound;\r\n\t\tif ( sound is not null \u0026\u0026 Volume \u003E 0f )\r\n\t\t{\r\n\t\t\tvar handle = Sound.Play( sound, position );\r\n\t\t\tif ( handle.IsValid() )\r\n\t\t\t{\r\n\t\t\t\thandle.Volume *= Volume;\r\n\t\t\t\thandle.TargetMixer = GolfMixers.Shelling ?? handle.TargetMixer;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif ( near \u0026\u0026 RumbleSound is not null \u0026\u0026 Volume \u003E 0f )\r\n\t\t{\r\n\t\t\tvar rumble = Sound.Play( RumbleSound, position );\r\n\t\t\tif ( rumble.IsValid() )\r\n\t\t\t{\r\n\t\t\t\trumble.Volume *= Volume;\r\n\t\t\t\trumble.TargetMixer = GolfMixers.Shelling ?? rumble.TargetMixer;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvar falloff = 1f - Math.Clamp( distance / Math.Max( 1f, ShakeRange ), 0f, 1f );\r\n\t\tvar amplitude = (near ? NearShake : FarShake) * falloff;\r\n\t\tvar duration = near ? NearShakeTime : FarShakeTime;\r\n\t\tLog.Info( $\u0022TrenchShelling: {( near ? \u0022near\u0022 : \u0022far\u0022 )} shell at {distance:0} units, yaw {yaw:0}, shake {amplitude:0.00} for {duration:0.0} s\u0022 );\r\n\t\tif ( amplitude \u003C= 0.01f || duration \u003C= 0f ) return;\r\n\r\n\t\t// The shake lives on the one instance that applies it. A stronger shell replaces a weaker\r\n\t\t// shake in progress; a weaker one is dropped while a stronger one still runs.\r\n\t\tvar target = Current.IsValid() \u0026\u0026 Current.Scene == Scene ? Current : this;\r\n\t\ttarget.StartShake( amplitude, duration, near );\r\n\t}\r\n\r\n\tvoid StartShake( float amplitude, float duration, bool near )\r\n\t{\r\n\t\tif ( Remaining \u003E 0f \u0026\u0026 _amplitude * Envelope( Time.Now - _started ) \u003E amplitude ) return;\r\n\r\n\t\t_amplitude = amplitude;\r\n\t\t_duration = duration;\r\n\t\t_started = Time.Now;\r\n\t\t_near = near;\r\n\t\t_kickDirection = (Vector3.Random.WithZ( 0f ).Normal * 0.7f \u002B Vector3.Down * 0.7f).Normal;\r\n\t\t_shell\u002B\u002B;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003ESeconds of the current shake still to run, 0 when there is none.\u003C/summary\u003E\r\n\tfloat Remaining =\u003E _duration \u003C= 0f ? 0f : Math.Max( 0f, _duration - (Time.Now - _started) );\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Strength over the life of a shake, 0 to 1: a fast attack, then an exponential decay that is\r\n\t/// nearly gone by the end. Near shells hit at once and roll off; far ones swell in and fade.\r\n\t/// \u003C/summary\u003E\r\n\tfloat Envelope( float age )\r\n\t{\r\n\t\tif ( age \u003C 0f || _duration \u003C= 0f || age \u003E= _duration ) return 0f;\r\n\t\tvar attack = _near ? 0.04f : 0.2f;\r\n\t\tvar tau = _duration / 4f;\r\n\t\tif ( age \u003C attack ) return age / attack;\r\n\t\treturn MathF.Exp( -(age - attack) / tau );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EThree layered sines with unrelated rates: smooth, never repeating within a shake, no steps.\u003C/summary\u003E\r\n\tstatic float Noise( float t, float seed )\r\n\t{\r\n\t\treturn MathF.Sin( t \u002B seed ) * 0.55f \u002B MathF.Sin( t * 1.83f \u002B seed * 1.7f \u002B 0.9f ) * 0.3f \u002B MathF.Sin( t * 3.11f \u002B seed * 2.3f \u002B 2.1f ) * 0.15f;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EThe shake right now: a position offset in units and a tilt of the view.\u003C/summary\u003E\r\n\tbool CurrentOffset( out Vector3 offset, out Rotation tilt )\r\n\t{\r\n\t\toffset = Vector3.Zero;\r\n\t\ttilt = Rotation.Identity;\r\n\t\tif ( Remaining \u003C= 0f ) return false;\r\n\r\n\t\tvar age = Time.Now - _started;\r\n\t\tvar strength = _amplitude * Envelope( age );\r\n\t\tvar t = Time.Now * ShakeFrequency * MathF.PI * 2f;\r\n\r\n\t\toffset = new Vector3( Noise( t, 1f ), Noise( t, 2f ), Noise( t, 3f ) ) * strength;\r\n\r\n\t\t// The near shell\u0027s hard first knock, gone in a quarter of a second.\r\n\t\tif ( _near )\r\n\t\t\toffset \u002B= _kickDirection * _amplitude * MathF.Exp( -age / 0.12f );\r\n\r\n\t\tvar degrees = ShakeAngle * strength / Math.Max( 0.01f, NearShake );\r\n\t\ttilt = new Angles( Noise( t, 4f ) * degrees, Noise( t, 5f ) * degrees, Noise( t, 6f ) * degrees * 0.5f ).ToRotation();\r\n\t\treturn true;\r\n\t}\r\n\r\n\t// ------------------------------------------------------------ reaching the active camera\r\n\r\n\t// After the fly-over (100) and the free camera (200), so the offset lands on the finished view.\r\n\tint ICameraModifier.CameraOrder =\u003E 900;\r\n\r\n\tvoid ICameraModifier.ModifyCamera( CameraComponent camera, ref CameraView view )\r\n\t{\r\n\t\tif ( Current != this ) return;\r\n\t\tif ( !camera.IsValid() ) return;\r\n\r\n\t\t// Remember what the camera\u0027s own transform was when its view was composed.\r\n\t\t_composedCamera = camera;\r\n\t\t_composedPosition = camera.WorldPosition;\r\n\t\t_composedRotation = camera.WorldRotation;\r\n\t\t_composedThisTick = true;\r\n\r\n\t\tif ( !CurrentOffset( out var offset, out var tilt ) ) return;\r\n\t\tview.Position \u002B= offset;\r\n\t\tview.Rotation *= tilt;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// End of the tick, after every PreRender: if the active camera\u0027s transform was rewritten\r\n\t/// after its view was composed (the fly-over, the free camera, the menu orbit), the engine\r\n\t/// renders from that transform, so the shake goes into the transform too.\r\n\t/// \u003C/summary\u003E\r\n\tpublic void ApplyLate()\r\n\t{\r\n\t\tvar composed = _composedThisTick;\r\n\t\t_composedThisTick = false;\r\n\r\n\t\tvar camera = composed \u0026\u0026 _composedCamera.IsValid() ? _composedCamera : Scene.Camera;\r\n\t\tif ( !camera.IsValid() ) return;\r\n\t\tif ( !CurrentOffset( out var offset, out var tilt ) ) return;\r\n\r\n\t\tvar untouched = composed \u0026\u0026 camera == _composedCamera\r\n\t\t\t\u0026\u0026 camera.WorldPosition == _composedPosition \u0026\u0026 camera.WorldRotation == _composedRotation;\r\n\r\n\t\tif ( untouched )\r\n\t\t{\r\n\t\t\tif ( _loggedShell != _shell )\r\n\t\t\t{\r\n\t\t\t\t_loggedShell = _shell;\r\n\t\t\t\tLog.Info( $\u0022TrenchShelling: shake on camera \u0027{camera.GameObject.Name}\u0027 through its composed view\u0022 );\r\n\t\t\t}\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tcamera.WorldPosition \u002B= offset;\r\n\t\tcamera.WorldRotation *= tilt;\r\n\t\t_rawCamera = camera;\r\n\t\t_rawOffset = offset;\r\n\t\t_rawTilt = tilt;\r\n\t\t_rawApplied = true;\r\n\r\n\t\tif ( _loggedShell != _shell )\r\n\t\t{\r\n\t\t\t_loggedShell = _shell;\r\n\t\t\tLog.Info( $\u0022TrenchShelling: shake on camera \u0027{camera.GameObject.Name}\u0027 through its transform (rewritten after composition)\u0022 );\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EStart of the next tick: take last tick\u0027s offset back out of the transform, so nothing accumulates.\u003C/summary\u003E\r\n\tpublic void RestoreEarly()\r\n\t{\r\n\t\tif ( !_rawApplied ) return;\r\n\t\t_rawApplied = false;\r\n\t\tif ( !_rawCamera.IsValid() ) return;\r\n\r\n\t\t_rawCamera.WorldPosition -= _rawOffset;\r\n\t\t_rawCamera.WorldRotation *= _rawTilt.Inverse;\r\n\t}\r\n}\r\n\r\n/// \u003Csummary\u003E\r\n/// Runs the shelling shake at the two ends of the tick: takes last tick\u0027s transform offset out at\r\n/// StartUpdate, before anything else, and puts this tick\u0027s in at FinishUpdate, after every\r\n/// component\u0027s PreRender, which is the last point before the frame renders.\r\n/// \u003C/summary\u003E\r\npublic sealed class TrenchShellingSystem : GameObjectSystem\u003CTrenchShellingSystem\u003E\r\n{\r\n\tpublic TrenchShellingSystem( Scene scene ) : base( scene )\r\n\t{\r\n\t\tListen( Stage.StartUpdate, -1000, RestoreEarly, \u0022TrenchShelling.RestoreEarly\u0022 );\r\n\t\tListen( Stage.FinishUpdate, 1000, ApplyLate, \u0022TrenchShelling.ApplyLate\u0022 );\r\n\t}\r\n\r\n\tvoid RestoreEarly()\r\n\t{\r\n\t\tvar shelling = TrenchShelling.Current;\r\n\t\tif ( shelling.IsValid() \u0026\u0026 shelling.Scene == Scene ) shelling.RestoreEarly();\r\n\t}\r\n\r\n\tvoid ApplyLate()\r\n\t{\r\n\t\tvar shelling = TrenchShelling.Current;\r\n\t\tif ( shelling.IsValid() \u0026\u0026 shelling.Scene == Scene ) shelling.ApplyLate();\r\n\t}\r\n}\r\n"},{"Ident":"mrtn.golfkit","Path":"KitModelWall.cs","FileName":"KitModelWall.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":440545,"IsPrivate":false,"Code":"using Sandbox;\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\n\r\n/// \u003Csummary\u003E\r\n/// A wall made from a kit wall model (Blender-made, built along its X axis), stretched to a run and\r\n/// sheared up a slope: a parallelogram with vertical ends and its top and bottom parallel to the\r\n/// ground line, like the Kit Shape wall\u0027s Rise. The mesh is a copy of the model\u0027s vertices with\r\n/// the model\u0027s own materials, so a sloped wall looks like the level ones. Built on load and never\r\n/// saved (like Kit Shape), so the scene file only stores the four numbers.\r\n///\r\n/// Local frame: the run starts at the object\u0027s origin and goes along \u002BX for Length (horizontal),\r\n/// rising by Rise; Line Y is the model\u0027s local Y that sits on that line (its bounds centre for a\r\n/// wall centred on the line, a side face for a wall standing beside it). The Course Wall Builder\r\n/// (Holekit style) and the hole\u0027s Add bounds button make these. A model built along Y instead\r\n/// (the trench wall) is turned 90 degrees first when Source Along Y is on, so the run is along X\r\n/// whichever way the model was made; Line Y and the bounds the tools read are in that wall frame\r\n/// (\u003Csee cref=\u0022WallBounds\u0022/\u003E).\r\n/// \u003C/summary\u003E\r\n[Title( \u0022Kit Model Wall\u0022 ), Icon( \u0022fence\u0022 )]\r\npublic sealed class KitModelWall : Component, Component.ExecuteInEditor\r\n{\r\n\t/// \u003Csummary\u003EThe kit wall model to copy (models/kit/wall_100.vmdl).\u003C/summary\u003E\r\n\t[Property] public Model Source { get; set; }\r\n\r\n\t/// \u003Csummary\u003EHorizontal length of the run, in units.\u003C/summary\u003E\r\n\t[Property] public float Length { get; set; } = 100f;\r\n\r\n\t/// \u003Csummary\u003EHeight difference over the run: the \u002Bx end sits this much higher.\u003C/summary\u003E\r\n\t[Property] public float Rise { get; set; }\r\n\r\n\t/// \u003Csummary\u003EThe model\u0027s local Y that lies on the run line.\u003C/summary\u003E\r\n\t[Property, Title( \u0022Line Y\u0022 )] public float LineY { get; set; }\r\n\r\n\t[Property] public bool Collision { get; set; } = true;\r\n\r\n\t/// \u003Csummary\u003EOn for a wall model built along Y (the trench wall): the copy is turned a quarter so the run is along X.\u003C/summary\u003E\r\n\t[Property, Title( \u0022Source Along Y\u0022 )] public bool SourceAlongY { get; set; }\r\n\r\n\t/// \u003Csummary\u003EMaterial drawn instead of the model\u0027s own (the kit wall material); empty keeps the model\u0027s.\u003C/summary\u003E\r\n\t[Property] public Material Material { get; set; }\r\n\r\n\t/// \u003Csummary\u003EWorld units per texture repeat. The mesh gets box-projected texture coordinates at its stretched size, so the texture repeats along the run instead of stretching with it.\u003C/summary\u003E\r\n\t[Property, Title( \u0022Texture Repeat\u0022 )] public float TextureRepeat { get; set; } = 100f;\r\n\r\n\tModel _model;\r\n\tModel _builtSource;\r\n\tMaterial _builtMaterial;\r\n\tfloat _builtLength, _builtRise, _builtLineY, _builtRepeat;\r\n\tbool _builtCollision, _builtAlongY;\r\n\r\n\tprotected override void OnEnabled() =\u003E Rebuild();\r\n\r\n\tprotected override void OnUpdate()\r\n\t{\r\n\t\tif ( _model is null || _builtSource != Source || _builtLength != Length || _builtRise != Rise || _builtLineY != LineY || _builtCollision != Collision || _builtMaterial != Material || _builtRepeat != TextureRepeat || _builtAlongY != SourceAlongY )\r\n\t\t\tRebuild();\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EHow many kit model walls have been rebuilt since load (see golf_perf).\u003C/summary\u003E\r\n\tpublic static int RebuildCount;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The source\u0027s draw calls as index ranges with their material, in the order of its index\r\n\t/// buffer; one range over everything in the model\u0027s first material when the draw call data\r\n\t/// does not line up with the index buffer (a sliced vertex buffer, a LOD).\r\n\t/// \u003C/summary\u003E\r\n\tstatic List\u003C(int start, int count, Material material)\u003E DrawCalls( Model model, int indexCount )\r\n\t{\r\n\t\tvar result = new List\u003C(int, int, Material)\u003E();\r\n\t\tvar info = model.MeshInfo;\r\n\t\tif ( info.Meshes is not null )\r\n\t\t{\r\n\t\t\tforeach ( var mesh in info.Meshes )\r\n\t\t\t{\r\n\t\t\t\tif ( (mesh.LodMask \u0026 1) == 0 || mesh.DrawCalls is null ) continue;\r\n\t\t\t\tforeach ( var call in mesh.DrawCalls )\r\n\t\t\t\t{\r\n\t\t\t\t\tif ( call.BaseVertex != 0 || call.StartIndex \u003C 0 || call.Indices \u003C= 0 || call.StartIndex \u002B call.Indices \u003E indexCount ) { result.Clear(); goto fallback; }\r\n\t\t\t\t\tresult.Add( (call.StartIndex, call.Indices, call.Material) );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif ( result.Count \u003E 0 \u0026\u0026 result.Sum( r =\u003E r.Item2 ) == indexCount ) return result;\r\n\tfallback:\r\n\t\tresult.Clear();\r\n\t\tresult.Add( (0, indexCount, model.Materials.FirstOrDefault()) );\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EA model-space direction or point in the wall frame (length along X): a quarter turn for a model built along Y.\u003C/summary\u003E\r\n\tstatic Vector3 ToWallFrame( Vector3 v, bool alongY ) =\u003E alongY ? new Vector3( v.y, -v.x, v.z ) : v;\r\n\r\n\t/// \u003Csummary\u003EThe model\u0027s bounds in the wall frame (length along X), what the tools read for Line Y and the wall\u0027s size; alongY as the piece\u0027s Source Along Y.\u003C/summary\u003E\r\n\tpublic static BBox WallBounds( Model model, bool alongY )\r\n\t{\r\n\t\tvar b = model.Bounds;\r\n\t\tif ( !alongY ) return b;\r\n\t\treturn new BBox( new Vector3( b.Mins.y, -b.Maxs.x, b.Mins.z ), new Vector3( b.Maxs.y, -b.Mins.x, b.Maxs.z ) );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EThe model\u0027s vertex positions in the wall frame (length along X).\u003C/summary\u003E\r\n\tpublic static IEnumerable\u003CVector3\u003E WallPositions( Model model, bool alongY )\r\n\t{\r\n\t\tvar vertices = model?.GetVertices();\r\n\t\tif ( vertices is null ) yield break;\r\n\t\tforeach ( var v in vertices ) yield return ToWallFrame( v.Position, alongY );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EBuilds the sheared copy and puts it on this object\u0027s renderer and collider.\u003C/summary\u003E\r\n\tpublic void Rebuild()\r\n\t{\r\n\t\tRebuildCount\u002B\u002B;\r\n\t\t_builtSource = Source;\r\n\t\t_builtLength = Length;\r\n\t\t_builtRise = Rise;\r\n\t\t_builtLineY = LineY;\r\n\t\t_builtCollision = Collision;\r\n\t\t_builtMaterial = Material;\r\n\t\t_builtRepeat = TextureRepeat;\r\n\t\t_builtAlongY = SourceAlongY;\r\n\r\n\t\tif ( Source is null || Source.IsError ) return;\r\n\t\tvar sourceVertices = Source.GetVertices();\r\n\t\tvar sourceIndices = Source.GetIndices();\r\n\t\tif ( sourceVertices is null || sourceIndices is null || sourceVertices.Length == 0 || sourceIndices.Length \u003C 3 ) return;\r\n\r\n\t\tvar alongY = SourceAlongY;\r\n\t\tvar bounds = WallBounds( Source, alongY );\r\n\t\tvar length = MathF.Max( 1f, Length );\r\n\t\tvar stretch = length / MathF.Max( 1f, bounds.Size.x );\r\n\t\tvar slope = Rise / length;\r\n\r\n\t\t// Shear: x\u0027 = stretch * (x - minX), z\u0027 = (z - minZ) \u002B slope * x\u0027. Normals take the inverse\r\n\t\t// transpose, tangents the matrix itself, both renormalised.\r\n\t\tvar vertices = new List\u003CSimpleVertex\u003E( sourceVertices.Length );\r\n\t\tvar positions = new List\u003CVector3\u003E( sourceVertices.Length );\r\n\t\tvar repeat = MathF.Max( 1f, TextureRepeat );\r\n\t\tforeach ( var v in sourceVertices )\r\n\t\t{\r\n\t\t\tvar position = ToWallFrame( v.Position, alongY );\r\n\t\t\tvar normal = ToWallFrame( v.Normal, alongY );\r\n\t\t\tvar tangent = ToWallFrame( new Vector3( v.Tangent.x, v.Tangent.y, v.Tangent.z ), alongY );\r\n\t\t\tvar x = (position.x - bounds.Mins.x) * stretch;\r\n\t\t\tvar p = new Vector3( x, position.y - LineY, position.z - bounds.Mins.z \u002B slope * x );\r\n\t\t\tvar n = new Vector3( normal.x / stretch - slope * normal.z, normal.y, normal.z ).Normal;\r\n\t\t\tvar t = new Vector3( stretch * tangent.x, tangent.y, slope * stretch * tangent.x \u002B tangent.z ).Normal;\r\n\t\t\t// Box projection on the stretched mesh: the texture repeats every TextureRepeat units\r\n\t\t\t// along the run (and up the wall) however long the wall is.\r\n\t\t\tvar ax = MathF.Abs( n.x ); var ay = MathF.Abs( n.y ); var az = MathF.Abs( n.z );\r\n\t\t\tvar uv = az \u003E= ax \u0026\u0026 az \u003E= ay ? new Vector2( p.x, p.y ) : ax \u003E= ay ? new Vector2( p.y, p.z ) : new Vector2( p.x, p.z );\r\n\t\t\tvertices.Add( new SimpleVertex( p, n, t, uv / repeat ) );\r\n\t\t\tpositions.Add( p );\r\n\t\t}\r\n\t\tvar indices = sourceIndices.Select( i =\u003E (int)i ).ToList();\r\n\r\n\t\t// One mesh per draw call of the source, so a wall with several materials (the hedge\u0027s pot,\r\n\t\t// soil and hedge) keeps them; every mesh shares the vertex list and takes its own indices.\r\n\t\tvar bounds3 = BBox.FromPoints( positions );\r\n\t\tvar builder = Model.Builder;\r\n\t\tforeach ( var (start, count, drawMaterial) in DrawCalls( Source, indices.Count ) )\r\n\t\t{\r\n\t\t\tvar mesh = new Mesh( drawMaterial ?? Material.Load( \u0022prefabs/holekit/kit.vmat\u0022 ) );\r\n\t\t\tmesh.CreateVertexBuffer( vertices.Count, vertices );\r\n\t\t\tmesh.CreateIndexBuffer( count, indices.GetRange( start, count ) );\r\n\t\t\tmesh.Bounds = bounds3;\r\n\t\t\tbuilder = builder.AddMesh( mesh );\r\n\t\t}\r\n\t\tif ( Collision )\r\n\t\t{\r\n\t\t\t// Physics gets a welded copy so the ball never meets an edge between a face\u0027s triangles.\r\n\t\t\tvar welded = new List\u003CVector3\u003E();\r\n\t\t\tvar weldedIndices = new List\u003Cint\u003E();\r\n\t\t\tvar lookup = new Dictionary\u003C(int, int, int), int\u003E();\r\n\t\t\tforeach ( var i in indices )\r\n\t\t\t{\r\n\t\t\t\tvar p = positions[i];\r\n\t\t\t\tvar key = ((int)MathF.Round( p.x * 16f ), (int)MathF.Round( p.y * 16f ), (int)MathF.Round( p.z * 16f ));\r\n\t\t\t\tif ( !lookup.TryGetValue( key, out var w ) )\r\n\t\t\t\t{\r\n\t\t\t\t\tw = welded.Count;\r\n\t\t\t\t\twelded.Add( p );\r\n\t\t\t\t\tlookup[key] = w;\r\n\t\t\t\t}\r\n\t\t\t\tweldedIndices.Add( w );\r\n\t\t\t}\r\n\t\t\tbuilder.AddCollisionMesh( welded, weldedIndices );\r\n\t\t}\r\n\t\t_model = builder.Create();\r\n\r\n\t\t// One renderer and one collider, driven from here and never saved (rebuilt on load).\r\n\t\tvar renderers = GameObject.GetComponents\u003CModelRenderer\u003E( true ).ToList();\r\n\t\tvar renderer = renderers.FirstOrDefault() ?? GameObject.AddComponent\u003CModelRenderer\u003E();\r\n\t\tforeach ( var spare in renderers.Skip( 1 ) ) spare.Destroy();\r\n\t\trenderer.Flags |= ComponentFlags.NotSaved;\r\n\t\trenderer.Model = _model;\r\n\t\trenderer.MaterialOverride = Material;\r\n\r\n\t\tvar colliders = GameObject.GetComponents\u003CModelCollider\u003E( true ).ToList();\r\n\t\tvar collider = colliders.FirstOrDefault();\r\n\t\tforeach ( var spare in colliders.Skip( 1 ) ) spare.Destroy();\r\n\t\tif ( Collision )\r\n\t\t{\r\n\t\t\tcollider ??= GameObject.AddComponent\u003CModelCollider\u003E();\r\n\t\t\tcollider.Flags |= ComponentFlags.NotSaved;\r\n\t\t\tcollider.Model = _model;\r\n\t\t\tcollider.Static = true;\r\n\t\t\tcollider.Surface = Surface.FindByName( GolfHoleCollision.SurfaceName ) ?? collider.Surface;\r\n\t\t\tcollider.Enabled = true;\r\n\t\t}\r\n\t\telse if ( collider.IsValid() )\r\n\t\t{\r\n\t\t\tcollider.Flags |= ComponentFlags.NotSaved;\r\n\t\t\tcollider.Enabled = false;\r\n\t\t}\r\n\r\n\t\t// Under a hole the hole\u0027s welded collider takes this piece in (and switches the collider off).\r\n\t\tGameObject.GetComponentInParent\u003CGolfHoleCollision\u003E( true )?.MarkDirty();\r\n\t}\r\n}\r\n"},{"Ident":"mrtn.golfkit","Path":"MudWaterRipple.cs","FileName":"MudWaterRipple.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":440545,"IsPrivate":false,"Code":"using Sandbox;\r\nusing System;\r\nusing System.Linq;\r\n\r\n/// \u003Csummary\u003E\r\n/// Ripples on a mud water plane. Every Interval (a random time between the min and max) a\r\n/// shockwave starts at a random point on the plane: a flat overlay quad carrying a ring texture\r\n/// (three concentric rings in its alpha and normal map, from Tools/make_mud_water.py) is placed on\r\n/// the surface, scaled up at Ring Speed until it reaches Max Radius, and fades to nothing on the\r\n/// way, about two seconds at the defaults. The overlay\u0027s fade is the renderer\u0027s Tint alpha; the\r\n/// complex shader has no attribute to drive a ripple inside the water material itself, so the\r\n/// overlay is the cheap route in this build. Nothing is networked, every machine ripples on its\r\n/// own; a small pool of overlays, no allocation per ripple. Put it on the object that renders the\r\n/// water plane: the plane\u0027s extent is that renderer\u0027s model bounds.\r\n///\r\n/// Between ripples the water also sways in place: the plane\u0027s material is copied at start and the\r\n/// copy\u0027s texture offset is moved round a tiny circle every frame (the complex shader has no\r\n/// wobble or animated normal option, only a straight scroll, so this is done from code). Nothing\r\n/// flows, the texture only drifts back and forth by a fraction of a texel.\r\n/// \u003C/summary\u003E\r\n[Title( \u0022Mud Water Ripple\u0022 ), Category( \u0022Golf\u0022 ), Icon( \u0022water\u0022 )]\r\npublic sealed class MudWaterRipple : Component\r\n{\r\n\t/// \u003Csummary\u003EShortest wait between ripples, seconds.\u003C/summary\u003E\r\n\t[Property, Range( 0.5f, 60f ), Title( \u0022Interval Min\u0022 )]\r\n\tpublic float IntervalMin { get; set; } = 5f;\r\n\r\n\t/// \u003Csummary\u003ELongest wait between ripples, seconds.\u003C/summary\u003E\r\n\t[Property, Range( 0.5f, 60f ), Title( \u0022Interval Max\u0022 )]\r\n\tpublic float IntervalMax { get; set; } = 15f;\r\n\r\n\t/// \u003Csummary\u003EHow fast the rings spread, units per second.\u003C/summary\u003E\r\n\t[Property, Range( 10f, 1000f ), Title( \u0022Ring Speed\u0022 )]\r\n\tpublic float RingSpeed { get; set; } = 100f;\r\n\r\n\t/// \u003Csummary\u003EHow visible the rings are when they start, 0 to 1.\u003C/summary\u003E\r\n\t[Property, Range( 0f, 1f ), Title( \u0022Ring Strength\u0022 )]\r\n\tpublic float RingStrength { get; set; } = 0.8f;\r\n\r\n\t/// \u003Csummary\u003ERadius the rings reach before they are gone, units.\u003C/summary\u003E\r\n\t[Property, Range( 20f, 2000f ), Title( \u0022Max Radius\u0022 )]\r\n\tpublic float MaxRadius { get; set; } = 200f;\r\n\r\n\t/// \u003Csummary\u003ERipples in flight at once; the pool size.\u003C/summary\u003E\r\n\t[Property, Range( 1, 8 )]\r\n\tpublic int MaxRipples { get; set; } = 3;\r\n\r\n\t/// \u003Csummary\u003ESway the water texture in place between ripples.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Wobble\u0022 )]\r\n\tpublic bool Wobble { get; set; } = true;\r\n\r\n\t/// \u003Csummary\u003EHow far the texture sways, in UV units; 0.002 is a fraction of a texel.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Wobble\u0022 ), Range( 0f, 0.02f ), Title( \u0022Wobble Radius\u0022 )]\r\n\tpublic float WobbleRadius { get; set; } = 0.002f;\r\n\r\n\t/// \u003Csummary\u003ESeconds for one full sway round the circle.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Wobble\u0022 ), Range( 1f, 30f ), Title( \u0022Wobble Period\u0022 )]\r\n\tpublic float WobblePeriod { get; set; } = 6f;\r\n\r\n\tconst string QuadModel = \u0022models/mud_water/ripple_quad.vmdl\u0022;\r\n\tconst string RingMaterial = \u0022textures/mud_water/ripple_ring.vmat\u0022;\r\n\tconst float Lift = 0.75f;   // the overlay floats this far above the water so it never z-fights\r\n\r\n\tModelRenderer[] _overlays = Array.Empty\u003CModelRenderer\u003E();\r\n\tfloat[] _born = Array.Empty\u003Cfloat\u003E();\r\n\tint _next;\r\n\tfloat _nextAt;\r\n\tModelRenderer _plane;\r\n\tMaterial _planeMaterial;   // what the plane had before the wobble copy, put back on disable\r\n\tMaterial _wobble;\r\n\r\n\tprotected override void OnStart()\r\n\t{\r\n\t\tvar model = Model.Load( QuadModel );\r\n\t\tvar material = Material.Load( RingMaterial );\r\n\t\tif ( model is null || material is null )\r\n\t\t{\r\n\t\t\tLog.Warning( $\u0022MudWaterRipple: missing {QuadModel} or {RingMaterial}\u0022 );\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tvar count = Math.Clamp( MaxRipples, 1, 8 );\r\n\t\t_overlays = new ModelRenderer[count];\r\n\t\t_born = new float[count];\r\n\t\tfor ( var i = 0; i \u003C count; i\u002B\u002B )\r\n\t\t{\r\n\t\t\tvar go = new GameObject( GameObject, false, $\u0022ripple {i}\u0022 );\r\n\t\t\tgo.Flags |= GameObjectFlags.NotSaved | GameObjectFlags.NotNetworked | GameObjectFlags.Hidden;\r\n\t\t\tvar renderer = go.AddComponent\u003CModelRenderer\u003E();\r\n\t\t\trenderer.Model = model;\r\n\t\t\trenderer.MaterialOverride = material;\r\n\t\t\t_overlays[i] = renderer;\r\n\t\t}\r\n\r\n\t\t_nextAt = Time.Now \u002B Wait();\r\n\r\n\t\t// The wobble works on a private copy of the plane\u0027s material, so the asset itself is untouched.\r\n\t\t_plane = GetComponent\u003CModelRenderer\u003E();\r\n\t\tvar source = _plane?.MaterialOverride ?? _plane?.Model?.Materials.FirstOrDefault();\r\n\t\tif ( Wobble \u0026\u0026 source is not null )\r\n\t\t{\r\n\t\t\t_planeMaterial = _plane.MaterialOverride;\r\n\t\t\t_wobble = source.CreateCopy( \u0022mud water wobble\u0022 );\r\n\t\t\t_plane.MaterialOverride = _wobble;\r\n\t\t}\r\n\t}\r\n\r\n\tprotected override void OnDisabled()\r\n\t{\r\n\t\tforeach ( var overlay in _overlays )\r\n\t\t\tif ( overlay.IsValid() ) overlay.GameObject.Enabled = false;\r\n\r\n\t\tif ( _wobble is not null \u0026\u0026 _plane.IsValid() \u0026\u0026 _plane.MaterialOverride == _wobble )\r\n\t\t\t_plane.MaterialOverride = _planeMaterial;\r\n\t\t_wobble = null;\r\n\t}\r\n\r\n\tprotected override void OnUpdate()\r\n\t{\r\n\t\tif ( Scene.IsEditor || _overlays.Length == 0 ) return;\r\n\r\n\t\tvar now = Time.Now;\r\n\r\n\t\tif ( _wobble is not null )\r\n\t\t{\r\n\t\t\tvar angle = now / Math.Max( 0.1f, WobblePeriod ) * MathF.PI * 2f;\r\n\t\t\tvar radius = Wobble ? WobbleRadius : 0f;\r\n\t\t\t_wobble.Set( \u0022g_vTexCoordOffset\u0022, new Vector2( MathF.Cos( angle ), MathF.Sin( angle ) ) * radius );\r\n\t\t}\r\n\t\tvar life = MaxRadius / Math.Max( 1f, RingSpeed );\r\n\r\n\t\tfor ( var i = 0; i \u003C _overlays.Length; i\u002B\u002B )\r\n\t\t{\r\n\t\t\tvar overlay = _overlays[i];\r\n\t\t\tif ( !overlay.IsValid() || !overlay.GameObject.Enabled ) continue;\r\n\r\n\t\t\tvar age = now - _born[i];\r\n\t\t\tif ( age \u003E= life )\r\n\t\t\t{\r\n\t\t\t\toverlay.GameObject.Enabled = false;\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\tvar t = age / life;\r\n\t\t\tvar radius = Math.Max( 1f, RingSpeed * age );\r\n\t\t\toverlay.GameObject.WorldScale = new Vector3( radius, radius, 1f );\r\n\t\t\toverlay.Tint = Color.White.WithAlpha( RingStrength * (1f - t) * (1f - t) );\r\n\t\t}\r\n\r\n\t\tif ( now \u003C _nextAt ) return;\r\n\t\t_nextAt = now \u002B Wait();\r\n\t\tSpawn();\r\n\t}\r\n\r\n\tfloat Wait()\r\n\t{\r\n\t\tvar min = Math.Min( IntervalMin, IntervalMax );\r\n\t\tvar max = Math.Max( IntervalMin, IntervalMax );\r\n\t\treturn Game.Random.Float( min, max );\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EA ripple at a random point on the plane\u0027s top surface.\u003C/summary\u003E\r\n\tvoid Spawn()\r\n\t{\r\n\t\tvar i = _next;\r\n\t\t_next = (_next \u002B 1) % _overlays.Length;\r\n\t\tvar overlay = _overlays[i];\r\n\t\tif ( !overlay.IsValid() ) return;\r\n\r\n\t\tvar plane = GetComponent\u003CModelRenderer\u003E();\r\n\t\tvar bounds = plane?.Model?.Bounds ?? new BBox( new Vector3( -100f, -100f, 0f ), new Vector3( 100f, 100f, 0f ) );\r\n\t\tvar local = new Vector3(\r\n\t\t\tGame.Random.Float( bounds.Mins.x, bounds.Maxs.x ),\r\n\t\t\tGame.Random.Float( bounds.Mins.y, bounds.Maxs.y ),\r\n\t\t\tbounds.Maxs.z );\r\n\t\tvar position = WorldTransform.PointToWorld( local ) \u002B Vector3.Up * Lift;\r\n\r\n\t\toverlay.GameObject.WorldPosition = position;\r\n\t\toverlay.GameObject.WorldRotation = Rotation.FromYaw( Game.Random.Float( 0f, 360f ) );\r\n\t\toverlay.GameObject.WorldScale = new Vector3( 1f, 1f, 1f );\r\n\t\toverlay.Tint = Color.White.WithAlpha( RingStrength );\r\n\t\t_born[i] = Time.Now;\r\n\t\toverlay.GameObject.Enabled = true;\r\n\t}\r\n}\r\n"},{"Ident":"mrtn.golfkit","Path":".obj/__compiler_extra.cs","FileName":"__compiler_extra.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":440545,"IsPrivate":false,"Code":"global using static Sandbox.Internal.GlobalGameNamespace;\r\nglobal using Microsoft.AspNetCore.Components;\r\nglobal using Microsoft.AspNetCore.Components.Rendering;\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022AddonTitle\u0022, \u0022Golf With Your Guns Kit\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022AddonIdent\u0022, \u0022golfkit\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022OrgIdent\u0022, \u0022mrtn\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022Ident\u0022, \u0022mrtn.golfkit\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022EngineVersion\u0022, \u002232\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022EngineMinorVersion\u0022, \u00221\u0022 )]\r\n\r\n[assembly: System.Runtime.Versioning.TargetFramework( \u0022.NETCoreApp,Version=v9.0\u0022, FrameworkDisplayName = \u0022.NET 9.0\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022CompileTime\u0022, \u00222026-10-28T22:14:35.7988931Z\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyVersion(\u00220.0.110.0\u0022)]\r\n[assembly: global::System.Reflection.AssemblyFileVersion(\u00220.0.110.0\u0022)]"},{"Ident":"mrtn.golfkit","Path":"Code/GolfPreviewCamera.cs","FileName":"GolfPreviewCamera.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":440545,"IsPrivate":false,"Code":"using Sandbox;\nusing System.Linq;\n\n/// \u003Csummary\u003E\n/// The camera a course scene plays through in the mapper\u0027s own project, so Play shows the course\n/// instead of a black screen. Sits on the course template\u0027s \u0022Preview Camera\u0022 object with a Camera\n/// Component and the on-screen note (\u003Csee cref=\u0022GolfPreviewNote\u0022/\u003E) that gameplay is tested from\n/// the game\u0027s course screen. The game switches the whole object off when it loads the course, and\n/// the kit\u0027s Set up course leaves it alone; every other camera a course brings along is removed.\n/// \u003C/summary\u003E\n[Title( \u0022Golf Preview Camera\u0022 ), Icon( \u0022preview\u0022 ), Category( \u0022Golf\u0022 )]\npublic sealed class GolfPreviewCamera : Component\n{\n\t/// \u003Csummary\u003EWith a Golf Menu Camera in the scene, the preview looks from there: the same view the game\u0027s menus show.\u003C/summary\u003E\n\t[Property, Title( \u0022Follow Menu Camera\u0022 )]\n\tpublic bool FollowMenuCamera { get; set; } = true;\n\n\tprotected override void OnStart()\n\t{\n\t\tif ( !FollowMenuCamera ) return;\n\t\tvar menu = Scene.GetAllComponents\u003CGolfMenuCamera\u003E().FirstOrDefault();\n\t\tif ( !menu.IsValid() ) return;\n\t\tWorldTransform = menu.ViewAt( 0f );\n\t\tvar camera = GetComponent\u003CCameraComponent\u003E( true );\n\t\tif ( camera.IsValid() ) camera.FieldOfView = menu.FieldOfView;\n\t}\n}\n"},{"Ident":"mrtn.golfkit","Path":"Code/TrenchFire.cs","FileName":"TrenchFire.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":440545,"IsPrivate":false,"Code":"using Sandbox;\r\nusing System;\r\n\r\n/// \u003Csummary\u003E\r\n/// Decorative machine-gun fire for the trench map: bursts of glowing tracers fly from a random\r\n/// point on the Start line to a random point on the End line, with a muzzle flash where they leave\r\n/// and a dust puff where they land, and a distant, softened shot sound for every round. Purely a\r\n/// show: nothing is traced against players or balls, nothing takes damage, nothing is networked.\r\n/// Every machine runs its own with its own random timing.\r\n///\r\n/// The two lines are each two child objects (Start A/B, End A/B) that you move with the normal\r\n/// move gizmo; they are created the first time the component is seen in the editor if missing.\r\n/// The lines and the handles are drawn as gizmos. The component\u0027s own Enabled checkbox turns the\r\n/// gun off. Small pool of tracers and flash lights, nothing allocated per shot but the engine\u0027s\r\n/// own sound handle and the surface\u0027s impact particle.\r\n/// \u003C/summary\u003E\r\n[Title( \u0022Trench Fire\u0022 ), Category( \u0022Golf\u0022 ), Icon( \u0022whatshot\u0022 )]\r\npublic sealed class TrenchFire : Component\r\n{\r\n\t/// \u003Csummary\u003EOne end of the line the tracers leave from.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Lines\u0022 ), Title( \u0022Start A\u0022 )]\r\n\tpublic GameObject StartA { get; set; }\r\n\r\n\t/// \u003Csummary\u003EThe other end of the line the tracers leave from.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Lines\u0022 ), Title( \u0022Start B\u0022 )]\r\n\tpublic GameObject StartB { get; set; }\r\n\r\n\t/// \u003Csummary\u003EOne end of the line the tracers land on.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Lines\u0022 ), Title( \u0022End A\u0022 )]\r\n\tpublic GameObject EndA { get; set; }\r\n\r\n\t/// \u003Csummary\u003EThe other end of the line the tracers land on.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Lines\u0022 ), Title( \u0022End B\u0022 )]\r\n\tpublic GameObject EndB { get; set; }\r\n\r\n\t/// \u003Csummary\u003ERandom scatter around the landing point, in units.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Lines\u0022 ), Range( 0f, 300f )]\r\n\tpublic float Spread { get; set; } = 40f;\r\n\r\n\t/// \u003Csummary\u003EBursts per minute.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Timing\u0022 ), Range( 0.1f, 60f ), Title( \u0022Rate (bursts per minute)\u0022 )]\r\n\tpublic float Rate { get; set; } = 6f;\r\n\r\n\t/// \u003Csummary\u003EFewest shots in a burst.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Timing\u0022 ), Range( 1, 60 ), Title( \u0022Burst Length Min\u0022 )]\r\n\tpublic int BurstMin { get; set; } = 8;\r\n\r\n\t/// \u003Csummary\u003EMost shots in a burst.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Timing\u0022 ), Range( 1, 60 ), Title( \u0022Burst Length Max\u0022 )]\r\n\tpublic int BurstMax { get; set; } = 15;\r\n\r\n\t/// \u003Csummary\u003EShots per second inside a burst.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Timing\u0022 ), Range( 1f, 30f )]\r\n\tpublic float ShotsPerSecond { get; set; } = 12f;\r\n\r\n\t/// \u003Csummary\u003EHow much the pause between bursts varies, 0 for a metronome, 1 for anything from no pause to double.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Timing\u0022 ), Range( 0f, 1f )]\r\n\tpublic float PauseVariance { get; set; } = 0.5f;\r\n\r\n\t/// \u003Csummary\u003EHow fast a tracer flies, units per second.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Tracer\u0022 ), Range( 500f, 20000f )]\r\n\tpublic float TracerSpeed { get; set; } = 6000f;\r\n\r\n\t/// \u003Csummary\u003EColour of the tracer streak, the flash and its light.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Tracer\u0022 )]\r\n\tpublic Color TracerColour { get; set; } = new Color( 1f, 0.55f, 0.15f );\r\n\r\n\t/// \u003Csummary\u003ELength of the streak, in units.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Tracer\u0022 ), Range( 10f, 1000f )]\r\n\tpublic float TracerLength { get; set; } = 160f;\r\n\r\n\t/// \u003Csummary\u003EWidth of the streak at its bright end, in units.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Tracer\u0022 ), Range( 0.5f, 10f )]\r\n\tpublic float TracerWidth { get; set; } = 2.5f;\r\n\r\n\t/// \u003Csummary\u003EHow much brighter than the colour the streak glows.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Tracer\u0022 ), Range( 1f, 8f )]\r\n\tpublic float Glow { get; set; } = 3f;\r\n\r\n\t/// \u003Csummary\u003EA short flash of light at the start point for every shot.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Effects\u0022 )]\r\n\tpublic bool MuzzleFlash { get; set; } = true;\r\n\r\n\t/// \u003Csummary\u003EThe surface\u0027s bullet impact particle where a tracer lands.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Effects\u0022 )]\r\n\tpublic bool DustPuff { get; set; } = true;\r\n\r\n\t/// \u003Csummary\u003EThe distant shot, played at the start point for every round. Empty uses sounds/trench_fire.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Sound\u0022 )]\r\n\tpublic SoundEvent ShotSound { get; set; }\r\n\r\n\t/// \u003Csummary\u003EVolume of the shots, 0 to 1.\u003C/summary\u003E\r\n\t[Property, Group( \u0022Sound\u0022 ), Range( 0f, 1f )]\r\n\tpublic float Volume { get; set; } = 0.35f;\r\n\r\n\tconst string DefaultSound = \u0022sounds/trench_fire.sound\u0022;\r\n\tconst float FlashSeconds = 0.05f;\r\n\tconst float FlashRadius = 160f;\r\n\r\n\tstruct Landing\r\n\t{\r\n\t\tpublic float At;        // Time.Now the tracer arrives; 0 for none pending\r\n\t\tpublic Vector3 Position;\r\n\t\tpublic Vector3 Normal;\r\n\t\tpublic Surface Surface;\r\n\t}\r\n\r\n\tTracerEffect[] _tracers = Array.Empty\u003CTracerEffect\u003E();\r\n\tLanding[] _landings = Array.Empty\u003CLanding\u003E();\r\n\tPointLight[] _flashes = Array.Empty\u003CPointLight\u003E();\r\n\tfloat[] _flashOff = Array.Empty\u003Cfloat\u003E();\r\n\tint _nextTracer;\r\n\tint _nextFlash;\r\n\tSurface _defaultSurface;\r\n\tColor _builtColour;\r\n\tfloat _builtWidth;\r\n\r\n\tfloat _nextBurstAt;\r\n\tfloat _nextShotAt;\r\n\tint _shotsLeft;\r\n\r\n\tprotected override void OnStart()\r\n\t{\r\n\t\tEnsureHandles();\r\n\t\tShotSound ??= ResourceLibrary.Get\u003CSoundEvent\u003E( DefaultSound );\r\n\t\t_defaultSurface = Surface.FindByName( \u0022default\u0022 );\r\n\t\tBuildPool();\r\n\t\t_nextBurstAt = Time.Now \u002B NextPause() * Game.Random.Float( 0f, 1f );\r\n\t}\r\n\r\n\tprotected override void OnDisabled()\r\n\t{\r\n\t\t_shotsLeft = 0;\r\n\t\tfor ( var i = 0; i \u003C _landings.Length; i\u002B\u002B ) _landings[i].At = 0f;\r\n\t\tforeach ( var flash in _flashes ) if ( flash.IsValid() ) flash.Enabled = false;\r\n\t}\r\n\r\n\tprotected override void OnUpdate()\r\n\t{\r\n\t\tif ( Scene.IsEditor ) return;\r\n\t\tif ( _tracers.Length == 0 ) return;\r\n\r\n\t\tvar now = Time.Now;\r\n\r\n\t\t// Flashes go out, landings puff.\r\n\t\tfor ( var i = 0; i \u003C _flashes.Length; i\u002B\u002B )\r\n\t\t{\r\n\t\t\tif ( _flashOff[i] \u003E 0f \u0026\u0026 now \u003E= _flashOff[i] )\r\n\t\t\t{\r\n\t\t\t\t_flashOff[i] = 0f;\r\n\t\t\t\tif ( _flashes[i].IsValid() ) _flashes[i].Enabled = false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfor ( var i = 0; i \u003C _landings.Length; i\u002B\u002B )\r\n\t\t{\r\n\t\t\tif ( _landings[i].At \u003C= 0f || now \u003C _landings[i].At ) continue;\r\n\t\t\t_landings[i].At = 0f;\r\n\t\t\tif ( DustPuff )\r\n\t\t\t\tBaseCombatWeapon.ImpactPrefab( null, _landings[i].Surface, _landings[i].Position, _landings[i].Normal );\r\n\t\t}\r\n\r\n\t\t// Bursts.\r\n\t\tif ( _shotsLeft \u003C= 0 )\r\n\t\t{\r\n\t\t\tif ( now \u003C _nextBurstAt ) return;\r\n\t\t\t_shotsLeft = Game.Random.Int( Math.Min( BurstMin, BurstMax ), Math.Max( BurstMin, BurstMax ) );\r\n\t\t\t_nextShotAt = now;\r\n\t\t\t_nextBurstAt = now \u002B NextPause();\r\n\t\t}\r\n\r\n\t\tif ( now \u003C _nextShotAt ) return;\r\n\t\t_nextShotAt = now \u002B 1f / Math.Max( 1f, ShotsPerSecond );\r\n\t\t_shotsLeft--;\r\n\t\tFire();\r\n\t}\r\n\r\n\tfloat NextPause()\r\n\t{\r\n\t\tvar mean = 60f / Math.Max( 0.1f, Rate );\r\n\t\treturn mean * (1f \u002B Game.Random.Float( -PauseVariance, PauseVariance ));\r\n\t}\r\n\r\n\tvoid Fire()\r\n\t{\r\n\t\tif ( !StartA.IsValid() || !StartB.IsValid() || !EndA.IsValid() || !EndB.IsValid() ) return;\r\n\r\n\t\tvar start = Vector3.Lerp( StartA.WorldPosition, StartB.WorldPosition, Game.Random.Float( 0f, 1f ) );\r\n\t\tvar end = Vector3.Lerp( EndA.WorldPosition, EndB.WorldPosition, Game.Random.Float( 0f, 1f ) )\r\n\t\t\t\u002B Vector3.Random * Spread;\r\n\r\n\t\t// Where it lands: the ground near the end point, for the puff\u0027s surface and facing.\r\n\t\tvar landing = new Landing { Position = end, Normal = Vector3.Up, Surface = _defaultSurface };\r\n\t\tvar trace = Scene.Trace.Ray( end \u002B Vector3.Up * 48f, end \u002B Vector3.Down * 96f ).WithoutTags( \u0022player\u0022, \u0022golfball\u0022 ).Run();\r\n\t\tif ( trace.Hit )\r\n\t\t{\r\n\t\t\tlanding.Position = trace.HitPosition;\r\n\t\t\tlanding.Normal = trace.Normal;\r\n\t\t\tlanding.Surface = trace.Surface ?? _defaultSurface;\r\n\t\t}\r\n\r\n\t\tvar distance = start.Distance( end );\r\n\t\tlanding.At = Time.Now \u002B distance / Math.Max( 1f, TracerSpeed );\r\n\r\n\t\t// Tracer: the pool\u0027s oldest one restarts from the new start point.\r\n\t\tvar i = _nextTracer;\r\n\t\t_nextTracer = (_nextTracer \u002B 1) % _tracers.Length;\r\n\t\tvar tracer = _tracers[i];\r\n\t\tif ( tracer.IsValid() )\r\n\t\t{\r\n\t\t\tif ( _builtColour != TracerColour || _builtWidth != TracerWidth ) BuildLook();\r\n\t\t\ttracer.Enabled = false;\r\n\t\t\ttracer.WorldPosition = start;\r\n\t\t\ttracer.EndPoint = end;\r\n\t\t\ttracer.DistancePerSecond = TracerSpeed;\r\n\t\t\ttracer.Length = TracerLength;\r\n\t\t\ttracer.Enabled = true;\r\n\t\t}\r\n\t\t_landings[i] = landing;\r\n\r\n\t\t// Muzzle flash.\r\n\t\tif ( MuzzleFlash \u0026\u0026 _flashes.Length \u003E 0 )\r\n\t\t{\r\n\t\t\tvar f = _nextFlash;\r\n\t\t\t_nextFlash = (_nextFlash \u002B 1) % _flashes.Length;\r\n\t\t\tvar flash = _flashes[f];\r\n\t\t\tif ( flash.IsValid() )\r\n\t\t\t{\r\n\t\t\t\tflash.WorldPosition = start \u002B (end - start).Normal * 12f;\r\n\t\t\t\tflash.LightColor = TracerColour * Glow;\r\n\t\t\t\tflash.Radius = FlashRadius;\r\n\t\t\t\tflash.Enabled = true;\r\n\t\t\t\t_flashOff[f] = Time.Now \u002B FlashSeconds;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// The distant shot.\r\n\t\tif ( ShotSound is not null \u0026\u0026 Volume \u003E 0f )\r\n\t\t{\r\n\t\t\tvar handle = Sound.Play( ShotSound, start );\r\n\t\t\tif ( handle.IsValid() ) handle.Volume = Volume;\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Enough tracers to cover the longest flight at the burst rate, and a couple of flash lights.\r\n\t/// Pool objects are hidden children that are never saved or networked.\r\n\t/// \u003C/summary\u003E\r\n\tvoid BuildPool()\r\n\t{\r\n\t\tvar longest = 0f;\r\n\t\tif ( StartA.IsValid() \u0026\u0026 StartB.IsValid() \u0026\u0026 EndA.IsValid() \u0026\u0026 EndB.IsValid() )\r\n\t\t{\r\n\t\t\tlongest = Math.Max( Math.Max( StartA.WorldPosition.Distance( EndA.WorldPosition ), StartA.WorldPosition.Distance( EndB.WorldPosition ) ),\r\n\t\t\t\tMath.Max( StartB.WorldPosition.Distance( EndA.WorldPosition ), StartB.WorldPosition.Distance( EndB.WorldPosition ) ) );\r\n\t\t}\r\n\t\tvar flight = (longest \u002B Spread \u002B TracerLength) / Math.Max( 1f, TracerSpeed );\r\n\t\tvar count = Math.Clamp( (int)MathF.Ceiling( flight * ShotsPerSecond ) \u002B 2, 4, 32 );\r\n\r\n\t\t_tracers = new TracerEffect[count];\r\n\t\t_landings = new Landing[count];\r\n\t\tfor ( var i = 0; i \u003C count; i\u002B\u002B )\r\n\t\t{\r\n\t\t\tvar go = new GameObject( GameObject, false, $\u0022tracer {i}\u0022 );\r\n\t\t\tgo.Flags |= GameObjectFlags.NotSaved | GameObjectFlags.NotNetworked | GameObjectFlags.Hidden;\r\n\t\t\tvar tracer = go.AddComponent\u003CTracerEffect\u003E( false );\r\n\t\t\ttracer.StartDistance = 0f;\r\n\t\t\ttracer.Opaque = false;\r\n\t\t\ttracer.CastShadows = false;\r\n\t\t\ttracer.EnableLight = false;\r\n\t\t\t_tracers[i] = tracer;\r\n\t\t\tgo.Enabled = true;\r\n\t\t}\r\n\t\tBuildLook();\r\n\r\n\t\t_flashes = new PointLight[2];\r\n\t\t_flashOff = new float[2];\r\n\t\tfor ( var i = 0; i \u003C _flashes.Length; i\u002B\u002B )\r\n\t\t{\r\n\t\t\tvar go = new GameObject( GameObject, false, $\u0022flash {i}\u0022 );\r\n\t\t\tgo.Flags |= GameObjectFlags.NotSaved | GameObjectFlags.NotNetworked | GameObjectFlags.Hidden;\r\n\t\t\tvar light = go.AddComponent\u003CPointLight\u003E( false );\r\n\t\t\tlight.Shadows = false;\r\n\t\t\tlight.Radius = FlashRadius;\r\n\t\t\tlight.Attenuation = 2f;\r\n\t\t\t_flashes[i] = light;\r\n\t\t\tgo.Enabled = true;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid BuildLook()\r\n\t{\r\n\t\t_builtColour = TracerColour;\r\n\t\t_builtWidth = TracerWidth;\r\n\t\tvar head = TracerColour * Glow;\r\n\t\thead.a = 1f;\r\n\t\tvar colour = new Gradient( new Gradient.ColorFrame( 0f, head ), new Gradient.ColorFrame( 0.35f, TracerColour ), new Gradient.ColorFrame( 1f, TracerColour.WithAlpha( 0f ) ) );\r\n\t\tvar width = new Curve( new Curve.Frame( 0f, TracerWidth ), new Curve.Frame( 1f, 0f ) );\r\n\t\tforeach ( var tracer in _tracers )\r\n\t\t{\r\n\t\t\tif ( !tracer.IsValid() ) continue;\r\n\t\t\ttracer.LineColor = colour;\r\n\t\t\ttracer.LineWidth = width;\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The four handle objects: found by name under this object, or made with default spots.\r\n\t/// \u003C/summary\u003E\r\n\tvoid EnsureHandles()\r\n\t{\r\n\t\tStartA = Handle( StartA, \u0022Start A\u0022, new Vector3( 0f, -150f, 40f ) );\r\n\t\tStartB = Handle( StartB, \u0022Start B\u0022, new Vector3( 0f, 150f, 40f ) );\r\n\t\tEndA = Handle( EndA, \u0022End A\u0022, new Vector3( 1200f, -250f, 0f ) );\r\n\t\tEndB = Handle( EndB, \u0022End B\u0022, new Vector3( 1200f, 250f, 0f ) );\r\n\t}\r\n\r\n\tGameObject Handle( GameObject current, string name, Vector3 localPosition )\r\n\t{\r\n\t\tif ( current.IsValid() ) return current;\r\n\r\n\t\tforeach ( var child in GameObject.Children )\r\n\t\t\tif ( child.IsValid() \u0026\u0026 child.Name == name ) return child;\r\n\r\n\t\tvar go = new GameObject( GameObject, true, name );\r\n\t\tgo.LocalPosition = localPosition;\r\n\t\treturn go;\r\n\t}\r\n\r\n\tprotected override void DrawGizmos()\r\n\t{\r\n\t\tEnsureHandles();\r\n\t\tif ( !StartA.IsValid() || !StartB.IsValid() || !EndA.IsValid() || !EndB.IsValid() ) return;\r\n\r\n\t\tvar alpha = Gizmo.IsSelected ? 1f : (Gizmo.IsHovered ? 0.6f : 0.3f);\r\n\t\tvar local = WorldTransform;\r\n\t\tvar sa = local.PointToLocal( StartA.WorldPosition );\r\n\t\tvar sb = local.PointToLocal( StartB.WorldPosition );\r\n\t\tvar ea = local.PointToLocal( EndA.WorldPosition );\r\n\t\tvar eb = local.PointToLocal( EndB.WorldPosition );\r\n\r\n\t\tGizmo.Draw.LineThickness = Gizmo.IsSelected ? 3f : 2f;\r\n\t\tGizmo.Draw.Color = TracerColour.WithAlpha( alpha );\r\n\t\tGizmo.Draw.Line( sa, sb );\r\n\t\tGizmo.Draw.LineSphere( new Sphere( sa, 8f ), 8 );\r\n\t\tGizmo.Draw.LineSphere( new Sphere( sb, 8f ), 8 );\r\n\r\n\t\tGizmo.Draw.Color = Color.Red.WithAlpha( alpha );\r\n\t\tGizmo.Draw.Line( ea, eb );\r\n\t\tGizmo.Draw.LineSphere( new Sphere( ea, 8f ), 8 );\r\n\t\tGizmo.Draw.LineSphere( new Sphere( eb, 8f ), 8 );\r\n\r\n\t\tGizmo.Draw.LineThickness = 1f;\r\n\t\tGizmo.Draw.Color = Color.White.WithAlpha( alpha * 0.7f );\r\n\t\tGizmo.Draw.Arrow( (sa \u002B sb) * 0.5f, (ea \u002B eb) * 0.5f, 24f, 8f );\r\n\t}\r\n}\r\n"}]}