Core/DmlrWorldEngine.cs

Static helper that adjusts scene rendering settings for LOD and performance: sets main camera ZFar, terrain clipmap levels, scales Fog/GradientFog distances, and time-slices shadow and light-shadow culling based on distance to the camera using scene-wide caches. Writes counters such as NearbyPlayers, OptimizedEntities and CulledWorldRenderers into DmlrCoreDatabase.

using Sandbox;
using System;
using System.Collections.Generic;

namespace DmlrAddon;

/// <summary>
/// BASE DE CODAGE 1 · Moteur Monde DMLR Ultra (time-sliced adaptatif, 0 pic CPU, 100 % réversible).
/// Pilote Render Distance Xtreme (120 000 / 250 000), Terrain ClipMap, Fog réversible,
/// Bouclier Anti-Chutes FPS (ombres &amp; lumières dynamiques lointaines) et Liaison Multiverselle Anti-Pics Ping.
/// </summary>
public static class DmlrWorldEngine
{
	private readonly struct FogSnapshot
	{
		public bool FogEnabled { get; init; }
		public bool DistanceEnabled { get; init; }
		public float StartDistance { get; init; }
		public Vector2 DistanceRange { get; init; }
		public float MaximumOpacity { get; init; }
	}

	private readonly struct LegacyFogSnapshot
	{
		public bool Enabled { get; init; }
		public float StartDistance { get; init; }
		public float EndDistance { get; init; }
		public Color Color { get; init; }
	}

	private static Scene _boundScene;
	private static readonly Dictionary<Guid, FogSnapshot> _fogBackups = new();
	private static readonly Dictionary<Guid, LegacyFogSnapshot> _legacyFogBackups = new();
	private static readonly Dictionary<Guid, ModelRenderer.ShadowRenderType> _origShadowTypes = new();
	private static readonly Dictionary<Guid, bool> _origLightShadows = new();

	private static readonly List<ModelRenderer> _worldRenderers = new( 512 );
	private static readonly List<Light> _worldDynamicLights = new( 128 );
	private static int _sliceCursor;
	private static int _sliceCulledAccum;
	private static float _cacheRefreshTimer = 99f;
	private static float _multiTimer;
	private static float _worldTimer;
	private static float _lightShieldTimer;

	private const int CruiseBatchSize = 64;
	private const int PressureBatchSize = 32;

	public static void ResetForScene( Scene scene )
	{
		_boundScene = scene;
		_fogBackups.Clear();
		_legacyFogBackups.Clear();
		_origShadowTypes.Clear();
		_origLightShadows.Clear();
		_worldRenderers.Clear();
		_worldDynamicLights.Clear();
		_sliceCursor = 0;
		_sliceCulledAccum = 0;
		_cacheRefreshTimer = 99f;
		_multiTimer = 0f;
		_worldTimer = 0f;
		_lightShieldTimer = 0f;
	}

	public static void ApplyImmediate( Scene scene )
	{
		if ( scene is null || !scene.IsValid() ) return;
		if ( _boundScene != scene ) ResetForScene( scene );

		float zfar = DmlrCoreDatabase.CameraZFar;
		bool xtremeRd = DmlrCoreDatabase.IsRenderDistanceXtreme;

		foreach ( var cam in scene.GetAllComponents<CameraComponent>() )
		{
			if ( !cam.IsValid() ) continue;
			if ( cam.IsMainCamera || cam == scene.Camera )
			{
				cam.ZFar = zfar;
			}
		}

		foreach ( var terrain in scene.GetAllComponents<Terrain>() )
		{
			if ( !terrain.IsValid() ) continue;
			int lod = xtremeRd ? 6 : 5;
			int extent = xtremeRd ? 256 : 128;
			if ( terrain.ClipMapLodLevels != lod ) terrain.ClipMapLodLevels = lod;
			if ( terrain.ClipMapLodExtentTexels != extent ) terrain.ClipMapLodExtentTexels = extent;
		}

		ApplyFogSurplus( scene, DmlrCoreDatabase.MapFogMode );

		_cacheRefreshTimer = 99f;
		_multiTimer = 99f;
		_worldTimer = 99f;
		_lightShieldTimer = 99f;
	}

