OMRVisualFoundation.cs
using Sandbox;
using Sandbox.Rendering;
using System;

/// <summary>
/// One More Round's baseline world-look controller.
///
/// Editor / camera-preview path:
/// - drives authored native S&box Pixelate, ColorAdjustments and FilmGrain
///   components on the gameplay Main Camera.
///
/// Runtime path:
/// - the game uses a second higher-priority camera for clean first-person
///   viewmodels. A post-process applied only to the lower world camera does not
///   survive that final camera composition reliably;
/// - therefore OMRViewModelCamera binds its runtime camera here;
/// - this component applies the world look at Stage.AfterDepthPrepass on that
///   final camera, before its opaque viewmodel is drawn;
/// - result: inherited world color is treated, while weapon/arms and the later
///   HUD draw stay clean.
///
/// This deliberately preserves the proven two-camera near-plane architecture.
/// </summary>
[Title( "OMR Visual Foundation" )]
[Category( "One More Round" )]
public sealed partial class OMRVisualFoundation : Component, Component.ExecuteInEditor
{
    private const string WorldLookShaderPath =
        "shaders/omr_world_look.shader";

    private const string ViewModelCompositeShaderPath =
        "shaders/omr_viewmodel_composite.shader";

    // Run after the overlay camera's depth prepass but before opaque viewmodel
    // rendering. The existing world color from the lower-priority camera is
    // still in the color target at this point.
    private const int RuntimeWorldLookCommandOrder = 1000;
    private const int RuntimeViewModelCompositeCommandOrder = 2000;

    // =========================================================
    // WORLD LOOK
    // =========================================================

    [Property, Group( "World Look" ), Title( "Enable World Look" )]
    public bool EnableWorldLook { get; set; } = false;

    [Property, Group( "World Look" ), Range( 0f, 1f ), Title( "Blend Weight" )]
    public float BlendWeight { get; set; } = 1f;

    [Button, Group( "World Look" ), Title( "Reset World Look" )]
    public void ResetWorldLook()
    {
        EnableWorldLook = false;
        BlendWeight = 1f;
        EnablePixelate = false;
        PixelateScale = 0f;
        EnableColorAdjustments = false;
        Brightness = 1f;
        Contrast = 1f;
        Saturation = 1f;
        HueRotate = 0f;
        EnableFilmGrain = false;
        FilmGrainIntensity = 0f;
        FilmGrainResponse = 0.5f;
        ResetBloomSettings();
        ResetTonemappingSettings();
        ResetColorGradingSettings();

        ResolveNativeEffects();
        ApplySettings();
        RebuildBloom();
        RebuildTonemapping();
        RebuildColorGrading();
        RebuildRuntimeCommands();
    }

    // =========================================================
    // NATIVE EFFECT SETUP
    // =========================================================

    [Button, Group( "World Look" ), Title( "Setup Native Preview Effects" )]
    public void SetupNativeEffects()
    {
        CameraComponent camera = GetComponent<CameraComponent>( true );
        if ( camera is null || !camera.IsValid )
        {
            Log.Warning(
                "[OMR VISUAL] Setup failed: OMRVisualFoundation must live on the same GameObject as the gameplay CameraComponent."
            );
            return;
        }

        _pixelate = GetOrAddComponent<Pixelate>();
        _colorAdjustments = GetOrAddComponent<ColorAdjustments>();
        _filmGrain = GetOrAddComponent<FilmGrain>();

        _bindingsResolved = true;
        _missingBindingsLogged = false;
        ApplySettings();

        Log.Info(
            $"[OMR VISUAL] Native effects ready on '{GameObject.Name}' | " +
            "Pixelate:true | ColorAdjustments:true | FilmGrain:true"
        );
    }

    // =========================================================
    // PIXELATE
    // =========================================================

    [Property, Group( "World Look/Pixelate" ), Title( "Enable Pixelate" )]
    public bool EnablePixelate { get; set; } = false;

    [Property, Group( "World Look/Pixelate" ), Range( 0f, 1f ), Title( "Pixelate Scale" )]
    public float PixelateScale { get; set; } = 0f;

    // =========================================================
    // COLOR
    // =========================================================

