7923 results

using System;
using Sandbox;

namespace Goo.Animation;

public record struct SmoothVector2
{
    public Vector2 Current;
    public Vector2 Target;
    public Vector2 Velocity;
    public float SmoothTime;

    public SmoothVector2(Vector2 initial, float smoothTime)
    {
        Current = initial;
        Target = initial;
        Velocity = default;
        SmoothTime = smoothTime;
    }

    public void Update(float dt)
    {
        float vx = Velocity.x, vy = Velocity.y;
        Current = new Vector2(
            MathX.SmoothDamp(Current.x, Target.x, ref vx, SmoothTime, dt),
            MathX.SmoothDamp(Current.y, Target.y, ref vy, SmoothTime, dt));
        Velocity = new Vector2(vx, vy);
    }

    public bool IsSettled =>
        MathF.Abs(Target.x - Current.x) < 0.0001f &&
        MathF.Abs(Target.y - Current.y) < 0.0001f &&
        MathF.Abs(Velocity.x) < 0.0001f &&
        MathF.Abs(Velocity.y) < 0.0001f;

    /// <summary>Advances by dt and returns true while still moving; chain calls with | (not ||) so every damper advances each frame.</summary>
    public bool Tick(float dt) { Update(dt); return !IsSettled; }
}
using Sandbox;
using Sandbox.Rendering;
using Sandbox.UI;

namespace Goo;

// Style helpers hoisted so generated Blob facades share them. Keep the early-return form: an engine-type ternary that resolves bare null via an implicit string operator silently produces magenta (Color.Parse fallback) instead of the intended absent-property. See engine-fact memories.

internal static class StyleAccumulator
{
    static StyleList Rent(StyleList current)
        => ReferenceEquals(current, StyleList.Empty)
            ? BuildContext.Current.RentStyleList()
            : current;

    public static StyleList Add(StyleList current, StyleField field, Length? value)
    {
        if (!value.HasValue) return current;
        var list = Rent(current);
        list.Add(field, StyleValue.FromLength(value.Value));
        return list;
    }

    public static StyleList Add<TEnum>(StyleList current, StyleField field, TEnum? value, System.Func<TEnum, StyleValue> wrap) where TEnum : struct
    {
        if (!value.HasValue) return current;
        var list = Rent(current);
        list.Add(field, wrap(value.Value));
        return list;
    }

    public static StyleList Add(StyleList current, StyleField field, Color? value, System.Func<Color, StyleValue> wrap)
    {
        if (!value.HasValue) return current;
        var list = Rent(current);
        list.Add(field, wrap(value.Value));
        return list;
    }

    public static StyleList Add(StyleList current, StyleField field, string? value)
    {
        if (value is null) return current;
        var list = Rent(current);
        list.Add(field, StyleValue.FromString(value));
        return list;
    }

    public static StyleList Add(StyleList current, StyleField field, float? value)
    {
        if (!value.HasValue) return current;
        var list = Rent(current);
        list.Add(field, StyleValue.FromSingle(value.Value));
        return list;
    }

    public static StyleList Add(StyleList current, StyleField field, bool? value)
    {
        if (!value.HasValue) return current;
        var list = Rent(current);
        list.Add(field, StyleValue.FromBoolean(value.Value));
        return list;
    }

    public static StyleList Add(StyleList current, StyleField field, int? value)
    {
        if (!value.HasValue) return current;
        var list = Rent(current);
        list.Add(field, StyleValue.FromInt32(value.Value));
        return list;
    }

    public static StyleList Add(StyleList current, StyleField field, Texture? value)
    {
        if (value is null) return current;
        var list = Rent(current);
        list.Add(field, StyleValue.FromTexture(value));
        return list;
    }
}
using System;
using Sandbox;

namespace Goo.FpsUI;

// ============================================================================
//  ALL demo / self-preview behaviour for the FPS UI pack lives in this ONE file.
//
//  DELETE THIS FILE to remove demo functionality.
//  deleting this file makes every Demo inspector toggle disappear
// ============================================================================
static class FpsDemo
{
    static readonly string[] Names = { "Vex", "Korr", "Juno", "Rhys", "Mara", "Dane", "Iko", "Sol" };
    static readonly (int Amount, string Action)[] Grants =
    {
        (100, "Kill"), (125, "Headshot"), (50, "Assist"), (200, "Double Kill"), (25, "Hitmarker"),
    };

    public static void Health( HealthModel m, ref float t, float dt )  // bleed in chunks, big heal when low
    {
        t += dt;
        if ( t < 2.4f ) return;
        t = 0f;
        if ( m.Health <= m.MaxHealth * 0.3f ) m.Heal( m.MaxHealth * 0.65f );
        else m.Damage( m.MaxHealth * 0.22f );
    }

    public static void Stamina( StaminaModel m, ref float t, float dt )  // sprint on/off cycle
    {
        t += dt;
        if ( t >= 3.1f ) { t = 0f; m.SetSprinting( !m.Sprinting ); }
        if ( m.Stamina <= 0f ) m.SetSprinting( false );
    }

    public static void Ammo( AmmoModel m, ref float t, float dt )  // steady fire, auto-reload on empty
    {
        t += dt;
        if ( m.Reloading ) return;
        if ( m.Mag <= 0 ) { m.Reload(); return; }
        if ( t >= 0.18f ) { t = 0f; m.Fire(); }
    }

    public static void Crosshair( CrosshairModel m, ref float t, float dt )  // steady fire cadence
    {
        t += dt;
        if ( t >= 0.18f ) { t = 0f; m.Fire(); }
    }

    public static void Hitmarker( HitmarkerModel m, ref float t, float dt )  // periodic pop
    {
        t += dt;
        if ( t >= 0.5f ) { t = 0f; m.Pop( false ); }
    }

    public static void Killfeed( KillfeedModel m, ref float t, ref int pick, float dt )  // periodic fake kills
    {
        t += dt;
        if ( t < 2.2f ) return;
        t = 0f;
        string a = Names[pick % Names.Length];
        string v = Names[(pick + 3) % Names.Length];
        // Alternate teams, occasionally make the local player the killer so the preview shows both.
        bool youKill = pick % 3 == 0;
        KillTeam at = youKill || pick % 2 == 0 ? KillTeam.Friendly : KillTeam.Enemy;
        KillTeam vt = at == KillTeam.Friendly ? KillTeam.Enemy : KillTeam.Friendly;
        pick++;
        m.Add( a, at, v, vt, attackerLocal: youKill );
    }

    public static void Xp( XpModel m, ref float t, ref int pick, float dt )  // periodic grants
    {
        t += dt;
        if ( t < 1.6f ) return;
        t = 0f;
        var g = Grants[pick % Grants.Length];
        pick++;
        m.Add( g.Amount, g.Action );
    }

    public static void Scoreboard( ScoreboardModel m, ref float t, float dt )  // loop the clock, nudge scores, cycle variant
    {
        if ( m.TimeRemaining <= 0f ) m.TimeRemaining = 600f;
        t += dt;
        if ( t < 4f ) return;
        t = 0f;
        m.Mode = m.Mode switch
        {
            ScoreboardMode.Tdm        => ScoreboardMode.Domination,
            ScoreboardMode.Domination => ScoreboardMode.Ffa,
            _                         => ScoreboardMode.Tdm,
        };
        m.FriendlyScore = (m.FriendlyScore + 7) % (m.ScoreLimit + 1);
        m.EnemyScore    = (m.EnemyScore + 5) % (m.ScoreLimit + 1);
        m.PlayerScore  += 150;
        m.LeaderScore   = Math.Max( m.LeaderScore, m.PlayerScore ) + 50;
        for ( int i = 0; i < m.Points.Length; i++ )  // rotate cap ownership
            m.Points[i] = (CapOwner)(((int)m.Points[i] + 1) % 3);
    }
}

// ---- per-widget demo hooks (the [Property] Demo toggle + timers + StepDemo body) ----

public sealed partial class HealthWidget
{
    [Property] public bool Demo { get; set; } = true;  // self-animate in editor
    float _demoT;
    partial void StepDemo( float dt, ref bool active )
    {
        if ( !Demo ) return;
        active = true;
        FpsDemo.Health( _m, ref _demoT, dt );
    }
}

public sealed partial class StaminaWidget
{
    [Property] public bool Demo { get; set; } = true;  // self-animate in editor
    float _demoT;
    partial void StepDemo( float dt, ref bool active )
    {
        if ( !Demo ) return;
        active = true;
        FpsDemo.Stamina( _m, ref _demoT, dt );
    }
}

public sealed partial class AmmoWidget
{
    [Property] public bool Demo { get; set; } = true;  // self-fire in editor
    float _demoT;
    partial void StepDemo( float dt, ref bool active )
    {
        if ( !Demo ) return;
        active = true;
        FpsDemo.Ammo( _m, ref _demoT, dt );
    }
}

public sealed partial class CrosshairWidget
{
    [Property] public bool Demo { get; set; } = true;  // self-fire in editor
    float _demoT;
    partial void StepDemo( float dt, ref bool active )
    {
        if ( !Demo ) return;
        active = true;
        FpsDemo.Crosshair( _m, ref _demoT, dt );
    }
}

public sealed partial class HitmarkerWidget
{
    [Property] public bool Demo { get; set; } = true;  // periodic pop in editor
    float _demoT;
    partial void StepDemo( float dt, ref bool active )
    {
        if ( !Demo ) return;
        active = true;
        FpsDemo.Hitmarker( _m, ref _demoT, dt );
    }
}

public sealed partial class KillfeedWidget
{
    [Property] public bool Demo { get; set; } = true;  // fake kills in editor
    float _demoT;
    int _demoPick;
    partial void StepDemo( float dt, ref bool active )
    {
        if ( !Demo ) return;
        active = true;
        FpsDemo.Killfeed( _m, ref _demoT, ref _demoPick, dt );
    }
}

public sealed partial class XpWidget
{
    [Property] public bool Demo { get; set; } = true;  // fake grants in editor
    float _demoT;
    int _demoPick;
    partial void StepDemo( float dt, ref bool active )
    {
        if ( !Demo ) return;
        active = true;
        FpsDemo.Xp( _m, ref _demoT, ref _demoPick, dt );
    }
}

public sealed partial class ScoreboardWidget
{
    [Property] public bool Demo { get; set; } = true;  // self-animate in editor
    float _demoT;
    partial void StepDemo( float dt, ref bool active )
    {
        if ( !Demo ) return;
        active = true;
        FpsDemo.Scoreboard( _m, ref _demoT, dt );
    }
}

// ---- the assembled HUD: one coordinated synthetic firefight ----

public sealed partial class FpsHud
{
    [Property, Group( "General" )] public bool Demo { get; set; } = true;  // self-run a synthetic firefight in editor

    readonly Random _demoRng = new();
    float _hpT, _stT, _kfT, _xpT, _sbT;  // per-subsystem demo timers
    int _kfPick, _xpPick;                // demo name / grant cursors
    float _triggerT, _modeT;             // synthetic trigger square-wave + fire-mode cycle

    partial void StepDemo( float dt, ref bool active )
    {
        if ( !Demo ) return;
        active = true;

        // Cycle the fire mode every few seconds, then drive a synthetic trigger square-wave (held ~1s,
        // released ~0.4s) through the real fire control so each mode visibly fires differently.
        _modeT -= dt;
        if ( _modeT <= 0f ) { _modeT = 3.0f; CycleFireMode(); }
        _fire.Mode = FireMode; _fire.BurstCount = BurstCount; _fire.Rpm = RoundsPerMinute;
        _triggerT += dt;
        bool trigger = _triggerT % 1.4f < 1.0f;
        if ( !_ammo.Reloading )
        {
            if ( _ammo.Mag <= 0 ) _ammo.Reload();
            else if ( _fire.Tick( trigger, dt ) )
            {
                _ammo.Fire(); _crosshair.Fire();
                if ( _demoRng.NextSingle() < 0.5f ) _hitmarker.Pop( _demoRng.NextSingle() < 0.15f );
            }
        }

        FpsDemo.Health( _health, ref _hpT, dt );
        FpsDemo.Stamina( _stamina, ref _stT, dt );
        FpsDemo.Killfeed( _killfeed, ref _kfT, ref _kfPick, dt );
        FpsDemo.Xp( _xp, ref _xpT, ref _xpPick, dt );
        if ( ShowScoreboard ) FpsDemo.Scoreboard( _scoreboard, ref _sbT, dt );
    }
}
using System;
using Sandbox;

namespace Goo.FpsUI;

// A drop-in shootable target for the FPS pack. Attach to any GameObject that has a Collider; the HUD's
// hitscan damages it through the engine's Component.IDamageable interface (the same path TriggerHurt uses).
// Exposes Health / IsDead / Name so FpsHud can drive the hitmarker, killfeed, and XP on a hit or kill.
// Engine-side component, not a Goo panel.
[Title( "FPS Target" ), Category( "FPS UI" ), Icon( "my_location" )]
public sealed class FpsTarget : Component, Component.IDamageable
{
    [Property] public string Name { get; set; } = "Target";                          // shown as the victim in the killfeed
    [Property, Range( 1f, 1000f )] public float MaxHealth { get; set; } = 100f;       // health restored on enable / respawn
    [Property] public bool RespawnOnDeath { get; set; } = true;                       // refill health a moment after dying
    [Property, Range( 0.5f, 10f )] public float RespawnDelay { get; set; } = 3f;      // seconds dead before respawning

    public float Health { get; private set; }
    public bool IsDead => Health <= 0f;

    float _respawnAt;

    protected override void OnEnabled() => Health = MaxHealth;

    // Engine damage entry point: TriggerHurt volumes and the HUD's hitscan both call this.
    public void OnDamage( in DamageInfo damage )
    {
        if ( IsDead ) return;                                       // already down, ignore extra hits
        Health = Math.Max( 0f, Health - damage.Damage );
        if ( IsDead && RespawnOnDeath ) _respawnAt = Time.Now + RespawnDelay;
    }