	public static void Tick( Scene scene, float dt )
	{
		if ( scene is null || !scene.IsValid() || scene.IsEditor ) return;
		if ( _boundScene != scene )
		{
			ResetForScene( scene );
			ApplyImmediate( scene );
		}

		DmlrCoreDatabase.ConnectedPlayers = Math.Max( 1, Connection.All.Count );

		var mainCam = scene.Camera;
		float targetZFar = DmlrCoreDatabase.CameraZFar;
		if ( mainCam.IsValid() && MathF.Abs( mainCam.ZFar - targetZFar ) > 10f )
		{
			mainCam.ZFar = targetZFar;
		}

		// Liaison Multiverselle (Anti-Pics Ping & allègement proxies réseau sans 1 seul octet réseau)
		if ( DmlrCoreDatabase.IsMultiplayer )
		{
			_multiTimer += dt;
			float multiInterval = DmlrCoreDatabase.IsMultiversalXtreme ? 0.22f : 0.42f;
			if ( _multiTimer >= multiInterval )
			{
				_multiTimer = 0f;
				TickMultiversal( scene, mainCam );
			}
		}
		else
		{
			DmlrCoreDatabase.NearbyPlayers = 1;
			DmlrCoreDatabase.OptimizedEntities = 0;
		}

		// Rafraîchissement léger du cache scène toutes les 4s (zéro scan par frame)
		_cacheRefreshTimer += dt;
		if ( _cacheRefreshTimer >= 4.0f )
		{
			_cacheRefreshTimer = 0f;
			RefreshWorldCache( scene );
		}

		// Culling d'ombres Next-Gen time-sliced (lots adaptatifs 32–64 objets/passe, zéro micro-freeze)
		_worldTimer += dt;
		if ( _worldTimer >= 0.08f )
		{
			_worldTimer = 0f;
			TickHeavyMapSlice( mainCam );
		}

		// Bouclier Anti-Chutes FPS sur les lumières locales (PointLight & SpotLight distantes)
		_lightShieldTimer += dt;
		if ( _lightShieldTimer >= 0.28f )
		{
			_lightShieldTimer = 0f;
			TickWorldLightShield( mainCam );
		}
	}

	private static void RefreshWorldCache( Scene scene )
	{
		_worldRenderers.Clear();
		foreach ( var mr in scene.GetAllComponents<ModelRenderer>() )
		{
			if ( !mr.IsValid() || !mr.Enabled ) continue;
			if ( mr.GameObject.IsProxy ) continue;
			_worldRenderers.Add( mr );
		}

		_worldDynamicLights.Clear();
		foreach ( var pl in scene.GetAllComponents<PointLight>() )
		{
			if ( !pl.IsValid() || !pl.Enabled || pl.GameObject.IsProxy ) continue;
			_worldDynamicLights.Add( pl );
		}
		foreach ( var sl in scene.GetAllComponents<SpotLight>() )
		{
			if ( !sl.IsValid() || !sl.Enabled || sl.GameObject.IsProxy ) continue;
			_worldDynamicLights.Add( sl );
		}

		DmlrCoreDatabase.ActiveWorldRenderers = _worldRenderers.Count;
		if ( _sliceCursor >= _worldRenderers.Count ) _sliceCursor = 0;

		// Nettoyage mémoire léger sur longues sessions RP 64 joueurs (évite la croissance infinie des snapshots)
		if ( _origShadowTypes.Count > 2048 || _origLightShadows.Count > 512 )
		{
			PruneStaleSnapshots( scene );
		}
	}

	private static void PruneStaleSnapshots( Scene scene )
	{
		var liveShadowIds = new HashSet<Guid>();
		foreach ( var mr in scene.GetAllComponents<ModelRenderer>() )
		{
			if ( mr.IsValid() ) liveShadowIds.Add( mr.Id );
		}

		var deadShadows = new List<Guid>();
		foreach ( var key in _origShadowTypes.Keys )
		{
			if ( !liveShadowIds.Contains( key ) ) deadShadows.Add( key );
		}
		for ( int i = 0; i < deadShadows.Count; i++ )
			_origShadowTypes.Remove( deadShadows[i] );

		var liveLightIds = new HashSet<Guid>();
		foreach ( var pl in scene.GetAllComponents<PointLight>() )
		{
			if ( pl.IsValid() ) liveLightIds.Add( pl.Id );
		}
		foreach ( var sl in scene.GetAllComponents<SpotLight>() )
		{
			if ( sl.IsValid() ) liveLightIds.Add( sl.Id );
		}

		var deadLights = new List<Guid>();
		foreach ( var key in _origLightShadows.Keys )
		{
			if ( !liveLightIds.Contains( key ) ) deadLights.Add( key );
		}
		for ( int i = 0; i < deadLights.Count; i++ )
			_origLightShadows.Remove( deadLights[i] );
	}