    [Property, Group( "World Look/Color" ), Title( "Enable Color Adjustments" )]
    public bool EnableColorAdjustments { get; set; } = false;

    [Property, Group( "World Look/Color" ), Range( 0f, 2f )]
    public float Brightness { get; set; } = 1f;

    [Property, Group( "World Look/Color" ), Range( 0f, 2f )]
    public float Contrast { get; set; } = 1f;

    [Property, Group( "World Look/Color" ), Range( 0f, 2f )]
    public float Saturation { get; set; } = 1f;

    [Property, Group( "World Look/Color" ), Range( -180f, 180f ), Title( "Hue Rotate" )]
    public float HueRotate { get; set; } = 0f;

    // =========================================================
    // FILM GRAIN
    // =========================================================

    [Property, Group( "World Look/Film Grain" ), Title( "Enable Film Grain" )]
    public bool EnableFilmGrain { get; set; } = false;

    [Property, Group( "World Look/Film Grain" ), Range( 0f, 1f ), Title( "Intensity" )]
    public float FilmGrainIntensity { get; set; } = 0f;

    [Property, Group( "World Look/Film Grain" ), Range( 0f, 1f ), Title( "Tonal Response" )]
    [Description( "0 = uniform grain strength. Higher values bias the legacy procedural grain toward darker image regions." )]
    public float FilmGrainResponse { get; set; } = 0.5f;

    // =========================================================
    // DIAGNOSTICS
    // =========================================================

    [Property, Group( "Diagnostics" )]
    public bool LogSetup { get; set; } = false;

    // =========================================================
    // SHARED WORLD-LOOK STATE
    // =========================================================

    /// <summary>
    /// Read-only effective values used by presentation systems that render the
    /// environment through a separate path, currently the M700 physical PiP
    /// scope. Keeping these values here makes the gameplay world and scope use
    /// one authored visual source of truth.
    /// </summary>
    public float EffectiveWorldLookBlend =>
        EnableWorldLook
            ? MathX.Clamp( BlendWeight, 0f, 1f )
            : 0f;

    public float EffectivePixelateScale =>
        EnableWorldLook && EnablePixelate
            ? MathX.Clamp( PixelateScale, 0f, 1f )
            : 0f;

    public bool EffectiveColorAdjustmentsEnabled =>
        EnableWorldLook && EnableColorAdjustments;

    public float EffectiveBrightness =>
        MathX.Clamp( Brightness, 0f, 2f );

    public float EffectiveContrast =>
        MathX.Clamp( Contrast, 0f, 2f );

    public float EffectiveSaturation =>
        MathX.Clamp( Saturation, 0f, 2f );

    public float EffectiveHueRotate =>
        MathX.Clamp( HueRotate, -180f, 180f );

    public float EffectiveFilmGrainIntensity =>
        EnableWorldLook && EnableFilmGrain
            ? MathX.Clamp( FilmGrainIntensity, 0f, 1f )
            : 0f;

    public float EffectiveFilmGrainResponse =>
        MathX.Clamp( FilmGrainResponse, 0f, 1f );

    private Pixelate _pixelate;
    private ColorAdjustments _colorAdjustments;
    private FilmGrain _filmGrain;

    private bool _bindingsResolved;
    private bool _missingBindingsLogged;
    private bool _setupLogged;

    private static readonly ProfilingSampler WorldLookGpuScope = new( "OMR World Look" );
    private static readonly ProfilingSampler ViewModelGpuScope = new( "OMR ViewModel Composite" );
    private bool _runtimeWorldCommandsBuilt;
    private int _runtimeWorldCommandsHash;
    private bool _runtimeViewModelCommandsBuilt;
    private int _runtimeViewModelCommandsHash;

    // Runtime world-look bridge. This belongs to the final viewmodel camera,
    // not to the authored world camera.
    private CameraComponent _runtimeOverlayCamera;
    private CommandList _runtimeWorldLookCommands;
    private Material _runtimeWorldLookMaterial;
    private RenderAttributes _runtimeWorldLookAttributes;
    private bool _runtimeCommandAttached;
    private bool _runtimeReadyLogged;
    private bool _runtimeMaterialFailureLogged;