    protected override void OnUpdate()
    {
        if ( IsDead && RespawnOnDeath && Time.Now >= _respawnAt ) Health = MaxHealth;
    }
}
using System;

namespace Goo.FpsUI;

// Compass logic: a 0..360 heading plus the shortest signed angular delta the view uses to
// place cardinal ticks. Engine-free.
public sealed class CompassModel
{
    public float Heading { get; private set; }  // current yaw, normalized 0..360

    public void SetHeading( float yawDeg )       // set heading from game code (any range)
        => Heading = ((yawDeg % 360f) + 360f) % 360f;

    // Signed delta from `from` to `to`, in (-180, 180]. Used to position ticks around center.
    public static float ShortestDelta( float from, float to ) => ((to - from + 540f) % 360f) - 180f;

    public bool Tick( float dt ) => false;  // heading changes drive rebuilds, not the damper
}
using System;
using Goo;
using Sandbox;
using Sandbox.UI;
using PanelTransform = Goo.PanelTransform;   // rule 18: ambiguous with Sandbox.UI otherwise

namespace Goo.FpsUI;

// Shared, stateless view helpers. Each returns a fresh Container (never cache a Container).
static class Parts
{
    public enum Corner { TopLeft, TopCenter, TopRight, BottomLeft, BottomRight, Center }

    // Absolute fill spanning `frac` (0..1) of its Relative parent's width, full height.
    public static Container FillRect( string key, float frac, Color color, float radius ) => new()
    {
        Key = key, Position = PositionMode.Absolute, Top = 0, Left = 0,
        Height = Length.Percent( 100 ),
        Width = Length.Percent( Math.Clamp( frac, 0f, 1f ) * 100f ),
        BorderRadius = radius, BackgroundColor = color,
    };

    // Absolute full-cover tint at a given opacity (flashes, warnings).
    public static Container Overlay( string key, Color color, float opacity, float radius ) => new()
    {
        Key = key, Position = PositionMode.Absolute, Top = 0, Left = 0,
        Width = Length.Percent( 100 ), Height = Length.Percent( 100 ),
        BorderRadius = radius, BackgroundColor = color, Opacity = opacity,
    };

    // Pin `child` to a screen corner/center inside a Relative, full-size root. `m` is the edge inset.
    // Container properties are init-only (record struct), so we use `with` expressions per corner.
    public static Container Anchor( string key, Corner c, float m, Container child )
    {
        var box = new Container
        {
            Key = key, Position = PositionMode.Absolute, PointerEvents = PointerEvents.None,
            Children = { child },
        };
        return c switch
        {
            Corner.TopLeft     => box with { Top = m, Left = m },
            Corner.TopRight    => box with { Top = m, Right = m },
            Corner.BottomLeft  => box with { Bottom = m, Left = m },
            Corner.BottomRight => box with { Bottom = m, Right = m },
            Corner.TopCenter   => box with
            {
                Top = m, Left = Length.Percent( 50 ),
                Transform = PanelTransform.Translate( Length.Percent( -50 ) ?? default, Length.Percent( 0 ) ?? default ),
            },
            _ => box with  // Center
            {
                Top = Length.Percent( 50 ), Left = Length.Percent( 50 ),
                Transform = PanelTransform.Translate( Length.Percent( -50 ) ?? default, Length.Percent( -50 ) ?? default ),
            },
        };
    }

    // Pin `child` horizontally centered, offset `dy` px from the screen center (positive = down, negative = up).
    public static Container CenterOffset( string key, float dy, Container child ) => new()
    {
        Key = key, Position = PositionMode.Absolute, PointerEvents = PointerEvents.None,
        Top = Length.Percent( 50 ), Left = Length.Percent( 50 ),
        Transform = PanelTransform.Translate( Length.Percent( -50 ) ?? default, Px.Of( dy ) ),
        Children = { child },
    };

    // Pin `child`'s top-left corner at a pixel offset from the screen center (positive dx = right, positive dy = down).
    public static Container Offset( string key, float dx, float dy, Container child ) => new()
    {
        Key = key, Position = PositionMode.Absolute, PointerEvents = PointerEvents.None,
        Top = Length.Percent( 50 ), Left = Length.Percent( 50 ),
        Transform = PanelTransform.Translate( Px.Of( dx ), Px.Of( dy ) ),
        Children = { child },
    };

    // Semi-opaque rounded backing behind a HUD readout, so text/bars stay legible over the world.
    // Wraps one child and sizes to it, all card styling comes from the theme.
    public static Container Panel( string key, FpsTheme t, Container child ) => new()
    {
        Key = key, Position = PositionMode.Relative,
        Padding = t.PanelPad, BorderRadius = t.PanelRadius,
        BackgroundColor = t.BackingBg,
        Children = { child },
    };

    // A full-size, pointer-through, Relative root used by every standalone widget and the FpsHud.
    public static Container Root( string key ) => new()
    {
        Key = key, Width = Length.Percent( 100 ), Height = Length.Percent( 100 ),
        Position = PositionMode.Relative, PointerEvents = PointerEvents.None,
    };
}
using System;
using Goo;
using Sandbox;
using Sandbox.UI;

namespace Goo.FpsUI;

// Stateless presenter: the secondary (stamina/armor) bar.
static class StaminaView
{
    public const float TrackW = 320f, TrackH = 10f;

    public static Container Build( StaminaModel m, FpsTheme t )
    {
        float frac = m.ShownFraction;
        Color fill = Color.Lerp( t.Warn, t.Good, frac );

        var track = new Container
        {
            Key = "stTrack", Position = PositionMode.Relative,
            Width = TrackW, Height = TrackH, BackgroundColor = t.TrackBg,
            BorderRadius = t.Radius, Overflow = OverflowMode.Hidden,
            Children = { Parts.FillRect( "fill", frac, fill, t.Radius ) },
        };
        if ( m.Flash > 0.001f ) track.Children.Add( Parts.Overlay( "flash", Color.White, m.Flash * 0.8f, t.Radius ) );
        return track;
    }
}

// Standalone stamina bar. Call Sprinting(bool) from your movement code each frame.
public sealed partial class StaminaWidget : GooPanel<Container>
{
    [Property, Range( 1f, 1000f )] public float MaxStamina { get; set; } = 100f; // full-bar value
    [Property, Range( 0.05f, 2f )] public float DrainRate { get; set; } = 0.55f;  // fraction of max drained per second while sprinting
    [Property] public PlayerController? Player { get; set; }                      // player to gate sprint on when stamina is empty (null = skip gating)

    readonly StaminaModel _m = new();
    readonly FpsTheme _t = new();
    bool _booted;
    bool _sprintBlocked;
    float _cachedRunSpeed;

    void Boot() { _m.MaxStamina = MaxStamina; _m.Reset(); _booted = true; }

    public void Sprinting( bool on ) => _m.SetSprinting( on ); // toggle sprint drain

    // Demo-only seam: implemented in FpsDemo.cs, compiles out when that file is deleted.
    partial void StepDemo( float dt, ref bool active );

    protected override bool Tick( float dt )
    {
        if ( !_booted ) Boot();
        _m.DrainRate = DrainRate;  // live-tunable
        bool demo = false;
        StepDemo( dt, ref demo );
        if ( !demo )
        {
            Sprinting( Sandbox.Input.Down( "run" ) );
            FpsInput.ApplySprintGate( Player, _m.Stamina, ref _sprintBlocked, ref _cachedRunSpeed );
        }
        bool moving = _m.Tick( dt );
        return demo || moving;
    }

    protected override Container Build()
    {
        if ( !_booted ) Boot();
        var root = Parts.Root( "fpsStamina" );
        // Sits just above where the health bar would be (health height + gap).
        root.Children.Add( Parts.Anchor( "a", Parts.Corner.BottomLeft, _t.Margin + HealthView.TrackH + 10f, Parts.Panel( "bg", _t, StaminaView.Build( _m, _t ) ) ) );
        return root;
    }
}
using System;
using Sandbox;
using Sandbox.UI;

namespace Goo.Internal;

internal sealed class StatefulShapePanel : Panel, IStatefulEventHost
{
    internal Action<MousePanelEvent>? _onClick;
    internal Action<MousePanelEvent>? _onRightClick;
    internal Action<MousePanelEvent>? _onMiddleClick;
    internal Action<MousePanelEvent>? _onMouseEnter;
    internal Action<MousePanelEvent>? _onMouseLeave;
    internal Action<MousePanelEvent>? _onMouseDown;
    internal Action<MousePanelEvent>? _onMouseUp;
    internal Action<MousePanelEvent>? _onMouseMove;
    internal bool    _userSetPointerEvents;
    internal Action? _requestRebuild;
    public Action? RequestRebuild { set => _requestRebuild = value; }

    public void ApplyEvents(in BlobEvents events)
    {
        _onClick      = events.OnClick;
        _onRightClick = events.OnRightClick;
        _onMiddleClick = events.OnMiddleClick;
        _onMouseEnter = events.OnMouseEnter;
        _onMouseLeave = events.OnMouseLeave;
        _onMouseDown  = events.OnMouseDown;
        _onMouseUp    = events.OnMouseUp;
        _onMouseMove  = events.OnMouseMove;
    }

    public bool HasEventHandlers =>
        _onClick != null || _onRightClick != null || _onMiddleClick != null || _onMouseEnter != null || _onMouseLeave != null ||
        _onMouseDown != null || _onMouseUp != null || _onMouseMove != null;

    public bool UserSetPointerEvents
    {
        get => _userSetPointerEvents;
        set => _userSetPointerEvents = value;
    }

    // Apply a baked alpha texture as BackgroundImage. The shape color comes from
    // BackgroundColor flowing through the engine's BgTint multiplier; this method
    // is only responsible for the alpha mask.
    public void ApplyShape(BlobKind kind, in ShapeParams shape)
    {
        Style.BackgroundImage = ShapeTextureCache.GetOrBake(kind, in shape);
        Style.BackgroundSizeX = Length.Percent(100);
        Style.BackgroundSizeY = Length.Percent(100);
    }

    public void ApplyPolygon(Vector2[] points)
    {
        Style.BackgroundImage = ShapeTextureCache.GetOrBakePolygon(points);
        Style.BackgroundSizeX = Length.Percent(100);
        Style.BackgroundSizeY = Length.Percent(100);
    }

    protected override void OnClick(MousePanelEvent e)       { base.OnClick(e);       EventDispatch.Fire(_onClick, e, _requestRebuild); }
    protected override void OnRightClick(MousePanelEvent e)  { base.OnRightClick(e);  EventDispatch.Fire(_onRightClick, e, _requestRebuild); }
    protected override void OnMiddleClick(MousePanelEvent e) { base.OnMiddleClick(e); EventDispatch.Fire(_onMiddleClick, e, _requestRebuild); }
    protected override void OnMouseOver(MousePanelEvent e)   { base.OnMouseOver(e);   EventDispatch.Fire(_onMouseEnter, e, _requestRebuild); }
    protected override void OnMouseOut(MousePanelEvent e)    { base.OnMouseOut(e);    EventDispatch.Fire(_onMouseLeave, e, _requestRebuild); }
    protected override void OnMouseDown(MousePanelEvent e)   { base.OnMouseDown(e);   EventDispatch.Fire(_onMouseDown, e, _requestRebuild); }
    protected override void OnMouseUp(MousePanelEvent e)     { base.OnMouseUp(e);     EventDispatch.Fire(_onMouseUp, e, _requestRebuild); }
    protected override void OnMouseMove(MousePanelEvent e)   { base.OnMouseMove(e);   EventDispatch.Fire(_onMouseMove, e, _requestRebuild); }
}
using System;
using Sandbox.UI;

namespace Goo.Internal;

internal sealed class StatefulSvgPanel : Sandbox.UI.SvgPanel, IStatefulEventHost
{
    internal Action<MousePanelEvent>? _onClick;
    internal Action<MousePanelEvent>? _onRightClick;
    internal Action<MousePanelEvent>? _onMiddleClick;
    internal Action<MousePanelEvent>? _onMouseEnter;
    internal Action<MousePanelEvent>? _onMouseLeave;
    internal Action<MousePanelEvent>? _onMouseDown;
    internal Action<MousePanelEvent>? _onMouseUp;
    internal Action<MousePanelEvent>? _onMouseMove;
    internal bool    _userSetPointerEvents;
    internal Action? _requestRebuild;
    public Action? RequestRebuild { set => _requestRebuild = value; }

    public void ApplyEvents(in BlobEvents events)
    {
        _onClick      = events.OnClick;
        _onRightClick = events.OnRightClick;
        _onMiddleClick = events.OnMiddleClick;
        _onMouseEnter = events.OnMouseEnter;
        _onMouseLeave = events.OnMouseLeave;
        _onMouseDown  = events.OnMouseDown;
        _onMouseUp    = events.OnMouseUp;
        _onMouseMove  = events.OnMouseMove;
    }

    public bool HasEventHandlers =>
        _onClick != null || _onRightClick != null || _onMiddleClick != null || _onMouseEnter != null || _onMouseLeave != null ||
        _onMouseDown != null || _onMouseUp != null || _onMouseMove != null;

    public bool UserSetPointerEvents
    {
        get => _userSetPointerEvents;
        set => _userSetPointerEvents = value;
    }