	private static void ApplyFogSurplus( Scene scene, DmlrMapFogMode fogMode )
	{
		float scale = fogMode switch
		{
			DmlrMapFogMode.OrigineMap => 1.00f,
			DmlrMapFogMode.Etendu => 1.45f,
			DmlrMapFogMode.Xtreme => 2.00f,
			_ => 0f
		};

		foreach ( var fog in scene.GetAllComponents<Fog>() )
		{
			if ( !fog.IsValid() ) continue;
			var id = fog.Id;
			if ( !_fogBackups.TryGetValue( id, out var orig ) )
			{
				orig = new FogSnapshot
				{
					FogEnabled = fog.FogEnabled,
					DistanceEnabled = fog.DistanceEnabled,
					StartDistance = fog.StartDistance,
					DistanceRange = fog.DistanceRange,
					MaximumOpacity = fog.MaximumOpacity
				};
				_fogBackups[id] = orig;
			}

			fog.FogEnabled = orig.FogEnabled;
			fog.DistanceEnabled = orig.DistanceEnabled;
			fog.StartDistance = orig.StartDistance * scale;
			fog.DistanceRange = new Vector2( orig.DistanceRange.x * scale, orig.DistanceRange.y * scale );
			fog.MaximumOpacity = fogMode == DmlrMapFogMode.Xtreme ? orig.MaximumOpacity * 0.78f : orig.MaximumOpacity;
		}

#pragma warning disable CS0618
		foreach ( var gfog in scene.GetAllComponents<GradientFog>() )
		{
			if ( !gfog.IsValid() ) continue;
			var id = gfog.Id;
			if ( !_legacyFogBackups.TryGetValue( id, out var orig ) )
			{
				orig = new LegacyFogSnapshot
				{
					Enabled = gfog.Enabled,
					StartDistance = gfog.StartDistance,
					EndDistance = gfog.EndDistance,
					Color = gfog.Color
				};
				_legacyFogBackups[id] = orig;
			}

			gfog.Enabled = orig.Enabled;
			gfog.StartDistance = orig.StartDistance * scale;
			gfog.EndDistance = orig.EndDistance * scale;
			gfog.Color = fogMode == DmlrMapFogMode.Xtreme
				? new Color( orig.Color.r, orig.Color.g, orig.Color.b, orig.Color.a * 0.78f )
				: orig.Color;
		}
#pragma warning restore CS0618
	}

	private static void TickMultiversal( Scene scene, CameraComponent cam )
	{
		if ( !cam.IsValid() ) return;

		bool xtreme = DmlrCoreDatabase.IsMultiversalXtreme;
		float gov = DmlrCoreDatabase.DynamicGovernorBias;
		Vector3 camPos = cam.WorldPosition;
		float shadowDist = (xtreme ? 1050f : 2200f) * gov;
		float lightDist = (xtreme ? 1450f : 2800f) * gov;
		float shadowDistSq = shadowDist * shadowDist;
		float lightDistSq = lightDist * lightDist;
		int nearby = 1;
		int optEnts = 0;
		int optLights = 0;

		foreach ( var go in scene.GetAllObjects( true ) )
		{
			if ( !go.IsValid() || !go.IsProxy ) continue;
			if ( go.Parent is not null && go.Parent.IsProxy ) continue;

			float distSq = (go.WorldPosition - camPos).LengthSquared;
			if ( distSq <= 2400f * 2400f ) nearby++;

			bool farShadow = distSq > shadowDistSq;
			if ( farShadow ) optEnts++;

			foreach ( var mr in go.Components.GetAll<ModelRenderer>( FindMode.EverythingInSelfAndDescendants ) )
			{
				if ( !mr.IsValid() ) continue;
				if ( !_origShadowTypes.ContainsKey( mr.Id ) ) _origShadowTypes[mr.Id] = mr.RenderType;
				var target = farShadow ? ModelRenderer.ShadowRenderType.Off : _origShadowTypes[mr.Id];
				if ( mr.RenderType != target ) mr.RenderType = target;
			}

			bool allowShadowLight = !xtreme && distSq <= lightDistSq;
			foreach ( var pl in go.Components.GetAll<PointLight>( FindMode.EverythingInSelfAndDescendants ) )
			{
				if ( !pl.IsValid() ) continue;
				if ( !_origLightShadows.ContainsKey( pl.Id ) ) _origLightShadows[pl.Id] = pl.Shadows;
				bool target = allowShadowLight && _origLightShadows[pl.Id];
				if ( !target && _origLightShadows[pl.Id] ) optLights++;
				if ( pl.Shadows != target ) pl.Shadows = target;
			}

			foreach ( var sl in go.Components.GetAll<SpotLight>( FindMode.EverythingInSelfAndDescendants ) )
			{
				if ( !sl.IsValid() ) continue;
				if ( !_origLightShadows.ContainsKey( sl.Id ) ) _origLightShadows[sl.Id] = sl.Shadows;
				bool target = allowShadowLight && _origLightShadows[sl.Id];
				if ( !target && _origLightShadows[sl.Id] ) optLights++;
				if ( sl.Shadows != target ) sl.Shadows = target;
			}
		}

		DmlrCoreDatabase.NearbyPlayers = nearby;
		DmlrCoreDatabase.OptimizedEntities = optEnts;
		DmlrCoreDatabase.OptimizedLights = optLights;
	}