    // Phase 8F2A: the local viewmodel is rendered to an alpha render target by
    // OMRViewModelCamera. This second command list treats/composites that layer
    // after the world look but before physical scope surfaces and HUD.
    private Texture _runtimeViewModelTexture;
    private CommandList _runtimeViewModelCommands;
    private Material _runtimeViewModelMaterial;
    private RenderAttributes _runtimeViewModelAttributes;
    private bool _runtimeViewModelCommandAttached;
    private bool _runtimeViewModelMaterialFailureLogged;

    protected override void OnStart()
    {
        ResolveNativeEffects();
        ApplySettings();
        RebuildBloom();
        RebuildTonemapping();
        RebuildColorGrading();
        RebuildAmbientOcclusion();
        RebuildAdaptivePixelation();
        RebuildEdgeCueCommands();
    }

    protected override void OnUpdate()
    {
        ResolveNativeEffects();
        ApplySettings();
        RebuildBloom();
        RebuildTonemapping();
        RebuildColorGrading();
        RebuildAmbientOcclusion();
        RebuildAdaptivePixelation();
        RebuildEdgeCueCommands();
        RebuildRuntimeCommands();
    }

    protected override void OnEnabled()
    {
        _bindingsResolved = false;
        _missingBindingsLogged = false;
        _setupLogged = false;

        ResolveNativeEffects();
        ApplySettings();
        RebuildBloom();
        RebuildTonemapping();
        RebuildColorGrading();
        RebuildAmbientOcclusion();
        RebuildAdaptivePixelation();
        RebuildEdgeCueCommands();
        RebuildRuntimeCommands();

        base.OnEnabled();
    }

    protected override void OnDisabled()
    {
        ResolveNativeEffects();
        SetNativeEffectsEnabled( false );
        ReleaseTonemapping();
        ReleaseColorGrading();
        ReleaseBloom();
        ReleaseAmbientOcclusion();
        ReleaseAdaptivePixelation();
        ReleaseEdgeCuePass();
        ReleaseRuntimePass();
        base.OnDisabled();
    }

    protected override void OnDestroy()
    {
        ReleaseTonemapping();
        ReleaseColorGrading();
        ReleaseBloom();
        ReleaseAmbientOcclusion();
        ReleaseAdaptivePixelation();
        ReleaseEdgeCuePass();
        ReleaseRuntimePass();
        base.OnDestroy();
    }

    /// <summary>
    /// Called by OMRViewModelCamera once its local final overlay camera exists.
    /// Idempotent: calling it repeatedly with the same camera is harmless.
    /// </summary>
    public void BindRuntimeOverlayCamera( CameraComponent camera )
    {
        if ( camera is null || !camera.IsValid )
            return;

        if ( _runtimeOverlayCamera == camera && _runtimeCommandAttached )
            return;

        ReleaseRuntimePass();
        _runtimeOverlayCamera = camera;
        EnsureRuntimePass();
        RebuildRuntimeCommands();
        RebuildColorGrading();
    }

    /// <summary>
    /// Releases the runtime pass only when it belongs to the supplied overlay
    /// camera. Called before OMRViewModelCamera destroys/replaces that camera.
    /// </summary>
    public void UnbindRuntimeOverlayCamera( CameraComponent camera )
    {
        if ( camera is not null && _runtimeOverlayCamera != camera )
            return;

        ReleaseRuntimePass();
    }

    /// <summary>
    /// Supplies the transparent offscreen viewmodel texture created by
    /// OMRViewModelCamera. The texture is local presentation state only.
    /// </summary>
    public void BindRuntimeViewModelTexture( Texture texture )
    {
        if ( texture is null || !texture.IsValid )
            return;

        if ( _runtimeViewModelTexture == texture && _runtimeViewModelCommandAttached &&
            _runtimeViewModelCommands?.Enabled == true ) return;
        _runtimeViewModelTexture = texture;
        _runtimeViewModelCommandsBuilt = false;
        EnsureRuntimePass();
        RebuildRuntimeCommands();
    }