    protected override void OnClick(MousePanelEvent e)       { base.OnClick(e);       EventDispatch.Fire(_onClick, e, _requestRebuild); }
    protected override void OnRightClick(MousePanelEvent e)  { base.OnRightClick(e);  EventDispatch.Fire(_onRightClick, e, _requestRebuild); }
    protected override void OnMiddleClick(MousePanelEvent e) { base.OnMiddleClick(e); EventDispatch.Fire(_onMiddleClick, e, _requestRebuild); }
    protected override void OnMouseOver(MousePanelEvent e)   { base.OnMouseOver(e);   EventDispatch.Fire(_onMouseEnter, e, _requestRebuild); }
    protected override void OnMouseOut(MousePanelEvent e)    { base.OnMouseOut(e);    EventDispatch.Fire(_onMouseLeave, e, _requestRebuild); }
    protected override void OnMouseDown(MousePanelEvent e)   { base.OnMouseDown(e);   EventDispatch.Fire(_onMouseDown, e, _requestRebuild); }
    protected override void OnMouseUp(MousePanelEvent e)     { base.OnMouseUp(e);     EventDispatch.Fire(_onMouseUp, e, _requestRebuild); }
    protected override void OnMouseMove(MousePanelEvent e)   { base.OnMouseMove(e);   EventDispatch.Fire(_onMouseMove, e, _requestRebuild); }
}

$primary: red !default;
$primary-alt: white !default;

$switch-padding: 6px !default;

.button.popupbutton.dropdown
{
	cursor: pointer;
	transition: all .1s ease-out;
	position: relative;

	> .dropdown_indicator
	{
		position: absolute;
		right: 8px;
	}

	&.open
	{
		border-bottom-left-radius: 1px;
		border-bottom-right-radius: 1px;
		transition: border-radius 0.2s ease-out;
	}
}

select
{
	min-height: 40px;

	> option
	{
		display: none;
	}
}
.navigator-body
{
	&.hidden
	{
		display: none;
	}
}
@import "base/_splitcontainer.scss";
@import "base/_navigator.scss";

button
{
	cursor: pointer;
}

IconPanel
{
	font-family: Material Icons;
}

.is-half
{
	width: 50%;
}

.is-third
{
	width: 33%;
}

.is-quarter
{
	width: 25%;
}

button.has-subtitle
{
	position: relative;
	flex-direction: column;
	justify-content: flex-start;
	align-items: flex-start;
	padding-left: 40px; // icon space

	.iconpanel
	{
		position: absolute;
		left: 5px;
		top: 0;
		bottom: 0;
		align-items: center;
	}

	.button-label
	{
		font-weight: bold;
	}

	.button-subtitle
	{
		font-size: 12px;
		opacity: 0.5;
		mix-blend-mode: lighten;
	}
}
.package-list
{
    flex-shrink: 1;
    flex-wrap: wrap;
    flex-grow: 1;

    h1
    {
        width: 100%;
        margin-top: 50px;
        font-size: 40px;
    }

    PackageCard
    {
        &:hover
        {
            sound-in: "ui.button.over";
        }
    }

    VirtualGrid
    {
        width: 100%;
        height: 100%;

        .cell
        {
            
        }
    }
}

$primary: red !default;
$primary-alt: white !default;

$switch-padding: 6px !default;