	private static void TickWorldLightShield( CameraComponent cam )
	{
		if ( !cam.IsValid() || _worldDynamicLights.Count == 0 ) return;

		Vector3 camPos = cam.WorldPosition;
		float gov = DmlrCoreDatabase.DynamicGovernorBias;
		float baseRange = DmlrCoreDatabase.IsMultiversalXtreme ? 1850f : 2900f;
		float range = baseRange * gov;
		float rangeSq = range * range;
		int shielded = 0;

		for ( int i = 0; i < _worldDynamicLights.Count; i++ )
		{
			var light = _worldDynamicLights[i];
			if ( !light.IsValid() ) continue;

			if ( !_origLightShadows.TryGetValue( light.Id, out bool origShadows ) )
			{
				origShadows = light.Shadows;
				_origLightShadows[light.Id] = origShadows;
			}
			if ( !origShadows ) continue;

			float distSq = (light.WorldPosition - camPos).LengthSquared;
			bool keepShadow = distSq <= rangeSq;
			if ( !keepShadow ) shielded++;
			if ( light.Shadows != keepShadow ) light.Shadows = keepShadow;
		}

		if ( !DmlrCoreDatabase.IsMultiplayer )
		{
			DmlrCoreDatabase.OptimizedLights = shielded;
		}
	}

	private static void TickHeavyMapSlice( CameraComponent cam )
	{
		if ( !cam.IsValid() || _worldRenderers.Count == 0 ) return;

		Vector3 camPos = cam.WorldPosition;
		float gov = DmlrCoreDatabase.DynamicGovernorBias;
		float shadowRange = (DmlrCoreDatabase.IsRenderDistanceXtreme ? 4600f : 3000f) * gov;
		float shadowRangeSq = shadowRange * shadowRange;

		int total = _worldRenderers.Count;
		int batch = DmlrCoreDatabase.IsAntiDropEngaged ? PressureBatchSize : CruiseBatchSize;
		int count = Math.Min( batch, total );

		for ( int i = 0; i < count; i++ )
		{
			if ( _sliceCursor >= total )
			{
				DmlrCoreDatabase.CulledWorldRenderers = _sliceCulledAccum;
				_sliceCulledAccum = 0;
				_sliceCursor = 0;
			}

			var mr = _worldRenderers[_sliceCursor++];
			if ( !mr.IsValid() || !mr.Enabled ) continue;

			if ( !_origShadowTypes.TryGetValue( mr.Id, out var orig ) )
			{
				orig = mr.RenderType;
				_origShadowTypes[mr.Id] = orig;
			}

			float distSq = (mr.WorldPosition - camPos).LengthSquared;
			bool keepShadow = distSq <= shadowRangeSq;
			var target = keepShadow ? orig : ModelRenderer.ShadowRenderType.Off;
			if ( !keepShadow && orig != ModelRenderer.ShadowRenderType.Off )
				_sliceCulledAccum++;
			if ( mr.RenderType != target )
				mr.RenderType = target;
		}
	}
}