    public void UnbindRuntimeViewModelTexture( Texture texture )
    {
        if (
            texture is not null &&
            _runtimeViewModelTexture is not null &&
            _runtimeViewModelTexture != texture
        )
            return;

        _runtimeViewModelTexture = null;
        _runtimeViewModelCommandsBuilt = false;

        if ( _runtimeViewModelCommands is not null )
        {
            _runtimeViewModelCommands.Enabled = false;
            _runtimeViewModelCommands.Reset();
        }
    }

    private void ResolveNativeEffects()
    {
        bool pixelValid = _pixelate is not null && _pixelate.IsValid;
        bool colorValid = _colorAdjustments is not null && _colorAdjustments.IsValid;
        bool grainValid = _filmGrain is not null && _filmGrain.IsValid;

        if ( pixelValid && colorValid && grainValid )
        {
            _bindingsResolved = true;
            return;
        }

        _pixelate = GetComponent<Pixelate>( true );
        _colorAdjustments = GetComponent<ColorAdjustments>( true );
        _filmGrain = GetComponent<FilmGrain>( true );

        _bindingsResolved =
            _pixelate is not null && _pixelate.IsValid &&
            _colorAdjustments is not null && _colorAdjustments.IsValid &&
            _filmGrain is not null && _filmGrain.IsValid;

        if ( _bindingsResolved )
        {
            _missingBindingsLogged = false;
            return;
        }

        if ( LogSetup && !_missingBindingsLogged )
        {
            _missingBindingsLogged = true;
            Log.Warning(
                $"[OMR VISUAL] Missing native effects on '{GameObject.Name}'. " +
                $"Pixelate:{_pixelate is not null && _pixelate.IsValid} | " +
                $"ColorAdjustments:{_colorAdjustments is not null && _colorAdjustments.IsValid} | " +
                $"FilmGrain:{_filmGrain is not null && _filmGrain.IsValid}. " +
                "Use 'Setup Native Effects' once in the Inspector."
            );
        }
    }

    private void ApplySettings()
    {
        if ( !_bindingsResolved )
            return;

        float weight = EnableWorldLook
            ? MathX.Clamp( BlendWeight, 0f, 1f )
            : 0f;

        bool active = weight > 0.0001f;

        // In editor/non-play mode, use the native components directly so scene
        // view and camera preview remain WYSIWYG.
        //
        // In runtime, the final two-camera composition needs the treatment on
        // the final overlay camera before it draws the viewmodel. Native effects
        // on the lower world camera are disabled to prevent double-processing on
        // render paths where they might otherwise survive.
        if ( Game.IsPlaying )
        {
            SetNativeEffectsEnabled( false );
            return;
        }

        _pixelate.Enabled = EffectivePixelateScale > 0.0001f && active;
        if ( _pixelate.Enabled )
        {
            _pixelate.Scale = MathX.Clamp(
                PixelateScale * weight,
                0f,
                1f
            );
        }

        _colorAdjustments.Enabled = EffectiveColorAdjustmentsEnabled && active;
        if ( _colorAdjustments.Enabled )
        {
            _colorAdjustments.Brightness = MathX.Lerp(
                1f,
                MathX.Clamp( Brightness, 0f, 2f ),
                weight
            );

            _colorAdjustments.Contrast = MathX.Lerp(
                1f,
                MathX.Clamp( Contrast, 0f, 2f ),
                weight
            );

            _colorAdjustments.Saturation = MathX.Lerp(
                1f,
                MathX.Clamp( Saturation, 0f, 2f ),
                weight
            );

            _colorAdjustments.HueRotate =
                MathX.Clamp( HueRotate, -180f, 180f ) * weight;
        }

        _filmGrain.Enabled = EffectiveFilmGrainIntensity > 0.0001f && active;
        if ( _filmGrain.Enabled )
        {
            _filmGrain.Intensity =
                MathX.Clamp( FilmGrainIntensity, 0f, 1f ) * weight;

            _filmGrain.Response =
                MathX.Clamp( FilmGrainResponse, 0f, 1f );
        }

        if ( LogSetup && !_setupLogged )
        {
            _setupLogged = true;
            Log.Info(
                $"[OMR VISUAL] Native editor-preview controller active | " +
                $"Camera:{GameObject.Name} | Weight:{weight:0.###} | " +
                $"Pixelate:{_pixelate.Enabled} {_pixelate.Scale:0.###} | " +
                $"Color:{_colorAdjustments.Enabled} | Grain:{_filmGrain.Enabled}"
            );
        }
    }

