From 2529ba62d268abc4bcd324ce6ef73a4d211ca841 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 4 Dec 2026 23:56:30 +0100 Subject: [PATCH] render: unified MultiMeshPartPool with MechPaint, PomDecalPool, and per-weapon VFX --- client/ArenaRenderer.cs | 849 +++++++++++++++++++++++++------- client/DebrisSystem.cs | 203 +++----- client/MultiMeshPartPool.cs | 247 ++++++++++ client/PomDecalPool.cs | 440 +++++++++++++++++ client/VehicleAssetCache.cs | 513 ++++++++++++++++++- client/VehicleRigAnimator.cs | 215 ++++---- client/VehicleVisualInstance.cs | 833 ++++++++++++++++--------------- client/mech_paint.gdshader | 139 +++++- client/tests/Smoke.cs | 143 +++--- 9 files changed, 2652 insertions(+), 930 deletions(-) create mode 100644 client/MultiMeshPartPool.cs create mode 100644 client/PomDecalPool.cs diff --git a/client/ArenaRenderer.cs b/client/ArenaRenderer.cs index 91862ca..6632783 100644 --- a/client/ArenaRenderer.cs +++ b/client/ArenaRenderer.cs @@ -8,9 +8,9 @@ namespace RustToDust.Client; /// /// Renders the 3D arena entities from : -/// cover ruins, shrinking Safe Circle ring, real Brokkr vehicle/mech GLBs with hardpoint snap-on gear, -/// live secondary mechanism animations, part-by-cell debris detachment, 3 alien spectator tiers + status halos/lock lasers, -/// real gear/chassis salvage drops, and weapon tracers. +/// cover ruins, shrinking Safe Circle ring, unified for all +/// 15 Brokkr vehicles/mechs, mounted gear, salvage drops, and tumbling debris, +/// live 1-draw-call combat scars, and pooled multi-class weapon VFX. /// public partial class ArenaRenderer : Node3D { @@ -34,39 +34,85 @@ public partial class ArenaRenderer : Node3D private sealed class DropVisualEntry { - public required Node3D Node; public VehicleVisualInstance? ChassisVisual; + public ArrayMesh? GearMesh; + public Vector3 GearScale; + public float GearYOffset; + public bool IsModule; + public bool IsImperial; public float BaseY; public int TileX; public int TileZ; public int TileVersion; } + private enum VfxShape + { + Beam, + Sphere, + Ring + } + + private struct TransientVfx + { + public VfxShape Shape; + public Vector3 Position; + public Vector3 Velocity; + public Basis BaseRotation; + public Vector3 StartScale; + public Vector3 EndScale; + public Color ColorStart; + public Color ColorEnd; + public float Age; + public float Lifetime; + } + + private const int MaxVfxBeams = 512; + private const int MaxVfxSpheres = 512; + private const int MaxVfxRings = 128; + private VehicleAssetCache _assetCache = null!; private Node3D _staticGroup = null!; private Node3D _actorsGroup = null!; - private Node3D _dropsGroup = null!; - private Node3D _tracersGroup = null!; + private MultiMeshPartPool _partPool = null!; + private PomDecalPool _pomDecals = null!; private DebrisSystem _debris = null!; private MeshInstance3D _safeRingMesh = null!; private ImmediateMesh _safeRingImm = null!; + // Pooled GroundDrop beacons & pillars + private MultiMesh _dropDiscMm = null!; + private MultiMeshInstance3D _dropDiscMmi = null!; + private MultiMesh _dropPillarMm = null!; + private MultiMeshInstance3D _dropPillarMmi = null!; + + // Pooled weapon VFX MultiMeshes + private ShaderMaterial _vfxMat = null!; + private MultiMesh _vfxBeamMm = null!; + private MultiMeshInstance3D _vfxBeamMmi = null!; + private MultiMesh _vfxSphereMm = null!; + private MultiMeshInstance3D _vfxSphereMmi = null!; + private MultiMesh _vfxRingMm = null!; + private MultiMeshInstance3D _vfxRingMmi = null!; + private readonly List _transientVfx = new(256); + private long _lastVfxHitId; + private uint _vfxRng = 0x51F15A3Du; + private readonly Dictionary _contenderVisuals = new(); private readonly Dictionary _spectatorVisuals = new(); private readonly Dictionary _dropVisuals = new(); - private readonly List _tracerPool = new(); private StandardMaterial3D _safeRingMat = null!; private StandardMaterial3D _coverMat = null!; private StandardMaterial3D _bermMat = null!; - private StandardMaterial3D _humanBeaconMat = null!; private StandardMaterial3D _imperialBeaconMat = null!; - private StandardMaterial3D _cyanBeaconMat = null!; private MatchState? _builtForState; private float _lastSafeRingRadius = -1f; public VehicleAssetCache AssetCache => _assetCache; public DebrisSystem Debris => _debris; + internal MultiMeshPartPool PartPool => _partPool; + internal PomDecalPool PomDecals => _pomDecals; public VehicleVisualInstance? GetContenderVisual(int contenderId) => _contenderVisuals.TryGetValue(contenderId, out var vis) ? vis.Visual : null; @@ -80,7 +126,19 @@ public partial class ArenaRenderer : Node3D : null; internal int ActiveDropVisualCount => _dropVisuals.Count; - internal int DropGroupChildCount => _dropsGroup.GetChildCount(); + + internal bool TryGetChassisDropVisual(int dropId, out VehicleVisualInstance? visual, out float baseY) + { + if (_dropVisuals.TryGetValue(dropId, out var entry) && entry.ChassisVisual is not null) + { + visual = entry.ChassisVisual; + baseY = entry.BaseY; + return true; + } + visual = null; + baseY = 0f; + return false; + } public override void _Ready() { @@ -88,27 +146,17 @@ public partial class ArenaRenderer : Node3D _staticGroup = new Node3D { Name = "StaticArena" }; _actorsGroup = new Node3D { Name = "Actors" }; - _dropsGroup = new Node3D { Name = "GroundDrops" }; - _tracersGroup = new Node3D { Name = "Tracers" }; + _partPool = new MultiMeshPartPool { Name = "PartPool" }; + _pomDecals = new PomDecalPool { Name = "PomDecals" }; _debris = new DebrisSystem { Name = "Debris" }; AddChild(_staticGroup); AddChild(_actorsGroup); - AddChild(_dropsGroup); - AddChild(_tracersGroup); + AddChild(_partPool); + AddChild(_pomDecals); AddChild(_debris); _coverMat = new StandardMaterial3D { AlbedoColor = CoverRust, Roughness = 0.88f, Metallic = 0.25f }; _bermMat = new StandardMaterial3D { AlbedoColor = BermDark, Roughness = 0.94f, Metallic = 0.1f }; - _humanBeaconMat = new StandardMaterial3D - { - AlbedoColor = new Color(OlivePaint.R, OlivePaint.G, OlivePaint.B, 0.72f), - Roughness = 0.55f, - Metallic = 0.35f, - EmissionEnabled = true, - Emission = OlivePaint, - EmissionEnergyMultiplier = 0.6f, - Transparency = BaseMaterial3D.TransparencyEnum.Alpha - }; _imperialBeaconMat = new StandardMaterial3D { AlbedoColor = new Color(TouristGold.R, TouristGold.G, TouristGold.B, 0.82f), @@ -119,14 +167,6 @@ public partial class ArenaRenderer : Node3D EmissionEnergyMultiplier = 1.4f, Transparency = BaseMaterial3D.TransparencyEnum.Alpha }; - _cyanBeaconMat = new StandardMaterial3D - { - AlbedoColor = new Color(CyanSalvage.R, CyanSalvage.G, CyanSalvage.B, 0.72f), - EmissionEnabled = true, - Emission = CyanSalvage, - EmissionEnergyMultiplier = 1.5f, - Transparency = BaseMaterial3D.TransparencyEnum.Alpha - }; _safeRingImm = new ImmediateMesh(); _safeRingMat = new StandardMaterial3D @@ -147,6 +187,128 @@ public partial class ArenaRenderer : Node3D CastShadow = GeometryInstance3D.ShadowCastingSetting.Off }; AddChild(_safeRingMesh); + + InitPooledVfxAndBeacons(); + } + + private void InitPooledVfxAndBeacons() + { + var vfxShader = new Shader + { + Code = """ + shader_type spatial; + render_mode unshaded, cull_back, blend_mix, depth_draw_never; + varying vec4 v_inst; + void vertex() { + v_inst = INSTANCE_CUSTOM; + } + void fragment() { + ALBEDO = max(v_inst.rgb, vec3(0.0)); + ALPHA = clamp(v_inst.a, 0.0, 1.0); + } + """ + }; + _vfxMat = new ShaderMaterial { Shader = vfxShader }; + + _vfxBeamMm = new MultiMesh + { + TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseCustomData = true, + Mesh = new BoxMesh { Size = Vector3.One }, + InstanceCount = MaxVfxBeams, + VisibleInstanceCount = 0 + }; + _vfxBeamMmi = new MultiMeshInstance3D + { + Name = "VfxBeams", + Multimesh = _vfxBeamMm, + MaterialOverride = _vfxMat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, + CustomAabb = new Aabb(new Vector3(-900f, -60f, -900f), new Vector3(1800f, 220f, 1800f)), + PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, + Visible = false + }; + AddChild(_vfxBeamMmi); + + _vfxSphereMm = new MultiMesh + { + TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseCustomData = true, + Mesh = new SphereMesh { Radius = 0.5f, Height = 1.0f, RadialSegments = 10, Rings = 5 }, + InstanceCount = MaxVfxSpheres, + VisibleInstanceCount = 0 + }; + _vfxSphereMmi = new MultiMeshInstance3D + { + Name = "VfxSpheres", + Multimesh = _vfxSphereMm, + MaterialOverride = _vfxMat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, + CustomAabb = new Aabb(new Vector3(-900f, -60f, -900f), new Vector3(1800f, 220f, 1800f)), + PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, + Visible = false + }; + AddChild(_vfxSphereMmi); + + _vfxRingMm = new MultiMesh + { + TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseCustomData = true, + Mesh = new TorusMesh { InnerRadius = 0.38f, OuterRadius = 0.50f, Rings = 16, RingSegments = 6 }, + InstanceCount = MaxVfxRings, + VisibleInstanceCount = 0 + }; + _vfxRingMmi = new MultiMeshInstance3D + { + Name = "VfxRings", + Multimesh = _vfxRingMm, + MaterialOverride = _vfxMat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, + CustomAabb = new Aabb(new Vector3(-900f, -60f, -900f), new Vector3(1800f, 220f, 1800f)), + PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, + Visible = false + }; + AddChild(_vfxRingMmi); + + _dropDiscMm = new MultiMesh + { + TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseCustomData = true, + Mesh = new CylinderMesh { TopRadius = 0.72f, BottomRadius = 0.85f, Height = 0.14f, RadialSegments = 14 }, + InstanceCount = 128, + VisibleInstanceCount = 0 + }; + _dropDiscMmi = new MultiMeshInstance3D + { + Name = "DropBeaconDiscs", + Multimesh = _dropDiscMm, + MaterialOverride = _vfxMat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, + CustomAabb = new Aabb(new Vector3(-900f, -60f, -900f), new Vector3(1800f, 180f, 1800f)), + PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, + Visible = false + }; + AddChild(_dropDiscMmi); + + _dropPillarMm = new MultiMesh + { + TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseCustomData = false, + Mesh = new CylinderMesh { TopRadius = 0.06f, BottomRadius = 0.22f, Height = 5.5f, RadialSegments = 8 }, + InstanceCount = 64, + VisibleInstanceCount = 0 + }; + _dropPillarMmi = new MultiMeshInstance3D + { + Name = "ImperialDropPillars", + Multimesh = _dropPillarMm, + MaterialOverride = _imperialBeaconMat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, + CustomAabb = new Aabb(new Vector3(-900f, -60f, -900f), new Vector3(1800f, 180f, 1800f)), + PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, + Visible = false + }; + AddChild(_dropPillarMmi); } public override void _ExitTree() @@ -168,20 +330,26 @@ public partial class ArenaRenderer : Node3D bool hasCam = cam is not null && cam.IsInsideTree(); Vector3 camPos = hasCam ? cam!.GlobalPosition : Vector3.Zero; + _partPool.BeginFrame(hasCam ? cam : null); UpdateSafeCircleRing(state.Terrain, state.Spectators.SafeRadius); SyncContenders(session, dt, hasCam, camPos); SyncSpectators(session, elapsedSeconds, dt, hasCam, camPos); SyncGroundDrops(state, elapsedSeconds, hasCam, camPos); - SyncTracers(state.Tracers); _debris.Step(dt, state.Terrain); + _debris.SubmitToPool(_partPool); + _partPool.EndFrame(); + + _pomDecals.Sync(session, dt, ResolveEntityVisual); + SyncWeaponVfx(state, dt); } + private VehicleVisualInstance? ResolveEntityVisual(bool isContender, int id) => + isContender ? GetContenderVisual(id) : GetSpectatorVisual(id); + private void RebuildStaticArena(MatchState state) { ClearChildren(_staticGroup); - // Bucket cover ruins into 4 world quadrants so frustum culling still culls off-screen quadrants - // while collapsing 36 individual MeshInstance3D draw calls down to <= 4. var quadArrays = new SurfaceTool[4]; for (int i = 0; i < state.ArenaCoverBoxes.Count; i++) { @@ -241,7 +409,6 @@ public partial class ArenaRenderer : Node3D Vector3 p111 = center + new Vector3( h.X, h.Y, h.Z); Vector3 p011 = center + new Vector3(-h.X, h.Y, h.Z); - // +Z, -Z, +X, -X, +Y, -Y (outward CCW in Godot right-handed coords) AddQuad(st, p001, p101, p111, p011); AddQuad(st, p100, p000, p010, p110); AddQuad(st, p101, p100, p110, p111); @@ -259,10 +426,20 @@ public partial class ArenaRenderer : Node3D private void ClearDynamicVisuals() { ClearChildren(_actorsGroup); - ClearChildren(_dropsGroup); + _partPool.ClearAll(); + _pomDecals.ClearAll(); _debris.ClearAll(); + _transientVfx.Clear(); + _lastVfxHitId = 0; _contenderVisuals.Clear(); _spectatorVisuals.Clear(); + foreach (var kv in _dropVisuals) + { + if (kv.Value.ChassisVisual is { } cv && GodotObject.IsInstanceValid(cv.Root)) + { + cv.Root.QueueFree(); + } + } _dropVisuals.Clear(); _lastSafeRingRadius = -1f; } @@ -327,7 +504,6 @@ public partial class ArenaRenderer : Node3D { if (_contenderVisuals.TryGetValue(c.Id, out var deadVis)) { - // Flush any final stripped plates/gear into debris before hiding wreck deadVis.Visual.SyncDamageAndHeat(c.Grid, _debris, Vector3.Zero); deadVis.Visual.Root.Visible = false; } @@ -371,28 +547,34 @@ public partial class ArenaRenderer : Node3D } float distSq = hasCam ? pos.DistanceSquaredTo(camPos) : 0f; - bool castShadows = !hasCam || c.IsPlayer || distSq <= 115f * 115f; - vis.Visual.SetLodState(useStaticLod: false, castShadows); + bool castShadows = !hasCam || c.IsPlayer || distSq <= 75f * 75f; + bool useStaticLod = hasCam && !c.IsPlayer && !vis.Visual.HasAnyStrippedCell && + (vis.Visual.IsStaticLod ? distSq > 64f * 64f : distSq > 68f * 68f); + vis.Visual.SetLodState(useStaticLod, castShadows); vis.Visual.SyncMountedGear(c.Grid); - if (!hasCam || c.IsPlayer || distSq <= 130f * 130f) + if (!useStaticLod) { - vis.RigDtAccum = 0f; - vis.RigSkipFrames = 0; - VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, dt); - } - else - { - vis.RigDtAccum += dt; - vis.RigSkipFrames++; - if (vis.RigSkipFrames >= 3) + if (!hasCam || c.IsPlayer || distSq <= 55f * 55f) { - VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, vis.RigDtAccum); vis.RigDtAccum = 0f; vis.RigSkipFrames = 0; + VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, dt); + } + else + { + vis.RigDtAccum += dt; + vis.RigSkipFrames++; + if (vis.RigSkipFrames >= 2) + { + VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, vis.RigDtAccum); + vis.RigDtAccum = 0f; + vis.RigSkipFrames = 0; + } } } vis.Visual.SyncDamageAndHeat(c.Grid, _debris, vel); + vis.Visual.SubmitToPool(_partPool); } } @@ -465,10 +647,10 @@ public partial class ArenaRenderer : Node3D if (hasCam) { float distSq = specPos.DistanceSquaredTo(camPos); - castShadows = distSq <= 115f * 115f; - if (s.Stance == SpectatorStance.Neutral && !vis.Visual.HasAnyStrippedCell) + castShadows = distSq <= 70f * 70f; + if (!vis.Visual.HasAnyStrippedCell) { - useStaticLod = vis.Visual.IsStaticLod ? distSq > 126f * 126f : distSq > 130f * 130f; + useStaticLod = vis.Visual.IsStaticLod ? distSq > 50f * 50f : distSq > 55f * 55f; } } vis.Visual.SetLodState(useStaticLod, castShadows); @@ -513,6 +695,8 @@ public partial class ArenaRenderer : Node3D VehicleRigAnimator.Update(vis.Visual, in rigInput, vis.Visual.Root.Basis); } + vis.Visual.SubmitToPool(_partPool); + // Status halo if (vis.HaloMat is not null && vis.HaloMesh is not null && (vis.LastHaloStance != s.Stance || s.Stance == SpectatorStance.Provoked)) @@ -622,6 +806,9 @@ public partial class ArenaRenderer : Node3D private void SyncGroundDrops(MatchState state, float elapsedSeconds, bool hasCam, Vector3 camPos) { + int discCount = 0; + int pillarCount = 0; + for (int i = 0; i < state.GroundDrops.Count; i++) { var d = state.GroundDrops[i]; @@ -629,33 +816,57 @@ public partial class ArenaRenderer : Node3D { if (_dropVisuals.TryGetValue(d.Id, out var pickedEntry)) { - if (GodotObject.IsInstanceValid(pickedEntry.Node)) + if (pickedEntry.ChassisVisual is { } cv && GodotObject.IsInstanceValid(cv.Root)) { - pickedEntry.Node.GetParent()?.RemoveChild(pickedEntry.Node); - pickedEntry.Node.QueueFree(); + cv.Root.GetParent()?.RemoveChild(cv.Root); + cv.Root.QueueFree(); } _dropVisuals.Remove(d.Id); } continue; } - bool isNew = false; if (!_dropVisuals.TryGetValue(d.Id, out var entry)) { - Node3D node = BuildGroundDropVisual(d, out var chassisVis); - _dropsGroup.AddChild(node); TerrainField.WorldToTile(d.X, d.Z, out int tx, out int tz); - entry = new DropVisualEntry + float baseY = state.Terrain.SampleHeight(d.X, d.Z); + if (d.Module is { } mod) { - Node = node, - ChassisVisual = chassisVis, - BaseY = state.Terrain.SampleHeight(d.X, d.Z), - TileX = tx, - TileZ = tz, - TileVersion = state.Terrain.TileVersions[tx, tz] - }; + VehicleVisualInstance.ResolveDropGearVisual(_assetCache, mod, out ArrayMesh gMesh, out Vector3 gScale, out float gYOff); + entry = new DropVisualEntry + { + IsModule = true, + IsImperial = mod.IsImperial, + GearMesh = gMesh, + GearScale = gScale * 1.45f, + GearYOffset = gYOff * 1.45f + 0.35f, + BaseY = baseY, + TileX = tx, + TileZ = tz, + TileVersion = state.Terrain.TileVersions[tx, tz] + }; + } + else + { + var spec = d.Chassis!; + var vis = VehicleVisualInstance.Create( + _assetCache, + spec.Id, + VehicleVisualRole.SalvageDrop, + visualScale: 0.72f); + vis.Root.Position = new Vector3(d.X, baseY + spec.HalfHeight * 0.72f, d.Z); + _actorsGroup.AddChild(vis.Root); + entry = new DropVisualEntry + { + IsModule = false, + ChassisVisual = vis, + BaseY = baseY, + TileX = tx, + TileZ = tz, + TileVersion = state.Terrain.TileVersions[tx, tz] + }; + } _dropVisuals[d.Id] = entry; - isNew = true; } else { @@ -664,169 +875,435 @@ public partial class ArenaRenderer : Node3D { entry.TileVersion = ver; entry.BaseY = state.Terrain.SampleHeight(d.X, d.Z); - isNew = true; + if (entry.ChassisVisual is { } cv) + { + cv.Root.Position = new Vector3(d.X, entry.BaseY + d.Chassis!.HalfHeight * 0.72f, d.Z); + } } } - if (isNew) + float distSq = hasCam ? new Vector3(d.X, entry.BaseY, d.Z).DistanceSquaredTo(camPos) : 0f; + if (entry.IsModule) { - entry.Node.Visible = true; - } - if (d.Module is not null) - { - bool visDrop = !hasCam || new Vector3(d.X, entry.BaseY, d.Z).DistanceSquaredTo(camPos) <= 240f * 240f; - if (entry.Node.Visible != visDrop) + if (hasCam && distSq > 240f * 240f) { - entry.Node.Visible = visDrop; + continue; } - if (visDrop) + + float bob = MathF.Sin(elapsedSeconds * 2.5f + d.Id) * 0.12f; + float yaw = elapsedSeconds * 0.9f + d.Id; + + if (entry.GearMesh is not null) { - float bob = MathF.Sin(elapsedSeconds * 2.5f + d.Id) * 0.12f; - entry.Node.Position = new Vector3(d.X, entry.BaseY + bob, d.Z); - entry.Node.Rotation = new Vector3(0f, elapsedSeconds * 0.9f + d.Id, 0f); + var gearXf = new Transform3D( + new Basis(Vector3.Up, yaw) * Basis.FromScale(entry.GearScale), + new Vector3(d.X, entry.BaseY + bob + entry.GearYOffset, d.Z)); + _partPool.Submit(entry.GearMesh, in gearXf, new Color(0f, 0f, 5f, 1f), wantsShadow: false); + } + + if (discCount < _dropDiscMm.InstanceCount) + { + _dropDiscMm.SetInstanceTransform(discCount, new Transform3D(Basis.Identity, new Vector3(d.X, entry.BaseY + bob + 0.08f, d.Z))); + Color dCol = entry.IsImperial + ? new Color(TouristGold.R * 2.2f, TouristGold.G * 2.2f, TouristGold.B * 2.2f, 0.82f) + : new Color(OlivePaint.R * 1.5f, OlivePaint.G * 1.5f, OlivePaint.B * 1.5f, 0.72f); + _dropDiscMm.SetInstanceCustomData(discCount, dCol); + discCount++; + } + + if (entry.IsImperial && pillarCount < _dropPillarMm.InstanceCount) + { + _dropPillarMm.SetInstanceTransform(pillarCount, new Transform3D(Basis.Identity, new Vector3(d.X, entry.BaseY + bob + 2.9f, d.Z))); + pillarCount++; } } - else + else if (entry.ChassisVisual is { } cv) { - if (isNew) + bool useFarLod = false; + bool castShadows = true; + if (hasCam) { - entry.Node.Position = new Vector3(d.X, entry.BaseY, d.Z); + useFarLod = cv.IsStaticLod ? distSq > 50f * 50f : distSq > 55f * 55f; + castShadows = distSq <= 70f * 70f; } - if (entry.ChassisVisual is { } cv) + cv.SetLodState(useFarLod, castShadows); + cv.SubmitToPool(_partPool); + + if (discCount < _dropDiscMm.InstanceCount) { - bool useFarLod = false; - bool castShadows = true; - if (hasCam) - { - float d2 = new Vector3(d.X, entry.BaseY, d.Z).DistanceSquaredTo(camPos); - useFarLod = cv.IsStaticLod ? d2 > 126f * 126f : d2 > 130f * 130f; - castShadows = d2 <= 95f * 95f; - } - cv.SetLodState(useFarLod, castShadows); + _dropDiscMm.SetInstanceTransform(discCount, new Transform3D(Basis.FromScale(new Vector3(2.4f, 1f, 2.4f)), new Vector3(d.X, entry.BaseY + 0.06f, d.Z))); + _dropDiscMm.SetInstanceCustomData(discCount, new Color(CyanSalvage.R * 1.8f, CyanSalvage.G * 1.8f, CyanSalvage.B * 1.8f, 0.65f)); + discCount++; } } } + + _dropDiscMm.VisibleInstanceCount = discCount; + _dropDiscMmi.Visible = discCount > 0; + _dropPillarMm.VisibleInstanceCount = pillarCount; + _dropPillarMmi.Visible = pillarCount > 0; } - private void SyncTracers(IReadOnlyList tracers) + private void SyncWeaponVfx(MatchState state, float dt) { - while (_tracerPool.Count < tracers.Count) - { - var mat = new StandardMaterial3D - { - ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded, - EmissionEnabled = true - }; - var mesh = new MeshInstance3D - { - Mesh = new BoxMesh { Size = new Vector3(0.14f, 0.14f, 1.0f) }, - MaterialOverride = mat, - CastShadow = GeometryInstance3D.ShadowCastingSetting.Off - }; - _tracersGroup.AddChild(mesh); - _tracerPool.Add(mesh); - } + float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.05f) : 0f; - for (int i = 0; i < _tracerPool.Count; i++) + // 1. Advance existing transient bursts (sparks, muzzle flashes, flak puffs, detonations, shockwaves) + for (int i = _transientVfx.Count - 1; i >= 0; i--) { - var m = _tracerPool[i]; - if (i >= tracers.Count) + TransientVfx v = _transientVfx[i]; + v.Age += stepDt; + if (v.Age >= v.Lifetime) { - m.Visible = false; + _transientVfx.RemoveAt(i); continue; } + v.Position += v.Velocity * stepDt; + _transientVfx[i] = v; + } + // 2. Spawn impact VFX once per HitFeedbackEvent + var hits = state.HitEvents; + for (int i = 0; i < hits.Count; i++) + { + var ev = hits[i]; + if (ev.EventId <= _lastVfxHitId) + { + continue; + } + _lastVfxHitId = ev.EventId; + SpawnHitVfx(in ev); + } + + // 3. Emit pooled beams/tracers + new-shot muzzle/smoke puffs from active TracerEvents + int beamIdx = 0; + int sphereIdx = 0; + int ringIdx = 0; + + var tracers = state.Tracers; + for (int i = 0; i < tracers.Count; i++) + { var t = tracers[i]; - var start = new Vector3(t.StartX, t.StartY, t.StartZ); - var end = new Vector3(t.EndX, t.EndY, t.EndZ); - float dist = start.DistanceTo(end); + Vector3 start = new(t.StartX, t.StartY, t.StartZ); + Vector3 end = new(t.EndX, t.EndY, t.EndZ); + Vector3 delta = end - start; + float dist = delta.Length(); if (dist < 0.1f) { - m.Visible = false; continue; } - m.Visible = true; - m.Position = (start + end) * 0.5f; - Vector3 dir = (end - start).Normalized(); + Vector3 dir = delta / dist; Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.95f ? Vector3.Right : Vector3.Up; - m.LookAt(end, up); - m.Scale = new Vector3(1f, 1f, dist); + Basis lookBasis = Basis.LookingAt(dir, up); + Vector3 mid = (start + end) * 0.5f; - var col = new Color( - ((t.ColorRgba >> 24) & 0xFF) / 255f, - ((t.ColorRgba >> 16) & 0xFF) / 255f, - ((t.ColorRgba >> 8) & 0xFF) / 255f, - 1f); - if (m.MaterialOverride is StandardMaterial3D sm) + switch (t.WeaponClass) { - sm.AlbedoColor = col; - sm.Emission = col; - sm.EmissionEnergyMultiplier = 2.5f; - } - } - } - - private Node3D BuildGroundDropVisual(GroundDrop drop, out VehicleVisualInstance? chassisVisual) - { - chassisVisual = null; - var root = new Node3D { Name = $"Drop_{drop.Id}" }; - if (drop.Module is { } mod) - { - var beaconMat = mod.IsImperial ? _imperialBeaconMat : _humanBeaconMat; - root.AddChild(new MeshInstance3D - { - Mesh = new CylinderMesh { TopRadius = 0.72f, BottomRadius = 0.85f, Height = 0.14f, RadialSegments = 14 }, - MaterialOverride = beaconMat, - Position = new Vector3(0f, 0.08f, 0f), - CastShadow = GeometryInstance3D.ShadowCastingSetting.Off - }); - - // Real Brokkr gear GLB hovering cleanly above the salvage beacon disc - Node3D gear = VehicleVisualInstance.CreateStandaloneGearVisual(_assetCache, mod); - gear.Scale *= 1.45f; - gear.Position += new Vector3(0f, 0.35f, 0f); - root.AddChild(gear); - - if (mod.IsImperial) - { - root.AddChild(new MeshInstance3D + case WeaponVisualClass.KineticLight: { - Mesh = new CylinderMesh { TopRadius = 0.06f, BottomRadius = 0.22f, Height = 5.5f, RadialSegments = 8 }, - MaterialOverride = _imperialBeaconMat, - Position = new Vector3(0f, 2.9f, 0f), - CastShadow = GeometryInstance3D.ShadowCastingSetting.Off - }); + bool isPd = string.Equals(t.WeaponId, "pd_flak", StringComparison.Ordinal); + Color col = isPd + ? new Color(2.8f, 1.35f, 0.35f, 0.94f) + : new Color(2.6f, 2.35f, 1.15f, 0.92f); + EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(isPd ? 0.09f : 0.06f, isPd ? 0.09f : 0.06f, dist), col); + if (t.Ttl > 0.068f) + { + EmitMuzzleFlash(start, 0.32f, new Color(2.8f, 2.0f, 0.7f, 0.95f)); + } + break; + } + + case WeaponVisualClass.Autocannon: + { + // Thick dual-tone amber-orange heavy bolt (outer jacket + bright core) + EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.20f, 0.20f, dist), new Color(2.5f, 0.85f, 0.14f, 0.72f)); + EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.08f, 0.08f, dist), new Color(3.6f, 2.7f, 1.3f, 0.98f)); + if (t.Ttl > 0.078f) + { + EmitMuzzleFlash(start, 0.68f, new Color(3.2f, 1.65f, 0.35f, 0.98f)); + } + break; + } + + case WeaponVisualClass.Explosive: + { + bool isRecoilless = string.Equals(t.WeaponId, "recoilless", StringComparison.Ordinal); + float w = isRecoilless ? 0.22f : 0.12f; + EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(w, w, dist), new Color(3.2f, 1.25f, 0.25f, 0.96f)); + if (t.Ttl > 0.085f) + { + EmitMuzzleFlash(start, isRecoilless ? 1.15f : 0.58f, new Color(3.4f, 1.55f, 0.35f, 0.98f)); + int puffs = isRecoilless ? 4 : 2; + for (int p = 1; p <= puffs; p++) + { + float frac = p / (float)(puffs + 1); + Vector3 smokePos = start.Lerp(end, frac); + AddTransient(new TransientVfx + { + Shape = VfxShape.Sphere, + Position = smokePos, + Velocity = new Vector3(0f, 1.4f, 0f), + BaseRotation = Basis.Identity, + StartScale = Vector3.One * (isRecoilless ? 0.45f : 0.28f), + EndScale = Vector3.One * (isRecoilless ? 1.55f : 0.85f), + ColorStart = new Color(0.62f, 0.56f, 0.48f, 0.65f), + ColorEnd = new Color(0.45f, 0.40f, 0.36f, 0.0f), + Age = 0f, + Lifetime = isRecoilless ? 0.48f : 0.32f + }); + } + } + break; + } + + case WeaponVisualClass.ThermalBeam: + { + bool isLance = string.Equals(t.WeaponId, "gilded_lance", StringComparison.Ordinal); + float outerW = isLance ? 0.34f : 0.20f; + float coreW = isLance ? 0.13f : 0.08f; + Color outerCol = isLance + ? new Color(2.8f, 1.95f, 0.45f, 0.62f) + : new Color(0.45f, 2.35f, 2.95f, 0.65f); + Color coreCol = isLance + ? new Color(1.6f, 3.6f, 3.8f, 0.98f) + : new Color(2.4f, 3.4f, 3.8f, 0.98f); + EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(outerW, outerW, dist), outerCol); + EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(coreW, coreW, dist), coreCol); + if (t.Ttl > 0.095f) + { + EmitMuzzleFlash(start, isLance ? 0.85f : 0.52f, outerCol with { A = 0.95f }); + } + break; + } } } - else if (drop.Chassis is { } ch) - { - const float dropScale = 0.85f; - var hull = VehicleVisualInstance.Create(_assetCache, ch.Id, VehicleVisualRole.SalvageDrop, dropScale); - chassisVisual = hull; - // ModelRoot sits at -HalfHeight*dropScale inside hull.Root, so lifting hull.Root by +HalfHeight*dropScale grounds minY=0 on terrain - hull.Root.Position = new Vector3(0f, ch.HalfHeight * dropScale, 0f); - root.AddChild(hull.Root); - var ring = new MeshInstance3D + // 4. Write active transient VFX into MultiMesh buffers + for (int i = 0; i < _transientVfx.Count; i++) + { + TransientVfx v = _transientVfx[i]; + float frac = Math.Clamp(v.Age / MathF.Max(0.01f, v.Lifetime), 0f, 1f); + Vector3 sc = v.StartScale.Lerp(v.EndScale, frac); + Color col = v.ColorStart.Lerp(v.ColorEnd, frac); + Transform3D xf = new(v.BaseRotation * Basis.FromScale(sc), v.Position); + + if (v.Shape == VfxShape.Beam && beamIdx < MaxVfxBeams) { - Mesh = new CylinderMesh { TopRadius = 2.6f, BottomRadius = 2.8f, Height = 0.14f, RadialSegments = 18 }, - MaterialOverride = _cyanBeaconMat, - Position = new Vector3(0f, 0.12f, 0f), - CastShadow = GeometryInstance3D.ShadowCastingSetting.Off - }; - root.AddChild(ring); + _vfxBeamMm.SetInstanceTransform(beamIdx, xf); + _vfxBeamMm.SetInstanceCustomData(beamIdx, col); + beamIdx++; + } + else if (v.Shape == VfxShape.Sphere && sphereIdx < MaxVfxSpheres) + { + _vfxSphereMm.SetInstanceTransform(sphereIdx, xf); + _vfxSphereMm.SetInstanceCustomData(sphereIdx, col); + sphereIdx++; + } + else if (v.Shape == VfxShape.Ring && ringIdx < MaxVfxRings) + { + _vfxRingMm.SetInstanceTransform(ringIdx, xf); + _vfxRingMm.SetInstanceCustomData(ringIdx, col); + ringIdx++; + } } - return root; + + _vfxBeamMm.VisibleInstanceCount = beamIdx; + _vfxBeamMmi.Visible = beamIdx > 0; + _vfxSphereMm.VisibleInstanceCount = sphereIdx; + _vfxSphereMmi.Visible = sphereIdx > 0; + _vfxRingMm.VisibleInstanceCount = ringIdx; + _vfxRingMmi.Visible = ringIdx > 0; } + private void SpawnHitVfx(in HitFeedbackEvent ev) + { + Vector3 pos = new(ev.HitX, ev.HitY, ev.HitZ); + Vector3 normal = new(ev.NormalX, ev.NormalY, ev.NormalZ); + if (normal.LengthSquared() < 1e-4f) normal = Vector3.Up; + normal = normal.Normalized(); + + if (ev.IsAirburst || (ev.WeaponClass == WeaponVisualClass.KineticLight && string.Equals(ev.WeaponId, "pd_flak", StringComparison.Ordinal))) + { + // Crisp dark-orange flak airburst puff + ember sparks + AddTransient(new TransientVfx + { + Shape = VfxShape.Sphere, + Position = pos, + Velocity = Vector3.Zero, + BaseRotation = Basis.Identity, + StartScale = Vector3.One * 0.4f, + EndScale = Vector3.One * 2.3f, + ColorStart = new Color(2.4f, 0.72f, 0.14f, 0.92f), + ColorEnd = new Color(0.28f, 0.14f, 0.08f, 0.0f), + Age = 0f, + Lifetime = 0.28f + }); + SpawnSparkBurst(pos, normal, 4, new Color(3.0f, 1.5f, 0.35f, 0.98f), 11f); + return; + } + + switch (ev.WeaponClass) + { + case WeaponVisualClass.KineticLight: + SpawnSparkBurst(pos, normal, 3, new Color(3.2f, 2.6f, 1.1f, 0.98f), 9f); + break; + + case WeaponVisualClass.Autocannon: + AddTransient(new TransientVfx + { + Shape = VfxShape.Sphere, + Position = pos + normal * 0.15f, + Velocity = normal * 2.2f, + BaseRotation = Basis.Identity, + StartScale = Vector3.One * 0.45f, + EndScale = Vector3.One * 1.55f, + ColorStart = new Color(1.5f, 0.95f, 0.55f, 0.85f), + ColorEnd = new Color(0.55f, 0.48f, 0.38f, 0.0f), + Age = 0f, + Lifetime = 0.26f + }); + SpawnSparkBurst(pos, normal, 4, new Color(3.2f, 1.85f, 0.55f, 0.98f), 12f); + break; + + case WeaponVisualClass.Explosive: + { + bool isRecoilless = string.Equals(ev.WeaponId, "recoilless", StringComparison.Ordinal); + float detSize = isRecoilless ? 4.4f : 2.1f; + float ringSize = isRecoilless ? 6.2f : 2.9f; + AddTransient(new TransientVfx + { + Shape = VfxShape.Sphere, + Position = pos + normal * 0.25f, + Velocity = normal * 1.6f, + BaseRotation = Basis.Identity, + StartScale = Vector3.One * 0.6f, + EndScale = Vector3.One * detSize, + ColorStart = new Color(3.8f, 2.1f, 0.65f, 0.98f), + ColorEnd = new Color(0.85f, 0.28f, 0.08f, 0.0f), + Age = 0f, + Lifetime = isRecoilless ? 0.34f : 0.24f + }); + + Vector3 upRef = MathF.Abs(normal.Y) > 0.92f ? Vector3.Forward : Vector3.Up; + Vector3 right = upRef.Cross(normal).Normalized(); + Vector3 fwd = normal.Cross(right).Normalized(); + Basis ringBasis = new(right, normal, fwd); + AddTransient(new TransientVfx + { + Shape = VfxShape.Ring, + Position = pos + normal * 0.18f, + Velocity = Vector3.Zero, + BaseRotation = ringBasis, + StartScale = new Vector3(0.7f, 1.0f, 0.7f), + EndScale = new Vector3(ringSize, 0.4f, ringSize), + ColorStart = new Color(3.2f, 1.65f, 0.45f, 0.92f), + ColorEnd = new Color(1.4f, 0.55f, 0.20f, 0.0f), + Age = 0f, + Lifetime = isRecoilless ? 0.32f : 0.22f + }); + SpawnSparkBurst(pos, normal, isRecoilless ? 6 : 4, new Color(3.4f, 1.6f, 0.35f, 0.98f), 15f); + break; + } + + case WeaponVisualClass.ThermalBeam: + AddTransient(new TransientVfx + { + Shape = VfxShape.Sphere, + Position = pos, + Velocity = Vector3.Zero, + BaseRotation = Basis.Identity, + StartScale = Vector3.One * 0.45f, + EndScale = Vector3.One * 1.65f, + ColorStart = new Color(1.6f, 3.4f, 3.8f, 0.95f), + ColorEnd = new Color(2.6f, 1.5f, 0.3f, 0.0f), + Age = 0f, + Lifetime = 0.22f + }); + SpawnSparkBurst(pos, normal, 5, new Color(2.0f, 3.2f, 3.6f, 0.98f), 13f); + break; + } + } + + private void SpawnSparkBurst(Vector3 pos, Vector3 normal, int count, Color color, float speed) + { + for (int i = 0; i < count; i++) + { + Vector3 rand = new(NextVfxSigned(), MathF.Abs(NextVfxSigned()) + 0.35f, NextVfxSigned()); + Vector3 dir = (normal * 0.8f + rand).Normalized(); + Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.95f ? Vector3.Right : Vector3.Up; + AddTransient(new TransientVfx + { + Shape = VfxShape.Beam, + Position = pos, + Velocity = dir * (speed * (0.65f + 0.7f * NextVfxFloat())), + BaseRotation = Basis.LookingAt(dir, up), + StartScale = new Vector3(0.05f, 0.05f, 0.55f), + EndScale = new Vector3(0.02f, 0.02f, 0.12f), + ColorStart = color, + ColorEnd = color with { A = 0f }, + Age = 0f, + Lifetime = 0.16f + 0.08f * NextVfxFloat() + }); + } + } + + private void EmitMuzzleFlash(Vector3 pos, float size, Color color) + { + AddTransient(new TransientVfx + { + Shape = VfxShape.Sphere, + Position = pos, + Velocity = Vector3.Zero, + BaseRotation = Basis.Identity, + StartScale = Vector3.One * size, + EndScale = Vector3.One * (size * 0.25f), + ColorStart = color, + ColorEnd = color with { A = 0f }, + Age = 0f, + Lifetime = 0.065f + }); + } + + private void EmitBeam(ref int beamIdx, Basis lookBasis, Vector3 mid, Vector3 scale, Color color) + { + if (beamIdx >= MaxVfxBeams) + { + return; + } + _vfxBeamMm.SetInstanceTransform(beamIdx, new Transform3D(lookBasis * Basis.FromScale(scale), mid)); + _vfxBeamMm.SetInstanceCustomData(beamIdx, color); + beamIdx++; + } + + private void AddTransient(in TransientVfx vfx) + { + if (_transientVfx.Count >= 512) + { + _transientVfx.RemoveAt(0); + } + _transientVfx.Add(vfx); + } + + private float NextVfxFloat() + { + uint x = _vfxRng; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + _vfxRng = x; + return (x & 0x00FFFFFFu) / 16777216f; + } + + private float NextVfxSigned() => NextVfxFloat() * 2f - 1f; + private static void ClearChildren(Node parent) { for (int i = parent.GetChildCount() - 1; i >= 0; i--) { - var child = parent.GetChild(i); - parent.RemoveChild(child); - child.QueueFree(); + Node ch = parent.GetChild(i); + parent.RemoveChild(ch); + ch.QueueFree(); } } } diff --git a/client/DebrisSystem.cs b/client/DebrisSystem.cs index 3a7fed2..474bb6e 100644 --- a/client/DebrisSystem.cs +++ b/client/DebrisSystem.cs @@ -7,7 +7,8 @@ namespace RustToDust.Client; /// /// Manages physically detached armor plates and sheared hardpoint gear as tumbling, -/// terrain-bouncing debris pieces that settle and fade out cleanly after 8 seconds. +/// terrain-bouncing debris pieces submitted directly into +/// (zero per-piece Node3D/MeshInstance3D/StandardMaterial3D allocations). /// public partial class DebrisSystem : Node3D { @@ -18,11 +19,15 @@ public partial class DebrisSystem : Node3D private sealed class DebrisPiece { - public required Node3D Node; - public required Vector3 Velocity; - public required Vector3 AngularVelocity; - public required List FadeMaterials; - public required float[] BaseAlphas; + public required ArrayMesh Mesh; + public Vector3 Position; + public Basis Rotation; + public Vector3 Scale; + public Vector3 Velocity; + public Vector3 AngularVelocity; + public float RoleIndex; + public float Scorch; + public float HeatGlow; public float Age; public float Lifetime; public bool Settled; @@ -33,60 +38,51 @@ public partial class DebrisSystem : Node3D public int ActiveCount => _pieces.Count; + public bool TryGetPiecePosition(int index, out Vector3 position) + { + if (index >= 0 && index < _pieces.Count) + { + position = _pieces[index].Position; + return true; + } + position = Vector3.Zero; + return false; + } + public void ClearAll() { - for (int i = 0; i < _pieces.Count; i++) - { - if (GodotObject.IsInstanceValid(_pieces[i].Node)) - { - _pieces[i].Node.QueueFree(); - } - } _pieces.Clear(); - - for (int i = GetChildCount() - 1; i >= 0; i--) - { - Node ch = GetChild(i); - RemoveChild(ch); - ch.QueueFree(); - } } /// - /// Reparents from its vehicle hierarchy at its exact world transform - /// into and launches it with an outward blast impulse and tumble. + /// Registers a detached rigid part or sheared gear mesh at its world transform + /// and launches it with an outward blast impulse and tumble. /// public void SpawnDetachedPart( - Node3D part, + ArrayMesh mesh, + Transform3D worldXform, Vector3 blastOriginWorld, Vector3 inheritedVelocity, + float roleIndex, float impulseScale = 1.0f, bool applyScorch = true) { - if (!GodotObject.IsInstanceValid(part)) + if (mesh is null || mesh.GetSurfaceCount() == 0) { return; } - // Evict oldest settled or oldest piece if we hit the cap so debris never leaks indefinitely while (_pieces.Count >= MaxActiveDebris) { - RemoveAt(0); + _pieces.RemoveAt(0); } - Transform3D worldXform = part.IsInsideTree() ? part.GlobalTransform : part.Transform; - Node? oldParent = part.GetParent(); - oldParent?.RemoveChild(part); - AddChild(part); - - if (part.IsInsideTree() && IsInsideTree()) + Vector3 scale = worldXform.Basis.Scale; + if (!scale.IsFinite() || scale.LengthSquared() < 1e-6f) { - part.GlobalTransform = worldXform; - } - else - { - part.Transform = worldXform; + scale = Vector3.One; } + Basis rot = worldXform.Basis.Orthonormalized(); Vector3 outward = worldXform.Origin - blastOriginWorld; outward.Y = 0f; @@ -109,21 +105,17 @@ public partial class DebrisSystem : Node3D (NextFloat() * 2f - 1f) * 7.5f, (NextFloat() * 2f - 1f) * 7.5f); - var fadeMats = new List(); - PrepareInstanceMaterials(part, fadeMats, applyScorch); - var baseAlphas = new float[fadeMats.Count]; - for (int i = 0; i < fadeMats.Count; i++) - { - baseAlphas[i] = fadeMats[i].AlbedoColor.A; - } - _pieces.Add(new DebrisPiece { - Node = part, + Mesh = mesh, + Position = worldXform.Origin, + Rotation = rot, + Scale = scale, Velocity = vel, AngularVelocity = angVel, - FadeMaterials = fadeMats, - BaseAlphas = baseAlphas, + RoleIndex = roleIndex, + Scorch = applyScorch ? 0.85f : 0.15f, + HeatGlow = applyScorch ? 0.45f : 0f, Age = 0f, Lifetime = DefaultLifetime, Settled = false @@ -141,30 +133,28 @@ public partial class DebrisSystem : Node3D for (int i = _pieces.Count - 1; i >= 0; i--) { DebrisPiece p = _pieces[i]; - if (!GodotObject.IsInstanceValid(p.Node)) + p.Age += stepDt; + if (p.Age >= p.Lifetime) { _pieces.RemoveAt(i); continue; } - p.Age += stepDt; - if (p.Age >= p.Lifetime) + if (p.HeatGlow > 0f) { - RemoveAt(i); - continue; + p.HeatGlow = MathF.Max(0f, p.HeatGlow - stepDt * 0.22f); } if (!p.Settled) { p.Velocity += new Vector3(0f, Gravity * stepDt, 0f); - Vector3 pos = p.Node.Position + p.Velocity * stepDt; + Vector3 pos = p.Position + p.Velocity * stepDt; - Basis basis = p.Node.Basis; + Basis rot = p.Rotation; float spinLen = p.AngularVelocity.Length(); if (spinLen > 1e-4f) { - basis = new Basis(p.AngularVelocity / spinLen, spinLen * stepDt) * basis; - basis = basis.Orthonormalized(); + rot = (new Basis(p.AngularVelocity / spinLen, spinLen * stepDt) * rot).Orthonormalized(); } float floorY = terrain.SampleHeight(pos.X, pos.Z) + 0.10f; @@ -187,94 +177,29 @@ public partial class DebrisSystem : Node3D } } - p.Node.Position = pos; - p.Node.Basis = basis; + p.Position = pos; + p.Rotation = rot; } + } + } - // Smooth alpha fade during final 2 seconds + public void SubmitToPool(MultiMeshPartPool pool) + { + for (int i = 0; i < _pieces.Count; i++) + { + DebrisPiece p = _pieces[i]; float remaining = p.Lifetime - p.Age; - if (remaining < FadeDuration) - { - float alphaFrac = Math.Clamp(remaining / FadeDuration, 0f, 1f); - for (int m = 0; m < p.FadeMaterials.Count; m++) - { - StandardMaterial3D sm = p.FadeMaterials[m]; - if (sm.Transparency == BaseMaterial3D.TransparencyEnum.Disabled) - { - sm.Transparency = BaseMaterial3D.TransparencyEnum.Alpha; - } - Color col = sm.AlbedoColor; - col.A = p.BaseAlphas[m] * alphaFrac; - sm.AlbedoColor = col; - } - } + float alpha = remaining < FadeDuration + ? Math.Clamp(remaining / FadeDuration, 0.02f, 1f) + : 1f; + float sinkY = remaining < FadeDuration ? (1f - alpha) * 0.65f : 0f; + Vector3 scale = p.Scale * (remaining < FadeDuration ? (0.35f + 0.65f * alpha) : 1f); + Transform3D xf = new(p.Rotation * Basis.FromScale(scale), p.Position - new Vector3(0f, sinkY, 0f)); + Color custom = new(p.Scorch, p.HeatGlow, p.RoleIndex, alpha); + pool.Submit(p.Mesh, in xf, in custom, wantsShadow: false); } } - private void RemoveAt(int index) - { - DebrisPiece p = _pieces[index]; - _pieces.RemoveAt(index); - if (GodotObject.IsInstanceValid(p.Node)) - { - if (p.Node.GetParent() == this) - { - RemoveChild(p.Node); - } - p.Node.QueueFree(); - } - } - - private static void PrepareInstanceMaterials(Node cur, List outMats, bool applyScorch) - { - if (cur is MeshInstance3D mi && mi.Mesh is not null) - { - if (mi.MaterialOverride is StandardMaterial3D ov) - { - var copy = (StandardMaterial3D)ov.Duplicate(); - if (applyScorch) - { - ApplyScorchTint(copy); - } - mi.MaterialOverride = copy; - outMats.Add(copy); - } - else - { - int surfCount = mi.Mesh.GetSurfaceCount(); - for (int s = 0; s < surfCount; s++) - { - Material? src = mi.GetActiveMaterial(s); - StandardMaterial3D copy = src is StandardMaterial3D sm - ? (StandardMaterial3D)sm.Duplicate() - : new StandardMaterial3D { AlbedoColor = new Color(0.28f, 0.25f, 0.23f), Roughness = 0.78f, Metallic = 0.45f }; - if (applyScorch) - { - ApplyScorchTint(copy); - } - mi.SetSurfaceOverrideMaterial(s, copy); - outMats.Add(copy); - } - } - } - - int count = cur.GetChildCount(); - for (int i = 0; i < count; i++) - { - PrepareInstanceMaterials(cur.GetChild(i), outMats, applyScorch); - } - } - - private static void ApplyScorchTint(StandardMaterial3D mat) - { - Color c = mat.AlbedoColor; - mat.AlbedoColor = new Color(c.R * 0.42f + 0.04f, c.G * 0.36f + 0.03f, c.B * 0.34f + 0.02f, c.A); - mat.Roughness = MathF.Max(mat.Roughness, 0.78f); - mat.EmissionEnabled = true; - mat.Emission = new Color(0.95f, 0.32f, 0.06f); - mat.EmissionEnergyMultiplier = 0.35f; - } - private float NextFloat() { uint x = _rngState; diff --git a/client/MultiMeshPartPool.cs b/client/MultiMeshPartPool.cs new file mode 100644 index 0000000..1de7bd8 --- /dev/null +++ b/client/MultiMeshPartPool.cs @@ -0,0 +1,247 @@ +using System; +using System.Collections.Generic; +using Godot; + +namespace RustToDust.Client; + +/// +/// Unified MultiMeshInstance3D part pool sharing mech_paint.gdshader in vertex-material mode. +/// Collapses all live vehicle limbs, armor chunks, mounted gear, salvage drops, and tumbling debris +/// sharing the same single-surface into one +/// draw call with per-instance INSTANCE_CUSTOM = (scorch, heat_glow, role_tint_index, alpha). +/// +public partial class MultiMeshPartPool : Node3D +{ + private readonly record struct PendingInstance( + Transform3D Xform, + Color Custom, + bool WantsShadow, + Vector3 WorldCenter, + float ScaledRadius); + + private sealed class PoolBucket + { + public required ArrayMesh Mesh; + public required Vector3 LocalCenter; + public required float LocalRadius; + public required MultiMesh MultiMesh; + public required MultiMeshInstance3D Node; + public readonly List Pending = new(16); + } + + private readonly Dictionary _buckets = new(); + private readonly List _bucketList = new(); + private readonly Plane[] _frustumPlanes = new Plane[6]; + private ShaderMaterial _sharedMat = null!; + private bool _hasFrustum; + private Vector3 _camPos; + + public int BucketCount => _bucketList.Count; + public int ActiveBucketCount { get; private set; } + public int TotalSubmittedInstances { get; private set; } + + public override void _Ready() + { + Shader shader = GD.Load("res://mech_paint.gdshader") + ?? throw new InvalidOperationException("Failed to load res://mech_paint.gdshader for MultiMeshPartPool."); + _sharedMat = new ShaderMaterial { Shader = shader }; + _sharedMat.SetShaderParameter("use_vertex_material", true); + _sharedMat.SetShaderParameter("heat_emission_energy", 2.6f); + } + + public void EnsureInitialized() + { + if (_sharedMat is null) + { + _Ready(); + } + } + + public void BeginFrame(Camera3D? cam) + { + EnsureInitialized(); + TotalSubmittedInstances = 0; + + for (int i = 0; i < _bucketList.Count; i++) + { + _bucketList[i].Pending.Clear(); + } + + if (cam is not null && cam.IsInsideTree()) + { + _camPos = cam.GlobalPosition; + var planes = cam.GetFrustum(); + if (planes.Count >= 6) + { + for (int i = 0; i < 6; i++) + { + _frustumPlanes[i] = planes[i]; + } + _hasFrustum = true; + return; + } + } + _hasFrustum = false; + } + + public void Submit( + ArrayMesh mesh, + in Transform3D worldXform, + in Color customData, + bool wantsShadow) + { + if (mesh is null || mesh.GetSurfaceCount() == 0) + { + return; + } + + PoolBucket bucket = GetOrCreateBucket(mesh); + + Basis b = worldXform.Basis; + float maxScaleSq = MathF.Max( + b.Column0.LengthSquared(), + MathF.Max(b.Column1.LengthSquared(), b.Column2.LengthSquared())); + float scale = MathF.Sqrt(MathF.Max(0.0001f, maxScaleSq)); + float scaledRadius = bucket.LocalRadius * scale; + Vector3 worldCenter = worldXform * bucket.LocalCenter; + + if (_hasFrustum && !IsSphereInFrustum(worldCenter, scaledRadius)) + { + return; + } + + bool castShadow = wantsShadow && bucket.LocalRadius >= 0.55f; + if (castShadow && _hasFrustum) + { + float maxShadowDist = 85f + scaledRadius; + if (worldCenter.DistanceSquaredTo(_camPos) > maxShadowDist * maxShadowDist) + { + castShadow = false; + } + } + + bucket.Pending.Add(new PendingInstance(worldXform, customData, castShadow, worldCenter, scaledRadius)); + TotalSubmittedInstances++; + } + + public void EndFrame() + { + int active = 0; + for (int i = 0; i < _bucketList.Count; i++) + { + PoolBucket bucket = _bucketList[i]; + int count = bucket.Pending.Count; + if (count == 0) + { + bucket.MultiMesh.VisibleInstanceCount = 0; + bucket.Node.Visible = false; + continue; + } + + active++; + if (bucket.MultiMesh.InstanceCount < count) + { + bucket.MultiMesh.InstanceCount = Math.Max(16, count * 2); + } + + Vector3 aabbMin = new(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + Vector3 aabbMax = new(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity); + bool anyShadow = false; + + for (int k = 0; k < count; k++) + { + PendingInstance inst = bucket.Pending[k]; + bucket.MultiMesh.SetInstanceTransform(k, inst.Xform); + bucket.MultiMesh.SetInstanceCustomData(k, inst.Custom); + if (inst.WantsShadow) + { + anyShadow = true; + } + + Vector3 r = new(inst.ScaledRadius, inst.ScaledRadius, inst.ScaledRadius); + Vector3 lo = inst.WorldCenter - r; + Vector3 hi = inst.WorldCenter + r; + aabbMin = new Vector3(MathF.Min(aabbMin.X, lo.X), MathF.Min(aabbMin.Y, lo.Y), MathF.Min(aabbMin.Z, lo.Z)); + aabbMax = new Vector3(MathF.Max(aabbMax.X, hi.X), MathF.Max(aabbMax.Y, hi.Y), MathF.Max(aabbMax.Z, hi.Z)); + } + + bucket.MultiMesh.VisibleInstanceCount = count; + bucket.Node.CustomAabb = new Aabb(aabbMin, aabbMax - aabbMin); + bucket.Node.CastShadow = anyShadow + ? GeometryInstance3D.ShadowCastingSetting.On + : GeometryInstance3D.ShadowCastingSetting.Off; + bucket.Node.Visible = true; + } + ActiveBucketCount = active; + } + + public void ClearAll() + { + for (int i = 0; i < _bucketList.Count; i++) + { + PoolBucket bucket = _bucketList[i]; + bucket.Pending.Clear(); + bucket.MultiMesh.VisibleInstanceCount = 0; + bucket.Node.Visible = false; + } + ActiveBucketCount = 0; + TotalSubmittedInstances = 0; + } + + private PoolBucket GetOrCreateBucket(ArrayMesh mesh) + { + ulong id = mesh.GetInstanceId(); + if (_buckets.TryGetValue(id, out PoolBucket? existing)) + { + return existing; + } + + Aabb aabb = mesh.GetAabb(); + Vector3 localCenter = aabb.GetCenter(); + float localRadius = MathF.Max(0.2f, aabb.Size.Length() * 0.5f); + + var mm = new MultiMesh + { + TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseCustomData = true, + Mesh = mesh, + InstanceCount = 16, + VisibleInstanceCount = 0 + }; + var mmi = new MultiMeshInstance3D + { + Name = $"MMPool_{_bucketList.Count}", + Multimesh = mm, + MaterialOverride = _sharedMat, + Visible = false, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, + PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off + }; + AddChild(mmi); + + var created = new PoolBucket + { + Mesh = mesh, + LocalCenter = localCenter, + LocalRadius = localRadius, + MultiMesh = mm, + Node = mmi + }; + _buckets[id] = created; + _bucketList.Add(created); + return created; + } + + private bool IsSphereInFrustum(Vector3 center, float radius) + { + float margin = radius + 1.5f; + for (int i = 0; i < 6; i++) + { + if (_frustumPlanes[i].DistanceTo(center) > margin) + { + return false; + } + } + return true; + } +} diff --git a/client/PomDecalPool.cs b/client/PomDecalPool.cs new file mode 100644 index 0000000..e03f7fb --- /dev/null +++ b/client/PomDecalPool.cs @@ -0,0 +1,440 @@ +using System; +using System.IO; +using Godot; +using RustToDust.Core; +using RustToDust.Ymir; + +namespace RustToDust.Client; + +/// +/// Live 4x4 Parallax Occlusion Mapping (POM) combat decal pool rendered in 1 draw call +/// using decal_pom.gdshader and assets/decals/decal_atlas_*.png. +/// Supports terrain impacts, static cover impacts, and vehicle-cell-attached scars +/// that cool smoothly over 3.5s, ride with moving limbs/turrets, and fade when armor detaches. +/// +public partial class PomDecalPool : Node3D +{ + public const int MaxDecals = 512; + private const float HeatCoolDuration = 3.5f; + private const float DetachFadeDuration = 0.35f; + private const float EndFadeDuration = 2.0f; + + private struct DecalSlot + { + public bool Active; + public float Age; + public float Lifetime; + public float TileIndex; + public float InitialHeat; + public float BaseOpacity; + public float DepthScale; + public Transform3D WorldXform; + + public bool IsAttached; + public VehicleVisualInstance? Visual; + public Node3D? Pivot; + public Transform3D LocalToPivot; + public ChassisGrid? Grid; + public int CellX; + public int CellY; + public float DetachedFadeRemaining; + } + + private readonly DecalSlot[] _slots = new DecalSlot[MaxDecals]; + private int _writeCursor; + private long _lastProcessedHitId; + private MatchState? _boundState; + + private MultiMesh _multiMesh = null!; + private MultiMeshInstance3D _instanceNode = null!; + private ShaderMaterial _material = null!; + private ImageTexture _albedoTex = null!; + private ImageTexture _normalTex = null!; + private ImageTexture _ormhTex = null!; + + public int ActiveCount { get; private set; } + + public override void _Ready() + { + Shader shader = GD.Load("res://decal_pom.gdshader") + ?? throw new InvalidOperationException("Failed to load res://decal_pom.gdshader"); + + string vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory(); + string assetsDir = Directory.GetParent(vehiclesDir)?.FullName + ?? throw new DirectoryNotFoundException("Could not locate assets directory."); + string decalsDir = Path.Combine(assetsDir, "decals"); + + _albedoTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_albedo.png")); + _normalTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_normal.png")); + _ormhTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_ormh.png")); + + _material = new ShaderMaterial { Shader = shader }; + _material.SetShaderParameter("albedo_tex", _albedoTex); + _material.SetShaderParameter("normal_tex", _normalTex); + _material.SetShaderParameter("ormh_tex", _ormhTex); + _material.SetShaderParameter("use_instance_custom", true); + _material.SetShaderParameter("default_depth_scale", 0.06f); + _material.SetShaderParameter("normal_offset", 0.012f); + _material.SetShaderParameter("heat_emission_energy", 2.8f); + + _multiMesh = new MultiMesh + { + TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseCustomData = true, + Mesh = new QuadMesh { Size = Vector2.One }, + InstanceCount = MaxDecals, + VisibleInstanceCount = 0 + }; + + _instanceNode = new MultiMeshInstance3D + { + Name = "PomDecalsBatch", + Multimesh = _multiMesh, + MaterialOverride = _material, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, + CustomAabb = new Aabb(new Vector3(-900f, -60f, -900f), new Vector3(1800f, 180f, 1800f)), + PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, + Visible = false + }; + AddChild(_instanceNode); + } + + public void EnsureInitialized() + { + if (_multiMesh is null) + { + _Ready(); + } + } + + public void ClearAll() + { + Array.Clear(_slots, 0, _slots.Length); + _writeCursor = 0; + _lastProcessedHitId = 0; + ActiveCount = 0; + if (_multiMesh is not null) + { + _multiMesh.VisibleInstanceCount = 0; + _instanceNode.Visible = false; + } + } + + public void Sync( + ArenaSession session, + float dt, + Func getVisual) + { + EnsureInitialized(); + var state = session.State; + if (!ReferenceEquals(_boundState, state)) + { + _boundState = state; + ClearAll(); + } + + var hits = state.HitEvents; + for (int i = 0; i < hits.Count; i++) + { + var ev = hits[i]; + if (ev.EventId <= _lastProcessedHitId) + { + continue; + } + _lastProcessedHitId = ev.EventId; + StampHit(ev, state, getVisual); + } + + UpdateAndCommit(dt); + } + + public void StampTestDecal( + Vector3 worldPos, + Vector3 worldNormal, + float size, + int tileIndex, + float heat = 0.95f, + float depth = 0.085f) + { + EnsureInitialized(); + Transform3D xf = BuildSurfaceTransform(worldPos, worldNormal, size, (float)_writeCursor * 1.17f); + AllocateSlot(new DecalSlot + { + Active = true, + Age = 0f, + Lifetime = 26f, + TileIndex = tileIndex, + InitialHeat = heat, + BaseOpacity = 1f, + DepthScale = depth, + WorldXform = xf, + DetachedFadeRemaining = -1f + }); + } + + private void StampHit( + in HitFeedbackEvent ev, + MatchState state, + Func getVisual) + { + if (ev.IsAirburst && ev.TargetKind == HitTargetKind.StaticCover && ev.TargetId < 0) + { + return; + } + + bool isVehicle = ev.TargetKind == HitTargetKind.Contender || ev.TargetKind == HitTargetKind.Spectator; + int tile; + float size; + float heat; + float depth; + float lifetime; + + switch (ev.WeaponClass) + { + case WeaponVisualClass.ThermalBeam: + tile = string.Equals(ev.WeaponId, "gilded_lance", StringComparison.Ordinal) || !isVehicle + ? 14 // molten plasma crater + : 14; + size = isVehicle + ? (string.Equals(ev.WeaponId, "gilded_lance", StringComparison.Ordinal) ? 0.78f : 0.56f) + : (string.Equals(ev.WeaponId, "gilded_lance", StringComparison.Ordinal) ? 2.10f : 1.35f); + heat = 1.0f; + depth = 0.095f; + lifetime = 26f; + break; + + case WeaponVisualClass.Explosive: + bool isRecoilless = string.Equals(ev.WeaponId, "recoilless", StringComparison.Ordinal); + tile = isVehicle ? 13 : 15; // shrapnel gouge on armor, blast scorch on ground + size = isVehicle ? (isRecoilless ? 0.88f : 0.66f) : (isRecoilless ? 3.20f : 1.75f); + heat = isRecoilless ? 0.98f : 0.82f; + depth = isRecoilless ? 0.095f : 0.075f; + lifetime = 28f; + break; + + case WeaponVisualClass.Autocannon: + tile = (ev.EventId % 3 == 0) ? 13 : 12; // AP hole or shrapnel gouge + size = isVehicle ? 0.54f : 0.92f; + heat = 0.90f; + depth = 0.088f; + lifetime = 24f; + break; + + default: // KineticLight (mg_762, pd_flak) + tile = string.Equals(ev.WeaponId, "pd_flak", StringComparison.Ordinal) ? 13 : 12; + size = isVehicle ? 0.36f : 0.58f; + heat = 0.78f; + depth = 0.078f; + lifetime = 20f; + break; + } + + Vector3 hitPos = new(ev.HitX, ev.HitY, ev.HitZ); + Vector3 normal = new(ev.NormalX, ev.NormalY, ev.NormalZ); + if (normal.LengthSquared() < 1e-4f) normal = Vector3.Up; + normal = normal.Normalized(); + + if (isVehicle) + { + bool isContender = ev.TargetKind == HitTargetKind.Contender; + VehicleVisualInstance? vis = getVisual(isContender, ev.TargetId); + if (vis is null || !vis.Root.IsInsideTree() || !vis.Root.Visible) + { + return; + } + + ChassisGrid? grid = null; + if (isContender) + { + if (ev.TargetId >= 0 && ev.TargetId < state.Contenders.Count) + grid = state.Contenders[ev.TargetId].Grid; + } + else + { + var specs = state.Spectators.Spectators; + for (int si = 0; si < specs.Count; si++) + { + if (specs[si].Id == ev.TargetId) + { + grid = specs[si].Grid; + break; + } + } + } + if (grid is null || grid.IsDestroyed) + { + return; + } + + Vector3 rayDir = (vis.Root.GlobalPosition - hitPos); + if (rayDir.LengthSquared() < 1e-4f) rayDir = -normal; + rayDir = rayDir.Normalized(); + Vector3 rayOrigin = hitPos - rayDir * 0.75f; + + if (vis.TryRayHitAttachedPart(rayOrigin, rayDir, out Node3D? hitPivot, out Transform3D localToPivot, size) && + hitPivot is not null) + { + AllocateSlot(new DecalSlot + { + Active = true, + Age = 0f, + Lifetime = lifetime, + TileIndex = tile, + InitialHeat = heat, + BaseOpacity = 1f, + DepthScale = depth, + IsAttached = true, + Visual = vis, + Pivot = hitPivot, + LocalToPivot = localToPivot, + Grid = grid, + CellX = ev.CellX, + CellY = ev.CellY, + DetachedFadeRemaining = -1f + }); + return; + } + + // Fallback: attach to Root if sculpted geometry ray glanced past edge + Transform3D worldXf = BuildSurfaceTransform(hitPos, normal, size, ev.EventId * 0.73f); + AllocateSlot(new DecalSlot + { + Active = true, + Age = 0f, + Lifetime = lifetime, + TileIndex = tile, + InitialHeat = heat, + BaseOpacity = 1f, + DepthScale = depth, + IsAttached = true, + Visual = vis, + Pivot = vis.Root, + LocalToPivot = vis.Root.GlobalTransform.AffineInverse() * worldXf, + Grid = grid, + CellX = ev.CellX, + CellY = ev.CellY, + DetachedFadeRemaining = -1f + }); + return; + } + + // Terrain or StaticCover decal + Transform3D groundXf = BuildSurfaceTransform(hitPos + normal * 0.045f, normal, size, ev.EventId * 1.13f); + AllocateSlot(new DecalSlot + { + Active = true, + Age = 0f, + Lifetime = lifetime, + TileIndex = tile, + InitialHeat = heat, + BaseOpacity = 0.96f, + DepthScale = depth, + WorldXform = groundXf, + DetachedFadeRemaining = -1f + }); + } + + private void UpdateAndCommit(float dt) + { + float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.05f) : 0f; + int visibleIdx = 0; + + for (int i = 0; i < MaxDecals; i++) + { + ref DecalSlot s = ref _slots[i]; + if (!s.Active) + { + continue; + } + + s.Age += stepDt; + if (s.Age >= s.Lifetime) + { + s.Active = false; + continue; + } + + Transform3D xf = s.WorldXform; + float opacity = s.BaseOpacity; + + if (s.IsAttached) + { + if (s.Visual is null || s.Pivot is null || !GodotObject.IsInstanceValid(s.Pivot) || + !s.Pivot.IsInsideTree() || !s.Visual.Root.Visible) + { + s.Active = false; + continue; + } + + if (s.DetachedFadeRemaining < 0f && s.Grid is not null) + { + bool cellStripped = s.Grid.IsDestroyed || + (s.CellX >= 0 && s.CellX < s.Grid.Spec.Width && + s.CellY >= 0 && s.CellY < s.Grid.Spec.Height && + s.Grid.Armor[s.CellX, s.CellY] <= 0.01f); + if (cellStripped) + { + s.DetachedFadeRemaining = DetachFadeDuration; + } + } + + if (s.DetachedFadeRemaining >= 0f) + { + s.DetachedFadeRemaining -= stepDt; + if (s.DetachedFadeRemaining <= 0f) + { + s.Active = false; + continue; + } + opacity *= Math.Clamp(s.DetachedFadeRemaining / DetachFadeDuration, 0f, 1f); + } + + xf = s.Pivot.GlobalTransform * s.LocalToPivot; + } + + float remaining = s.Lifetime - s.Age; + if (remaining < EndFadeDuration) + { + opacity *= Math.Clamp(remaining / EndFadeDuration, 0f, 1f); + } + + float heatGlow = s.InitialHeat * MathF.Max(0f, 1f - s.Age / HeatCoolDuration); + _multiMesh.SetInstanceTransform(visibleIdx, xf); + _multiMesh.SetInstanceCustomData(visibleIdx, new Color(s.TileIndex, heatGlow, opacity, s.DepthScale)); + visibleIdx++; + } + + ActiveCount = visibleIdx; + _multiMesh.VisibleInstanceCount = visibleIdx; + _instanceNode.Visible = visibleIdx > 0; + } + + private void AllocateSlot(in DecalSlot slot) + { + _slots[_writeCursor] = slot; + _writeCursor = (_writeCursor + 1) % MaxDecals; + } + + private static Transform3D BuildSurfaceTransform(Vector3 worldPos, Vector3 worldNormal, float size, float spinRad) + { + Vector3 n = worldNormal.LengthSquared() > 1e-6f ? worldNormal.Normalized() : Vector3.Up; + Vector3 upRef = MathF.Abs(n.Y) > 0.92f ? Vector3.Forward : Vector3.Up; + Vector3 right = upRef.Cross(n).Normalized(); + Vector3 up = n.Cross(right).Normalized(); + Basis spin = new(n, spinRad); + right = spin * right; + up = spin * up; + return new Transform3D(new Basis(right * size, up * size, n), worldPos); + } + + private static ImageTexture LoadTextureWithMips(string path) + { + var img = Image.LoadFromFile(path); + if (img is null) + { + throw new FileNotFoundException($"Could not load POM decal texture '{path}'.", path); + } + img.GenerateMipmaps(); + return ImageTexture.CreateFromImage(img); + } +} diff --git a/client/VehicleAssetCache.cs b/client/VehicleAssetCache.cs index a917e63..80d618b 100644 --- a/client/VehicleAssetCache.cs +++ b/client/VehicleAssetCache.cs @@ -41,6 +41,13 @@ public sealed class VehicleAssetCache : IDisposable NodePath RelativePath, bool HasProtectedDescendant); + public sealed record RigidPartTemplate( + NodePath PivotPath, + ArrayMesh Mesh, + int CellX, + int CellY, + string Kind); + public sealed class VehicleTemplate { public required VehiclePackage Package { get; init; } @@ -48,12 +55,18 @@ public sealed class VehicleAssetCache : IDisposable public required Node3D SceneTemplate { get; init; } public required ArrayMesh BakedStaticMesh { get; init; } public required ArrayMesh BakedLodFarMesh { get; init; } + public required ArrayMesh SingleSurfaceStaticMesh { get; init; } + public required ArrayMesh SingleSurfaceLodFarMesh { get; init; } + public required Vector3[] FarRayTris { get; init; } + public required Aabb FarRayAabb { get; init; } public required float MinY { get; init; } public required float MaxY { get; init; } public required IReadOnlyDictionary Anchors { get; init; } public required IReadOnlyDictionary Joints { get; init; } public required IReadOnlyDictionary NodesByOriginalName { get; init; } public required IReadOnlyList DetachableParts { get; init; } + public required IReadOnlyList StaticRigidParts { get; init; } + public required IReadOnlyList DetachableRigidParts { get; init; } public required IReadOnlyList MobilityNodePaths { get; init; } } @@ -63,9 +76,11 @@ public sealed class VehicleAssetCache : IDisposable public required string GlbPath { get; init; } public required Node3D SceneTemplate { get; init; } public required ArrayMesh BakedDropMesh { get; init; } + public required ArrayMesh SingleSurfaceMesh { get; init; } public required Vector3 Size { get; init; } public required float MinY { get; init; } public required Vector3 LocalModelForward { get; init; } + public required IReadOnlyDictionary PartCentroidsLocal { get; init; } } public static readonly string[] ExpectedGearIds = @@ -75,6 +90,7 @@ public sealed class VehicleAssetCache : IDisposable private readonly Dictionary _vehicles = new(StringComparer.OrdinalIgnoreCase); private readonly Dictionary _gear = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _gearVariantMeshes = new(StringComparer.OrdinalIgnoreCase); private readonly string _vehiclesDir; private readonly string _gearDir; private bool _disposed; @@ -153,6 +169,26 @@ public sealed class VehicleAssetCache : IDisposable return template; } + public ArrayMesh GetOrBuildGearVariantMesh( + string moduleId, + string gearGlbId, + Color? paintTint, + Color? accentTint) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_gearVariantMeshes.TryGetValue(moduleId, out ArrayMesh? cached)) + { + return cached; + } + + GearTemplate tpl = GetOrLoadGear(gearGlbId); + ArrayMesh mesh = !paintTint.HasValue && !accentTint.HasValue + ? tpl.SingleSurfaceMesh + : CollapseToSingleSurfaceMechPaintMesh(tpl.BakedDropMesh, paintTint, accentTint); + _gearVariantMeshes[moduleId] = mesh; + return mesh; + } + private static VehicleTemplate LoadVehicleTemplate(VehiclePackage pkg, string glbPath) { byte[] jsonBytes = ReadGlbJsonChunk(glbPath); @@ -443,10 +479,24 @@ public sealed class VehicleAssetCache : IDisposable } // C: Build single-node BakedStaticMesh + decimated BakedLodFarMesh (>130m) per template - ArrayMesh bakedStaticMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false); - ArrayMesh bakedCoarseStatic = BuildBakedStaticMesh(sceneRoot, coarseMaterials: true); + ArrayMesh bakedStaticMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false, bakeVertexColor: false); + ArrayMesh bakedCoarseStatic = BuildBakedStaticMesh(sceneRoot, coarseMaterials: true, bakeVertexColor: false); ArrayMesh bakedLodFarMesh = DecimateMeshGrid(bakedCoarseStatic, cellSize: 0.45f, targetMinY: minY); + ArrayMesh singleSurfaceStatic = CollapseToSingleSurfaceMechPaintMesh(bakedStaticMesh); + ArrayMesh singleSurfaceLodFar = CollapseToSingleSurfaceMechPaintMesh(bakedLodFarMesh); + Vector3[] farRayTris = ExtractFlatTriangles(singleSurfaceLodFar); + Aabb farRayAabb = singleSurfaceLodFar.GetAabb().Grow(0.20f); + + // D: Extract single-surface MechPaint rigid parts (static limbs + detachable armor chunks) + // and strip all MeshInstance3D nodes from SceneTemplate so live rigs have zero MeshInstance3D children! + ExtractRigidPartsAndStripMeshes( + sceneRoot, + protectedNodes, + mergedDetachableInfos, + out var staticRigidParts, + out var detachableRigidParts); + return new VehicleTemplate { Package = pkg, @@ -454,12 +504,18 @@ public sealed class VehicleAssetCache : IDisposable SceneTemplate = sceneRoot, BakedStaticMesh = bakedStaticMesh, BakedLodFarMesh = bakedLodFarMesh, + SingleSurfaceStaticMesh = singleSurfaceStatic, + SingleSurfaceLodFarMesh = singleSurfaceLodFar, + FarRayTris = farRayTris, + FarRayAabb = farRayAabb, MinY = minY, MaxY = maxY, Anchors = anchors, Joints = joints, NodesByOriginalName = survivingNames, DetachableParts = mergedDetachableInfos, + StaticRigidParts = staticRigidParts, + DetachableRigidParts = detachableRigidParts, MobilityNodePaths = mobilityPaths }; } @@ -489,8 +545,10 @@ public sealed class VehicleAssetCache : IDisposable ClearOwnerRecursive(sceneRoot); ComputeSceneMeshBounds(sceneRoot, out Vector3 bMin, out Vector3 bMax); + var partCentroids = CollectGearPartCentroids(sceneRoot); MergeGearSubMeshes(sceneRoot, gearId); ArrayMesh bakedDropMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false, bakeVertexColor: false); + ArrayMesh singleSurfaceMesh = CollapseToSingleSurfaceMechPaintMesh(bakedDropMesh); Vector3 localFwd = new Vector3(0f, 0f, 1f); return new GearTemplate @@ -499,9 +557,11 @@ public sealed class VehicleAssetCache : IDisposable GlbPath = glbPath, SceneTemplate = sceneRoot, BakedDropMesh = bakedDropMesh, + SingleSurfaceMesh = singleSurfaceMesh, Size = bMax - bMin, MinY = bMin.Y, - LocalModelForward = localFwd + LocalModelForward = localFwd, + PartCentroidsLocal = partCentroids }; } @@ -887,6 +947,453 @@ public sealed class VehicleAssetCache : IDisposable return BuildMergedArrayMesh(items, coarseMaterials, bakeVertexColor) ?? new ArrayMesh(); } + private static Dictionary CollectGearPartCentroids(Node3D sceneRoot) + { + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + var allMeshes = new List(); + CollectAllMeshInstances(sceneRoot, allMeshes); + + for (int i = 0; i < allMeshes.Count; i++) + { + MeshInstance3D mi = allMeshes[i]; + if (!PreservedGearPartNames.Contains(mi.Name) || mi.Mesh is null) + { + continue; + } + Transform3D toRoot = ComputeRelativeTransform(sceneRoot, mi); + Vector3 sum = Vector3.Zero; + int count = 0; + int surfCount = mi.Mesh.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + var arr = mi.Mesh.SurfaceGetArrays(s); + if (arr.Count > (int)Mesh.ArrayType.Vertex && + arr[(int)Mesh.ArrayType.Vertex].VariantType == Variant.Type.PackedVector3Array) + { + Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + for (int v = 0; v < verts.Length; v++) + { + sum += toRoot * verts[v]; + count++; + } + } + } + if (count > 0) + { + result[mi.Name] = sum / count; + } + } + return result; + } + + private static void ExtractRigidPartsAndStripMeshes( + Node3D sceneRoot, + HashSet protectedNodes, + List detachableInfos, + out List staticPartsOut, + out List detachablePartsOut) + { + staticPartsOut = new List(); + detachablePartsOut = new List(); + + var detachableSet = new Dictionary(); + for (int i = 0; i < detachableInfos.Count; i++) + { + var dp = detachableInfos[i]; + if (sceneRoot.GetNodeOrNull(dp.RelativePath) is MeshInstance3D dmi) + { + detachableSet[dmi] = dp; + } + } + + // 1. Extract detachable per-cell armor chunks in their rigidParent's local space + foreach (var (mi, dp) in detachableSet) + { + if (!CanMergeMeshInstance(mi) || mi.Mesh is null) + { + continue; + } + Node3D rigidParent = protectedNodes.Contains(mi) + ? mi + : FindNearestProtectedParent(mi, sceneRoot, protectedNodes); + Transform3D relXf = ReferenceEquals(mi, rigidParent) + ? Transform3D.Identity + : ComputeRelativeTransform(rigidParent, mi); + var single = new List<(Mesh Mesh, Transform3D RelXf)>(1) { (mi.Mesh, relXf) }; + ArrayMesh? collapsed = CollapseToSingleSurfaceMechPaintMesh(single); + if (collapsed is not null) + { + detachablePartsOut.Add(new RigidPartTemplate( + BuildRelativeNodePath(sceneRoot, rigidParent), + collapsed, + dp.CellX, + dp.CellY, + dp.Kind)); + } + } + + // 2. Group remaining non-detachable rigid meshes by rigidParent and collapse each to 1 surface + var allMeshes = new List(); + CollectAllMeshInstances(sceneRoot, allMeshes); + var staticByPivot = new Dictionary>(); + for (int i = 0; i < allMeshes.Count; i++) + { + MeshInstance3D mi = allMeshes[i]; + if (detachableSet.ContainsKey(mi) || !CanMergeMeshInstance(mi) || mi.Mesh is null) + { + continue; + } + Node3D rigidParent = protectedNodes.Contains(mi) + ? mi + : FindNearestProtectedParent(mi, sceneRoot, protectedNodes); + Transform3D relXf = ReferenceEquals(mi, rigidParent) + ? Transform3D.Identity + : ComputeRelativeTransform(rigidParent, mi); + if (!staticByPivot.TryGetValue(rigidParent, out var list)) + { + list = new List<(Mesh, Transform3D)>(); + staticByPivot[rigidParent] = list; + } + list.Add((mi.Mesh, relXf)); + } + + foreach (var (rigidParent, items) in staticByPivot) + { + ArrayMesh? collapsed = CollapseToSingleSurfaceMechPaintMesh(items); + if (collapsed is not null) + { + staticPartsOut.Add(new RigidPartTemplate( + BuildRelativeNodePath(sceneRoot, rigidParent), + collapsed, + -1, + -1, + "static")); + } + } + + // 3. Strip all MeshInstance3D nodes from sceneRoot: + // - Protected MeshInstance3Ds become plain Node3D pivots preserving Name, Transform, and children. + // - Non-protected MeshInstance3Ds are removed cleanly. + for (int i = 0; i < allMeshes.Count; i++) + { + MeshInstance3D mi = allMeshes[i]; + if (!GodotObject.IsInstanceValid(mi) || ReferenceEquals(mi, sceneRoot)) + { + continue; + } + if (protectedNodes.Contains(mi)) + { + ReplaceMeshInstanceWithPivot(mi); + } + else + { + ReparentChildrenAndRemove(mi); + } + } + } + + private static void ReplaceMeshInstanceWithPivot(MeshInstance3D mi) + { + Node? parent = mi.GetParent(); + if (parent is null) + { + return; + } + int idx = mi.GetIndex(); + var pivot = new Node3D + { + Name = mi.Name, + Transform = mi.Transform + }; + parent.RemoveChild(mi); + parent.AddChild(pivot); + parent.MoveChild(pivot, idx); + while (mi.GetChildCount() > 0) + { + Node ch = mi.GetChild(0); + mi.RemoveChild(ch); + pivot.AddChild(ch); + } + mi.QueueFree(); + } + + private static Vector3[] ExtractFlatTriangles(ArrayMesh mesh) + { + var tris = new List(); + int surfCount = mesh.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + var arr = mesh.SurfaceGetArrays(s); + if (arr.Count <= (int)Mesh.ArrayType.Vertex || + arr[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) + { + continue; + } + Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + int[]? indices = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array + ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() + : null; + int triCount = (indices is not null ? indices.Length : verts.Length) / 3; + for (int t = 0; t < triCount; t++) + { + int i0 = indices is not null ? indices[t * 3] : t * 3; + int i1 = indices is not null ? indices[t * 3 + 1] : t * 3 + 1; + int i2 = indices is not null ? indices[t * 3 + 2] : t * 3 + 2; + tris.Add(verts[i0]); + tris.Add(verts[i1]); + tris.Add(verts[i2]); + } + } + return tris.ToArray(); + } + + public static ArrayMesh CollapseToSingleSurfaceMechPaintMesh( + ArrayMesh src, + Color? gearPaintTint = null, + Color? gearAccentTint = null) + { + var list = new List<(Mesh Mesh, Transform3D RelXf)>(1) { (src, Transform3D.Identity) }; + return CollapseToSingleSurfaceMechPaintMesh(list, gearPaintTint, gearAccentTint) ?? new ArrayMesh(); + } + + private static ArrayMesh? CollapseToSingleSurfaceMechPaintMesh( + List<(Mesh Mesh, Transform3D RelXf)> sources, + Color? gearPaintTint = null, + Color? gearAccentTint = null) + { + int totalVerts = 0; + int totalIndices = 0; + var chunks = new List<(Godot.Collections.Array Arrays, Transform3D RelXf, Vector3 LinearCol, int Band, float Rough, int VertCount, int IdxCount)>(); + + for (int i = 0; i < sources.Count; i++) + { + var (mesh, relXf) = sources[i]; + int surfCount = mesh.GetSurfaceCount(); + var am = mesh as ArrayMesh; + for (int s = 0; s < surfCount; s++) + { + if (am is not null && am.SurfaceGetPrimitiveType(s) != Mesh.PrimitiveType.Triangles) + { + continue; + } + var arr = mesh.SurfaceGetArrays(s); + if (arr.Count <= (int)Mesh.ArrayType.Vertex || + arr[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) + { + continue; + } + Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + if (verts.Length == 0) + { + continue; + } + + int idxCount = verts.Length; + if (arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array) + { + idxCount = arr[(int)Mesh.ArrayType.Index].AsInt32Array().Length; + } + if (idxCount < 3) + { + continue; + } + + ClassifyMaterialForMechPaint(mesh.SurfaceGetMaterial(s), gearPaintTint, gearAccentTint, out Vector3 linCol, out int band, out float rough); + chunks.Add((arr, relXf, linCol, band, rough, verts.Length, idxCount)); + totalVerts += verts.Length; + totalIndices += idxCount; + } + } + + if (totalVerts == 0 || totalIndices == 0) + { + return null; + } + + var outVerts = new Vector3[totalVerts]; + var outNorms = new Vector3[totalVerts]; + var outColors = new Color[totalVerts]; + var outUvs = new Vector2[totalVerts]; + var outUv2s = new Vector2[totalVerts]; + var outIndices = new int[totalIndices]; + + int vOff = 0; + int iOff = 0; + for (int c = 0; c < chunks.Count; c++) + { + var (arr, relXf, linCol, band, rough, vCount, idxCount) = chunks[c]; + Vector3[] srcV = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + bool flipWinding = relXf.Basis.Determinant() < 0f; + Basis normBasis = relXf.Basis.Inverse().Transposed(); + + for (int v = 0; v < vCount; v++) + { + outVerts[vOff + v] = relXf * srcV[v]; + } + + if (arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array) + { + Vector3[] srcN = arr[(int)Mesh.ArrayType.Normal].AsVector3Array(); + for (int v = 0; v < vCount; v++) + { + Vector3 n = normBasis * srcN[v]; + outNorms[vOff + v] = n.LengthSquared() > 1e-10f ? n.Normalized() : Vector3.Up; + } + } + else + { + for (int v = 0; v < vCount; v++) outNorms[vOff + v] = Vector3.Up; + } + + if (arr.Count > (int)Mesh.ArrayType.Color && arr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray) + { + Array.Copy(arr[(int)Mesh.ArrayType.Color].AsColorArray(), 0, outColors, vOff, vCount); + } + else + { + // Gear or unbaked submesh: neutral cavity AO, crisp edge highlight, steady rest height above mud line + var defaultCol = new Color(0.86f, 0.36f, 0.50f, 0.65f); + for (int v = 0; v < vCount; v++) outColors[vOff + v] = defaultCol; + } + + var uv0 = new Vector2(linCol.X, linCol.Y); + var uv1 = new Vector2(linCol.Z, band * 2.0f + rough); + for (int v = 0; v < vCount; v++) + { + outUvs[vOff + v] = uv0; + outUv2s[vOff + v] = uv1; + } + + bool hasIdx = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array; + int[]? srcIdx = hasIdx ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() : null; + if (!flipWinding) + { + if (srcIdx is not null) + { + for (int k = 0; k < idxCount; k++) outIndices[iOff + k] = srcIdx[k] + vOff; + } + else + { + for (int k = 0; k < idxCount; k++) outIndices[iOff + k] = k + vOff; + } + } + else + { + for (int k = 0; k + 2 < idxCount; k += 3) + { + int a = srcIdx is not null ? srcIdx[k] : k; + int bIdx = srcIdx is not null ? srcIdx[k + 1] : k + 1; + int cIdx = srcIdx is not null ? srcIdx[k + 2] : k + 2; + outIndices[iOff + k] = a + vOff; + outIndices[iOff + k + 1] = cIdx + vOff; + outIndices[iOff + k + 2] = bIdx + vOff; + } + } + + vOff += vCount; + iOff += idxCount; + } + + var surfArrays = new Godot.Collections.Array(); + surfArrays.Resize((int)Mesh.ArrayType.Max); + surfArrays[(int)Mesh.ArrayType.Vertex] = outVerts; + surfArrays[(int)Mesh.ArrayType.Normal] = outNorms; + surfArrays[(int)Mesh.ArrayType.Color] = outColors; + surfArrays[(int)Mesh.ArrayType.TexUV] = outUvs; + surfArrays[(int)Mesh.ArrayType.TexUV2] = outUv2s; + surfArrays[(int)Mesh.ArrayType.Index] = outIndices; + + var outMesh = new ArrayMesh(); + outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, surfArrays); + return outMesh; + } + + private static void ClassifyMaterialForMechPaint( + Material? mat, + Color? gearPaintTint, + Color? gearAccentTint, + out Vector3 linearColor, + out int band, + out float roughness) + { + if (mat is not StandardMaterial3D sm) + { + linearColor = new Vector3(0.08f, 0.09f, 0.06f); + band = 3; + roughness = 0.58f; + return; + } + + string mName = (sm.ResourceName ?? string.Empty).ToLowerInvariant(); + roughness = Math.Clamp(sm.Roughness, 0.08f, 0.90f); + + if (mName.Contains("lamp") || mName.Contains("glow") || mName.Contains("cyan") || + mName.Contains("amber") || mName.Contains("optic_red")) + { + Color eCol = (sm.EmissionEnabled ? sm.Emission : sm.AlbedoColor).SrgbToLinear(); + linearColor = new Vector3(eCol.R, eCol.G, eCol.B); + band = 5; + roughness = 0.22f; + return; + } + + if (mName.Contains("olive") || mName.Contains("khaki") || mName.Contains("armour") || mName.Contains("armor")) + { + if (gearPaintTint.HasValue) + { + Color c = gearPaintTint.Value.SrgbToLinear(); + linearColor = new Vector3(c.R, c.G, c.B); + band = 6; + roughness = 0.56f; + return; + } + Color b = sm.AlbedoColor.SrgbToLinear(); + linearColor = new Vector3(b.R, b.G, b.B); + band = 3; + roughness = 0.58f; + return; + } + + if (mName.Contains("ivory") && gearPaintTint.HasValue) + { + Color c = gearPaintTint.Value.SrgbToLinear(); + linearColor = new Vector3(c.R, c.G, c.B); + band = 6; + roughness = 0.42f; + return; + } + + if (mName.Contains("signal") || mName.Contains("orange") || mName.Contains("hazard")) + { + if (gearAccentTint.HasValue) + { + Color c = gearAccentTint.Value.SrgbToLinear(); + linearColor = new Vector3(c.R, c.G, c.B); + band = 7; + roughness = 0.42f; + return; + } + Color b = sm.AlbedoColor.SrgbToLinear(); + linearColor = new Vector3(b.R, b.G, b.B); + band = 4; + roughness = 0.44f; + return; + } + + if (gearAccentTint.HasValue && (mName.Contains("copper") || mName.Contains("gold"))) + { + Color c = gearAccentTint.Value.SrgbToLinear(); + linearColor = new Vector3(c.R, c.G, c.B); + band = 7; + roughness = 0.36f; + return; + } + + Color lin = sm.AlbedoColor.SrgbToLinear(); + linearColor = new Vector3(lin.R, lin.G, lin.B); + band = sm.Metallic >= 0.70f ? 2 : (sm.Metallic >= 0.35f ? 1 : 0); + } + private static void PruneEmptyNonProtectedNodes(Node cur, Node sceneRoot, HashSet protectedNodes) { for (int i = cur.GetChildCount() - 1; i >= 0; i--) diff --git a/client/VehicleRigAnimator.cs b/client/VehicleRigAnimator.cs index aa35ba8..ca73f27 100644 --- a/client/VehicleRigAnimator.cs +++ b/client/VehicleRigAnimator.cs @@ -875,12 +875,108 @@ public static class VehicleRigAnimator } var list = new List(); - var stack = new List(); float cutoffY = visual.Template.MinY + 0.75f; - int count = visual.ModelRoot.GetChildCount(); - for (int i = 0; i < count; i++) + var parts = visual.StaticParts; + + for (int i = 0; i < parts.Count; i++) { - CollectFootSamplesRecursive(visual.ModelRoot.GetChild(i), Transform3D.Identity, cutoffY, stack, list); + var part = parts[i]; + if (!GodotObject.IsInstanceValid(part.Pivot)) + { + continue; + } + + // Build chain from ModelRoot -> part.Pivot + var chain = new List(); + Transform3D toModel = Transform3D.Identity; + for (Node? cur = part.Pivot; cur is Node3D n3d && !ReferenceEquals(cur, visual.ModelRoot); cur = cur.GetParent()) + { + chain.Add(n3d); + toModel = n3d.Transform * toModel; + } + chain.Reverse(); + + Aabb aabb = part.Mesh.GetAabb(); + float aabbMinY = float.PositiveInfinity; + for (int c = 0; c < 8; c++) + { + Vector3 corner = aabb.Position + new Vector3( + (c & 1) != 0 ? aabb.Size.X : 0f, + (c & 2) != 0 ? aabb.Size.Y : 0f, + (c & 4) != 0 ? aabb.Size.Z : 0f); + float wy = (toModel * corner).Y; + if (wy < aabbMinY) + { + aabbMinY = wy; + } + } + + if (aabbMinY >= cutoffY) + { + continue; + } + + var bestPts = new Vector3[FootSupportDirs.Length]; + var bestDots = new float[FootSupportDirs.Length]; + for (int d = 0; d < FootSupportDirs.Length; d++) + { + bestDots[d] = float.NegativeInfinity; + } + + bool anyVert = false; + int surfCount = part.Mesh.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + var arrays = part.Mesh.SurfaceGetArrays(s); + if (arrays.Count <= (int)Mesh.ArrayType.Vertex || + arrays[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) + { + continue; + } + Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + for (int v = 0; v < verts.Length; v++) + { + Vector3 localPt = verts[v]; + Vector3 mPt = toModel * localPt; + for (int d = 0; d < FootSupportDirs.Length; d++) + { + float score = mPt.Dot(FootSupportDirs[d]); + if (score > bestDots[d]) + { + bestDots[d] = score; + bestPts[d] = localPt; + } + } + anyVert = true; + } + } + + if (anyVert) + { + var unique = new List(FootSupportDirs.Length); + for (int d = 0; d < bestPts.Length; d++) + { + bool dup = false; + for (int u = 0; u < unique.Count; u++) + { + if ((unique[u] - bestPts[d]).LengthSquared() < 1e-6f) + { + dup = true; + break; + } + } + if (!dup) + { + unique.Add(bestPts[d]); + } + } + + list.Add(new WalkerFootSample + { + ChainFromModelRoot = chain.ToArray(), + LocalPoints = unique.ToArray() + }); + } } st.FootSamples = list; } @@ -898,117 +994,6 @@ public static class VehicleRigAnimator new(-0.45f, -1f, -0.45f), }; - private static void CollectFootSamplesRecursive( - Node cur, - Transform3D parentToModel, - float cutoffY, - List stack, - List list) - { - Transform3D toModel = parentToModel; - bool pushed = false; - if (cur is Node3D n3d) - { - toModel = parentToModel * n3d.Transform; - stack.Add(n3d); - pushed = true; - } - - if (cur is MeshInstance3D mi && mi.Mesh is { } mesh) - { - Aabb aabb = mesh.GetAabb(); - float aabbMinY = float.PositiveInfinity; - for (int c = 0; c < 8; c++) - { - Vector3 corner = aabb.Position + new Vector3( - (c & 1) != 0 ? aabb.Size.X : 0f, - (c & 2) != 0 ? aabb.Size.Y : 0f, - (c & 4) != 0 ? aabb.Size.Z : 0f); - float wy = (toModel * corner).Y; - if (wy < aabbMinY) - { - aabbMinY = wy; - } - } - - if (aabbMinY < cutoffY) - { - var bestPts = new Vector3[FootSupportDirs.Length]; - var bestDots = new float[FootSupportDirs.Length]; - for (int d = 0; d < FootSupportDirs.Length; d++) - { - bestDots[d] = float.NegativeInfinity; - } - - bool anyVert = false; - int surfCount = mesh.GetSurfaceCount(); - for (int s = 0; s < surfCount; s++) - { - var arrays = mesh.SurfaceGetArrays(s); - if (arrays.Count <= (int)Mesh.ArrayType.Vertex || - arrays[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) - { - continue; - } - Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array(); - for (int v = 0; v < verts.Length; v++) - { - Vector3 localPt = verts[v]; - Vector3 mPt = toModel * localPt; - for (int d = 0; d < FootSupportDirs.Length; d++) - { - float score = mPt.Dot(FootSupportDirs[d]); - if (score > bestDots[d]) - { - bestDots[d] = score; - bestPts[d] = localPt; - } - } - anyVert = true; - } - } - - if (anyVert) - { - var unique = new List(FootSupportDirs.Length); - for (int d = 0; d < bestPts.Length; d++) - { - bool dup = false; - for (int u = 0; u < unique.Count; u++) - { - if ((unique[u] - bestPts[d]).LengthSquared() < 1e-6f) - { - dup = true; - break; - } - } - if (!dup) - { - unique.Add(bestPts[d]); - } - } - - list.Add(new WalkerFootSample - { - ChainFromModelRoot = stack.ToArray(), - LocalPoints = unique.ToArray() - }); - } - } - } - - int childCount = cur.GetChildCount(); - for (int i = 0; i < childCount; i++) - { - CollectFootSamplesRecursive(cur.GetChild(i), toModel, cutoffY, stack, list); - } - - if (pushed) - { - stack.RemoveAt(stack.Count - 1); - } - } - private static void ApplyWalkerFloorClearance(VehicleVisualInstance visual, RigState st, string rootNodeName) { var samples = st.FootSamples; diff --git a/client/VehicleVisualInstance.cs b/client/VehicleVisualInstance.cs index 8e36ae1..7c53e01 100644 --- a/client/VehicleVisualInstance.cs +++ b/client/VehicleVisualInstance.cs @@ -16,12 +16,9 @@ public enum VehicleVisualRole } /// -/// Live Godot 3D instance of a Brokkr vehicle/mech GLB, managing: -/// - grounded model alignment (minY = 0 at physics chassis bottom -HalfHeight), -/// - exterior hardpoint anchor bindings and snap-on modular gear GLBs, -/// - joint pivot bindings with rest transforms and vehicle-space axes, -/// - part-by-cell armor/shroud detachment and hardpoint gear shearing into , -/// - per-cell scorch/damage darkening and thermal heat glow. +/// Lightweight Node3D rig hierarchy for a Brokkr vehicle/mech GLB, submitting all +/// rigid limbs, detachable armor chunks, and mounted gear into +/// (zero rendering MeshInstance3D children on rigs, zero per-hit material clones). /// public sealed class VehicleVisualInstance { @@ -35,6 +32,12 @@ public sealed class VehicleVisualInstance public required float MaxRad; } + public sealed class StaticPartBinding + { + public required Node3D Pivot; + public required ArrayMesh Mesh; + } + private sealed class BoundHardpoint { public required HardpointSpec Spec; @@ -42,15 +45,18 @@ public sealed class VehicleVisualInstance public required Node3D AnchorNode; public string? MountedModuleId; public Node3D? GearNode; - public readonly List GearHeatMaterials = new(); + public ArrayMesh? GearMesh; + public VehicleAssetCache.GearTemplate? GearTemplate; + public float HeatGlow; } private sealed class CellPartBinding { - public required MeshInstance3D Node; - public readonly List<(StandardMaterial3D Mat, Color BaseColor, float BaseRoughness)> Materials = new(); + public required Node3D Pivot; + public required ArrayMesh Mesh; public bool Detached; - public float LastTintScore = -1f; + public float Scorch; + public float HeatGlow; } private readonly record struct GearVisualRecipe( @@ -59,16 +65,8 @@ public sealed class VehicleVisualInstance Color? PaintTint, Color? AccentTint); - private static readonly Color RivalArmorColor = Color.FromHtml("#5d4d42"); - private static readonly Color RivalAccentColor = Color.FromHtml("#b64a32"); private static readonly Color TouristGold = Color.FromHtml("#e6b838"); private static readonly Color TouristIvory = Color.FromHtml("#f2ead8"); - private static readonly Color PatronTeal = Color.FromHtml("#2d7a78"); - private static readonly Color PatronBronze = Color.FromHtml("#a86c36"); - private static readonly Color ExemplarObsidian = Color.FromHtml("#1b1b22"); - private static readonly Color ExemplarCrimson = Color.FromHtml("#c92a2a"); - private static readonly Color SalvageSteel = Color.FromHtml("#545b5c"); - private static readonly Color SalvageCyan = Color.FromHtml("#44d9e8"); private readonly VehicleAssetCache _cache; private readonly VehicleAssetCache.VehicleTemplate _template; @@ -80,17 +78,21 @@ public sealed class VehicleVisualInstance private readonly Dictionary _restLocalByName = new(StringComparer.Ordinal); private readonly Dictionary _restModelByName = new(StringComparer.Ordinal); private readonly Dictionary _restModelByNode = new(); + private readonly List _staticParts = new(); private readonly List[,] _cellParts; + private readonly List _allCellParts = new(); private readonly bool[,] _strippedCells; private readonly HashSet _shearedHardpoints = new(StringComparer.Ordinal); private readonly VehicleRigAnimator.RigState _rigState = new(); private readonly VehicleVisualRole _role; + private readonly float _roleIndex; private readonly string _chassisId; - private MeshInstance3D? _lodStaticMesh; private bool _isStaticLod; private bool _castShadows = true; private bool _hasAnyStrippedCell; + private float _hullScorch; + private float _hullHeatGlow; public static double PerfDamageHeatMs; public static int PerfMaterialDupCount; @@ -109,6 +111,15 @@ public sealed class VehicleVisualInstance ModelRoot = modelRoot; _chassisId = chassisId; _role = role; + _roleIndex = role switch + { + VehicleVisualRole.Rival => 1f, + VehicleVisualRole.SpectatorTourist => 2f, + VehicleVisualRole.SpectatorPatron => 3f, + VehicleVisualRole.SpectatorExemplar => 4f, + VehicleVisualRole.SalvageDrop => 5f, + _ => 0f + }; int w = template.Package.GridWidth; int h = template.Package.GridHeight; @@ -131,31 +142,21 @@ public sealed class VehicleVisualInstance public string ModelId => _template.Package.Id; public VehicleRigAnimator.RigState RigState => _rigState; public IReadOnlyDictionary Joints => _joints; + public IReadOnlyList StaticParts => _staticParts; public int BoundHardpointCount => _hardpoints.Count; public bool IsStaticLod => _isStaticLod; public bool HasAnyStrippedCell => _hasAnyStrippedCell; + public float RoleIndex => _roleIndex; public void SetLodState(bool useStaticLod, bool castShadows) { - if (_lodStaticMesh is null) + if (_role == VehicleVisualRole.SalvageDrop) { - if (ModelRoot is MeshInstance3D dropMi) - { - if (_isStaticLod != useStaticLod) - { - _isStaticLod = useStaticLod; - dropMi.Mesh = useStaticLod ? _template.BakedLodFarMesh : _template.BakedStaticMesh; - } - if (_castShadows != castShadows) - { - _castShadows = castShadows; - dropMi.CastShadow = castShadows - ? GeometryInstance3D.ShadowCastingSetting.On - : GeometryInstance3D.ShadowCastingSetting.Off; - } - } + _isStaticLod = useStaticLod; + _castShadows = castShadows; return; } + if (_hasAnyStrippedCell) { useStaticLod = false; @@ -170,15 +171,8 @@ public sealed class VehicleVisualInstance ModelRoot.ProcessMode = useStaticLod ? Node.ProcessModeEnum.Disabled : Node.ProcessModeEnum.Inherit; - _lodStaticMesh.Visible = useStaticLod; - } - if (_castShadows != castShadows) - { - _castShadows = castShadows; - _lodStaticMesh.CastShadow = castShadows - ? GeometryInstance3D.ShadowCastingSetting.On - : GeometryInstance3D.ShadowCastingSetting.Off; } + _castShadows = castShadows; } public static VehicleVisualInstance Create( @@ -202,16 +196,14 @@ public sealed class VehicleVisualInstance if (role == VehicleVisualRole.SalvageDrop) { - var dropMesh = new MeshInstance3D + var dropPivot = new Node3D { Name = $"Model_{pkg.Id}", - Mesh = template.BakedStaticMesh, Scale = modelScale, Position = modelPos }; - ApplyRoleTint(dropMesh, role); - root.AddChild(dropMesh); - return new VehicleVisualInstance(cache, template, root, dropMesh, chassisId, role); + root.AddChild(dropPivot); + return new VehicleVisualInstance(cache, template, root, dropPivot, chassisId, role); } if (template.SceneTemplate.Duplicate() is not Node3D modelRoot) @@ -223,29 +215,12 @@ public sealed class VehicleVisualInstance modelRoot.Position = modelPos; root.AddChild(modelRoot); - var lodMesh = new MeshInstance3D - { - Name = $"LodStatic_{pkg.Id}", - Mesh = template.BakedLodFarMesh, - Scale = modelScale, - Position = modelPos, - Visible = false - }; - if (role != VehicleVisualRole.Player) - { - ApplyRoleTint(lodMesh, role); - } - root.AddChild(lodMesh); - - var instance = new VehicleVisualInstance(cache, template, root, modelRoot, chassisId, role) - { - _lodStaticMesh = lodMesh - }; - instance.BindAll(role); + var instance = new VehicleVisualInstance(cache, template, root, modelRoot, chassisId, role); + instance.BindAll(); return instance; } - private void BindAll(VehicleVisualRole role) + private void BindAll() { var pkg = _template.Package; @@ -339,13 +314,15 @@ public sealed class VehicleVisualInstance _hardpointList.Add(bh); } - // Apply role palette tinting to painted hull meshes before binding per-cell damage clones - if (role != VehicleVisualRole.Player) + // Bind rigid static parts & detachable per-cell armor parts to their live Node3D pivots + foreach (var sp in _template.StaticRigidParts) { - ApplyRoleTint(ModelRoot, role); + if (ResolveRelative(ModelRoot, sp.PivotPath) is { } pivot) + { + _staticParts.Add(new StaticPartBinding { Pivot = pivot, Mesh = sp.Mesh }); + } } - // Bind detachable exterior armor/shroud parts to their (CellX, CellY) int w = pkg.GridWidth; int h = pkg.GridHeight; for (int y = 0; y < h; y++) @@ -358,15 +335,17 @@ public sealed class VehicleVisualInstance } } } - foreach (var dp in _template.DetachableParts) + foreach (var dp in _template.DetachableRigidParts) { if (dp.CellX < 0 || dp.CellX >= w || dp.CellY < 0 || dp.CellY >= h) { continue; } - if (ResolveRelative(ModelRoot, dp.RelativePath) is MeshInstance3D mi) + if (ResolveRelative(ModelRoot, dp.PivotPath) is { } pivot) { - _cellParts[dp.CellX, dp.CellY].Add(new CellPartBinding { Node = mi }); + var binding = new CellPartBinding { Pivot = pivot, Mesh = dp.Mesh }; + _cellParts[dp.CellX, dp.CellY].Add(binding); + _allCellParts.Add(binding); } } } @@ -394,8 +373,50 @@ public sealed class VehicleVisualInstance ? _cellParts[x, y].Count : 0; + public bool TryGetMountedWeaponCentroidsInModel( + string hardpointId, + string frontPartName, + string rearPartName, + out Vector3 frontInModel, + out Vector3 rearInModel) + { + frontInModel = Vector3.Zero; + rearInModel = Vector3.Zero; + if (!_hardpoints.TryGetValue(hardpointId, out var bh) || + bh.GearNode is null || + !GodotObject.IsInstanceValid(bh.GearNode) || + bh.GearTemplate is null) + { + return false; + } + if (!bh.GearTemplate.PartCentroidsLocal.TryGetValue(frontPartName, out Vector3 fLocal) || + !bh.GearTemplate.PartCentroidsLocal.TryGetValue(rearPartName, out Vector3 rLocal)) + { + return false; + } + + Transform3D gearToModel = ComputeRelativeTransform(bh.GearNode, ModelRoot); + frontInModel = gearToModel * fLocal; + rearInModel = gearToModel * rLocal; + return true; + } + + public static void ResolveDropGearVisual( + VehicleAssetCache cache, + ModuleSpec mod, + out ArrayMesh mesh, + out Vector3 scale, + out float yOffset) + { + GearVisualRecipe recipe = ResolveGearRecipe(mod); + var template = cache.GetOrLoadGear(recipe.GearGlbId); + mesh = cache.GetOrBuildGearVariantMesh(mod.Id, recipe.GearGlbId, recipe.PaintTint, recipe.AccentTint); + scale = recipe.VariantScale; + yOffset = -template.MinY * recipe.VariantScale.Y; + } + /// - /// Synchronizes visible exterior gear GLBs on all hardpoint anchors with . + /// Synchronizes exterior gear transform anchors on all hardpoints with . /// public void SyncMountedGear(ChassisGrid grid) { @@ -414,14 +435,15 @@ public sealed class VehicleVisualInstance continue; } - // Clear old gear visual if unmounted or swapped if (bh.GearNode is not null && GodotObject.IsInstanceValid(bh.GearNode)) { bh.GearNode.GetParent()?.RemoveChild(bh.GearNode); bh.GearNode.QueueFree(); } bh.GearNode = null; - bh.GearHeatMaterials.Clear(); + bh.GearMesh = null; + bh.GearTemplate = null; + bh.HeatGlow = 0f; bh.MountedModuleId = desiredId; if (mounted is null) @@ -429,26 +451,46 @@ public sealed class VehicleVisualInstance continue; } - Node3D gearNode = InstantiateGearForHardpoint(mounted.Spec, bh.Spec, bh.AnchorInfo, bh.GearHeatMaterials); + Node3D gearNode = CreateGearPivotForHardpoint( + mounted.Spec, + bh.Spec, + bh.AnchorInfo, + out ArrayMesh gearMesh, + out VehicleAssetCache.GearTemplate gearTemplate); bh.AnchorNode.AddChild(gearNode); bh.GearNode = gearNode; + bh.GearMesh = gearMesh; + bh.GearTemplate = gearTemplate; } } /// /// Detaches exterior armor/shroud plates when Armor[x, y] <= 0.01f, - /// shears mounted gear off non-operational hardpoints, and applies scorch/heat glow. + /// shears mounted gear off non-operational hardpoints into , + /// and updates per-part scorch/heat channels for . /// public void SyncDamageAndHeat(ChassisGrid grid, DebrisSystem debris, Vector3 vehicleVelocity) { long t0 = RustToDust.Ymir.ArenaSession.PerfEnabled ? System.Diagnostics.Stopwatch.GetTimestamp() : 0; Vector3 blastOrigin = Root.IsInsideTree() ? Root.GlobalPosition : Root.Position; - // 1. Part-by-cell detachment & cell scorch/heat tinting - for (int c = 0; c < _activeCells.Count; c++) + float scorchSum = 0f; + float maxHeat = 0f; + int cellCount = _activeCells.Count; + + // 1. Part-by-cell detachment & cell scorch/heat channels + for (int c = 0; c < cellCount; c++) { var (x, y) = _activeCells[c]; float armor = grid.Armor[x, y]; + float maxArmor = MathF.Max(1f, grid.MaxArmor[x, y]); + float temp = grid.Temperature[x, y]; + float dmgFrac = 1f - Math.Clamp(armor / maxArmor, 0f, 1f); + float cellScorch = Math.Clamp((dmgFrac - 0.18f) / 0.82f, 0f, 1f); + float cellHeat = Math.Clamp((temp - 65f) / 110f, 0f, 1f); + scorchSum += cellScorch; + if (cellHeat > maxHeat) maxHeat = cellHeat; + var parts = _cellParts[x, y]; if (!_strippedCells[x, y] && armor <= 0.01f) { @@ -457,53 +499,32 @@ public sealed class VehicleVisualInstance for (int i = 0; i < parts.Count; i++) { var pb = parts[i]; - if (!pb.Detached && GodotObject.IsInstanceValid(pb.Node)) + if (!pb.Detached && GodotObject.IsInstanceValid(pb.Pivot)) { pb.Detached = true; - pb.Node.Visible = true; - debris.SpawnDetachedPart(pb.Node, blastOrigin, vehicleVelocity, impulseScale: 1.0f, applyScorch: true); + Transform3D worldXf = pb.Pivot.IsInsideTree() + ? pb.Pivot.GlobalTransform + : ComputeWorldTransformFallback(pb.Pivot); + debris.SpawnDetachedPart(pb.Mesh, worldXf, blastOrigin, vehicleVelocity, _roleIndex, impulseScale: 1.0f, applyScorch: true); } } continue; } - if (parts.Count == 0) - { - continue; - } - - float maxArmor = MathF.Max(1f, grid.MaxArmor[x, y]); - float temp = grid.Temperature[x, y]; - if (armor > maxArmor * 0.75f && temp < 70.5f) - { - continue; - } - - float dmgFrac = 1f - Math.Clamp(armor / maxArmor, 0f, 1f); - float heatGlow = Math.Clamp((temp - 65f) / 110f, 0f, 1f); - float tintScore = MathF.Round(dmgFrac * 20f) + MathF.Round(heatGlow * 20f) * 32f; - - if (dmgFrac < 0.25f && heatGlow < 0.05f) - { - continue; - } - for (int i = 0; i < parts.Count; i++) { var pb = parts[i]; - if (pb.Detached || !GodotObject.IsInstanceValid(pb.Node)) + if (!pb.Detached) { - continue; + pb.Scorch = cellScorch; + pb.HeatGlow = cellHeat; } - if (MathF.Abs(pb.LastTintScore - tintScore) < 0.5f) - { - continue; - } - pb.LastTintScore = tintScore; - ApplyCellDamageAndHeat(pb, dmgFrac, heatGlow); } } + _hullScorch = cellCount > 0 ? Math.Clamp((scorchSum / cellCount) * 0.85f, 0f, 0.85f) : 0f; + _hullHeatGlow = maxHeat * 0.72f; + // 2. Hardpoint shear & mounted gear heat glow for (int i = 0; i < _hardpointList.Count; i++) { @@ -512,94 +533,187 @@ public sealed class VehicleVisualInstance { _shearedHardpoints.Add(bh.Spec.Id); _hasAnyStrippedCell = true; - if (bh.GearNode is not null && GodotObject.IsInstanceValid(bh.GearNode)) + if (bh.GearNode is not null && GodotObject.IsInstanceValid(bh.GearNode) && bh.GearMesh is not null) { + Transform3D worldXf = bh.GearNode.IsInsideTree() + ? bh.GearNode.GlobalTransform + : ComputeWorldTransformFallback(bh.GearNode); + ArrayMesh gearMesh = bh.GearMesh; Node3D sheared = bh.GearNode; bh.GearNode = null; + bh.GearMesh = null; + bh.GearTemplate = null; bh.MountedModuleId = null; - bh.GearHeatMaterials.Clear(); - sheared.Visible = true; - debris.SpawnDetachedPart(sheared, blastOrigin, vehicleVelocity, impulseScale: 1.15f, applyScorch: true); + bh.HeatGlow = 0f; + sheared.GetParent()?.RemoveChild(sheared); + sheared.QueueFree(); + debris.SpawnDetachedPart(gearMesh, worldXf, blastOrigin, vehicleVelocity, _roleIndex, impulseScale: 1.15f, applyScorch: true); } continue; } - if (bh.GearNode is null || bh.GearHeatMaterials.Count == 0) + if (bh.GearNode is null) { continue; } MountedModule? mounted = grid.GetMountedOn(bh.Spec.Id); - if (mounted is null) - { - continue; - } - - float heatFrac = Math.Clamp((mounted.CurrentTemp - 65f) / 115f, 0f, 1f); - for (int m = 0; m < bh.GearHeatMaterials.Count; m++) - { - StandardMaterial3D gm = bh.GearHeatMaterials[m]; - bool wantEmit = heatFrac > 0.02f; - if (gm.EmissionEnabled != wantEmit || wantEmit) - { - gm.EmissionEnabled = wantEmit; - if (wantEmit) - { - gm.Emission = new Color(1.0f, 0.34f, 0.08f); - gm.EmissionEnergyMultiplier = heatFrac * 2.2f; - } - } - } + bh.HeatGlow = mounted is not null + ? Math.Clamp((mounted.CurrentTemp - 65f) / 115f, 0f, 1f) + : 0f; } + if (t0 != 0) { PerfDamageHeatMs += (System.Diagnostics.Stopwatch.GetTimestamp() - t0) * 1000.0 / System.Diagnostics.Stopwatch.Frequency; } } - public static Node3D CreateStandaloneGearVisual(VehicleAssetCache cache, ModuleSpec mod) + public void SubmitToPool(MultiMeshPartPool pool) { - var list = new List(); - GearVisualRecipe recipe = ResolveGearRecipe(mod); - var template = cache.GetOrLoadGear(recipe.GearGlbId); - var node = new MeshInstance3D + if (!Root.Visible) { - Name = $"GearDrop_{mod.Id}", - Mesh = template.BakedDropMesh, - Scale = recipe.VariantScale, - Position = new Vector3(0f, -template.MinY * recipe.VariantScale.Y, 0f) - }; - if (recipe.PaintTint.HasValue || recipe.AccentTint.HasValue) - { - ApplyGearVariantTint(node, recipe.PaintTint, recipe.AccentTint, list); + return; + } + + Transform3D modelWorld = ModelRoot.IsInsideTree() ? ModelRoot.GlobalTransform : Root.Transform * ModelRoot.Transform; + + if (_role == VehicleVisualRole.SalvageDrop) + { + ArrayMesh dropMesh = _isStaticLod ? _template.SingleSurfaceLodFarMesh : _template.SingleSurfaceStaticMesh; + pool.Submit(dropMesh, in modelWorld, new Color(0f, 0f, _roleIndex, 1f), _castShadows); + return; + } + + if (_isStaticLod) + { + pool.Submit(_template.SingleSurfaceLodFarMesh, in modelWorld, new Color(_hullScorch, _hullHeatGlow, _roleIndex, 1f), _castShadows); + return; + } + + for (int i = 0; i < _staticParts.Count; i++) + { + var sp = _staticParts[i]; + if (!GodotObject.IsInstanceValid(sp.Pivot)) + { + continue; + } + Transform3D xf = ReferenceEquals(sp.Pivot, ModelRoot) + ? modelWorld + : (sp.Pivot.IsInsideTree() ? sp.Pivot.GlobalTransform : ComputeWorldTransformFallback(sp.Pivot)); + pool.Submit(sp.Mesh, in xf, new Color(_hullScorch, _hullHeatGlow, _roleIndex, 1f), _castShadows); + } + + for (int i = 0; i < _allCellParts.Count; i++) + { + var pb = _allCellParts[i]; + if (pb.Detached || !GodotObject.IsInstanceValid(pb.Pivot)) + { + continue; + } + Transform3D xf = ReferenceEquals(pb.Pivot, ModelRoot) + ? modelWorld + : (pb.Pivot.IsInsideTree() ? pb.Pivot.GlobalTransform : ComputeWorldTransformFallback(pb.Pivot)); + pool.Submit(pb.Mesh, in xf, new Color(pb.Scorch, pb.HeatGlow, _roleIndex, 1f), wantsShadow: false); + } + + for (int i = 0; i < _hardpointList.Count; i++) + { + var bh = _hardpointList[i]; + if (bh.GearNode is null || bh.GearMesh is null || !GodotObject.IsInstanceValid(bh.GearNode)) + { + continue; + } + Transform3D xf = bh.GearNode.IsInsideTree() ? bh.GearNode.GlobalTransform : ComputeWorldTransformFallback(bh.GearNode); + pool.Submit(bh.GearMesh, in xf, new Color(0f, bh.HeatGlow, _roleIndex, 1f), wantsShadow: false); } - return node; } - private Node3D InstantiateGearForHardpoint( + /// + /// Fast zero-allocation ray intersection against cached far-LOD triangles in space + /// so POM impact decals sit flush on sculpted armor surfaces without per-hit GPU mesh readbacks. + /// + public bool TryRayHitAttachedPart( + Vector3 rayOriginWorld, + Vector3 rayDirWorld, + out Node3D? hitPivot, + out Transform3D decalLocalToPivot, + float decalSize) + { + hitPivot = null; + decalLocalToPivot = Transform3D.Identity; + if (!Root.IsInsideTree() || !ModelRoot.IsInsideTree() || _template.FarRayTris.Length < 3) + { + return false; + } + + Transform3D modelXf = ModelRoot.GlobalTransform; + Transform3D inv = modelXf.AffineInverse(); + Vector3 locOrig = inv * rayOriginWorld; + Vector3 locDir = inv.Basis * rayDirWorld; + float dirLen = locDir.Length(); + if (dirLen < 1e-6f) + { + return false; + } + locDir /= dirLen; + + if (!RayIntersectsAabb(_template.FarRayAabb, locOrig, locDir)) + { + return false; + } + + Vector3[] tris = _template.FarRayTris; + float bestT = float.PositiveInfinity; + Vector3 bestLocalN = Vector3.Back; + + for (int t = 0; t + 2 < tris.Length; t += 3) + { + Vector3 v0 = tris[t]; + Vector3 v1 = tris[t + 1]; + Vector3 v2 = tris[t + 2]; + if (RayTriangle(locOrig, locDir, v0, v1, v2, out float hitT) && hitT < bestT) + { + Vector3 fn = (v1 - v0).Cross(v2 - v0); + if (fn.LengthSquared() > 1e-10f) + { + fn = fn.Normalized(); + if (fn.Dot(-locDir) < 0f) fn = -fn; + bestT = hitT; + bestLocalN = fn; + } + } + } + + if (!float.IsFinite(bestT)) + { + return false; + } + + Vector3 hitWorld = modelXf * (locOrig + locDir * bestT); + Vector3 normalWorld = (modelXf.Basis.Inverse().Transposed() * bestLocalN).Normalized(); + Vector3 upRef = MathF.Abs(normalWorld.Y) > 0.92f ? Vector3.Forward : Vector3.Up; + Vector3 right = upRef.Cross(normalWorld).Normalized(); + Vector3 up = normalWorld.Cross(right).Normalized(); + Transform3D worldDecalXf = new(new Basis(right * decalSize, up * decalSize, normalWorld), hitWorld); + + hitPivot = ModelRoot; + decalLocalToPivot = inv * worldDecalXf; + return true; + } + + private Node3D CreateGearPivotForHardpoint( ModuleSpec mod, HardpointSpec hp, VehicleAssetCache.GlbAnchorInfo anchorInfo, - List heatMaterialsOut) + out ArrayMesh gearMesh, + out VehicleAssetCache.GearTemplate gearTemplate) { GearVisualRecipe recipe = ResolveGearRecipe(mod); - VehicleAssetCache.GearTemplate gearTemplate = _cache.GetOrLoadGear(recipe.GearGlbId); - Node3D gearNode; - if (_role == VehicleVisualRole.Player) - { - if (gearTemplate.SceneTemplate.Duplicate() is not Node3D dup) - { - throw new InvalidOperationException($"Failed to duplicate gear GLB '{recipe.GearGlbId}'."); - } - gearNode = dup; - } - else - { - gearNode = new MeshInstance3D { Mesh = gearTemplate.BakedDropMesh }; - } - gearNode.Name = $"Mounted_{mod.Id}_{hp.Id}"; + gearTemplate = _cache.GetOrLoadGear(recipe.GearGlbId); + gearMesh = _cache.GetOrBuildGearVariantMesh(mod.Id, recipe.GearGlbId, recipe.PaintTint, recipe.AccentTint); + var gearNode = new Node3D { Name = $"Mounted_{mod.Id}_{hp.Id}" }; - // Compute outward socket normal & desired gear forward direction in vehicle/model space Basis anchorModelBasis = anchorInfo.ModelSpaceTransform.Basis.Orthonormalized(); Vector3 upOut = anchorModelBasis.Y.Normalized(); if (upOut.LengthSquared() < 1e-6f) upOut = Vector3.Up; @@ -609,8 +723,6 @@ public sealed class VehicleVisualInstance if (hp.Kind == HardpointKind.Weapon) { - // Special guard for forward-facing chin mounts (e.g. manticore hp.weapon.chin): - // drop the turret base under the chin (-Y) so the barrel points straight forward (+Z) instead of up into the nose. if (upOut.Z > 0.72f) { upOut = upOut.Y <= 0.1f ? new Vector3(0f, -1f, 0f) : new Vector3(0f, 1f, 0f); @@ -626,7 +738,6 @@ public sealed class VehicleVisualInstance } else { - // Non-weapon modules (radiator / engine / armor): align neatly to hull tangent plane if (MathF.Abs(upOut.Z) > 0.78f) { Vector3 upProj = Vector3.Up - upOut * Vector3.Up.Dot(upOut); @@ -639,20 +750,11 @@ public sealed class VehicleVisualInstance } } - // Right-handed basis: Y = upOut, Z = desiredGearFwd, X = Y x Z Vector3 rightX = upOut.Cross(desiredGearFwd); - if (rightX.LengthSquared() < 1e-5f) - { - rightX = Vector3.Right; - } - else - { - rightX = rightX.Normalized(); - } + rightX = rightX.LengthSquared() < 1e-5f ? Vector3.Right : rightX.Normalized(); desiredGearFwd = rightX.Cross(upOut).Normalized(); var desiredModelBasis = new Basis(rightX, upOut, desiredGearFwd); - // If the gear GLB's own forward points along -Z, rotate 180 deg around Y if (gearTemplate.LocalModelForward.Z < 0f) { desiredModelBasis *= new Basis(Vector3.Up, MathF.PI); @@ -660,7 +762,6 @@ public sealed class VehicleVisualInstance Basis localBasis = anchorModelBasis.Inverse() * desiredModelBasis; - // Fit cleanly to the socket's physical rtd.size float sx = MathF.Max(0.25f, anchorInfo.Size.X); float sy = MathF.Max(0.25f, anchorInfo.Size.Y); Vector3 fitScale; @@ -681,11 +782,8 @@ public sealed class VehicleVisualInstance } gearNode.Basis = localBasis * Basis.FromScale(fitScale); - // Seat gear minY right on the anchor collar origin (with slight downward offset if chin flipped) float ySeat = -gearTemplate.MinY * fitScale.Y; gearNode.Position = (anchorModelBasis.Inverse() * upOut) * ySeat; - - ApplyGearVariantTint(gearNode, recipe.PaintTint, recipe.AccentTint, heatMaterialsOut); return gearNode; } @@ -700,7 +798,6 @@ public sealed class VehicleVisualInstance "gilded_lance" => new("gilded_lance", Vector3.One, null, null), "gold_radiator" => new("gold_radiator", Vector3.One, null, null), - // Clean tint/scale variants from the 6 real gear GLBs "flak" => new("autocannon", new Vector3(1.12f, 0.92f, 0.68f), Color.FromHtml("#5a4a3f"), Color.FromHtml("#d96c27")), "pd_flak" => new("mg_762", new Vector3(1.22f, 1.10f, 0.85f), Color.FromHtml("#3d4440"), Color.FromHtml("#e08a4a")), "touring_plasma" => new("gilded_lance", new Vector3(1.05f, 0.96f, 0.72f), TouristIvory, Color.FromHtml("#38c9d8")), @@ -714,152 +811,6 @@ public sealed class VehicleVisualInstance }; } - private static void ApplyGearVariantTint( - Node cur, - Color? paintTint, - Color? accentTint, - List trackMaterials) - { - if (cur is MeshInstance3D mi && mi.Mesh is not null) - { - int surfCount = mi.Mesh.GetSurfaceCount(); - for (int s = 0; s < surfCount; s++) - { - Material? src = mi.GetActiveMaterial(s); - if (src is not StandardMaterial3D sm) - { - continue; - } - - var copy = (StandardMaterial3D)sm.Duplicate(); - string matName = (sm.ResourceName ?? string.Empty).ToLowerInvariant(); - if (accentTint.HasValue && (matName.Contains("copper") || matName.Contains("signal") || matName.Contains("cyan") || matName.Contains("gold"))) - { - copy.AlbedoColor = accentTint.Value; - } - else if (paintTint.HasValue && (matName.Contains("olive") || matName.Contains("ivory") || matName.Contains("armor"))) - { - copy.AlbedoColor = paintTint.Value; - } - - mi.SetSurfaceOverrideMaterial(s, copy); - if (!matName.Contains("rubber") && !matName.Contains("glass")) - { - trackMaterials.Add(copy); - } - } - } - - int count = cur.GetChildCount(); - for (int i = 0; i < count; i++) - { - ApplyGearVariantTint(cur.GetChild(i), paintTint, accentTint, trackMaterials); - } - } - - private static void ApplyRoleTint(Node root, VehicleVisualRole role) - { - var (armorColor, accentColor) = role switch - { - VehicleVisualRole.Rival => (RivalArmorColor, RivalAccentColor), - VehicleVisualRole.SpectatorTourist => (TouristGold, TouristIvory), - VehicleVisualRole.SpectatorPatron => (PatronTeal, PatronBronze), - VehicleVisualRole.SpectatorExemplar => (ExemplarObsidian, ExemplarCrimson), - VehicleVisualRole.SalvageDrop => (SalvageSteel, SalvageCyan), - _ => (RivalArmorColor, RivalAccentColor) - }; - - var clonedCache = new Dictionary(); - TintSubtreeRecursive(root, armorColor, accentColor, role, clonedCache); - } - - private static void TintSubtreeRecursive( - Node cur, - Color armorColor, - Color accentColor, - VehicleVisualRole role, - Dictionary clonedCache) - { - if (cur is MeshInstance3D mi && mi.Mesh is not null) - { - int surfCount = mi.Mesh.GetSurfaceCount(); - for (int s = 0; s < surfCount; s++) - { - if (mi.GetActiveMaterial(s) is not StandardMaterial3D sm) - { - continue; - } - - string mName = (sm.ResourceName ?? string.Empty).ToLowerInvariant(); - bool isPrimaryPaint = mName.Contains("olive") || mName.Contains("khaki"); - bool isAccentPaint = mName.Contains("signal") || mName.Contains("orange"); - if (!isPrimaryPaint && !isAccentPaint) - { - continue; - } - - if (!clonedCache.TryGetValue(sm, out var copy)) - { - copy = (StandardMaterial3D)sm.Duplicate(); - copy.AlbedoColor = isPrimaryPaint ? armorColor : accentColor; - if (role == VehicleVisualRole.SpectatorTourist && isPrimaryPaint) - { - copy.Metallic = 0.72f; - copy.Roughness = 0.30f; - } - else if (role == VehicleVisualRole.SpectatorExemplar && isAccentPaint) - { - copy.EmissionEnabled = true; - copy.Emission = ExemplarCrimson; - copy.EmissionEnergyMultiplier = 0.65f; - } - clonedCache[sm] = copy; - } - - mi.SetSurfaceOverrideMaterial(s, copy); - } - } - - int count = cur.GetChildCount(); - for (int i = 0; i < count; i++) - { - TintSubtreeRecursive(cur.GetChild(i), armorColor, accentColor, role, clonedCache); - } - } - - private static void ApplyCellDamageAndHeat(CellPartBinding binding, float dmgFrac, float heatGlow) - { - if (binding.Materials.Count == 0 && binding.Node.Mesh is not null) - { - int surfCount = binding.Node.Mesh.GetSurfaceCount(); - for (int s = 0; s < surfCount; s++) - { - Material? src = binding.Node.GetActiveMaterial(s); - StandardMaterial3D copy = src is StandardMaterial3D sm - ? (StandardMaterial3D)sm.Duplicate() - : new StandardMaterial3D { AlbedoColor = new Color(0.32f, 0.34f, 0.30f), Roughness = 0.6f, Metallic = 0.35f }; - PerfMaterialDupCount++; - binding.Node.SetSurfaceOverrideMaterial(s, copy); - binding.Materials.Add((copy, copy.AlbedoColor, copy.Roughness)); - } - } - - float scorch = Math.Clamp((dmgFrac - 0.25f) / 0.75f, 0f, 1f) * 0.65f; - for (int i = 0; i < binding.Materials.Count; i++) - { - var (mat, baseCol, baseRough) = binding.Materials[i]; - mat.AlbedoColor = new Color( - baseCol.R * (1f - scorch) + 0.05f * scorch, - baseCol.G * (1f - scorch) + 0.035f * scorch, - baseCol.B * (1f - scorch) + 0.03f * scorch, - baseCol.A); - mat.Roughness = MathF.Min(0.95f, baseRough + scorch * 0.35f); - mat.EmissionEnabled = heatGlow > 0.05f; - mat.Emission = new Color(1.0f, 0.32f, 0.08f); - mat.EmissionEnergyMultiplier = heatGlow * 1.4f; - } - } - private static Node3D? ResolveRelative(Node3D root, NodePath relPath) { if (relPath.IsEmpty) @@ -880,77 +831,179 @@ public sealed class VehicleVisualInstance } } + private Transform3D ComputeWorldTransformFallback(Node3D node) + { + Transform3D xf = Transform3D.Identity; + for (Node? cur = node; cur is Node3D n3d; cur = cur.GetParent()) + { + xf = n3d.Transform * xf; + if (ReferenceEquals(cur, Root)) + { + break; + } + } + return xf; + } + + private static Transform3D ComputeRelativeTransform(Node3D node, Node3D ancestor) + { + Transform3D xf = Transform3D.Identity; + for (Node? cur = node; cur is Node3D n3d && !ReferenceEquals(cur, ancestor); cur = cur.GetParent()) + { + xf = n3d.Transform * xf; + } + return xf; + } + /// - /// Computes the highest rendered vertex Y in local space across the hull + /// Computes the highest rendered vertex Y in local space across active rigid parts /// and all currently mounted gear meshes. /// public float ComputeMountedMaxY() { float maxY = float.NegativeInfinity; - AccumulateMaxYRecursive(ModelRoot, Transform3D.Identity, ref maxY, isRoot: true); - if (!float.IsFinite(maxY)) + if (_role == VehicleVisualRole.SalvageDrop) { - return ModelRoot.Position.Y + _template.MaxY * ModelRoot.Scale.Y; + ArrayMesh m = _isStaticLod ? _template.SingleSurfaceLodFarMesh : _template.SingleSurfaceStaticMesh; + AccumulateMeshMinMaxY(m, ModelRoot.Transform, out _, out maxY); + return float.IsFinite(maxY) ? maxY : ModelRoot.Position.Y + _template.MaxY * ModelRoot.Scale.Y; } - return maxY; + + for (int i = 0; i < _staticParts.Count; i++) + { + AccumulateMeshMinMaxY(_staticParts[i].Mesh, ComputeRelativeTransform(_staticParts[i].Pivot, Root), out _, out float pyMax); + if (pyMax > maxY) maxY = pyMax; + } + for (int i = 0; i < _allCellParts.Count; i++) + { + var pb = _allCellParts[i]; + if (!pb.Detached) + { + AccumulateMeshMinMaxY(pb.Mesh, ComputeRelativeTransform(pb.Pivot, Root), out _, out float cyMax); + if (cyMax > maxY) maxY = cyMax; + } + } + for (int i = 0; i < _hardpointList.Count; i++) + { + var bh = _hardpointList[i]; + if (bh.GearNode is not null && bh.GearMesh is not null && GodotObject.IsInstanceValid(bh.GearNode)) + { + AccumulateMeshMinMaxY(bh.GearMesh, ComputeRelativeTransform(bh.GearNode, Root), out _, out float gyMax); + if (gyMax > maxY) maxY = gyMax; + } + } + + return float.IsFinite(maxY) ? maxY : ModelRoot.Position.Y + _template.MaxY * ModelRoot.Scale.Y; } - private static void AccumulateMaxYRecursive(Node cur, Transform3D parentToRoot, ref float maxY, bool isRoot = false) + /// + /// Computes the lowest rendered vertex Y in world/parent space (or space if ). + /// + public float ComputeMinVertexY(float baseWorldY = 0f, bool relativeToModelRoot = false) { - Transform3D toRoot = parentToRoot; - if (cur is Node3D n3d) + float minY = float.PositiveInfinity; + Transform3D rootBase = relativeToModelRoot + ? Transform3D.Identity + : new Transform3D(Basis.Identity, new Vector3(0f, baseWorldY, 0f)) * Root.Transform; + + if (_role == VehicleVisualRole.SalvageDrop) { - if (!isRoot && !n3d.Visible) - { - return; - } - toRoot = parentToRoot * n3d.Transform; + ArrayMesh m = _isStaticLod ? _template.SingleSurfaceLodFarMesh : _template.SingleSurfaceStaticMesh; + Transform3D xf = relativeToModelRoot ? Transform3D.Identity : rootBase * ModelRoot.Transform; + AccumulateMeshMinMaxY(m, xf, out minY, out _); + return minY; } - if (cur is MeshInstance3D mi && mi.Mesh is { } mesh) - { - int surfCount = mesh.GetSurfaceCount(); - bool foundVerts = false; - for (int s = 0; s < surfCount; s++) - { - var arrays = mesh.SurfaceGetArrays(s); - if (arrays.Count > (int)Mesh.ArrayType.Vertex && - arrays[(int)Mesh.ArrayType.Vertex].VariantType == Variant.Type.PackedVector3Array) - { - Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array(); - for (int v = 0; v < verts.Length; v++) - { - float wy = (toRoot * verts[v]).Y; - if (wy > maxY) - { - maxY = wy; - } - } - foundVerts = true; - } - } - if (!foundVerts) - { - Aabb aabb = mesh.GetAabb(); - for (int c = 0; c < 8; c++) - { - Vector3 corner = aabb.Position + new Vector3( - (c & 1) != 0 ? aabb.Size.X : 0f, - (c & 2) != 0 ? aabb.Size.Y : 0f, - (c & 4) != 0 ? aabb.Size.Z : 0f); - float wy = (toRoot * corner).Y; - if (wy > maxY) - { - maxY = wy; - } - } - } - } + Node3D relTarget = relativeToModelRoot ? ModelRoot : Root; + Transform3D baseXf = relativeToModelRoot ? Transform3D.Identity : rootBase; - int childCount = cur.GetChildCount(); - for (int i = 0; i < childCount; i++) + for (int i = 0; i < _staticParts.Count; i++) { - AccumulateMaxYRecursive(cur.GetChild(i), toRoot, ref maxY); + Transform3D xf = baseXf * ComputeRelativeTransform(_staticParts[i].Pivot, relTarget); + AccumulateMeshMinMaxY(_staticParts[i].Mesh, xf, out float pyMin, out _); + if (pyMin < minY) minY = pyMin; } + for (int i = 0; i < _allCellParts.Count; i++) + { + var pb = _allCellParts[i]; + if (!pb.Detached) + { + Transform3D xf = baseXf * ComputeRelativeTransform(pb.Pivot, relTarget); + AccumulateMeshMinMaxY(pb.Mesh, xf, out float cyMin, out _); + if (cyMin < minY) minY = cyMin; + } + } + return minY; + } + + private static void AccumulateMeshMinMaxY(ArrayMesh mesh, Transform3D xform, out float minY, out float maxY) + { + minY = float.PositiveInfinity; + maxY = float.NegativeInfinity; + int surfCount = mesh.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + var arrays = mesh.SurfaceGetArrays(s); + if (arrays.Count <= (int)Mesh.ArrayType.Vertex || + arrays[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) + { + continue; + } + Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + for (int v = 0; v < verts.Length; v++) + { + float wy = (xform * verts[v]).Y; + if (wy < minY) minY = wy; + if (wy > maxY) maxY = wy; + } + } + } + + private static bool RayIntersectsAabb(Aabb aabb, Vector3 orig, Vector3 dir) + { + Vector3 min = aabb.Position; + Vector3 max = aabb.End; + float tmin = float.NegativeInfinity; + float tmax = float.PositiveInfinity; + + for (int axis = 0; axis < 3; axis++) + { + float o = orig[axis]; + float d = dir[axis]; + if (MathF.Abs(d) < 1e-7f) + { + if (o < min[axis] || o > max[axis]) return false; + } + else + { + float inv = 1f / d; + float t1 = (min[axis] - o) * inv; + float t2 = (max[axis] - o) * inv; + if (t1 > t2) (t1, t2) = (t2, t1); + tmin = MathF.Max(tmin, t1); + tmax = MathF.Min(tmax, t2); + if (tmin > tmax) return false; + } + } + return tmax >= 0f; + } + + private static bool RayTriangle(Vector3 orig, Vector3 dir, Vector3 v0, Vector3 v1, Vector3 v2, out float t) + { + t = 0f; + Vector3 e1 = v1 - v0; + Vector3 e2 = v2 - v0; + Vector3 pvec = dir.Cross(e2); + float det = e1.Dot(pvec); + if (MathF.Abs(det) < 1e-7f) return false; + float invDet = 1f / det; + Vector3 tvec = orig - v0; + float u = tvec.Dot(pvec) * invDet; + if (u < 0f || u > 1f) return false; + Vector3 qvec = tvec.Cross(e1); + float v = dir.Dot(qvec) * invDet; + if (v < 0f || u + v > 1f) return false; + t = e2.Dot(qvec) * invDet; + return t > 0.01f; } } diff --git a/client/mech_paint.gdshader b/client/mech_paint.gdshader index 9fdd554..e8450a8 100644 --- a/client/mech_paint.gdshader +++ b/client/mech_paint.gdshader @@ -44,12 +44,16 @@ uniform float wet_top : hint_range(0.1, 6.0) = 2.80; uniform float scorch : hint_range(0.0, 1.0) = 0.0; uniform float heat_glow : hint_range(0.0, 1.0) = 0.0; uniform float heat_emission_energy : hint_range(0.0, 8.0) = 2.6; +uniform bool use_vertex_material = false; varying vec3 v_local_pos; varying vec3 v_local_nrm; varying vec4 v_color; +varying vec4 v_mat_data; varying float v_scorch; varying float v_heat; +varying float v_role; +varying float v_alpha; // Safe remapping helper supporting inverted bounds (lo > hi) without GLSL smoothstep UB. float map_range(float v, float lo, float hi, float out_lo, float out_hi) { @@ -120,11 +124,80 @@ void vertex() { v_local_pos = VERTEX; v_local_nrm = NORMAL; v_color = COLOR; + v_mat_data = vec4(UV.x, UV.y, UV2.x, UV2.y); v_scorch = clamp(max(INSTANCE_CUSTOM.x, scorch), 0.0, 1.0); v_heat = clamp(max(INSTANCE_CUSTOM.y, heat_glow), 0.0, 1.0); + v_role = INSTANCE_CUSTOM.z; + v_alpha = use_vertex_material ? clamp(INSTANCE_CUSTOM.w, 0.0, 1.0) : 1.0; +} + +void resolve_role_armor(int role, out vec3 col, out float met, out float rgh) { + if (role == 1) { + col = vec3(0.109, 0.074, 0.054); met = 0.26; rgh = 0.58; // Rival (#5d4d42) + } else if (role == 2) { + col = vec3(0.791, 0.479, 0.039); met = 0.72; rgh = 0.30; // SpectatorTourist (#e6b838) + } else if (role == 3) { + col = vec3(0.026, 0.195, 0.188); met = 0.32; rgh = 0.50; // SpectatorPatron (#2d7a78) + } else if (role == 4) { + col = vec3(0.011, 0.011, 0.016); met = 0.45; rgh = 0.42; // SpectatorExemplar (#1b1b22) + } else if (role == 5) { + col = vec3(0.089, 0.105, 0.107); met = 0.55; rgh = 0.48; // SalvageDrop (#545b5c) + } else { + col = vec3(0.076, 0.095, 0.051); met = 0.28; rgh = 0.58; // Player (#4e5740) + } +} + +void resolve_role_accent(int role, out vec3 col, out float met, out float rgh, out float emit_e) { + emit_e = 0.0; + if (role == 1) { + col = vec3(0.468, 0.068, 0.032); met = 0.20; rgh = 0.46; // Rival (#b64a32) + } else if (role == 2) { + col = vec3(0.896, 0.823, 0.687); met = 0.16; rgh = 0.38; // SpectatorTourist (#f2ead8) + } else if (role == 3) { + col = vec3(0.392, 0.147, 0.037); met = 0.65; rgh = 0.36; // SpectatorPatron (#a86c36) + } else if (role == 4) { + col = vec3(0.584, 0.023, 0.023); met = 0.25; rgh = 0.36; emit_e = 0.65; // SpectatorExemplar (#c92a2a) + } else if (role == 5) { + col = vec3(0.058, 0.694, 0.807); met = 0.22; rgh = 0.34; emit_e = 0.45; // SalvageDrop (#44d9e8) + } else { + col = vec3(0.694, 0.150, 0.020); met = 0.18; rgh = 0.44; // Player (#d96c27) + } } void fragment() { + vec3 mat_base_col = base_color.rgb; + float mat_rough = roughness; + float mat_metal = metallic; + float mat_wear = wear; + float mat_mud = mud; + float mat_static_emit = 0.0; + if (use_vertex_material) { + int band = int(floor((v_mat_data.w + 0.5) * 0.5)); + mat_rough = clamp(v_mat_data.w - float(band) * 2.0, 0.08, 0.95); + mat_base_col = clamp(v_mat_data.rgb, vec3(0.0), vec3(1.0)); + int role = int(floor(v_role + 0.5)); + if (band == 0) { + mat_metal = 0.12; + } else if (band == 1) { + mat_metal = 0.55; + } else if (band == 2) { + mat_metal = 0.85; + } else if (band == 3) { + resolve_role_armor(role, mat_base_col, mat_metal, mat_rough); + } else if (band == 4) { + resolve_role_accent(role, mat_base_col, mat_metal, mat_rough, mat_static_emit); + } else if (band == 5) { + mat_metal = 0.15; + mat_static_emit = 1.85; + mat_wear = 0.0; + mat_mud = 0.0; + } else if (band == 6) { + mat_metal = 0.26; + } else { + mat_metal = 0.65; + } + } + vec3 pos = v_local_pos * noise_scale; vec3 nrm = normalize(v_local_nrm); float up = nrm.y; @@ -134,85 +207,97 @@ void fragment() { float island_rand = clamp(v_color.b, 0.0, 1.0); float height_m = clamp(v_color.a, 0.0, 1.0) * 6.0; - // Layer 1: Base paint + per-island tone variation + 2-octave 3D object-space mottle + // Shared rotated multi-scale 3D noise basis (5 lookups total vs 352 hashes across 6 layers) + const mat3 rot = mat3( + vec3(0.80, -0.48, 0.36), + vec3(0.60, 0.64, -0.48), + vec3(0.00, 0.60, 0.80) + ); + vec3 rpos = rot * pos; + float n_macro = noise3d(pos * 0.85); + float n_mid = noise3d(rpos * 3.8 + vec3(17.3, 9.1, 23.7)); + float n_fine = noise3d(pos * 10.5 + vec3(5.7, 31.4, 11.2)); + float n_speck = noise3d(rpos * 27.0 + vec3(11.1, 3.7, 19.4)); + float n_streak = noise3d(pos * vec3(13.0, 0.5, 13.0)); + + // Layer 1: Base paint + per-island tone variation + multi-octave mottle float rand2 = fract(island_rand * 7.31 + 0.37); - vec3 hsv = rgb_to_hsv(base_color.rgb); + vec3 hsv = rgb_to_hsv(mat_base_col); hsv.x = fract(hsv.x + (rand2 - 0.5) * tone_variation * 0.14); hsv.y = clamp(hsv.y * (1.0 + (rand2 - 0.5) * tone_variation * 0.75), 0.0, 1.0); hsv.z = clamp(hsv.z * (1.0 + (island_rand * 2.0 - 1.0) * tone_variation * 0.65), 0.01, 2.0); vec3 col = hsv_to_rgb(hsv); - float blotch = fbm2(pos * 0.75); - float speck = fbm2(pos * 26.0); - float mid_n = fbm2(pos * 4.5); + float blotch = n_macro * 0.70 + n_mid * 0.30; + float mid_n = n_mid * 0.68 + n_fine * 0.32; float shade = map_range(blotch, 0.25, 0.75, -0.14, 0.14) - + map_range(speck, 0.25, 0.75, -0.07, 0.07) + + map_range(n_speck, 0.25, 0.75, -0.07, 0.07) + map_range(mid_n, 0.25, 0.75, -0.09, 0.09); col *= clamp(1.0 + shade * mottle, 0.55, 1.35); // Layer 2: Cavity grime darkening + roughness boost from (1 - AO) - float cavity = clamp(map_range(occ, 0.90, 0.42, 0.0, 1.0) * map_range(fbm2(pos * 5.0), 0.30, 0.65, 0.45, 1.0) * grime, 0.0, 1.0); - float film = clamp(map_range(fbm2(pos * 2.1), 0.54, 0.72, 0.0, 1.0) * 0.30 * grime, 0.0, 1.0); + float cavity = clamp(map_range(occ, 0.90, 0.42, 0.0, 1.0) * map_range(mid_n, 0.30, 0.65, 0.45, 1.0) * grime, 0.0, 1.0); + float film = clamp(map_range(n_macro * 0.5 + n_mid * 0.5, 0.54, 0.72, 0.0, 1.0) * 0.30 * grime, 0.0, 1.0); float grime_amt = max(cavity, film); col = mix(col, grime_color.rgb, min(grime_amt, 0.85)); // Layer 3: Vertical rain/oil streaks on upright surfaces boosted by cavity - vec3 stretch = pos * vec3(13.0, 0.5, 13.0); float upright = map_range(abs(up), 0.80, 0.35, 0.0, 1.0); float under = map_range(occ, 0.96, 0.65, 0.40, 1.0); - float broken = map_range(noise3d(pos * 1.4), 0.35, 0.55, 0.15, 1.0); - float dark_run = clamp(map_range(fbm2(stretch), 0.52, 0.68, 0.0, 1.0) * upright * under * broken * streaks, 0.0, 1.0); - float pale_run = clamp(map_range(fbm2(stretch + vec3(31.0, 5.0, 17.0)), 0.62, 0.76, 0.0, 1.0) * upright * 0.28 * streaks, 0.0, 1.0); + float broken = map_range(n_macro, 0.35, 0.55, 0.15, 1.0); + float streak_mix = n_streak * 0.72 + n_fine * 0.28; + float dark_run = clamp(map_range(streak_mix, 0.52, 0.68, 0.0, 1.0) * upright * under * broken * streaks, 0.0, 1.0); + float pale_run = clamp(map_range(1.0 - streak_mix, 0.62, 0.76, 0.0, 1.0) * upright * 0.28 * streaks, 0.0, 1.0); col = mix(col, dust_color.rgb, pale_run); col = mix(col, grime_color.rgb, dark_run * 0.85); // Layer 4: Pale dust on upward-facing normals (v_local_nrm.y) - float dust_amt = clamp(map_range(up, 0.45, 0.95, 0.0, 1.0) * map_range(fbm2(pos * 3.0), 0.25, 0.70, 0.25, 1.0) * dust * 0.55, 0.0, 1.0); + float dust_amt = clamp(map_range(up, 0.45, 0.95, 0.0, 1.0) * map_range(mid_n, 0.25, 0.70, 0.25, 1.0) * dust * 0.55, 0.0, 1.0); col = mix(col, dust_color.rgb, dust_amt); // Layer 5: Metallic edge chipping + thin primer_color halo from edge_curvature * noise float exposed = map_range(occ, 0.42, 0.88, 0.0, 1.0); float edge_sharp = pow(edge, 1.85); - float chip_n = map_range(fbm2(pos * 6.5), 0.30, 0.72, 0.0, 0.44) - + map_range(noise3d(pos * 46.0), 0.30, 0.70, -0.06, 0.06); - float wear_level = chip_n + edge_sharp * exposed * wear * 0.56; - float scuff = map_range(fbm2(pos * 4.5), 0.68, 0.72, 0.0, 1.0) * clamp(wear / 1.8, 0.0, 1.0) * 0.55; + float chip_n = map_range(n_mid * 0.6 + n_fine * 0.4, 0.30, 0.72, 0.0, 0.44) + + map_range(n_speck, 0.30, 0.70, -0.06, 0.06); + float wear_level = chip_n + edge_sharp * exposed * mat_wear * 0.56; + float scuff = map_range(mid_n, 0.68, 0.72, 0.0, 1.0) * clamp(mat_wear / 1.8, 0.0, 1.0) * 0.55; float chip_metal_mask = clamp(max(map_range(wear_level, 0.76, 0.80, 0.0, 1.0), scuff * 0.85), 0.0, 1.0); float primer_mask = clamp(max(map_range(wear_level, 0.71, 0.75, 0.0, 1.0), scuff), 0.0, 1.0); col = mix(col, primer_color.rgb, primer_mask * 0.75); col = mix(col, chip_color.rgb, chip_metal_mask); // Layer 6: Lower-hull/foot mud & wet gloss driven by rest_height (COLOR.a) - float wet_amt = clamp(map_range(height_m, wet_top, 0.0, 0.0, 1.0) * wet, 0.0, 1.0); + float wet_amt = clamp(map_range(height_m, wet_top, 0.0, 0.0, 1.0) * wet * clamp(mat_mud, 0.0, 1.0), 0.0, 1.0); col *= (1.0 - 0.50 * wet_amt); - float mud_n = fbm2(pos * 3.2); + float mud_n = n_macro * 0.35 + n_mid * 0.65; float thick = map_range(height_m, mud_top, 0.0, 0.0, 1.0) * map_range(mud_n, 0.35, 0.62, 0.1, 1.5) - * map_range(occ, 0.95, 0.50, 0.7, 1.6) * mud; - float splash = map_range(fbm2(pos * 11.0), 0.62, 0.66, 0.0, 1.0) - * map_range(height_m, mud_top * 2.2, mud_top * 0.4, 0.0, 1.0) * mud * 0.85; + * map_range(occ, 0.95, 0.50, 0.7, 1.6) * mat_mud; + float splash = map_range(n_fine, 0.62, 0.66, 0.0, 1.0) + * map_range(height_m, mud_top * 2.2, mud_top * 0.4, 0.0, 1.0) * mat_mud * 0.85; float mud_amt = clamp(max(map_range(thick, 0.20, 0.50, 0.0, 1.0), splash), 0.0, 1.0); col = mix(col, mud_color.rgb * map_range(mud_n, 0.30, 0.70, 0.70, 1.30), mud_amt); // PBR metallic & roughness synthesis - float out_metallic = mix(metallic, chip_metallic, chip_metal_mask); + float out_metallic = mix(mat_metal, chip_metallic, chip_metal_mask); out_metallic *= (1.0 - mud_amt) * (1.0 - grime_amt * 0.70); - float out_rough = roughness + grime_amt * 0.22 + (1.0 - occ) * 0.12 * clamp(grime, 0.0, 1.0); + float out_rough = mat_rough + grime_amt * 0.22 + (1.0 - occ) * 0.12 * clamp(grime, 0.0, 1.0); out_rough = mix(out_rough, chip_roughness, chip_metal_mask); out_rough -= wet_amt * 0.18; out_rough += mud_amt * 0.18; out_rough = clamp(out_rough, 0.12, 0.98); // Live combat channel 1: scorch (char/soot darkening + matte roughness) - float soot_pat = mix(0.65, 1.0, fbm2(pos * 4.5)); + float soot_pat = mix(0.65, 1.0, mid_n); float scorch_mask = clamp(v_scorch * soot_pat, 0.0, 1.0); col = mix(col, vec3(0.022, 0.018, 0.016), scorch_mask * 0.88); out_metallic *= (1.0 - scorch_mask * 0.75); out_rough = mix(out_rough, 0.94, scorch_mask); // Live combat channel 2: heat_glow (incandescent orange-red emission without cloning material) - float heat_mod = mix(0.25, 1.15, pow(edge, 1.4) * 0.6 + fbm2(pos * 3.8) * 0.4); + float heat_mod = mix(0.25, 1.15, pow(edge, 1.4) * 0.6 + mid_n * 0.4); float h_val = clamp(v_heat * heat_mod, 0.0, 1.0); vec3 heat_col = mix(vec3(0.85, 0.12, 0.01), vec3(1.0, 0.52, 0.10), smoothstep(0.25, 0.95, h_val)); @@ -221,5 +306,5 @@ void fragment() { ROUGHNESS = out_rough; AO = mix(1.0, occ, 0.65); AO_LIGHT_AFFECT = 0.65; - EMISSION = heat_col * (pow(v_heat, 1.35) * heat_mod * heat_emission_energy); + EMISSION = mat_base_col * mat_static_emit + heat_col * (pow(v_heat, 1.35) * heat_mod * heat_emission_energy); } diff --git a/client/tests/Smoke.cs b/client/tests/Smoke.cs index 6d0076f..9a20975 100644 --- a/client/tests/Smoke.cs +++ b/client/tests/Smoke.cs @@ -314,14 +314,6 @@ public partial class Smoke : Node Check(mappedHp is { Id: "hp.weapon.main" }, $"Expected GetHardpointAt(1,1) to return hp.weapon.main, got {mappedHp?.Id ?? "null"}"); - // Toggle thermal mode off -> on -> off - _main.Hud.SetThermalMode(true, instant: true); - Check(_main.Hud.ThermalMode && MathF.Abs(schematic.ThermalBlend - 1f) < 0.01f, - "Expected ThermalMode to activate immediately"); - _main.Hud.SetThermalMode(false, instant: true); - Check(!_main.Hud.ThermalMode && MathF.Abs(schematic.ThermalBlend) < 0.01f, - "Expected ThermalMode to deactivate immediately"); - // Regression check (Finding 3): same-dimension SwapChassis updates _hardpointLookup and clears hover state schematic._GuiInput(new InputEventMouseMotion { Position = probePos }); Check(schematic.HoveredCell == new Vector2I(1, 1) && schematic.HoveredHardpoint is { Id: "hp.weapon.main" }, @@ -383,7 +375,7 @@ public partial class Smoke : Node return; } - // GPU verification on OpenGL 3.3: render isolated InventoryGridControl (tactical + thermal) & panel_chrome.gdshader + // GPU verification on OpenGL 3.3: render isolated InventoryGridControl (ambient vs live bilinear heat) & panel_chrome.gdshader var gridVp = new SubViewport { Size = new Vector2I(240, 240), @@ -398,36 +390,42 @@ public partial class Smoke : Node gridVp.AddChild(vpGrid); AddChild(gridVp); + var coolGrid = new ChassisGrid(Catalog.Ironclad); + coolGrid.TryMount(Catalog.Recoilless, "hp.weapon.main"); + coolGrid.TryMount(Catalog.Mg762, "hp.weapon.coax"); + coolGrid.TryMount(Catalog.TurboCore, "hp.engine.rear"); + coolGrid.TryMount(Catalog.CopperRad, "hp.radiator.l"); + coolGrid.TryMount(Catalog.WeldedPlate, "hp.armor.front"); + coolGrid.Armor[0, 0] = 0f; + + vpGrid.SetGrid(coolGrid); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var coolImg = gridVp.GetTexture().GetImage(); + int coolOpaque = CountNonZeroAlphaPixels(coolImg, 0.08f); + GD.Print($"SMOKE INFO: InventoryGrid GPU cool opaque pixels={coolOpaque}"); + Check(coolOpaque > 4000, $"Expected > 4000 rendered pixels from InventoryGrid shader, got {coolOpaque}"); + vpGrid.SetGrid(testGrid); vpGrid.TriggerHitPulse(1, 1, 1f); - vpGrid.SetThermalInstant(false); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); - var tacticalImg = gridVp.GetTexture().GetImage(); - int tacticalOpaque = CountNonZeroAlphaPixels(tacticalImg, 0.08f); - GD.Print($"SMOKE INFO: InventoryGrid GPU tactical opaque pixels={tacticalOpaque}"); - Check(tacticalOpaque > 4000, $"Expected > 4000 rendered pixels from InventoryGrid tactical shader, got {tacticalOpaque}"); + var hotImg = gridVp.GetTexture().GetImage(); + int hotOpaque = CountNonZeroAlphaPixels(hotImg, 0.08f); + int heatDiff = CountDifferentPixels(coolImg, hotImg, 0.05f); + GD.Print($"SMOKE INFO: InventoryGrid GPU hot opaque={hotOpaque}, diff vs cool={heatDiff}"); + Check(hotOpaque > 4000, $"Expected > 4000 rendered pixels from heated InventoryGrid shader, got {hotOpaque}"); + Check(heatDiff > 400, $"Expected always-active temp_tex + hit pulse to visibly change > 400 pixels, got {heatDiff}"); - vpGrid.SetThermalInstant(true); - await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); - await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); - - var thermalImg = gridVp.GetTexture().GetImage(); - int thermalOpaque = CountNonZeroAlphaPixels(thermalImg, 0.08f); - int modeDiff = CountDifferentPixels(tacticalImg, thermalImg, 0.05f); - GD.Print($"SMOKE INFO: InventoryGrid GPU thermal opaque={thermalOpaque}, diff vs tactical={modeDiff}"); - Check(thermalOpaque > 4000, $"Expected > 4000 rendered pixels from InventoryGrid thermal shader, got {thermalOpaque}"); - Check(modeDiff > 500, $"Expected thermal conduit toggle to visibly change > 500 pixels, got {modeDiff}"); - - // Finding 2 GPU check: overheated (350C+, thermal_mode = 1.0f) must obey blend_premul_alpha (out_rgb <= out_a) + // Finding 2 GPU check: overheated (350C..550C+) must obey blend_premul_alpha (out_rgb <= out_a) testGrid.InjectHardpointHeat("hp.engine.rear", 45000f); testGrid.InjectHardpointHeat("hp.weapon.main", 25000f); testGrid.StepHeat(0.05f); float hotTemp = testGrid.Temperature[1, 3]; Check(hotTemp >= 350f, $"Expected overheated cell >= 350C for premul test, got {hotTemp:F1}C"); vpGrid.SetGrid(testGrid); - vpGrid.SetThermalInstant(true); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); @@ -436,7 +434,7 @@ public partial class Smoke : Node GD.Print($"SMOKE INFO: InventoryGrid GPU overheat ({hotTemp:F1}C) premul violations={premulViolations}"); Check(premulViolations == 0, $"Expected 0 blend_premul_alpha violations (max(RGB) > A + 0.01) on overheated grid, got {premulViolations}"); - // Finding 1 GPU check: asymmetric Raptor chassis with thermal_mode = 1.0f must leave 0 lit pixels in inactive cell holes + // Finding 1 GPU check: asymmetric heated Raptor chassis must leave 0 lit pixels in inactive cell holes var raptorGrid = new ChassisGrid(Catalog.Raptor); Check(raptorGrid.TryMount(Catalog.CopperRad, "hp.radiator.sh_l"), "Expected CopperRad on Raptor hp.radiator.sh_l"); Check(raptorGrid.TryMount(Catalog.CopperRad, "hp.radiator.sh_r"), "Expected CopperRad on Raptor hp.radiator.sh_r"); @@ -447,7 +445,6 @@ public partial class Smoke : Node raptorGrid.StepHeat(0.25f); vpGrid.SetGrid(raptorGrid); - vpGrid.SetThermalInstant(true); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); @@ -480,7 +477,6 @@ public partial class Smoke : Node raptorGrid.Cargo.Clear(); Check(raptorGrid.TryAddCargo(Catalog.Autocannon), "Expected Autocannon in Raptor Cargo[0]"); vpGrid.SetGrid(raptorGrid, selectedCargoIndex: 0); - vpGrid.SetThermalInstant(false); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); @@ -650,6 +646,8 @@ public partial class Smoke : Node if (pkg is null) continue; var vis = VehicleVisualInstance.Create(cache, spec.Id, VehicleVisualRole.Player); + Check(CountMeshInstances(vis.Root) == 0, + $"Expected zero MeshInstance3D children on MultiMesh rig '{spec.Id}', got {CountMeshInstances(vis.Root)}"); Check(vis.BoundHardpointCount == spec.Hardpoints.Length, $"Expected {spec.Hardpoints.Length} bound hardpoints on '{spec.Id}', got {vis.BoundHardpointCount}"); Check(vis.Joints.Count == pkg.Joints.Count, @@ -663,7 +661,7 @@ public partial class Smoke : Node foreach (var m in grid.Mounted) { var gNode = vis.GetMountedGearNode(m.HardpointId); - if (gNode is not null && CountMeshInstances(gNode) > 0) + if (gNode is not null) { mountedMeshes++; if (m.Spec.Kind == HardpointKind.Weapon) @@ -675,18 +673,18 @@ public partial class Smoke : Node "recoilless" => ("sight_tube", "breech_band"), _ => ("condenser_ring_2", "ivory_cowl") }; - Vector3? frontC = ComputeSubtreeVertexCentroidInAncestor(gNode, vis.ModelRoot, frontPart); - Vector3? rearC = ComputeSubtreeVertexCentroidInAncestor(gNode, vis.ModelRoot, rearPart); - Check(frontC.HasValue && rearC.HasValue, + bool hasCentroids = vis.TryGetMountedWeaponCentroidsInModel( + m.HardpointId, frontPart, rearPart, out Vector3 frontC, out Vector3 rearC); + Check(hasCentroids, $"Missing weapon submeshes '{frontPart}'/'{rearPart}' on '{spec.Id}.{m.HardpointId}' ({m.Spec.Id})"); - if (frontC.HasValue && rearC.HasValue) + if (hasCentroids) { - Vector3 muzzleDir = (frontC.Value - rearC.Value).Normalized(); + Vector3 muzzleDir = (frontC - rearC).Normalized(); if (m.Spec.Id == "recoilless") { - GD.Print($"SMOKE INFO: recoilless {spec.Id}.{m.HardpointId} sight_tube={frontC.Value} breech={rearC.Value} dir={muzzleDir}"); - Check(frontC.Value.Z > rearC.Value.Z + 0.20f, - $"Expected recoilless sight_tube (+Z) ahead of breech_band on '{spec.Id}.{m.HardpointId}', got sight={frontC.Value}, breech={rearC.Value}"); + GD.Print($"SMOKE INFO: recoilless {spec.Id}.{m.HardpointId} sight_tube={frontC} breech={rearC} dir={muzzleDir}"); + Check(frontC.Z > rearC.Z + 0.20f, + $"Expected recoilless sight_tube (+Z) ahead of breech_band on '{spec.Id}.{m.HardpointId}', got sight={frontC}, breech={rearC}"); } Check(muzzleDir.Z > 0.75f, $"Expected weapon '{m.Spec.Id}' on '{spec.Id}.{m.HardpointId}' mesh geometry to point forward (+Z), got dir={muzzleDir}"); @@ -800,15 +798,15 @@ public partial class Smoke : Node Check(anvilVis.GetMountedGearNode("hp.weapon.siege_l") is null, "Expected hp.weapon.siege_l gear to shear off when hardpoint becomes non-operational"); - if (debris.GetChildCount() > 0 && debris.GetChild(0) is Node3D firstPiece) + if (debris.TryGetPiecePosition(0, out Vector3 p0)) { - Vector3 p0 = firstPiece.Position; for (int s = 0; s < 25; s++) { debris.Step(1f / 60f, _main.Session.State.Terrain); } - float moved = firstPiece.Position.DistanceTo(p0); - Check(moved > 0.1f && !HasNaN(firstPiece.Transform), + debris.TryGetPiecePosition(0, out Vector3 p1); + float moved = p1.DistanceTo(p0); + Check(moved > 0.1f && p1.IsFinite(), $"Expected debris piece to travel/fall > 0.1m under blast + gravity, got {moved:F3}m"); } @@ -848,12 +846,11 @@ public partial class Smoke : Node debris.QueueFree(); } - // 5. All 15 ChassisDrop salvage wrecks ground within 0.05m of terrain & PickedUp frees drop nodes cleanly + // 5. All 15 ChassisDrop salvage wrecks ground within 0.05m of terrain & PickedUp frees drops cleanly { var drops = _main.Session.State.GroundDrops; int baseCount = drops.Count; _main.Arena.Sync(_main.Session, 1.0f, 1f / 60f); - int dropNodesBefore = _main.Arena.DropGroupChildCount; int trackedBefore = _main.Arena.ActiveDropVisualCount; int nextId = 90000; @@ -876,37 +873,30 @@ public partial class Smoke : Node for (int i = 0; i < added.Count; i++) { var d = added[i]; - Node3D? dropNode = _main.Arena.GetNodeOrNull($"GroundDrops/Drop_{d.Id}"); - Check(dropNode is not null, $"Missing Drop_{d.Id} node for ChassisDrop '{d.Chassis!.Id}'"); - if (dropNode is not null) + bool hasDrop = _main.Arena.TryGetChassisDropVisual(d.Id, out var dropVis, out _); + Check(hasDrop && dropVis is not null, $"Missing ChassisDrop visual for Drop_{d.Id} ('{d.Chassis!.Id}')"); + if (hasDrop && dropVis is not null) { - Node3D? actorNode = dropNode.GetNodeOrNull($"Actor_{d.Chassis!.Id}"); - Check(actorNode is not null, $"Missing Actor_{d.Chassis!.Id} under Drop_{d.Id}"); - if (actorNode is not null) - { - float minWorldY = ComputeSubtreeMinWorldY(actorNode, dropNode.Position.Y); - float terrainY = _main.Session.State.Terrain.SampleHeight(d.X, d.Z); - float err = MathF.Abs(minWorldY - terrainY); - if (err > maxGroundErr) maxGroundErr = err; - Check(err <= 0.05f, - $"ChassisDrop '{d.Chassis!.Id}' buried/floating: minWorldY={minWorldY:F4}m terrainY={terrainY:F4}m err={err:F4}m"); - } + dropVis.SetLodState(useStaticLod: false, castShadows: false); + float minWorldY = dropVis.ComputeMinVertexY(); + float terrainY = _main.Session.State.Terrain.SampleHeight(d.X, d.Z); + float err = MathF.Abs(minWorldY - terrainY); + if (err > maxGroundErr) maxGroundErr = err; + Check(err <= 0.05f, + $"ChassisDrop '{d.Chassis!.Id}' buried/floating: minWorldY={minWorldY:F4}m terrainY={terrainY:F4}m err={err:F4}m"); } } GD.Print($"SMOKE INFO: ChassisDrop max ground err={maxGroundErr:F4}m across {added.Count} chassis"); - // Also verify far LOD (BakedLodFarMesh) ChassisDrop grounding stays <= 0.05m across all 15 chassis + // Also verify far LOD (SingleSurfaceLodFarMesh) ChassisDrop grounding stays <= 0.05m across all 15 chassis float maxFarGroundErr = 0f; for (int i = 0; i < added.Count; i++) { var d = added[i]; - Node3D? dropNode = _main.Arena.GetNodeOrNull($"GroundDrops/Drop_{d.Id}"); - Node3D? actorNode = dropNode?.GetNodeOrNull($"Actor_{d.Chassis!.Id}"); - MeshInstance3D? dropMesh = actorNode?.GetNodeOrNull($"Model_{d.Chassis!.Id}"); - if (dropNode is not null && actorNode is not null && dropMesh is not null) + if (_main.Arena.TryGetChassisDropVisual(d.Id, out var dropVis, out _) && dropVis is not null) { - dropMesh.Mesh = cache.GetOrLoadVehicle(d.Chassis!.Id).BakedLodFarMesh; - float minFarWorldY = ComputeSubtreeMinWorldY(actorNode, dropNode.Position.Y); + dropVis.SetLodState(useStaticLod: true, castShadows: false); + float minFarWorldY = dropVis.ComputeMinVertexY(); float terrainY = _main.Session.State.Terrain.SampleHeight(d.X, d.Z); float err = MathF.Abs(minFarWorldY - terrainY); if (err > maxFarGroundErr) maxFarGroundErr = err; @@ -924,8 +914,6 @@ public partial class Smoke : Node await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); Check(_main.Arena.ActiveDropVisualCount == trackedBefore, $"Expected picked-up drops removed from _dropVisuals ({trackedBefore}), got {_main.Arena.ActiveDropVisualCount}"); - Check(_main.Arena.DropGroupChildCount == dropNodesBefore, - $"Expected picked-up drop nodes freed from GroundDrops ({dropNodesBefore}), got {_main.Arena.DropGroupChildCount}"); drops.RemoveRange(baseCount, added.Count); } @@ -946,7 +934,7 @@ public partial class Smoke : Node foreach (var (wId, footNodeName, pelvisNodeName, checkSagittal) in walkerChecks) { var vis = VehicleVisualInstance.Create(cache, wId, VehicleVisualRole.Player); - float restMinY = ComputeSubtreeMinWorldY(vis.ModelRoot, 0f, relativeToModelRoot: true); + float restMinY = vis.ComputeMinVertexY(relativeToModelRoot: true); float worstRelMinY = float.PositiveInfinity; float minFootZ = float.PositiveInfinity, maxFootZ = float.NegativeInfinity; float minFootX = float.PositiveInfinity, maxFootX = float.NegativeInfinity; @@ -959,7 +947,7 @@ public partial class Smoke : Node for (int step = 0; step < 48; step++) { VehicleRigAnimator.Update(vis, in walkInp, Basis.Identity); - float curMinY = ComputeSubtreeMinWorldY(vis.ModelRoot, 0f, relativeToModelRoot: true); + float curMinY = vis.ComputeMinVertexY(relativeToModelRoot: true); float relMinY = curMinY - restMinY; if (relMinY < worstRelMinY) worstRelMinY = relMinY; Check(!float.IsNaN(curMinY), $"NaN vertex Y on walker '{wId}' step {step}"); @@ -1099,6 +1087,21 @@ public partial class Smoke : Node debris.QueueFree(); } + // 10. MultiMeshPartPool & PomDecalPool sanity: live arena submits into MultiMeshPartPool and PomDecalPool stamps impacts cleanly + { + _main.Arena.PomDecals.StampTestDecal( + new Vector3(_main.Session.State.Player.X + 2f, _main.Session.State.Terrain.SampleHeight(_main.Session.State.Player.X + 2f, _main.Session.State.Player.Z) + 0.03f, _main.Session.State.Player.Z), + Vector3.Up, 1.2f, tileIndex: 14); + _main.Arena.Sync(_main.Session, 1.6f, 1f / 60f); + Check(_main.Arena.PartPool.TotalSubmittedInstances > 0, + $"Expected MultiMeshPartPool to submit active instances, got {_main.Arena.PartPool.TotalSubmittedInstances}"); + Check(_main.Arena.PomDecals.ActiveCount >= 1, + $"Expected PomDecalPool to hold >= 1 active decal, got {_main.Arena.PomDecals.ActiveCount}"); + + _main.Hud.PushTestHitArc(_main.Session.State.Player.X + 20f, _main.Session.State.Player.Z + 10f, WeaponVisualClass.Explosive); + Check(_main.Hud.ActiveHitArcCount >= 1, "Expected CrosshairOverlay to accept incoming hit arc"); + } + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); }