.coloreditor
{
	flex-direction: column;
	min-width: 250px;
	max-width: 250px;

	> .canvas
	{
		border-top: 1px solid rgba( white, 0.5 );
		flex-grow: 1;
		flex-direction: column;
		padding: 10px 15px;


		> textentry.textentry
		{
			flex-grow: 0;
			flex-shrink: 0;
			width: auto;
		}
	}

	.slider
	{
		padding: 6.5px;
	}

	.slider .track
	{
		height: 14px;
		border-radius: 14px;
		left: 0px;
		right: 0px;
		transition: all 0.1s ease-out;

		.inner
		{
			display: none;
		}
	}

	.slider:hover, .slider:active
	{
		padding: 7px;

		.track
		{
			height: 20px;
			border-radius: 6px;
		}

		.thumb
		{
			width: 10px;
			height: 16px;
			margin-left: 2px;
		}
	}

	.slider .thumb
	{
		width: 10px;
		height: 10px;
		box-shadow: 0px 0px 0px transparent;
		background-color: white;
		backdrop-filter: invert( 1 );
		margin-left: 1px;
		pointer-events: none;
	}

	.alpha_slider .track
	{
		background-image: linear-gradient( to right, rgba( #ccc, 0.05 ), rgba( #ccc, 0.9 ) );
	}

	.hue .track
	{
		background: linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);

		.inner
		{
			display: none;
		}
	}

	.satval
	{
		background: linear-gradient(to right, white, transparent);
		height: 200px;
		position: relative;

		&:active
		{
			z-index: 10;
			cursor: none;
		}

		.value_gradient
		{
			background: linear-gradient(to bottom, black, white);
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			pointer-events: none;
			mix-blend-mode: multiply;
		}

		.thumb
		{
			z-index: 10;
		}
	}

	.presets
	{
		flex-wrap: wrap;
		align-content: center;
		justify-content: center;
		padding: 15px;
		border-top: 1px solid rgba( white, 0.5 );

		.preset
		{
			background-color: white;
			width: 16px;
			height: 16px;
			margin: 2px;
			border-radius: 20px;
			cursor: pointer;
			
			&:hover
			{
				box-shadow: 0px 0px 1px 2px white;
			}
		}
	}
}


.coloreditorrgba
{
	flex-direction: column;

	.slider
	{
		padding-right: 16px;
	}

	.slider .track
	{
		background-color: transparent;
		height: 14px;
		border-radius: 14px;
		left: 0px;
		right: 0px;

		.inner
		{
			display: none;
		}
	}

	.slider .thumb
	{
		width: 12px;
		height: 12px;
		box-shadow: 0px 0px 0px transparent;
		background-color: white;
		margin-left: 2px;
		backdrop-filter: invert( 1 );
	}

	.red_slider .track
	{
		background-image: linear-gradient( to right, rgba( #e63439, 0.1 ), rgba( #e63439, 0.9 ) );
	}

	.green_slider .track
	{
		background-image: linear-gradient( to right, rgba( #54be35, 0.1 ), rgba( #54be35, 0.9 ) );
	}

	.blue_slider .track
	{
		background-image: linear-gradient( to right, rgba( #3472e6, 0.1 ), rgba( #3472e6, 0.9 ) );
	}

	.alpha_slider .track
	{
		background-image: linear-gradient( to right, rgba( #ccc, 0.05 ), rgba( #ccc, 0.9 ) );
	}
}


.coloreditorhsva
{
	flex-direction: column;

	.slider
	{
		padding-right: 16px;
	}

	.slider .track
	{
		background-color: transparent;
		height: 14px;
		border-radius: 14px;
		left: 0px;
		right: 0px;

		.inner
		{
			display: none;
		}
	}

	.slider .thumb
	{
		width: 12px;
		height: 12px;
		box-shadow: 0px 0px 0px transparent;
		background-color: white;
		margin-left: 2px;
		backdrop-filter: invert( 1 );
	}
		
	.hue_slider .track
	{
		background-image: linear-gradient( to right, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00 );
	}

	.alpha_slider .track
	{
		background-image: linear-gradient( to right, rgba( #ccc, 0.05 ), rgba( #ccc, 0.9 ) );
	}
}
MapChooser {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    pointer-events: all;
    background: linear-gradient( 140deg, #0f141a 0%, #0a0e14 60%, #111926 100% );
    justify-content: flex-start;
    align-items: stretch;
    font-weight: bold;
    font-family: Poppins;
    color: white;
    flex-direction: column;
    padding: 48px 60px;
    gap: 24px;

    .header {
        flex-direction: column;
        gap: 6px;

        h1 {
            font-size: 48px;
            letter-spacing: 1px;
        }

        .subtitle {
            font-size: 16px;
            opacity: 0.65;
        }
    }

    .content {
        flex-grow: 1;
        flex-direction: row;
        gap: 24px;
    }

    .map-list {
        flex-direction: column;
        flex-grow: 1;
        min-width: 0;

        .map-entries {
            flex-direction: column;
            gap: 10px;
            padding: 12px;
            border-radius: 16px;
            background: #0a0c10cc;
            border: 1px solid #ffffff14;
            overflow-y: scroll;
        }

        button {
            padding: 12px 14px;
            border-radius: 12px;
            background: #ffffff0f;
            text-align: left;
            transition: transform 0.12s ease, box-shadow 0.12s ease, background 0.12s ease;
            gap: 4px;
            cursor: pointer;
            flex-direction: row;
            align-items: center;
        }

            button:hover {
                transform: translateY( -1px );
                box-shadow: 0 6px 18px rgba( 0, 0, 0, 0.35 );
            }

            button.active {
                background: #db3984;
                box-shadow: 0 6px 18px rgba( 219, 57, 132, 0.35 );
            }

        .title {
            font-size: 18px;
        }

        .thumb {
            width: 84px;
            height: 48px;
            border-radius: 10px;
            background-color: #0b0f15;
            background-position: center;
            background-size: cover;
            flex-shrink: 0;
            box-shadow: inset 0 0 0 1px #ffffff12;
        }

        .text {
            flex-direction: column;
            gap: 2px;
        }

        .ident {
            font-size: 12px;
            opacity: 0.6;
        }
    }

    .settings {
        width: 360px;
        padding: 16px;
        border-radius: 16px;
        background: #0a0c10cc;
        border: 1px solid #ffffff14;
        flex-direction: column;
        gap: 14px;
    }

    .section-title {
        font-size: 18px;
        text-transform: uppercase;
        letter-spacing: 1px;
        opacity: 0.85;
    }

    .field {
        flex-direction: column;
        gap: 6px;

        label {
            font-size: 14px;
            opacity: 0.7;
        }

        textentry {
            width: 100%;
            padding: 8px 10px;
            background: #ffffff0f;
            border-radius: 8px;
        }
    }

        .field.split {
            flex-direction: row;
            gap: 12px;

            .field {
                flex-grow: 1;
            }
        }

    .privacy {
        flex-direction: row;
        gap: 8px;

        button {
            flex-grow: 1;
            padding: 8px 10px;
            border-radius: 8px;
            background: #ffffff0f;
            opacity: 0.7;
            cursor: pointer;
            transition: transform 0.12s ease, box-shadow 0.12s ease, opacity 0.12s ease, background 0.12s ease;
        }

            button:hover {
                opacity: 0.9;
                transform: translateY( -1px );
            }

            button.active {
                background: #db3984;
                opacity: 1;
                box-shadow: 0 6px 16px rgba( 219, 57, 132, 0.35 );
                transform: translateY( -1px );
            }
    }

    .selected-map {
        padding: 10px 12px;
        border-radius: 10px;
        background: #ffffff0a;
        flex-direction: column;
        gap: 4px;

        .label {
            font-size: 12px;
            opacity: 0.6;
        }
    }

    .launch {
        margin-top: 4px;
        padding: 12px;
        border-radius: 10px;
        background: #47c27c;
        color: #0b0f12;
        font-size: 18px;
    }

        .launch.disabled {
            opacity: 0.4;
            background: #ffffff1f;
            color: white;
        }
}
@import "/styles/_theme.scss";
$background-size: 8px;

PackageCard
{
	flex-shrink: 0;

	&:hover
	{
		sound-in: "ui.button.over";
	}

	&:active
	{
		sound-in: "ui.button.press";
	}

	flex-direction: column;
	position: relative;
	background-color: rgba( $default-950, 0 );
	border-radius: $rounding-default;
	transition: all 150ms ease;
	cursor: pointer;
	z-index: 0;
	height: 200px;

	.image
	{
		flex-grow: 1;
		flex-shrink: 0;
		transition: all 150ms ease;
		border: 1px solid rgba( white, 0.025 );
		aspect-ratio: 16 / 9;
		background-position: center;
		background-size: cover;
		border-radius: $rounding-small;
		position: relative;
	}

	column
	{
		padding: 8px 2px; // Optically aligned
	}

	&.list
	{
		flex-grow: 1;
		height: 64px;
		flex-direction: row;
		gap: 12px;
		padding: 4px;

		.inner column
		{
			flex-grow: 1;
		}

		.image
		{
			height: 100%;
			aspect-ratio: 1;
			flex-grow: 0;
			flex-shrink: 0;
		}

		column
		{
			gap: 3px;
			justify-content: center;
		}

		.package-title
		{
			flex-shrink: 0;
			max-width: 500px;
		}

		.package-users
		{
			top: 1px;
			right: 1px;
		}

		&:hover
		{
			background-color: $default-800;
			transform: none;

			&::after
			{
				display: none;
			}
		}
	}

	&.wide
	{
		height: 250px;

		.package-title
		{
			max-width: 300px;
		}
	}

	&.small
	{
		height: 200px;
		aspect-ratio: 3/4;

		.image
		{
			aspect-ratio: 1;
		}

		.package-title
		{
			max-width: 140px;
		}
	}

	&.tall
	{
		height: 400px;

		.image
		{
			aspect-ratio: 9/16;
		}

		.package-title
		{
			max-width: 200px;
		}
	}

	.package-title
	{
		text-overflow: ellipsis;
		max-height: 24px;
		flex-shrink: 1;
		font-size: 14px;
	}

	.package-users
	{
		position: absolute;
		bottom: 4px;
		right: 4px;
		background-color: rgba( 10, 40, 10, 0.95 );
		padding: 3px 5px;
		border-radius: 2px;
		justify-content: center;
		align-items: center;
		gap: 3px;
		font-size: 11px;
		color: #def;
		border: 1px solid #252;
		color: #2f3;

		&:before
		{
			content: '●';
			font-size: 0.5rem;
		}
	}
	// Hover effect (not for list)
	&:not(.list)
	{
		&::after
		{
			content: "";
			position: absolute;
			top: 0;
			left: 0;
			bottom: 0;
			right: 0;
			background-color: rgba( $default-950, 0 );
			transition: all 150ms ease;
			z-index: -10;
			border-radius: $rounding-large;
			pointer-events: none;
		}

		&:hover
		{
			transform: scale( 1.05 );

			&::after
			{
				background-color: $default-800;
				top: -$background-size;
				left: -$background-size;
				right: -$background-size;
				bottom: -$background-size;
				box-shadow: 0 0 25px rgba( black, 0.3 );
			}

			z-index: 100;
			background-color: $default-900;
		}
	}
}
namespace Skateboard.Entities;

public sealed class GrindPathNodeEntity : Component
{
}

$primary: red !default;
$primary-alt: white !default;

$switch-padding: 6px !default;

.checkbox.switch
{
	cursor: pointer;

	> .checkmark
	{
		font-size: 22px;
		border: 0px solid $primary;
		border-radius: 100px;
		text-align: center;
		justify-content: center;
		align-items: center;
		color: $primary-alt;
		padding: $switch-padding;
		padding-right: 32px;
		padding-left: $switch-padding;
		transition: all 0.3s ease;
		background-color: rgba( $primary, 0.1 );

		> .handle
		{
			background-color: $primary-alt;
			width: 20px;
			height: 20px;
			border-radius: 100px;
			box-shadow: 2px 2px 12px black;
		}
	}

	&.checked
	{
		> .checkmark
		{
			background-color: $primary;
			padding-left: 32px;
			padding-right: $switch-padding;
		}
	}

	&:active
	{
		transform: scale( 0.9 );
		transform-origin: 20px 50%;
	}
}

.slidercontrol
{
    flex-direction: row;
    min-width: 50px;
    position: relative;
    flex-shrink: 0;
    flex-direction: row;
    cursor: pointer;
    gap: 8px;
    flex-grow: 1;
    align-items: center;
    pointer-events: all;

    > .inner
    {
        flex-direction: column;
        flex-shrink: 1;
        flex-grow: 1;
        min-height: 32px;
        justify-content: center;

        > .values
        {
            width: 100%;
            pointer-events: none;
            font-size: 14px;
            color: #aaa;

            > .left
            {
                flex-grow: 1;
            }
        }

        > .track
        {
            position: relative;
            background-color: #888;
            height: 7px;
            margin: 8px;
            align-items: center;
            border-radius: 4px;

            > .track-active
            {
                background-color: #fff;
                position: absolute;
                height: 100%;
                left: 0px;
                border-radius: 4px;
            }

            > .thumb
            {
                position: relative;
                background-color: #fff;
                border-radius: 100px;
                width: 16px;
                height: 16px;
                transform: translateX( -50% );
            }
        }
    }

    > .entry
    {
        flex-shrink: 0;
        flex-grow: 0;
        width: 50px;

        > numberentry
        {
            background-color: transparent;

            > .content-label
            {
                padding: 0 4px;
            }
        }
    }
}


.slidercontrol .value-tooltip
{
    position: absolute;
    bottom: 150%;
    left: -8px;
    z-index: 1000;
    flex-direction: column;

    > .label
    {       
        background-color: black;
        padding: 8px 12px;
        border-radius: 8px;
    }

    >.tail
    {
        bottom: -0px;
        background-color: black;
        width: 10px;
        height: 10px;
        transform: rotateZ(45 deg) translateX( 4px );
        position: absolute;
    }
}

$primary: red !default;
$primary-alt: white !default;

$switch-padding: 6px !default;

.button.popupbutton.dropdown
{
	cursor: pointer;
	transition: all .1s ease-out;
	position: relative;

	> .dropdown_indicator
	{
		position: absolute;
		right: 8px;
	}

	&.open
	{
		border-bottom-left-radius: 1px;
		border-bottom-right-radius: 1px;
		transition: border-radius 0.2s ease-out;
	}
}

select
{
	min-height: 40px;

	> option
	{
		display: none;
	}
}

$primary: red !default;
$primary-alt: white !default;

$switch-padding: 6px !default;

.coloreditor
{
	flex-direction: column;
	min-width: 250px;
	max-width: 250px;

	> .canvas
	{
		border-top: 1px solid rgba( white, 0.5 );
		flex-grow: 1;
		flex-direction: column;
		padding: 10px 15px;


		> textentry.textentry
		{
			flex-grow: 0;
			flex-shrink: 0;
			width: auto;
		}
	}

	.slider
	{
		padding: 6.5px;
	}

	.slider .track
	{
		height: 14px;
		border-radius: 14px;
		left: 0px;
		right: 0px;
		transition: all 0.1s ease-out;

		.inner
		{
			display: none;
		}
	}

	.slider:hover, .slider:active
	{
		padding: 7px;

		.track
		{
			height: 20px;
			border-radius: 6px;
		}

		.thumb
		{
			width: 10px;
			height: 16px;
			margin-left: 2px;
		}
	}

	.slider .thumb
	{
		width: 10px;
		height: 10px;
		box-shadow: 0px 0px 0px transparent;
		background-color: white;
		backdrop-filter: invert( 1 );
		margin-left: 1px;
		pointer-events: none;
	}

	.alpha_slider .track
	{
		background-image: linear-gradient( to right, rgba( #ccc, 0.05 ), rgba( #ccc, 0.9 ) );
	}

	.hue .track
	{
		background: linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);

		.inner
		{
			display: none;
		}
	}

	.satval
	{
		background: linear-gradient(to right, white, transparent);
		height: 200px;
		position: relative;

		&:active
		{
			z-index: 10;
			cursor: none;
		}

		.value_gradient
		{
			background: linear-gradient(to bottom, black, white);
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			pointer-events: none;
			mix-blend-mode: multiply;
		}

		.thumb
		{
			z-index: 10;
		}
	}

	.presets
	{
		flex-wrap: wrap;
		align-content: center;
		justify-content: center;
		padding: 15px;
		border-top: 1px solid rgba( white, 0.5 );

		.preset
		{
			background-color: white;
			width: 16px;
			height: 16px;
			margin: 2px;
			border-radius: 20px;
			cursor: pointer;
			
			&:hover
			{
				box-shadow: 0px 0px 1px 2px white;
			}
		}
	}
}


.coloreditorrgba
{
	flex-direction: column;

	.slider
	{
		padding-right: 16px;
	}

	.slider .track
	{
		background-color: transparent;
		height: 14px;
		border-radius: 14px;
		left: 0px;
		right: 0px;

		.inner
		{
			display: none;
		}
	}

	.slider .thumb
	{
		width: 12px;
		height: 12px;
		box-shadow: 0px 0px 0px transparent;
		background-color: white;
		margin-left: 2px;
		backdrop-filter: invert( 1 );
	}

	.red_slider .track
	{
		background-image: linear-gradient( to right, rgba( #e63439, 0.1 ), rgba( #e63439, 0.9 ) );
	}

	.green_slider .track
	{
		background-image: linear-gradient( to right, rgba( #54be35, 0.1 ), rgba( #54be35, 0.9 ) );
	}

	.blue_slider .track
	{
		background-image: linear-gradient( to right, rgba( #3472e6, 0.1 ), rgba( #3472e6, 0.9 ) );
	}

	.alpha_slider .track
	{
		background-image: linear-gradient( to right, rgba( #ccc, 0.05 ), rgba( #ccc, 0.9 ) );
	}
}


.coloreditorhsva
{
	flex-direction: column;

	.slider
	{
		padding-right: 16px;
	}

	.slider .track
	{
		background-color: transparent;
		height: 14px;
		border-radius: 14px;
		left: 0px;
		right: 0px;

		.inner
		{
			display: none;
		}
	}

	.slider .thumb
	{
		width: 12px;
		height: 12px;
		box-shadow: 0px 0px 0px transparent;
		background-color: white;
		margin-left: 2px;
		backdrop-filter: invert( 1 );
	}
		
	.hue_slider .track
	{
		background-image: linear-gradient( to right, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00 );
	}

	.alpha_slider .track
	{
		background-image: linear-gradient( to right, rgba( #ccc, 0.05 ), rgba( #ccc, 0.9 ) );
	}
}

menupanel
{
    position: absolute;
    z-index: 1000;
    pointer-events: all;
    font-size: 12px;
    flex-shrink: 0;

    .background
    {
        position: absolute;
        left: -5000px;
        right: -5000px;
        top: -5000px;
        bottom: -5000px;
    }

    > .inner
    {
        min-width: 200px;
        min-height: 20px;
        flex-direction: column;
        font-family: Poppins;
        font-weight: bold;
        border-radius: 10px;
        box-shadow: 5px 5px 30px #000e;
        background-color: #2a2a2a;
        flex-shrink: 0;

        .spacer
        {
            height: 1px;
            background-color: #0005;
        }

        .option
        {
            color: #fffa;
            padding: 0px 8px;
            cursor: pointer;
            flex-shrink: 0;
            height: 32px;

            &:first-child
            {
                border-top-left-radius: 10px;
                border-top-right-radius: 10px;
            }

            &:last-child
            {
                border-bottom-left-radius: 10px;
                border-bottom-right-radius: 10px;
            }

            .icon
            {
                padding: 8px;
                font-family: Material Icons;
                justify-content: center;
                align-items: center;
                flex-shrink: 0;
            }

            .text
            {
                padding: 8px;
                flex-shrink: 0;
            }

            &:hover
            {
                background-color: #3472e6;
                color: #f5f8fe;
            }
        }
    }
}
ColorAlphaControl
{
	gap: 0.5rem;
	flex-grow: 1;
	pointer-events: all;
	background: linear-gradient( to right, black, white );
	border-radius: 4px;
	padding: 2px;
	height: 12px;
	position: relative;
	cursor: pointer;
	border: 1px solid #333;

	&:hover
	{
		border: 1px solid #08f;
	}

	&:active
	{
		border: 1px solid #fff;
	}

	.handle
	{
		top: -5px;
		bottom: -5px;
		aspect-ratio: 1;
		border-radius: 100px;
		border: 2px solid #444;
		position: absolute;
		background-color: white;
		box-shadow: 2px 2px 16px #000a;
		transform: translateX( -50% );
		pointer-events: none;
	}
}

@import "/styles/_theme.scss";

$primary: $primary-blue !default;
$primary-alt: white !default;
$form-control-height: 24px !default;

.checkbox
{
	cursor: pointer;
	color: rgba( $primary-alt, 0.6 );
	align-items: center;
	gap: 8px;

	label
	{
		pointer-events: none;
	}

	> .checkmark
	{
		padding: 1px;
		font-size: 22px;
		border: 1px solid $primary;
		border-radius: $rounding-small;
		text-align: center;
		justify-content: center;
		align-items: center;
		color: transparent;
		min-height: $form-control-height;
		pointer-events: none;
		flex-shrink: 0;
	}

	&.checked
	{
		> .checkmark
		{
			color: $primary-alt;
			background-color: $primary;
		}
	}

	&:active
	{
		color: $primary-alt;
	}

	&:hover
	{
		color: $primary-alt;
	}
}
#nullable enable

using Sandbox;

public abstract class Item
{
    public Scene? Scene {get;set;} = null;
    public GameObject? GameObject {get;set;} = null;
    public string Name {get;set;} = "empty";
    
    public abstract Item Init();
    public abstract void Act();
    public abstract void Drop();
}
using Sandbox;

public class SCP_173_SFX : Component
{
    [Property] public CharacterController Character_Controller {get;set;}
    [Property] public SoundPointComponent Rattle {get;set;}
    
    protected override void OnUpdate()
    { if (IsProxy) return;
        if (Character_Controller.IsOnGround && Character_Controller.Velocity.LengthSquared > 0
        && !GameObject.Tags.Has("seen")) {Rattle.StartSound(); return;} Rattle.StopSound();
    }
}


.colorproperty
{
	align-items: center;
	position: relative;

	.colorsquare
	{
		width: 20px;
		height: 20px;
		border-radius: 4px;
		margin-right: 8px;
		position: absolute;
		left: 7px;
		z-index: 1;
		cursor: pointer;
	}

	> .textentry:not( .a.b.c )
	{
		padding-left: 36px;
	}
}
VectorControl
{
	gap: 2px;
	flex-grow: 1;
}

VectorControl NumberEntry
{
	flex-basis: 50%;
}

ControlSheetRow
{
	flex-direction: row;
	flex-shrink: 0;
	max-height: 32px;
	border-radius: 4px;

	&.hidden
	{
		display: none;
	}
}

ControlSheetRow > .left
{
	width: 150px;
	flex-shrink: 0;
	flex-grow: 0;
	padding: 6px;
}

ControlSheetRow > .right
{
	flex-grow: 1;
}

ControlSheetRow > .left > .title
{
	width: 150px;
	flex-shrink: 0;
	flex-grow: 0;
	font-size: 13px;
	white-space: nowrap;
	overflow: hidden;
}

ControlSheetRow > .right > textentry,
ControlSheetRow > .right numberentry
{
	background-color: #000a;
	flex-grow: 1;
	padding: 4px 8px;
	border-radius: 2px;
}

.package-list
{
    flex-shrink: 1;
    flex-wrap: wrap;
    flex-grow: 1;

    h1
    {
        width: 100%;
        margin-top: 50px;
        font-size: 40px;
    }

    PackageCard
    {
        &:hover
        {
            sound-in: "ui.button.over";
        }
    }

    VirtualGrid
    {
        width: 100%;
        height: 100%;

        .cell
        {
            
        }
    }
}

@import "/styles/_theme.scss";

.packagefilter
{
	width: 100%;
	flex-shrink: 0;

	.left
	{
		flex-grow: 1;
		flex-shrink: 0;
		gap: 16px;
	}

	.right
	{
		flex-grow: 1;
		flex-shrink: 0;
		gap: 16px;
	}
}

.packagefilter textentry
{
	flex-grow: 1;
	padding: 8px 12px;
	pointer-events: all;

	Label
	{
		margin-left: 26px;
	}

	iconpanel
	{
		position: absolute;
		left: 12px;
		opacity: 0.3;
		font-size: $text-large;
	}
}

	.packagefilterfacet, .packagefilter textentry
	{
		background-color: rgba($default-950, 0.3);
		color: $default-text;
		outline: 1px solid $default-border;
		transition: all 150ms $easing;
		border-radius: $rounding-default;
		padding: 4px 12px;
		gap: 16px;
		flex-shrink: 0;
		font-size: 14px;
		cursor: pointer;
		align-items: center;

		.clear-button
		{
			height: 100%;
			margin-right: -8px;
			align-items: center;
			padding: 0px 4px;

			&:hover
			{
				color: red;
				border-radius: 100%;
			}
		}

		&.is-active
		{
			background-color: $default-700;
		}

		&:not(.is-active)
		{
			&:hover
			{
				outline: 1px solid $default-50;
			}
		}
	}
@import "/styles/_theme.scss";
$background-size: 8px;

PackageCard
{
	flex-shrink: 0;

	&:hover
	{
		sound-in: "ui.button.over";
	}

	&:active
	{
		sound-in: "ui.button.press";
	}

	flex-direction: column;
	position: relative;
	background-color: rgba( $default-950, 0 );
	border-radius: $rounding-default;
	transition: all 150ms ease;
	cursor: pointer;
	z-index: 0;
	height: 200px;

	.image
	{
		flex-grow: 1;
		flex-shrink: 0;
		transition: all 150ms ease;
		border: 1px solid rgba( white, 0.025 );
		aspect-ratio: 16 / 9;
		background-position: center;
		background-size: cover;
		border-radius: $rounding-small;
		position: relative;
	}

	column
	{
		padding: 8px 2px; // Optically aligned
	}

	

	&.list
	{
		flex-grow: 1;
		height: 64px;
		flex-direction: row;
		gap: 12px;
		padding: 4px;

		.inner column
		{
			flex-grow: 1;
		}

		.image
		{
			height: 100%;
			aspect-ratio: 1;
			flex-grow: 0;
			flex-shrink: 0;
		}

		column
		{
			gap: 3px;
			justify-content: center;
		}

		.package-title
		{
			flex-shrink: 0;
			max-width: 500px;
		}

		.package-users
		{
			top: 1px;
			right: 1px;
		}

		&:hover
		{
			background-color: $default-800;
			transform: none;

			&::after
			{
				display: none;
			}
		}
	}

	&.wide
	{
		height: 250px;

		.package-title
		{
			max-width: 300px;
		}
	}

	&.small
	{
		height: 200px;
		aspect-ratio: 3/4;

		.image
		{
			aspect-ratio: 1;
		}

		.package-title
		{
			max-width: 140px;
		}
	}

	&.tall
	{
		height: 400px;

		.image
		{
			aspect-ratio: 9/16;
		}

		.package-title
		{
			max-width: 200px;
		}
	}

	.package-title
	{
		text-overflow: ellipsis;
		max-height: 24px;
		flex-shrink: 1;
		font-size: 14px;
	}

	.package-users
	{
		position: absolute;
		bottom: 4px;
		right: 4px;
		background-color: rgba( 10, 40, 10, 0.95 );
		padding: 3px 5px;
		border-radius: 2px;
		justify-content: center;
		align-items: center;
		gap: 3px;
		font-size: 11px;
		color: #def;
		border: 1px solid #252;
		color: #2f3;

		&:before
		{
			content: '●';
			font-size: 0.5rem;
		}
	}
	// Hover effect (not for list)
	&:not(.list)
	{
		&::after
		{
			content: "";
			position: absolute;
			top: 0;
			left: 0;
			bottom: 0;
			right: 0;
			background-color: rgba( $default-950, 0 );
			transition: all 150ms ease;
			z-index: -10;
			border-radius: $rounding-large;
			pointer-events: none;
		}

		&:hover
		{
			transform: scale( 1.05 );

			&::after
			{
				background-color: $default-800;
				top: -$background-size;
				left: -$background-size;
				right: -$background-size;
				bottom: -$background-size;
				box-shadow: 0 0 25px rgba( black, 0.3 );
			}

			z-index: 100;
			background-color: $default-900;
		}
	}
}


.package-card.list packageflairbar
{
	display: none;
}

.package-card.list .package-users
{
	display: none;
}
ColorControl
{
	gap: 0.5rem;
	flex-grow: 1;
	pointer-events: all;
	background-color: #000a;
	border-radius: 4px;
	padding: 2px;
	height: 32px;
}

ColorControl TextEntry
{
	flex-grow: 1;
	flex-shrink: 0;
	color: #aaa;
	font-size: 1.2rem;

	&:hover, &:focus
	{
		color: #ddd;

		.icon
		{
			color: #3af;
		}
	}

	&:active
	{
		color: white;
	}
}

ColorControl > .colorswatch
{
	aspect-ratio: 1;
	border-radius: 4px;
	height: 100%;
	flex-shrink: 0;
	cursor: pointer;
	border: 2px solid #000;
}
ComponentHandle
{
	width: 38px;
	height: 38px;
	background-color: #eee;
	box-shadow: 2px 2px 16px black;
	border-radius: 20px;
	position: absolute;
	justify-content: center;
	align-items: center;
	cursor: pointer;
	transform: scale( 1 ) translateX( -50% ) translateY( -50% );
	z-index: 100;

	.icon
	{
		font-family: "Material Icons";
		color: #08f;
		font-size: 23px;
		pointer-events: none;
	}

	&:hover
	{
		opacity: 1;
		background-color: #fff;
	}

	&:active
	{
		border: 1px solid #08f;
		background-color: #fff;
		opacity: 1;
		transform: scale( 0.95 ) translateX( -50% ) translateY( -50% );
	}

	&.active
	{
		border: 2px solid #fff;
		background-color: #08f;
		opacity: 1;

		.icon
		{
			color: #fff;
		}
	}

	&:outro
	{
		transform: scale( 0 ) translateX( -50% ) translateY( -50% );
		transition: transform 0.2s ease-out;
	}
}

ControlSheetRow
{
	flex-direction: row;
	flex-shrink: 0;
	max-height: 32px;
	border-radius: 4px;

	&.hidden
	{
		display: none;
	}
}

ControlSheetRow > .left
{
	width: 150px;
	flex-shrink: 0;
	flex-grow: 0;
	padding: 6px;
}

ControlSheetRow > .right
{
	flex-grow: 1;
}

ControlSheetRow > .left > .title
{
	width: 150px;
	flex-shrink: 0;
	flex-grow: 0;
	font-size: 13px;
	white-space: nowrap;
	overflow: hidden;
}

ControlSheetRow > .right > textentry,
ControlSheetRow > .right numberentry
{
	background-color: #000a;
	flex-grow: 1;
	padding: 4px 8px;
	border-radius: 2px;
}

@import "/UI/Theme.scss";

PressableHud
{
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	justify-content: center;
	align-items: center;
	font-family: $body-font;
	font-size: 14px;
	font-weight: 600;
	z-index: 1000;
	opacity: 0.2;

	.crosshair
	{
		width: 12px;
		height: 12px;
		background-color: white;
		border-radius: 50%;
		box-shadow: 0px 0px 8px black;
		opacity: 0;
		transition: all 0.1s linear;
	}

	&.active
	{
		opacity: 1;

		.crosshair
		{
			opacity: 1;
		}
	}
}
$deadzone-x: 2vw;
$deadzone-y: 2vw;

$color-accent: #0094ff;
$color-text: #fafaff;

$title-font: "Poppins";
$body-font: "Inter";
$subtitle-font: "Poppins";

@import "/UI/Menu.scss";
@import "/UI/Hud.scss";
@import "/UI/Theme.scss";

FacePoseEditor
{
    flex-direction: column;
    width: 100%;
    max-height: 400px;
}

FacePoseEditor .group-header
{
    font-size: 11px;
    font-weight: 700;
    color: rgba( 255, 255, 255, 0.35 );
    padding: 6px 6px 2px 6px;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    flex-shrink: 0;
}
$menu-color:#cdf;
$menu-text: #fffa;
$menu-text-strong: #fff;
$menu-surface-soft: #0004;
$menu-accent: $color-accent;
$menu-accent-soft: rgba($color-accent, 0.13);
$menu-panel-bg: #0c202fcc;

.menu-header-bar
{
	border-radius: 8px 8px 0 0;
	z-index: 100;
	font-family: $title-font;
	font-weight: 600;
}

.menu-input
{
	background-color: $menu-surface-soft;
	border-radius: 8px;
	padding: 2px 10px;
}

.menu-segmented-group
{
	background-color: #0008;
	border-radius: 8px;
	overflow: visible;
}

.menu-mode-button
{
	color: $menu-text;
	font-size: 1rem;
	font-weight: 600;
	padding: 1rem;
	font-family: $subtitle-font;
	cursor: pointer;
	pointer-events: all;
	justify-content: center;
	align-items: center;
	overflow: visible;
	border-radius: 8px;

	.icon
	{
		margin-left: -4px;
		margin-top: -1.5px;
		padding-right: 4px;
		font-size: 1.5rem;
	}

	.title
	{
		font-size: 1.1rem;
		font-weight: 700;
	}

	&:hover
	{
		color: $menu-text-strong;
	}

	&.active
	{
		outline: 1px solid $menu-accent;
		background-color: rgba( $menu-accent, 0.2 );
		color: $menu-text-strong;
	}
}

.menu-icon-toggle-group
{
	background-color: $menu-surface-soft;
	border-radius: 8px;
	gap: 0.5rem;
	padding: 4px 4px;
	padding-left: 8px;
	align-items: center;

	IconPanel
	{
		width: 20px;
		aspect-ratio: 1;
		opacity: 0.35;
		align-items: center;
		cursor: pointer;

		&:hover
		{
			opacity: 0.7;
		}

		&.active
		{
			opacity: 1;
		}
	}
}

span
{
	&.grow
	{
		gap: 8px;

		> *
		{
			flex-grow: 1;
		}
	}
}

.menu-action
{
	color: $menu-text-strong;
	border: 1px solid transparent;
	border-radius: 4px;
	cursor: pointer;
	padding: 6px 10px;
	align-items: center;
	justify-content: center;
	gap: 0.5rem;
	font-weight: 600;

	label, .title
	{
		font-size: 14px;
	}

	IconPanel, .icon
	{
		font-size: 1.2rem;
	}

	&.disabled
	{
		pointer-events: none;
		opacity: 0.25;
	}

	&.soft
	{
		background-color: $menu-accent-soft;

		&:hover
		{
			background-color: rgba($color-accent, 0.4);
			sound-in: ui.button.over;
		}
	}

	&.primary
	{
		border-color: $menu-accent;

		&:hover
		{
			background-color: $menu-accent-soft;
			sound-in: ui.button.over;
		}
	}

	&.wide
	{
		width: 100%;
	}
}

.menu-filter-input
{
	width: 200px;
}

TextEntry 
{
	color: $color-text;
	font-family: $body-font;
}
using Sandbox.UI;

namespace Sandbox;

public interface ICleanupEvents
{
	public void OnCleanup( int removedObjects, int restoredObjects );
}

/// <summary>
/// A system that tracks the baseline scene state and allows resetting the map to its original state.
/// Removes all spawned props and restores destroyed map objects while leaving players untouched.
/// </summary>
internal sealed class CleanupSystem : GameObjectSystem<CleanupSystem>, ISceneLoadingEvents
{
	/// <summary>
	/// Set of GameObjects that existed in the original scene baseline.
	/// </summary>
	private readonly HashSet<Guid> _baselineObjectIds = new();

	/// <summary>
	/// Serialized data of baseline objects so we can restore them if destroyed.
	/// </summary>
	private readonly Dictionary<Guid, string> _baselineObjectData = new();

	private static bool _restorePersistedBaseline;
	private static HashSet<Guid> _persistedBaselineIds;
	private static Dictionary<Guid, string> _persistedBaselineData;

	/// <summary>
	/// Whether a baseline has been captured.
	/// </summary>
	public bool HasBaseline => _baselineObjectIds.Count > 0;

	public CleanupSystem( Scene scene ) : base( scene )
	{
	}

	/// <summary>
	/// Call from SaveSystem before Game.ChangeScene() to snapshot the current baseline
	/// </summary>
	public static void PreserveBaselineForSaveLoad()
	{
		if ( Current is null || !Current.HasBaseline ) return;

		_restorePersistedBaseline = true;
		_persistedBaselineIds = new HashSet<Guid>( Current._baselineObjectIds );
		_persistedBaselineData = new Dictionary<Guid, string>( Current._baselineObjectData );
	}

	void ISceneLoadingEvents.BeforeLoad( Scene scene, SceneLoadOptions options )
	{
		// Clear any existing baseline when a new scene is loading
		_baselineObjectIds.Clear();
		_baselineObjectData.Clear();
	}

	async Task ISceneLoadingEvents.OnLoad( Scene scene, SceneLoadOptions options, LoadingContext context )
	{
		// We don't care if the game is not playing
		if ( !Game.IsPlaying ) return;

		// Wait for next frame to ensure all objects are spawned
		await Task.Yield();

		// Could be null if the scene was unloaded before this runs
		if ( !Scene.IsValid() ) return;

		// When loading a save, restore the baseline captured before the scene was destroyed
		if ( _restorePersistedBaseline && _persistedBaselineIds is not null )
		{
			_baselineObjectIds.UnionWith( _persistedBaselineIds );
			foreach ( var kvp in _persistedBaselineData )
				_baselineObjectData.TryAdd( kvp.Key, kvp.Value );

			_restorePersistedBaseline = false;
			Log.Info( $"CleanupSystem: Restored persisted baseline with {_baselineObjectIds.Count} objects." );
		}
		else
		{
			CaptureBaseline();
		}
	}

	/// <summary>
	/// Captures the current scene state as the baseline.
	/// All objects that exist at this point are considered part of the original map.
	/// </summary>
	public void CaptureBaseline()
	{
		_baselineObjectIds.Clear();
		_baselineObjectData.Clear();

		foreach ( var go in Scene.Children?.ToArray() ?? [] )
		{
			CaptureObjectRecursive( go );
		}

		Log.Info( $"CleanupSystem: Captured baseline with {_baselineObjectIds.Count} objects." );
	}

	private void CaptureObjectRecursive( GameObject go )
	{
		if ( !go.IsValid() )
			return;

		// Skip player objects
		if ( IsPlayerObject( go ) )
			return;

		if ( go.Flags.Contains( GameObjectFlags.DontDestroyOnLoad ) )
			return;

		_baselineObjectIds.Add( go.Id );

		var serialized = go.Serialize();
		if ( serialized is not null )
		{
			_baselineObjectData[go.Id] = serialized.ToJsonString();
		}

		foreach ( var child in go.Children?.ToArray() ?? [] )
		{
			CaptureObjectRecursive( child );
		}
	}

	/// <summary>
	/// Determines if a GameObject is a player or belongs to a player.
	/// </summary>
	private static bool IsPlayerObject( GameObject go )
	{
		if ( !go.IsValid() )
			return false;

		if ( go.Components.Get<Player>( true ) is not null )
			return true;

		if ( go.Components.Get<PlayerData>( true ) is not null )
			return true;

		var parent = go.Parent;
		while ( parent is not null && parent != go.Scene )
		{
			if ( parent.Components.Get<Player>( true ) is not null )
				return true;
			if ( parent.Components.Get<PlayerData>( true ) is not null )
				return true;
			parent = parent.Parent;
		}

		return false;
	}

	/// <summary>
	/// Cleans up the scene by removing all spawned objects and restoring destroyed baseline objects.
	/// Players and their belongings are preserved.
	/// </summary>
	public void Cleanup()
	{
		if ( !HasBaseline )
		{
			Log.Warning( "CleanupSystem: No baseline captured. Cannot cleanup." );
			return;
		}

		if ( !Networking.IsHost )
		{
			Log.Warning( "CleanupSystem: Only the host can perform cleanup." );
			return;
		}

		var removedCount = 0;
		var restoredCount = 0;
		var objectsToRemove = new List<GameObject>();
		var existingBaselineIds = new HashSet<Guid>();

		foreach ( var go in Scene.GetAllObjects( true ) )
		{
			if ( !go.IsValid() )
				continue;

			// Never remove player objects
			if ( IsPlayerObject( go ) )
				continue;

			if ( go.Flags.Contains( GameObjectFlags.DontDestroyOnLoad ) )
				continue;

			if ( _baselineObjectIds.Contains( go.Id ) )
			{
				existingBaselineIds.Add( go.Id );
			}
			else
			{
				if ( go.Parent == Scene )
				{
					objectsToRemove.Add( go );
				}
			}
		}

		// Remove spawned objects
		foreach ( var go in objectsToRemove )
		{
			if ( go.IsValid() )
			{
				go.Destroy();
				removedCount++;
			}
		}

		// Restore destroyed baseline objects
		foreach ( var kvp in _baselineObjectData )
		{
			var id = kvp.Key;

			// Skip if the object still exists
			if ( existingBaselineIds.Contains( id ) )
				continue;

			// Skip if we already processed the parent object
			var go = Scene.Directory.FindByGuid( id );
			if ( go.IsValid() )
				continue;

			try
			{
				var json = System.Text.Json.Nodes.JsonNode.Parse( kvp.Value );
				if ( json is System.Text.Json.Nodes.JsonObject jso )
				{
					var restored = new GameObject();
					restored.Deserialize( jso );
					restoredCount++;
				}
			}
			catch ( System.Exception ex )
			{
				Log.Warning( $"CleanupSystem: Failed to restore object {id}: {ex.Message}" );
			}
		}

		BroadcastCleanup( removedCount, restoredCount );
	}

	[Rpc.Broadcast( NetFlags.HostOnly )]
	private static void BroadcastCleanup( int removedObjects, int restoredObjects )
	{
		Game.ActiveScene?.RunEvent<ICleanupEvents>( x => x.OnCleanup( removedObjects, restoredObjects ) );

		Log.Info( $"Cleanup complete. Removed {removedObjects} spawned objects, restored {restoredObjects} destroyed objects." );
	}

	/// <summary>
	/// Console command to cleanup the map.
	/// </summary>
	[ConCmd( "cleanup" )]
	public static void CleanupCommand( string targetName = null )
	{
		if ( !Networking.IsHost ) return;

		//
		// Targeted cleanup, doesn't use the same cleanup shit
		//
		if ( !string.IsNullOrEmpty( targetName ) )
		{
			var target = GameManager.FindPlayerWithName( targetName );
			if ( target is not null )
			{
				CleanupPlayer( target );
			}
			else
			{
				Notices.AddNotice( "cleaning_services", Color.Red, $"Can't find {targetName} to clean up" );
			}

			return;
		}

		if ( Current is null )
		{
			Log.Warning( "CleanupSystem: No active cleanup system." );
			return;
		}

		Current.Cleanup();
	}

	[Rpc.Host]
	public static void RpcCleanUpMine()
	{
		CleanupPlayer( Rpc.Caller );
	}

	[Rpc.Host]
	public static void RpcCleanUpAll()
	{
		if ( !Rpc.Caller.HasPermission( "admin" ) ) return;

		Current?.Cleanup();
	}

	[Rpc.Host]
	public static void RpcCleanUpTarget( Connection target )
	{
		if ( !Rpc.Caller.HasPermission( "admin" ) ) return;

		CleanupPlayer( target );
	}

	public static void CleanupPlayer( Connection caller )
	{
		Assert.True( Networking.IsHost, "Only the host may call this method!" );

		var removable = Game.ActiveScene.GetAllComponents<Ownable>()
			.Where( o => o.Owner == caller );

		var count = 0;
		foreach ( var ownable in removable.ToArray() )
		{
			ownable.GameObject.Destroy();
			count++;
		}

		Notices.SendNotice( caller, "cleaning_services", Color.Green, $"Cleaned up {count} objects" );
	}

}
[Alias( "dynamite" )]
public sealed class DynamiteEntity : Component, IPlayerControllable, Component.IDamageable
{
	[Property, Range( 1, 500 ), Step( 1 ), ClientEditable]
	public float Damage { get; set; } = 128;

	[Property, Range( 16, 4096 ), Step( 16 ), ClientEditable]
	public float Radius { get; set; } = 1024f;

	[Property, Range( 1, 100 ), Step( 1 ), ClientEditable]
	public float Force { get; set; } = 1;

	[Property, Sync, ClientEditable]
	public ClientInput Activate { get; set; }

	bool _isDead = false;

	[Rpc.Host]
	public void Explode()
	{
		_isDead = true;

		var explosionPrefab = ResourceLibrary.Get<PrefabFile>( "/prefabs/engine/explosion_med.prefab" );
		if ( explosionPrefab == null )
		{
			Log.Warning( "Can't find /prefabs/engine/explosion_med.prefab" );
			return;
		}

		var go = GameObject.Clone( explosionPrefab, new CloneConfig { Transform = WorldTransform.WithScale( 1 ), StartEnabled = false } );
		if ( !go.IsValid() ) return;

		go.RunEvent<RadiusDamage>( x =>
		{
			x.Radius = Radius;
			x.PhysicsForceScale = Force;
			x.DamageAmount = Damage;
			x.Attacker = go;
		}, FindMode.EverythingInSelfAndDescendants );

		go.Enabled = true;
		go.NetworkSpawn( true, null );

		GameObject.Destroy();
	}

	void IDamageable.OnDamage( in DamageInfo damage )
	{
		if ( _isDead ) return;
		if ( IsProxy ) return;

		Explode();
	}

	void IPlayerControllable.OnControl()
	{
		if ( Activate.Pressed() )
		{
			Explode();
		}
	}

	void IPlayerControllable.OnEndControl()
	{
		// nothing to do
	}

	void IPlayerControllable.OnStartControl()
	{
		// nothing to do
	}
}
/// <summary>
/// Whether the emitter fires while the input is held, or toggles on/off with a press.
/// </summary>
public enum EmitMode
{
	/// <summary>
	/// Press once to turn on, press again to turn off.
	/// </summary>
	Toggle,
	/// <summary>
	/// Emits only while the input is held down.
	/// </summary>
	Hold,
}

/// <summary>
/// A world-placed SENT that spawns and controls a particle/VFX emitter.
/// The emitter prefab is defined by a <see cref="ScriptedEmitter"/> resource.
/// </summary>
[Alias( "emitter" )]
public sealed class EmitterEntity : Component, IPlayerControllable
{
	/// <summary>
	/// The emitter definition points to a prefab containing a particle system.
	/// </summary>
	[Property, ClientEditable]
	public ScriptedEmitter Emitter { get; set; }

	/// <summary>
	/// Whether this emitter toggles on/off with a press, or emits only while held.
	/// </summary>
	[Property, ClientEditable]
	public EmitMode Mode { get; set; } = EmitMode.Toggle;

	/// <summary>
	/// Used when <see cref="Mode"/> is <see cref="EmitMode.Toggle"/>.
	/// </summary>
	[Property, Sync, ClientEditable, Group( "Input" )]
	public ClientInput ToggleInput { get; set; }

	/// <summary>
	/// Used when <see cref="Mode"/> is <see cref="EmitMode.Hold"/>.
	/// </summary>
	[Property, Sync, ClientEditable, Group( "Input" )]
	public ClientInput HoldInput { get; set; }

	/// <summary>
	/// Whether the emitter is currently active. Synced to all clients.
	/// </summary>
	[Sync] public bool IsEmitting { get; private set; }

	/// <summary>
	/// When enabled, forces the emitter on regardless of input or mode.
	/// Can be set from the editor or wired up externally.
	/// </summary>
	[Property, ClientEditable]
	public bool ManualOn
	{
		get => _manualOn;
		set { _manualOn = value; if ( !IsProxy ) UpdateEmitState(); }
	}
	private bool _manualOn;
	private bool _inputEmitting;

	private GameObject _particleInstance;
	private ScriptedEmitter _lastEmitter;

	protected override void OnStart() { }

	protected override void OnUpdate()
	{
		// Emitter resource changed — destroy existing instance so it gets recreated
		if ( _lastEmitter != Emitter && _particleInstance.IsValid() )
			DestroyParticle();

		_lastEmitter = Emitter;

		if ( IsEmitting && !_particleInstance.IsValid() )
			SpawnParticle();
		else if ( !IsEmitting && _particleInstance.IsValid() )
			DestroyParticle();
	}

	void IPlayerControllable.OnStartControl() { }
	void IPlayerControllable.OnEndControl()
	{
		if ( Mode == EmitMode.Hold )
		{
			_inputEmitting = false;
			UpdateEmitState();
		}
	}

	void IPlayerControllable.OnControl()
	{
		if ( Mode == EmitMode.Toggle )
		{
			if ( ToggleInput.Pressed() )
			{
				_inputEmitting = !_inputEmitting;
				UpdateEmitState();
			}
		}
		else
		{
			var held = HoldInput.Down();
			if ( held != _inputEmitting )
			{
				_inputEmitting = held;
				UpdateEmitState();
			}
		}
	}

	private void UpdateEmitState() => SetEmitting( _inputEmitting || _manualOn );

	[Rpc.Broadcast]
	private void SetEmitting( bool active )
	{
		IsEmitting = active;
	}

	private void SpawnParticle()
	{
		if ( !Emitter.IsValid() || Emitter.Prefab is null ) return;

		_particleInstance = GameObject.Clone( Emitter.Prefab, new CloneConfig
		{
			Parent = GameObject,
			Transform = new Transform( Vector3.Forward * 4f ),
			StartEnabled = true,
		} );
	}

	private void DestroyParticle()
	{
		_particleInstance.Destroy();
		_particleInstance = null;
	}
}


public sealed class SpotLightEntity : Component, IPlayerControllable
{
	[Property, ClientEditable, Group( "Light" )]
	public bool On { get; set { field = value; UpdateLight(); } } = true;

	[Property, ClientEditable, Group( "Light" )]
	public bool Shadows { get; set { field = value; UpdateLight(); } } = true;

	[Property, Range( 0, 1 ), ClientEditable, Group( "Light" )]
	public Color Color { get; set { field = value; UpdateLight(); } }

	[Property, Range( 0, 50 ), ClientEditable, Group( "Light" )]
	public float Brightness { get; set { field = value; UpdateLight(); } } = 2;

	[Property, Range( 0, 1000 ), ClientEditable, Group( "Light" )]
	public float Radius { get; set { field = value; UpdateLight(); } } = 500;

	[Property, Range( 0, 90 ), ClientEditable, Group( "Light" )]
	public float Angle { get; set { field = value; UpdateLight(); } } = 35;

	[Property, Range( 0, 16 ), ClientEditable, Group( "Light" )]
	public float Attenuation { get; set { field = value; UpdateLight(); } } = 2.4f;


	[Property, Sync, ClientEditable, Group( "State" )]
	public ClientInput TurnOn { get; set; }

	[Property, Sync, ClientEditable, Group( "State" )]
	public ClientInput TurnOff { get; set; }

	[Property, Sync, ClientEditable, Group( "State" )]
	public ClientInput Toggle { get; set; }

	[Property]
	public GameObject OnGameObject { get; set; }

	[Property]
	public GameObject OffGameObject { get; set; }

	void IPlayerControllable.OnControl()
	{

		if ( Toggle.Pressed() )
		{
			On = !On;
		}

		if ( TurnOn.Pressed() )
		{
			On = true;
		}

		if ( TurnOff.Pressed() )
		{
			On = false;
		}
	}

	void IPlayerControllable.OnEndControl()
	{

	}

	void IPlayerControllable.OnStartControl()
	{

	}

	void UpdateLight()
	{
		OnGameObject?.Enabled = On;
		OffGameObject?.Enabled = !On;

		if ( GetComponentInChildren<SpotLight>( true ) is not SpotLight light )
			return;

		light.Enabled = On;

		var color = Color;
		color.r *= Brightness;
		color.g *= Brightness;
		color.b *= Brightness;

		light.Shadows = Shadows;
		light.LightColor = color;
		light.Radius = Radius;
		light.Attenuation = Attenuation;
		light.ConeOuter = Angle;
		light.ConeInner = Angle * 0.5f;

		Network.Refresh();
	}
}
public partial class BaseBulletWeapon : BaseWeapon
{
	[Property]
	public SoundEvent ShootSound { get; set; }

	[Property, Group( "Bullet" )]
	public BulletConfiguration Bullet { get; set; } = new()
	{
		Damage = 12f,
		BulletRadius = 1f,
		Range = 4096f,
		AimConeBase = new Vector2( 0.5f, 0.25f ),
		AimConeSpread = new Vector2( 3f, 3f ),
		AimConeRecovery = 0.2f,
		RecoilPitch = new Vector2( -0.3f, -0.1f ),
		RecoilYaw = new Vector2( -0.1f, 0.1f ),
		CameraRecoilStrength = 1f,
		CameraRecoilFrequency = 1f,
	};

	[Property, Group( "Bullet" ), ClientEditable, Range( 0f, 500000f ), Step( 10f )]
	public float ShootForce { get; set; } = 100000f;

	protected TimeSince TimeSinceShoot = 0;

	/// <summary>
	/// Returns 0 for no aim spread, 1 for full aim cone, based on time since last shot.
	/// </summary>
	protected float GetAimConeAmount( float recovery )
	{
		return TimeSinceShoot.Relative.Remap( 0, recovery, 1, 0 );
	}

	/// <summary>
	/// Returns the aim cone amount using the configured recovery time
	/// </summary>
	protected float GetAimConeAmount()
	{
		return GetAimConeAmount( Bullet.AimConeRecovery );
	}

	/// <inheritdoc cref="ShootBullet(float, in BulletConfiguration)"/>
	protected void ShootBullet( float fireRate )
	{
		ShootBullet( fireRate, Bullet );
	}

	/// <summary>
	/// Shoot a bullet out of the front of the gun.
	/// When held by a player, fires from the player's eye with aim cone and recoil.
	/// When standalone (no owner), fires straight from the weapon's muzzle.
	/// </summary>
	protected void ShootBullet( float fireRate, in BulletConfiguration config )
	{
		if ( HasOwner && ( !HasAmmo() || IsReloading() ) )
		{
			TryAutoReload();
			return;
		}

		if ( TimeUntilNextShotAllowed > 0 )
			return;

		// Only consume ammo when held by a player
		if ( HasOwner && !TakeAmmo( 1 ) )
		{
			AddShootDelay( 0.2f );
			return;
		}

		AddShootDelay( fireRate );

		var aimConeAmount = GetAimConeAmount( config.AimConeRecovery );
		var forward = AimRay.Forward
			.WithAimCone(
				config.AimConeBase.x + aimConeAmount * config.AimConeSpread.x,
				config.AimConeBase.y + aimConeAmount * config.AimConeSpread.y
			);
		var traceRay = AimRay with { Forward = forward };

		var tr = Scene.Trace.Ray( traceRay, config.Range )
			.IgnoreGameObjectHierarchy( AimIgnoreRoot )
			.WithCollisionRules( "bullet" )
			.WithoutTags( "playercontroller" )
			.Radius( config.BulletRadius )
			.UseHitboxes()
			.Run();

		ShootEffects( tr.EndPosition, tr.Hit, tr.Normal, tr.GameObject, tr.Surface );
		TraceAttack( TraceAttackInfo.From( tr, config.Damage ) );
		TimeSinceShoot = 0;

		// Recoil only applies when held by a player
		if ( !HasOwner )
		{
			// Simulate physical recoil by pushing the weapon opposite to its fire direction
			if ( ShootForce > 0f && GetComponent<Rigidbody>( true ) is var rb )
			{
				var muzzle = WeaponModel?.MuzzleTransform?.WorldTransform ?? WorldTransform;
				rb.ApplyForce( muzzle.Rotation.Up * ShootForce );
			}
			return;
		}

		Owner.Controller.EyeAngles += new Angles(
			Random.Shared.Float( config.RecoilPitch.x, config.RecoilPitch.y ),
			Random.Shared.Float( config.RecoilYaw.x, config.RecoilYaw.y ),
			0
		);

		if ( !Owner.Controller.ThirdPerson && Owner.IsLocalPlayer )
		{
			_ = new Sandbox.CameraNoise.Recoil( config.CameraRecoilStrength, config.CameraRecoilFrequency );
		}
	}

	[Rpc.Broadcast]
	public void ShootEffects( Vector3 hitpoint, bool hit, Vector3 normal, GameObject hitObject, Surface hitSurface, Vector3? origin = null, bool noEvents = false )
	{
		if ( Application.IsDedicatedServer ) return;
		if ( !hitSurface.IsValid() ) return;

		Owner?.Controller.Renderer.Set( "b_attack", true );

		if ( !noEvents )
		{
			if ( WeaponModel.IsValid() )
			{
				WeaponModel.GameObject.RunEvent<WeaponModel>( x => x.OnAttack() );
				WeaponModel.GameObject.RunEvent<WeaponModel>( x => x.CreateRangedEffects( this, hitpoint, origin ) );
			}

			if ( ShootSound.IsValid() )
			{
				var snd = GameObject.PlaySound( ShootSound );

				// If we're shooting, the sound should not be spatialized
				if ( HasOwner && Owner.IsLocalPlayer && snd.IsValid() )
				{
					snd.SpacialBlend = 0;
				}
			}
		}

		if ( !hit || !hitObject.IsValid() )
			return;

		var baseSurface = hitSurface.GetBaseSurface();
		var bulletSound = hitSurface.SoundCollection.Bullet ?? baseSurface?.SoundCollection.Bullet;
		if ( bulletSound.IsValid() )
		{
			Sound.Play( bulletSound, hitpoint );
		}

		var prefab = hitSurface.PrefabCollection.BulletImpact ?? baseSurface?.PrefabCollection.BulletImpact;

		// Still null?
		if ( prefab is null )
			return;

		var fwd = Rotation.LookAt( normal * -1.0f, Vector3.Random );

		var impact = prefab.Clone();
		impact.WorldPosition = hitpoint;
		impact.WorldRotation = fwd;
		impact.SetParent( hitObject, true );

		if ( hitObject.GetComponentInChildren<SkinnedModelRenderer>() is not { CreateBoneObjects: true } skinned )
			return;

		// find closest bone
		var bones = skinned.GetBoneTransforms( true );

		var closestDist = float.MaxValue;

		for ( var i = 0; i < bones.Length; i++ )
		{
			var bone = bones[i];
			var dist = bone.Position.Distance( hitpoint );
			if ( dist < closestDist )
			{
				closestDist = dist;
				impact.SetParent( skinned.GetBoneObject( i ), true );
			}
		}
	}

	public record struct BulletConfiguration
	{
		public float Damage { get; set; }
		public float BulletRadius { get; set; }
		public Vector2 AimConeBase { get; set; }
		public Vector2 AimConeSpread { get; set; }
		public float AimConeRecovery { get; set; }
		public Vector2 RecoilPitch { get; set; }
		public Vector2 RecoilYaw { get; set; }
		public float CameraRecoilStrength { get; set; }
		public float CameraRecoilFrequency { get; set; }
		public float Range { get; set; }
	}
}
using System.Threading;

public partial class BaseWeapon
{
	/// <summary>
	/// Should we consume 1 bullet per reload instead of filling the clip?
	/// </summary>
	[Property, Feature( "Ammo" )]
	public bool IncrementalReloading { get; set; } = false;

	/// <summary>
	/// Extra delay after the first shell reload before subsequent shells begin (e.g. longer carrier insertion animation).
	/// Only used with incremental reloading. If zero, no extra delay is added.
	/// </summary>
	[Property, Feature( "Ammo" ), ShowIf( nameof( IncrementalReloading ), true )]
	public float FirstShellReloadTime { get; set; } = 0f;

	/// <summary>
	/// Delay before the first shell is inserted during incremental reload.
	/// If zero, uses <see cref="ReloadTime"/>.
	/// </summary>
	[Property, Feature( "Ammo" ), ShowIf( nameof( IncrementalReloading ), true )]
	public float ReloadStartTime { get; set; } = 0f;

	/// <summary>
	/// Can we cancel reloads?
	/// </summary>
	[Property, Feature( "Ammo" )]
	public bool CanCancelReload { get; set; } = true;

	private CancellationTokenSource reloadToken;
	private bool isReloading;

	public bool CanReload()
	{
		if ( !UsesClips ) return false;
		if ( ClipContents >= ClipMaxSize ) return false;
		if ( isReloading ) return false;
		if ( !WeaponConVars.InfiniteReserves && ReserveAmmo <= 0 ) return false;

		return true;
	}

	public bool IsReloading() => isReloading;

	public virtual void CancelReload()
	{
		if ( reloadToken?.IsCancellationRequested == false )
		{
			reloadToken?.Cancel();
			isReloading = false;

			ViewModel?.RunEvent<ViewModel>( x => x.OnReloadCancel() );
		}
	}

	public virtual async void OnReloadStart()
	{
		if ( !CanReload() )
			return;

		CancelReload();

		var cts = new CancellationTokenSource();
		reloadToken = cts;
		isReloading = true;

		try
		{
			await ReloadAsync( cts.Token );
		}
		finally
		{
			// Only clean up our own reload
			if ( reloadToken == cts )
			{
				isReloading = false;
				reloadToken = null;
			}
			cts.Dispose();
		}
	}

	[Rpc.Broadcast]
	private void BroadcastReload()
	{
		if ( !HasOwner ) return;

		Assert.True( Owner.Controller.IsValid(), "BaseWeapon::BroadcastReload - Player Controller is invalid!" );
		Assert.True( Owner.Controller.Renderer.IsValid(), "BaseWeapon::BroadcastReload - Renderer is invalid!" );

		Owner.Controller.Renderer.Set( "b_reload", true );
	}

	protected virtual async Task ReloadAsync( CancellationToken ct )
	{
		// Capture so we can tell if a newer reload has replaced us by the time finally runs.
		var mySource = reloadToken;
		var isFirstShell = ClipContents == 0;

		try
		{
			ViewModel?.RunEvent<ViewModel>( x => x.OnReloadStart() );

			BroadcastReload();

			var firstIteration = true;

			while ( ClipContents < ClipMaxSize && !ct.IsCancellationRequested )
				{
					var delay = (firstIteration && IncrementalReloading && ReloadStartTime > 0f) ? ReloadStartTime : ReloadTime;
					firstIteration = false;
					await Task.DelaySeconds( delay, ct );

					var needed = IncrementalReloading ? 1 : (ClipMaxSize - ClipContents);

					if ( WeaponConVars.InfiniteReserves )
					{
						ViewModel?.RunEvent<ViewModel>( x => x.OnIncrementalReload( isFirstShell ) );
						ClipContents += needed;
					}
					else
					{
						var available = Math.Min( needed, ReserveAmmo );

						if ( available <= 0 )
							break;

						ViewModel?.RunEvent<ViewModel>( x => x.OnIncrementalReload( isFirstShell ) );

						ReserveAmmo -= available;
						ClipContents += available;
					}

					// After the first shell, wait longer before the next one starts
					if ( isFirstShell && FirstShellReloadTime > 0f )
					{
						await Task.DelaySeconds( FirstShellReloadTime, ct );
					}

					isFirstShell = false;
				}
		}
		finally
		{
			if ( reloadToken == mySource )
			{
				ViewModel?.RunEvent<ViewModel>( x => x.OnReloadFinish() );
			}
		}
	}
}
/// <summary>
/// The local user's preferences in Deathmatch
/// </summary>
internal static class GamePreferences
{
	/// <summary>
	/// Enables automatic switching to better weapons on item pickup
	/// </summary>
	[ConVar( "sb.autoswitch", ConVarFlags.UserInfo | ConVarFlags.Saved )]
	public static bool AutoSwitch { get; set; } = true;

	/// <summary>
	/// Enables fast switching between inventory weapons
	/// </summary>
	[ConVar( "sb.fastswitch", ConVarFlags.Saved )]
	public static bool FastSwitch { get; set; } = false;

	/// <summary>
	/// Intensity of your camera's screenshake
	/// </summary>
	[ConVar( "sb.viewbob", ConVarFlags.Saved )]
	[Group( "Camera" )]
	public static bool ViewBobbing { get; set; } = true;

	/// <summary>
	/// Intensity of your camera's screenshake
	/// </summary>
	[ConVar( "sb.screenshake", ConVarFlags.Saved )]
	[Range( 0.1f, 2f ), Step( 0.1f ), Group( "Camera" )]
	public static float Screenshake { get; set; } = 0.3f;
}
namespace Sandbox.Npcs;

/// <summary>
/// Console variables that control NPC AI behaviour globally.
/// </summary>
public static class NpcConVars
{
	/// <summary>
	/// When disabled, all NPC AI thinking is paused — they just stand idle.
	/// </summary>
	[ConVar( "sb.ai.enabled", ConVarFlags.Replicated | ConVarFlags.Saved, Help = "Enable or disable NPC AI thinking." )]
	public static bool Enabled { get; set; } = true;

	/// <summary>
	/// When enabled, NPCs cannot target players.
	/// </summary>
	[ConVar( "sb.ai.notarget", ConVarFlags.Replicated | ConVarFlags.Saved, Help = "When enabled, NPCs cannot target players." )]
	public static bool NoTarget { get; set; } = false;
}
using Sandbox.Npcs.Layers;
using Sandbox.Npcs.Tasks;

namespace Sandbox.Npcs.Schedules;

/// <summary>
/// Panic flee — scream while sprinting away from the source.
/// </summary>
public sealed class ScientistFleeSchedule : ScheduleBase
{
	private static readonly string[] PanicLines =
	[
		"AHHH!",
		"Don't hurt me!",
		"Help! HELP!",
		"Stay away from me!",
		"I'm just a scientist!",
		"Please, no!",
		"Somebody help!",
		"Oh god oh god oh god!",
		"What did I do?!",
		"Leave me alone!",
	];

	public GameObject Source { get; set; }

	/// <summary>
	/// 0–1 panic intensity. Higher values mean faster speed and longer flee distance.
	/// </summary>
	public float PanicLevel { get; set; } = 0.5f;

	protected override void OnStart()
	{
		if ( !Source.IsValid() ) return;

		// Sprint speed scales with panic (200–350)
		Npc.Navigation.WishSpeed = 200f + 150f * PanicLevel;

		// Don't stare at the player — look where we're running
		Npc.Animation.ClearLookTarget();

		// Scream immediately — but only if not already mid-speech
		if ( Npc.Speech.CanSpeak )
		{
			var line = PanicLines[Game.Random.Int( 0, PanicLines.Length - 1 )];
			Npc.Speech.Say( line, 2f );
		}

		// Flee direction — away from the attacker with some randomness
		var awayDir = (GameObject.WorldPosition - Source.WorldPosition).WithZ( 0 ).Normal;
		var randomAngle = Game.Random.Float( -40f, 40f );
		awayDir = Rotation.FromAxis( Vector3.Up, randomAngle ) * awayDir;

		// Distance scales with panic (200–500)
		var fleeDist = 512f + 1024f * PanicLevel;
		var fleeTarget = GameObject.WorldPosition + awayDir * fleeDist;

		// Snap to navmesh
		if ( Npc.Scene.NavMesh.GetClosestPoint( fleeTarget ) is { } navPoint )
		{
			AddTask( new MoveTo( navPoint, 15f ) );
		}
		else
		{
			AddTask( new MoveTo( fleeTarget, 15f ) );
		}
	}

	protected override void OnEnd()
	{
		// Reset to normal walk speed
		// TODO: this is shit, can we scope these somehow so the IDisposable handles all this ?
		Npc.Navigation.WishSpeed = 100f;
	}

	protected override bool ShouldCancel()
	{
		return !Source.IsValid();
	}
}
/// <summary>
/// Apply fall damage to the player
/// </summary>
public class PlayerFallDamage : Component, Local.IPlayerEvents
{
	[RequireComponent] public Player Player { get; set; }

	/// <summary>
	/// Fatal fall speed, you will die if you fall at or above this speed
	/// </summary>
	[Property] public float FatalFallSpeed { get; set; } = 1536.0f;

	/// <summary>
	/// Maximum safe fall speed, you won't take damage at or below this speed
	/// </summary>
	[Property] public float MaxSafeFallSpeed { get; set; } = 512.0f;

	/// <summary>
	/// Multiply damage amount by this much
	/// </summary>
	[Property] public float DamageMultiplier { get; set; } = 1.0f;

	/// <summary>
	/// Fall damage sound
	/// </summary>
	[Property] public SoundEvent FallSound { get; set; }

	[Rpc.Owner]
	private void PlayFallSound()
	{
		GameObject.PlaySound( FallSound );
	}

	void Local.IPlayerEvents.OnLand( float distance, Vector3 velocity )
	{
		var fallSpeed = Math.Abs( velocity.z );

		if ( fallSpeed <= MaxSafeFallSpeed )
			return;

		var damageAmount = MathX.Remap( fallSpeed, MaxSafeFallSpeed, FatalFallSpeed, 0f, 100f ) * DamageMultiplier;
		if ( damageAmount < 1 ) return;

		if ( Networking.IsHost && damageAmount >= Player.Health )
			Player.PlayerData?.AddStat( "player.fall.death" );

		TakeFallDamage( damageAmount );
	}


	[Rpc.Broadcast]
	public void TakeFallDamage( float amount )
	{
		if ( !Networking.IsHost ) return;


		if ( Player is IDamageable damage )
		{
			var dmg = new DamageInfo( amount.CeilToInt(), Player.GameObject, null );
			dmg.Tags.Add( DamageTags.Fall );
			damage.OnDamage( dmg );

			PlayFallSound();
		}
	}
}
/// <summary>
/// Manages loadout persistence, presets, and restoration for a player.
/// Lives on the Player GameObject alongside PlayerInventory.
/// Listens to inventory events to auto-save, and handles all loadout RPCs directly.
/// </summary>
public sealed class PlayerLoadout : Component, Local.IPlayerEvents, Global.IPlayerEvents, Global.ISaveEvents
{
	[RequireComponent] public Player Player { get; set; }
	[RequireComponent] public PlayerInventory Inventory { get; set; }

	private bool _isRestoringLoadout;

	/// <summary>
	/// One entry in a serialized loadout: the prefab resource path and the slot it occupies.
	/// </summary>
	public struct LoadoutEntry
	{
		public string PrefabPath { get; set; }
		public int Slot { get; set; }
		public string SpawnerDataPayload { get; set; }
	}

	public struct SavedPreset
	{
		public string Name { get; set; }
		public string LoadoutJson { get; set; }
	}

	public static IReadOnlyList<SavedPreset> GetLoadoutPresets()
	{
		return LocalData.Get<List<SavedPreset>>( "presets", new() );
	}

	public static void SaveLoadoutPreset( string name, string loadoutJson )
	{
		var presets = LocalData.Get<List<SavedPreset>>( "presets", new() );
		var idx = presets.FindIndex( p => p.Name == name );
		var entry = new SavedPreset { Name = name, LoadoutJson = loadoutJson };
		if ( idx >= 0 )
			presets[idx] = entry;
		else
			presets.Add( entry );
		LocalData.Set( "presets", presets );
	}

	public static void DeleteLoadoutPreset( string name )
	{
		var presets = LocalData.Get<List<SavedPreset>>( "presets", new() );
		presets.RemoveAll( p => p.Name == name );
		LocalData.Set( "presets", presets );
	}

	public string SerializeLoadout()
	{
		var entries = Inventory.Weapons
			.Where( w => !string.IsNullOrEmpty( w.GameObject.PrefabInstanceSource ) )
			.Select( w => new LoadoutEntry
			{
				PrefabPath = w.GameObject.PrefabInstanceSource,
				Slot = w.InventorySlot,
				SpawnerDataPayload = (w as SpawnerWeapon)?.SpawnerData
			} )
			.ToList();

		return entries.Count > 0 ? Json.Serialize( entries ) : null;
	}

	public void SaveLoadout()
	{
		if ( _isRestoringLoadout ) return;

		var json = SerializeLoadout();
		if ( string.IsNullOrEmpty( json ) ) return;

		if ( Player.IsLocalPlayer )
		{
			LocalData.Set( "hotbar", json );
		}
		else
		{
			PushLoadoutToClient( json );
		}
	}

	public void GiveLoadoutWeapons( string json )
	{
		var entries = Json.Deserialize<List<LoadoutEntry>>( json );
		if ( entries is null ) return;

		_isRestoringLoadout = true;
		try
		{
			foreach ( var entry in entries )
			{
				if ( !Inventory.Pickup( entry.PrefabPath, entry.Slot, false ) )
					continue;

				if ( !string.IsNullOrEmpty( entry.SpawnerDataPayload ) && Inventory.GetSlot( entry.Slot ) is SpawnerWeapon spawnerWeapon )
				{
					spawnerWeapon.RestoreSpawnerData( entry.SpawnerDataPayload );
				}
			}
		}
		finally
		{
			_isRestoringLoadout = false;
		}
	}

	private static async Task EnsureMountedAsync( string json )
	{
		var entries = Json.Deserialize<List<LoadoutEntry>>( json );
		if ( entries is null ) return;

		var needsMounts = entries.Any( e => !string.IsNullOrEmpty( e.SpawnerDataPayload )
			&& e.SpawnerDataPayload.EndsWith( ".vmdl", StringComparison.OrdinalIgnoreCase ) );

		if ( !needsMounts ) return;

		foreach ( var entry in Sandbox.Mounting.Directory.GetAll().Where( e => e.Available ) )
			await Sandbox.Mounting.Directory.Mount( entry.Ident );
	}

	public void SwitchToPreset( string loadoutJson )
	{
		if ( !Networking.IsHost )
		{
			HostSwitchToPreset( loadoutJson );
			return;
		}
		_ = SwitchToPresetAsync( loadoutJson );
	}

	public void ResetToDefault()
	{
		if ( !Networking.IsHost )
		{
			HostResetToDefault();
			return;
		}
		_ = ResetToDefaultAsync();
	}

	[Rpc.Host]
	private void HostSwitchToPreset( string loadoutJson )
	{
		_ = SwitchToPresetAsync( loadoutJson );
	}

	[Rpc.Host]
	private void HostResetToDefault()
	{
		_ = ResetToDefaultAsync();
	}

	private async Task SwitchToPresetAsync( string loadoutJson )
	{
		var previousSlot = Inventory.ActiveWeapon?.InventorySlot ?? 0;

		foreach ( var weapon in Inventory.Weapons.ToList() )
			weapon.DestroyGameObject();

		await Task.Yield();

		await EnsureMountedAsync( loadoutJson );
		GiveLoadoutWeapons( loadoutJson );

		var toEquip = Inventory.GetSlot( previousSlot ) ?? Inventory.GetBestWeapon();
		if ( toEquip.IsValid() )
			Inventory.SwitchWeapon( toEquip );

		SaveLoadout();
	}

	private async Task ResetToDefaultAsync()
	{
		foreach ( var weapon in Inventory.Weapons.ToList() )
			weapon.DestroyGameObject();

		await Task.Yield();

		Inventory.GiveDefaultWeapons();
		Inventory.SwitchWeapon( Inventory.GetBestWeapon() );
		SaveLoadout();
	}

	[Rpc.Owner]
	private void PushLoadoutToClient( string loadoutJson )
	{
		LocalData.Set( "hotbar", loadoutJson );
	}

	[Rpc.Owner]
	private void RequestClientLoadout()
	{
		var json = LocalData.Get<string>( "hotbar" );
		if ( !string.IsNullOrEmpty( json ) )
			HostRestoreLoadoutFromClient( json );
	}

	/// <summary>
	/// Clears the current inventory, waits a frame, then gives the loadout from JSON and equips the best weapon.
	/// </summary>
	private async Task ReplaceLoadoutAsync( string json )
	{
		foreach ( var weapon in Inventory.Weapons.ToList() )
			weapon.DestroyGameObject();

		await Task.Yield();

		await EnsureMountedAsync( json );
		GiveLoadoutWeapons( json );

		var best = Inventory.GetBestWeapon();
		if ( best.IsValid() )
			Inventory.SwitchWeapon( best );
	}

	[Rpc.Host]
	private async void HostRestoreLoadoutFromClient( string loadoutJson )
	{
		await ReplaceLoadoutAsync( loadoutJson );
	}

	void Global.IPlayerEvents.OnPlayerSpawned( Player player )
	{
		if ( player != Player ) return;
		if ( !Networking.IsHost ) return;

		_ = RestoreOnSpawnAsync();
	}

	private async Task RestoreOnSpawnAsync()
	{
		if ( Player.IsLocalPlayer )
		{
			var json = LocalData.Get<string>( "hotbar" );
			if ( !string.IsNullOrEmpty( json ) )
			{
				await ReplaceLoadoutAsync( json );
				return;
			}
		}
		else
		{
			RequestClientLoadout();
			return;
		}

		Inventory.GiveDefaultWeapons();
		var bestWeapon = Inventory.GetBestWeapon();
		if ( bestWeapon.IsValid() )
			Inventory.SwitchWeapon( bestWeapon );
	}

	void Local.IPlayerEvents.OnDied( PlayerDiedParams args )
	{
		if ( !Networking.IsHost ) return;
		SaveLoadout();
	}

	void Local.IPlayerEvents.OnPickup( PlayerPickupEvent e )
	{
		if ( e.Cancelled ) return;
		if ( !Networking.IsHost ) return;
		SaveLoadout();
	}

	void Local.IPlayerEvents.OnDrop( PlayerDropEvent e )
	{
		if ( e.Cancelled ) return;
		if ( !Networking.IsHost ) return;
		_ = SaveLoadoutAfterYield();
	}

	void Local.IPlayerEvents.OnRemoveWeapon( PlayerRemoveWeaponEvent e )
	{
		if ( e.Cancelled ) return;
		if ( !Networking.IsHost ) return;
		_ = SaveLoadoutAfterYield();
	}

	void Local.IPlayerEvents.OnMoveSlot( PlayerMoveSlotEvent e )
	{
		if ( e.Cancelled ) return;
		if ( !Networking.IsHost ) return;
		SaveLoadout();
	}

	private async Task SaveLoadoutAfterYield()
	{
		await Task.Yield();
		SaveLoadout();
	}

	void Global.ISaveEvents.BeforeSave( string filename )
	{
		if ( !Networking.IsHost ) return;

		var steamId = (long)(Player.Network.Owner?.SteamId ?? 0);
		if ( steamId == 0 ) return;

		var json = SerializeLoadout();
		if ( string.IsNullOrEmpty( json ) ) return;

		SaveSystem.Current?.SetMetadata( $"Loadout_{steamId}", json );
	}

	void Global.ISaveEvents.AfterLoad( string filename )
	{
		if ( !Networking.IsHost ) return;

		var steamId = (long)(Player.Network.Owner?.SteamId ?? 0);
		if ( steamId == 0 ) return;

		var json = SaveSystem.Current?.GetMetadata( $"Loadout_{steamId}" );
		if ( string.IsNullOrEmpty( json ) ) return;

		_ = RestoreLoadoutFromSaveAsync( json );
	}

	private async Task RestoreLoadoutFromSaveAsync( string json )
	{
		await ReplaceLoadoutAsync( json );
	}
}