    private void SetNativeEffectsEnabled( bool enabled )
    {
        if ( _pixelate is not null && _pixelate.IsValid )
            _pixelate.Enabled = enabled;

        if ( _colorAdjustments is not null && _colorAdjustments.IsValid )
            _colorAdjustments.Enabled = enabled;

        if ( _filmGrain is not null && _filmGrain.IsValid )
            _filmGrain.Enabled = enabled;
    }

    private void EnsureRuntimePass()
    {
        if ( !Game.IsPlaying )
            return;

        if (
            _runtimeOverlayCamera is null ||
            !_runtimeOverlayCamera.IsValid
        )
            return;

        if (
            _runtimeWorldLookMaterial is null ||
            !_runtimeWorldLookMaterial.IsValid
        )
        {
            _runtimeWorldLookMaterial =
                Material.FromShader( WorldLookShaderPath );

            if (
                _runtimeWorldLookMaterial is null ||
                !_runtimeWorldLookMaterial.IsValid
            )
            {
                if ( !_runtimeMaterialFailureLogged )
                {
                    _runtimeMaterialFailureLogged = true;
                    Log.Warning(
                        $"[OMR VISUAL] Could not create runtime world-look material from '{WorldLookShaderPath}'."
                    );
                }

                return;
            }

            _runtimeMaterialFailureLogged = false;
        }

        _runtimeWorldLookAttributes ??=
            new RenderAttributes();

        _runtimeWorldLookCommands ??=
            new CommandList( "OMR Runtime World Look" );

        if ( !_runtimeCommandAttached )
        {
            _runtimeOverlayCamera.AddCommandList(
                _runtimeWorldLookCommands,
                Stage.AfterDepthPrepass,
                RuntimeWorldLookCommandOrder
            );

            _runtimeCommandAttached = true;
        }

        if (
            _runtimeViewModelTexture is not null &&
            _runtimeViewModelTexture.IsValid
        )
        {
            if (
                _runtimeViewModelMaterial is null ||
                !_runtimeViewModelMaterial.IsValid
            )
            {
                _runtimeViewModelMaterial =
                    Material.FromShader( ViewModelCompositeShaderPath );

                if (
                    _runtimeViewModelMaterial is null ||
                    !_runtimeViewModelMaterial.IsValid
                )
                {
                    if ( !_runtimeViewModelMaterialFailureLogged )
                    {
                        _runtimeViewModelMaterialFailureLogged = true;
                        Log.Warning(
                            $"[OMR VISUAL] Could not create viewmodel composite material from '{ViewModelCompositeShaderPath}'."
                        );
                    }
                }
                else
                {
                    _runtimeViewModelMaterialFailureLogged = false;
                }
            }

            _runtimeViewModelAttributes ??= new RenderAttributes();
            _runtimeViewModelCommands ??= new CommandList( "OMR Runtime Viewmodel Composite" );

            if (
                !_runtimeViewModelCommandAttached &&
                _runtimeViewModelMaterial is not null &&
                _runtimeViewModelMaterial.IsValid
            )
            {
                _runtimeOverlayCamera.AddCommandList(
                    _runtimeViewModelCommands,
                    Stage.AfterDepthPrepass,
                    RuntimeViewModelCompositeCommandOrder
                );

                _runtimeViewModelCommandAttached = true;
            }
        }

        if ( LogSetup && !_runtimeReadyLogged )
        {
            _runtimeReadyLogged = true;
            Log.Info(
                $"[OMR VISUAL] Runtime bridge ready | " +
                $"OverlayCamera:{_runtimeOverlayCamera.GameObject.Name} | " +
                $"Stage:{Stage.AfterDepthPrepass} | " +
                $"Shader:{WorldLookShaderPath}"
            );
        }
    }

    private void RebuildRuntimeCommands()
    {
        if ( !Game.IsPlaying )
            return;

        EnsureRuntimePass();

        if (
            _runtimeWorldLookCommands is not null &&
            _runtimeWorldLookMaterial is not null &&
            _runtimeWorldLookMaterial.IsValid &&
            _runtimeWorldLookAttributes is not null
        )
        {
            HashCode worldHash = new();
            worldHash.Add( _runtimeWorldLookMaterial );
            worldHash.Add( EffectiveWorldLookBlend );
            worldHash.Add( EffectivePixelateScale );
            worldHash.Add( EffectiveColorAdjustmentsEnabled );
            worldHash.Add( Brightness ); worldHash.Add( Contrast );
            worldHash.Add( Saturation ); worldHash.Add( HueRotate );
            worldHash.Add( EffectiveFilmGrainIntensity ); worldHash.Add( EffectiveFilmGrainResponse );
            int signature = worldHash.ToHashCode();
            if ( !_runtimeWorldCommandsBuilt || signature != _runtimeWorldCommandsHash )
            {
                _runtimeWorldCommandsBuilt = true;
                _runtimeWorldCommandsHash = signature;
                _runtimeWorldLookCommands.Reset();

                float weight = EffectiveWorldLookBlend;

                _runtimeWorldLookCommands.Enabled = weight > 0.0001f;

                if ( _runtimeWorldLookCommands.Enabled )
                {
                    _runtimeWorldLookAttributes.Set( "OMRBlend", weight );
                    _runtimeWorldLookAttributes.Set(
                        "OMRPixelateScale",
                        EffectivePixelateScale
                    );
                    _runtimeWorldLookAttributes.Set( "OMRColorEnabled", EffectiveColorAdjustmentsEnabled ? 1f : 0f );
                    _runtimeWorldLookAttributes.Set( "OMRBrightness", MathX.Clamp( Brightness, 0f, 2f ) );
                    _runtimeWorldLookAttributes.Set( "OMRContrast", MathX.Clamp( Contrast, 0f, 2f ) );
                    _runtimeWorldLookAttributes.Set( "OMRSaturation", MathX.Clamp( Saturation, 0f, 2f ) );
                    _runtimeWorldLookAttributes.Set( "OMRHueRotate", MathX.Clamp( HueRotate, -180f, 180f ) );
                    _runtimeWorldLookAttributes.Set( "OMRGrainIntensity", EffectiveFilmGrainIntensity );
                    _runtimeWorldLookAttributes.Set( "OMRGrainResponse", EffectiveFilmGrainResponse );

                    using ( _runtimeWorldLookCommands.ProfileScope( WorldLookGpuScope ) )
                    {
                        _runtimeWorldLookCommands.Attributes.GrabFrameTexture( "ColorBuffer" );
                        _runtimeWorldLookCommands.Blit( _runtimeWorldLookMaterial, _runtimeWorldLookAttributes );
                    }
                }
            }
        }

        // The viewmodel capture camera renders offscreen, so this composite must
        // run even when EnableViewModelLook is false. In that case the shader
        // simply composites the untreated texture.
        RebuildRuntimeViewModelCommands();
    }

    private void RebuildRuntimeViewModelCommands()
    {
        if (
            _runtimeViewModelCommands is null ||
            _runtimeViewModelMaterial is null ||
            !_runtimeViewModelMaterial.IsValid ||
            _runtimeViewModelAttributes is null ||
            _runtimeViewModelTexture is null ||
            !_runtimeViewModelTexture.IsValid
        )
            return;

        HashCode modelHash = new();
        modelHash.Add( _runtimeViewModelTexture ); modelHash.Add( _runtimeViewModelMaterial );
        modelHash.Add( EffectiveViewModelLookBlend ); modelHash.Add( EffectiveViewModelPixelateScale );
        modelHash.Add( EffectiveViewModelColorAdjustmentsEnabled );
        modelHash.Add( EffectiveViewModelBrightness ); modelHash.Add( EffectiveViewModelContrast );
        modelHash.Add( EffectiveViewModelSaturation ); modelHash.Add( EffectiveViewModelHueRotate );
        modelHash.Add( EffectiveViewModelTint ); modelHash.Add( EffectiveViewModelTintStrength );
        modelHash.Add( EffectiveViewModelFilmGrainIntensity ); modelHash.Add( EffectiveViewModelFilmGrainResponse );
        int signature = modelHash.ToHashCode();
        if ( _runtimeViewModelCommandsBuilt && signature == _runtimeViewModelCommandsHash ) return;
        _runtimeViewModelCommandsBuilt = true;
        _runtimeViewModelCommandsHash = signature;

        _runtimeViewModelCommands.Reset();
        _runtimeViewModelCommands.Enabled = true;

        _runtimeViewModelAttributes.Set( "OMRViewModelTexture", _runtimeViewModelTexture );
        _runtimeViewModelAttributes.Set( "OMRViewModelLookBlend", EffectiveViewModelLookBlend );
        _runtimeViewModelAttributes.Set( "OMRViewModelPixelateScale", EffectiveViewModelPixelateScale );
        _runtimeViewModelAttributes.Set( "OMRViewModelColorEnabled", EffectiveViewModelColorAdjustmentsEnabled ? 1f : 0f );
        _runtimeViewModelAttributes.Set( "OMRViewModelBrightness", EffectiveViewModelBrightness );
        _runtimeViewModelAttributes.Set( "OMRViewModelContrast", EffectiveViewModelContrast );
        _runtimeViewModelAttributes.Set( "OMRViewModelSaturation", EffectiveViewModelSaturation );
        _runtimeViewModelAttributes.Set( "OMRViewModelHueRotate", EffectiveViewModelHueRotate );
        _runtimeViewModelAttributes.Set( "OMRViewModelTint", EffectiveViewModelTint );
        _runtimeViewModelAttributes.Set( "OMRViewModelTintStrength", EffectiveViewModelTintStrength );
        _runtimeViewModelAttributes.Set( "OMRViewModelGrainIntensity", EffectiveViewModelFilmGrainIntensity );
        _runtimeViewModelAttributes.Set( "OMRViewModelGrainResponse", EffectiveViewModelFilmGrainResponse );

        using ( _runtimeViewModelCommands.ProfileScope( ViewModelGpuScope ) )
        {
            _runtimeViewModelCommands.Attributes.GrabFrameTexture( "ColorBuffer" );
            _runtimeViewModelCommands.Blit( _runtimeViewModelMaterial, _runtimeViewModelAttributes );
        }
    }

    private void ReleaseRuntimePass()
    {
        _runtimeWorldCommandsBuilt = false;
        _runtimeViewModelCommandsBuilt = false;
        ReleaseRuntimeColorGradingPass();

        if (
            _runtimeViewModelCommandAttached &&
            _runtimeOverlayCamera is not null &&
            _runtimeOverlayCamera.IsValid &&
            _runtimeViewModelCommands is not null
        )
        {
            _runtimeOverlayCamera.RemoveCommandList( _runtimeViewModelCommands );
        }

        _runtimeViewModelCommandAttached = false;

        if ( _runtimeViewModelCommands is not null )
        {
            _runtimeViewModelCommands.Enabled = false;
            _runtimeViewModelCommands.Reset();
        }

        if (
            _runtimeCommandAttached &&
            _runtimeOverlayCamera is not null &&
            _runtimeOverlayCamera.IsValid &&
            _runtimeWorldLookCommands is not null
        )
        {
            _runtimeOverlayCamera.RemoveCommandList(
                _runtimeWorldLookCommands
            );
        }

        _runtimeCommandAttached = false;

        if ( _runtimeWorldLookCommands is not null )
        {
            _runtimeWorldLookCommands.Enabled = false;
            _runtimeWorldLookCommands.Reset();
        }

        _runtimeWorldLookCommands = null;
        _runtimeWorldLookAttributes = null;
        _runtimeWorldLookMaterial = null;

        _runtimeViewModelCommands = null;
        _runtimeViewModelAttributes = null;
        _runtimeViewModelMaterial = null;
        _runtimeViewModelTexture = null;
        _runtimeViewModelMaterialFailureLogged = false;

        _runtimeOverlayCamera = null;
        _runtimeReadyLogged = false;
        _runtimeMaterialFailureLogged = false;
    }
}