Optimize arena rendering and simulation loop to 60 FPS
This commit is contained in:
parent
805c169794
commit
0f36eed3a0
12 changed files with 1810 additions and 231 deletions
|
|
@ -26,6 +26,18 @@ public partial class ArenaRenderer : Node3D
|
|||
public MeshInstance3D? HaloMesh;
|
||||
public StandardMaterial3D? HaloMat;
|
||||
public MeshInstance3D? LaserMesh;
|
||||
public SpectatorStance? LastHaloStance;
|
||||
public bool LastLaserVisible;
|
||||
}
|
||||
|
||||
private sealed class DropVisualEntry
|
||||
{
|
||||
public required Node3D Node;
|
||||
public VehicleVisualInstance? ChassisVisual;
|
||||
public float BaseY;
|
||||
public int TileX;
|
||||
public int TileZ;
|
||||
public int TileVersion;
|
||||
}
|
||||
|
||||
private VehicleAssetCache _assetCache = null!;
|
||||
|
|
@ -39,7 +51,7 @@ public partial class ArenaRenderer : Node3D
|
|||
|
||||
private readonly Dictionary<int, ActorVisual> _contenderVisuals = new();
|
||||
private readonly Dictionary<int, ActorVisual> _spectatorVisuals = new();
|
||||
private readonly Dictionary<int, Node3D> _dropVisuals = new();
|
||||
private readonly Dictionary<int, DropVisualEntry> _dropVisuals = new();
|
||||
private readonly List<MeshInstance3D> _tracerPool = new();
|
||||
|
||||
private StandardMaterial3D _safeRingMat = null!;
|
||||
|
|
@ -49,6 +61,7 @@ public partial class ArenaRenderer : Node3D
|
|||
private StandardMaterial3D _imperialBeaconMat = null!;
|
||||
private StandardMaterial3D _cyanBeaconMat = null!;
|
||||
private MatchState? _builtForState;
|
||||
private float _lastSafeRingRadius = -1f;
|
||||
|
||||
public VehicleAssetCache AssetCache => _assetCache;
|
||||
public DebrisSystem Debris => _debris;
|
||||
|
|
@ -149,10 +162,14 @@ public partial class ArenaRenderer : Node3D
|
|||
_builtForState = state;
|
||||
}
|
||||
|
||||
Camera3D? cam = GetViewport()?.GetCamera3D();
|
||||
bool hasCam = cam is not null && cam.IsInsideTree();
|
||||
Vector3 camPos = hasCam ? cam!.GlobalPosition : Vector3.Zero;
|
||||
|
||||
UpdateSafeCircleRing(state.Terrain, state.Spectators.SafeRadius);
|
||||
SyncContenders(session, dt);
|
||||
SyncSpectators(session, elapsedSeconds, dt);
|
||||
SyncGroundDrops(state, elapsedSeconds);
|
||||
SyncContenders(session, dt, hasCam, camPos);
|
||||
SyncSpectators(session, elapsedSeconds, dt, hasCam, camPos);
|
||||
SyncGroundDrops(state, elapsedSeconds, hasCam, camPos);
|
||||
SyncTracers(state.Tracers);
|
||||
_debris.Step(dt, state.Terrain);
|
||||
}
|
||||
|
|
@ -180,7 +197,8 @@ public partial class ArenaRenderer : Node3D
|
|||
{
|
||||
Mesh = new BoxMesh { Size = new Vector3(b.HalfX * 2f, b.HalfY * 2f, b.HalfZ * 2f) },
|
||||
MaterialOverride = _bermMat,
|
||||
Position = new Vector3(b.X, b.Y, b.Z)
|
||||
Position = new Vector3(b.X, b.Y, b.Z),
|
||||
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off
|
||||
};
|
||||
_staticGroup.AddChild(mesh);
|
||||
}
|
||||
|
|
@ -194,10 +212,17 @@ public partial class ArenaRenderer : Node3D
|
|||
_contenderVisuals.Clear();
|
||||
_spectatorVisuals.Clear();
|
||||
_dropVisuals.Clear();
|
||||
_lastSafeRingRadius = -1f;
|
||||
}
|
||||
|
||||
private void UpdateSafeCircleRing(TerrainField terrain, float safeRadius)
|
||||
{
|
||||
if (_lastSafeRingRadius >= 0f && MathF.Abs(safeRadius - _lastSafeRingRadius) < 0.15f)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_lastSafeRingRadius = safeRadius;
|
||||
|
||||
_safeRingImm.ClearSurfaces();
|
||||
_safeRingImm.SurfaceBegin(Mesh.PrimitiveType.Triangles);
|
||||
|
||||
|
|
@ -238,7 +263,7 @@ public partial class ArenaRenderer : Node3D
|
|||
_safeRingImm.SurfaceEnd();
|
||||
}
|
||||
|
||||
private void SyncContenders(ArenaSession session, float dt)
|
||||
private void SyncContenders(ArenaSession session, float dt, bool hasCam, Vector3 camPos)
|
||||
{
|
||||
var view = session.World.View;
|
||||
var contenders = session.State.Contenders;
|
||||
|
|
@ -266,6 +291,7 @@ public partial class ArenaRenderer : Node3D
|
|||
|
||||
var role = c.IsPlayer ? VehicleVisualRole.Player : VehicleVisualRole.Rival;
|
||||
var instance = VehicleVisualInstance.Create(_assetCache, c.Grid.Spec.Id, role);
|
||||
instance.SyncMountedGear(c.Grid);
|
||||
_actorsGroup.AddChild(instance.Root);
|
||||
vis = new ActorVisual { Visual = instance };
|
||||
_contenderVisuals[c.Id] = vis;
|
||||
|
|
@ -273,30 +299,45 @@ public partial class ArenaRenderer : Node3D
|
|||
|
||||
vis.Visual.Root.Visible = true;
|
||||
|
||||
Vector3 pos;
|
||||
Vector3 vel;
|
||||
var body = session.GetContenderBody(c.Id);
|
||||
if (body is { } h)
|
||||
{
|
||||
int lane = h.Lane;
|
||||
var pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]);
|
||||
pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]);
|
||||
var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]);
|
||||
vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]);
|
||||
vis.Visual.Root.Transform = new Transform3D(new Basis(q), pos);
|
||||
}
|
||||
else
|
||||
{
|
||||
pos = new Vector3(c.X, c.Y, c.Z);
|
||||
vel = Vector3.Zero;
|
||||
vis.Visual.Root.Position = new Vector3(c.X, c.Y, c.Z);
|
||||
vis.Visual.Root.Position = pos;
|
||||
vis.Visual.Root.Rotation = new Vector3(0f, c.Yaw, 0f);
|
||||
}
|
||||
|
||||
vis.Visual.SyncMountedGear(c.Grid);
|
||||
VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, dt);
|
||||
vis.Visual.SyncDamageAndHeat(c.Grid, _debris, vel);
|
||||
bool useStaticLod = false;
|
||||
bool castShadows = true;
|
||||
if (hasCam && !c.IsPlayer)
|
||||
{
|
||||
float distSq = pos.DistanceSquaredTo(camPos);
|
||||
useStaticLod = vis.Visual.IsStaticLod ? distSq > 126f * 126f : distSq > 130f * 130f;
|
||||
castShadows = distSq <= 150f * 150f;
|
||||
}
|
||||
vis.Visual.SetLodState(useStaticLod, castShadows);
|
||||
|
||||
if (!useStaticLod)
|
||||
{
|
||||
vis.Visual.SyncMountedGear(c.Grid);
|
||||
VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, dt);
|
||||
vis.Visual.SyncDamageAndHeat(c.Grid, _debris, vel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void SyncSpectators(ArenaSession session, float elapsedSeconds, float dt)
|
||||
private void SyncSpectators(ArenaSession session, float elapsedSeconds, float dt, bool hasCam, Vector3 camPos)
|
||||
{
|
||||
var view = session.World.View;
|
||||
var specs = session.State.Spectators.Spectators;
|
||||
|
|
@ -358,47 +399,62 @@ public partial class ArenaRenderer : Node3D
|
|||
vis.Visual.Root.Rotation = new Vector3(0f, s.Yaw, 0f);
|
||||
}
|
||||
|
||||
bool useStaticLod = false;
|
||||
bool castShadows = true;
|
||||
if (hasCam)
|
||||
{
|
||||
float distSq = specPos.DistanceSquaredTo(camPos);
|
||||
useStaticLod = vis.Visual.IsStaticLod ? distSq > 126f * 126f : distSq > 130f * 130f;
|
||||
castShadows = distSq <= 150f * 150f;
|
||||
}
|
||||
vis.Visual.SetLodState(useStaticLod, castShadows);
|
||||
|
||||
ContenderState? target = s.TargetContenderId.HasValue &&
|
||||
s.TargetContenderId.Value >= 0 &&
|
||||
s.TargetContenderId.Value < session.State.Contenders.Count
|
||||
? session.State.Contenders[s.TargetContenderId.Value]
|
||||
: null;
|
||||
|
||||
float aimYawWorld = s.Yaw;
|
||||
float aimPitchDeg = 0f;
|
||||
if (s.Stance != SpectatorStance.Neutral && target is { Alive: true })
|
||||
if (!useStaticLod)
|
||||
{
|
||||
float tdx = target.X - s.X;
|
||||
float tdz = target.Z - s.Z;
|
||||
if (tdx * tdx + tdz * tdz > 0.01f)
|
||||
float aimYawWorld = s.Yaw;
|
||||
float aimPitchDeg = 0f;
|
||||
if (s.Stance != SpectatorStance.Neutral && target is { Alive: true })
|
||||
{
|
||||
aimYawWorld = MathF.Atan2(tdx, tdz);
|
||||
float horiz = MathF.Sqrt(tdx * tdx + tdz * tdz);
|
||||
float eyeY = MatchRules.GetObserverEyeY(s.Y, s.Grid.Spec.HalfHeight);
|
||||
float targetY = MatchRules.GetTargetAimY(target.Y, target.Grid.Spec.HalfHeight);
|
||||
aimPitchDeg = Mathf.RadToDeg(MathF.Atan2(targetY - eyeY, horiz));
|
||||
float tdx = target.X - s.X;
|
||||
float tdz = target.Z - s.Z;
|
||||
if (tdx * tdx + tdz * tdz > 0.01f)
|
||||
{
|
||||
aimYawWorld = MathF.Atan2(tdx, tdz);
|
||||
float horiz = MathF.Sqrt(tdx * tdx + tdz * tdz);
|
||||
float eyeY = MatchRules.GetObserverEyeY(s.Y, s.Grid.Spec.HalfHeight);
|
||||
float targetY = MatchRules.GetTargetAimY(target.Y, target.Grid.Spec.HalfHeight);
|
||||
aimPitchDeg = Mathf.RadToDeg(MathF.Atan2(targetY - eyeY, horiz));
|
||||
}
|
||||
}
|
||||
|
||||
var rigInput = new VehicleRigDriveInput(
|
||||
Velocity: vel,
|
||||
Yaw: s.Yaw,
|
||||
AimYawWorld: aimYawWorld,
|
||||
AimPitchDeg: aimPitchDeg,
|
||||
SteerCmd: 0f,
|
||||
ThrottleCmd: vel.Length() > 0.5f ? 0.6f : 0f,
|
||||
VerticalThrottleCmd: 0f,
|
||||
EngineThermalPerf: s.Grid.ComputeEngineThermalPerformance(),
|
||||
DeltaTime: dt,
|
||||
IsGrounded: !s.Grid.Spec.IsVtol);
|
||||
|
||||
vis.Visual.SyncMountedGear(s.Grid);
|
||||
VehicleRigAnimator.Update(vis.Visual, in rigInput, vis.Visual.Root.Basis);
|
||||
vis.Visual.SyncDamageAndHeat(s.Grid, _debris, vel);
|
||||
}
|
||||
|
||||
var rigInput = new VehicleRigDriveInput(
|
||||
Velocity: vel,
|
||||
Yaw: s.Yaw,
|
||||
AimYawWorld: aimYawWorld,
|
||||
AimPitchDeg: aimPitchDeg,
|
||||
SteerCmd: 0f,
|
||||
ThrottleCmd: vel.Length() > 0.5f ? 0.6f : 0f,
|
||||
VerticalThrottleCmd: 0f,
|
||||
EngineThermalPerf: s.Grid.ComputeEngineThermalPerformance(),
|
||||
DeltaTime: dt,
|
||||
IsGrounded: !s.Grid.Spec.IsVtol);
|
||||
|
||||
vis.Visual.SyncMountedGear(s.Grid);
|
||||
VehicleRigAnimator.Update(vis.Visual, in rigInput, vis.Visual.Root.Basis);
|
||||
vis.Visual.SyncDamageAndHeat(s.Grid, _debris, vel);
|
||||
|
||||
// Status halo
|
||||
if (vis.HaloMat is not null && vis.HaloMesh is not null)
|
||||
if (vis.HaloMat is not null && vis.HaloMesh is not null &&
|
||||
(vis.LastHaloStance != s.Stance || s.Stance == SpectatorStance.Provoked))
|
||||
{
|
||||
vis.LastHaloStance = s.Stance;
|
||||
if (s.Stance == SpectatorStance.Neutral)
|
||||
{
|
||||
vis.HaloMat.AlbedoColor = new Color(0.88f, 0.65f, 0.25f, 0.45f);
|
||||
|
|
@ -430,20 +486,26 @@ public partial class ArenaRenderer : Node3D
|
|||
float dist = start.DistanceTo(end);
|
||||
if (dist > 0.5f)
|
||||
{
|
||||
vis.LaserMesh.Visible = true;
|
||||
if (!vis.LastLaserVisible)
|
||||
{
|
||||
vis.LastLaserVisible = true;
|
||||
vis.LaserMesh.Visible = true;
|
||||
}
|
||||
vis.LaserMesh.GlobalPosition = (start + end) * 0.5f;
|
||||
Vector3 dir = (end - start) / dist;
|
||||
Vector3 dir = (end - start).Normalized();
|
||||
Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.99f ? Vector3.Right : Vector3.Up;
|
||||
vis.LaserMesh.LookAt(end, up);
|
||||
vis.LaserMesh.Scale = new Vector3(1f, 1f, dist);
|
||||
}
|
||||
else
|
||||
else if (vis.LastLaserVisible)
|
||||
{
|
||||
vis.LastLaserVisible = false;
|
||||
vis.LaserMesh.Visible = false;
|
||||
}
|
||||
}
|
||||
else
|
||||
else if (vis.LastLaserVisible)
|
||||
{
|
||||
vis.LastLaserVisible = false;
|
||||
vis.LaserMesh.Visible = false;
|
||||
}
|
||||
}
|
||||
|
|
@ -495,39 +557,82 @@ public partial class ArenaRenderer : Node3D
|
|||
};
|
||||
}
|
||||
|
||||
private void SyncGroundDrops(MatchState state, float elapsedSeconds)
|
||||
private void SyncGroundDrops(MatchState state, float elapsedSeconds, bool hasCam, Vector3 camPos)
|
||||
{
|
||||
for (int i = 0; i < state.GroundDrops.Count; i++)
|
||||
{
|
||||
var d = state.GroundDrops[i];
|
||||
if (d.PickedUp)
|
||||
{
|
||||
if (_dropVisuals.TryGetValue(d.Id, out var pickedNode))
|
||||
if (_dropVisuals.TryGetValue(d.Id, out var pickedEntry))
|
||||
{
|
||||
if (GodotObject.IsInstanceValid(pickedNode))
|
||||
if (GodotObject.IsInstanceValid(pickedEntry.Node))
|
||||
{
|
||||
pickedNode.GetParent()?.RemoveChild(pickedNode);
|
||||
pickedNode.QueueFree();
|
||||
pickedEntry.Node.GetParent()?.RemoveChild(pickedEntry.Node);
|
||||
pickedEntry.Node.QueueFree();
|
||||
}
|
||||
_dropVisuals.Remove(d.Id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!_dropVisuals.TryGetValue(d.Id, out var node))
|
||||
bool isNew = false;
|
||||
if (!_dropVisuals.TryGetValue(d.Id, out var entry))
|
||||
{
|
||||
node = BuildGroundDropVisual(d);
|
||||
Node3D node = BuildGroundDropVisual(d, out var chassisVis);
|
||||
_dropsGroup.AddChild(node);
|
||||
_dropVisuals[d.Id] = node;
|
||||
TerrainField.WorldToTile(d.X, d.Z, out int tx, out int tz);
|
||||
entry = new DropVisualEntry
|
||||
{
|
||||
Node = node,
|
||||
ChassisVisual = chassisVis,
|
||||
BaseY = state.Terrain.SampleHeight(d.X, d.Z),
|
||||
TileX = tx,
|
||||
TileZ = tz,
|
||||
TileVersion = state.Terrain.TileVersions[tx, tz]
|
||||
};
|
||||
_dropVisuals[d.Id] = entry;
|
||||
isNew = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
int ver = state.Terrain.TileVersions[entry.TileX, entry.TileZ];
|
||||
if (ver != entry.TileVersion)
|
||||
{
|
||||
entry.TileVersion = ver;
|
||||
entry.BaseY = state.Terrain.SampleHeight(d.X, d.Z);
|
||||
isNew = true;
|
||||
}
|
||||
}
|
||||
|
||||
node.Visible = true;
|
||||
float bob = d.Module is not null ? MathF.Sin(elapsedSeconds * 2.5f + d.Id) * 0.12f : 0f;
|
||||
float baseY = state.Terrain.SampleHeight(d.X, d.Z);
|
||||
node.Position = new Vector3(d.X, baseY + bob, d.Z);
|
||||
if (isNew)
|
||||
{
|
||||
entry.Node.Visible = true;
|
||||
}
|
||||
if (d.Module is not null)
|
||||
{
|
||||
node.Rotation = new Vector3(0f, elapsedSeconds * 0.9f + d.Id, 0f);
|
||||
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);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (isNew)
|
||||
{
|
||||
entry.Node.Position = new Vector3(d.X, entry.BaseY, d.Z);
|
||||
}
|
||||
if (entry.ChassisVisual is { } cv)
|
||||
{
|
||||
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 <= 150f * 150f;
|
||||
}
|
||||
cv.SetLodState(useFarLod, castShadows);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -591,8 +696,9 @@ public partial class ArenaRenderer : Node3D
|
|||
}
|
||||
}
|
||||
|
||||
private Node3D BuildGroundDropVisual(GroundDrop drop)
|
||||
private Node3D BuildGroundDropVisual(GroundDrop drop, out VehicleVisualInstance? chassisVisual)
|
||||
{
|
||||
chassisVisual = null;
|
||||
var root = new Node3D { Name = $"Drop_{drop.Id}" };
|
||||
if (drop.Module is { } mod)
|
||||
{
|
||||
|
|
@ -601,7 +707,8 @@ public partial class ArenaRenderer : Node3D
|
|||
{
|
||||
Mesh = new CylinderMesh { TopRadius = 0.72f, BottomRadius = 0.85f, Height = 0.14f, RadialSegments = 14 },
|
||||
MaterialOverride = beaconMat,
|
||||
Position = new Vector3(0f, 0.08f, 0f)
|
||||
Position = new Vector3(0f, 0.08f, 0f),
|
||||
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off
|
||||
});
|
||||
|
||||
// Real Brokkr gear GLB hovering cleanly above the salvage beacon disc
|
||||
|
|
@ -616,7 +723,8 @@ public partial class ArenaRenderer : Node3D
|
|||
{
|
||||
Mesh = new CylinderMesh { TopRadius = 0.06f, BottomRadius = 0.22f, Height = 5.5f, RadialSegments = 8 },
|
||||
MaterialOverride = _imperialBeaconMat,
|
||||
Position = new Vector3(0f, 2.9f, 0f)
|
||||
Position = new Vector3(0f, 2.9f, 0f),
|
||||
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -624,6 +732,7 @@ public partial class ArenaRenderer : Node3D
|
|||
{
|
||||
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);
|
||||
|
|
@ -632,7 +741,8 @@ public partial class ArenaRenderer : Node3D
|
|||
{
|
||||
Mesh = new CylinderMesh { TopRadius = 2.6f, BottomRadius = 2.8f, Height = 0.14f, RadialSegments = 18 },
|
||||
MaterialOverride = _cyanBeaconMat,
|
||||
Position = new Vector3(0f, 0.12f, 0f)
|
||||
Position = new Vector3(0f, 0.12f, 0f),
|
||||
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off
|
||||
};
|
||||
root.AddChild(ring);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -55,8 +55,11 @@ public partial class InventoryGridControl : Control
|
|||
|
||||
private HardpointSpec?[,] _hardpointLookup = new HardpointSpec?[0, 0];
|
||||
private float[,] _prevArmor = new float[0, 0];
|
||||
private float[,] _prevTemp = new float[0, 0];
|
||||
private float[,] _hitPulse = new float[0, 0];
|
||||
|
||||
private int _lastSelectedCargoIndex = int.MinValue;
|
||||
private int _lastMountedSig = int.MinValue;
|
||||
private Vector2I? _hoveredCell;
|
||||
private bool _thermalEnabled;
|
||||
private float _thermalBlend;
|
||||
|
|
@ -217,17 +220,42 @@ public partial class InventoryGridControl : Control
|
|||
if (gridIdentityChanged)
|
||||
{
|
||||
EnsureBackingBuffers(grid);
|
||||
}
|
||||
else
|
||||
{
|
||||
DetectHits(grid);
|
||||
_lastSelectedCargoIndex = selectedCargoIndex;
|
||||
_lastMountedSig = ComputeMountedSignature(grid);
|
||||
SnapshotTemperatures(grid);
|
||||
PackDataTexture(grid);
|
||||
PackTempTexture(grid);
|
||||
FlushTextures();
|
||||
SyncRectUniform();
|
||||
_labelsOverlay.QueueRedraw();
|
||||
return;
|
||||
}
|
||||
|
||||
PackDataTexture(grid);
|
||||
PackTempTexture(grid);
|
||||
FlushTextures();
|
||||
SyncRectUniform();
|
||||
_labelsOverlay.QueueRedraw();
|
||||
bool dataChanged = DetectHits(grid);
|
||||
int mountedSig = ComputeMountedSignature(grid);
|
||||
if (_lastSelectedCargoIndex != selectedCargoIndex || _lastMountedSig != mountedSig)
|
||||
{
|
||||
_lastSelectedCargoIndex = selectedCargoIndex;
|
||||
_lastMountedSig = mountedSig;
|
||||
dataChanged = true;
|
||||
}
|
||||
|
||||
bool tempChanged = HasTemperatureChanged(grid);
|
||||
|
||||
if (dataChanged)
|
||||
{
|
||||
PackDataTexture(grid);
|
||||
_labelsOverlay.QueueRedraw();
|
||||
}
|
||||
if (tempChanged)
|
||||
{
|
||||
SnapshotTemperatures(grid);
|
||||
PackTempTexture(grid);
|
||||
}
|
||||
if (dataChanged || tempChanged)
|
||||
{
|
||||
FlushTextures();
|
||||
}
|
||||
}
|
||||
|
||||
public void TriggerHitPulse(int x, int y, float intensity = 1f)
|
||||
|
|
@ -332,12 +360,14 @@ public partial class InventoryGridControl : Control
|
|||
}
|
||||
|
||||
_prevArmor = new float[w, h];
|
||||
_prevTemp = new float[w, h];
|
||||
_hitPulse = new float[w, h];
|
||||
for (int y = 0; y < h; y++)
|
||||
{
|
||||
for (int x = 0; x < w; x++)
|
||||
{
|
||||
_prevArmor[x, y] = grid.Armor[x, y];
|
||||
_prevTemp[x, y] = grid.Temperature[x, y];
|
||||
}
|
||||
}
|
||||
_lastHitSequence = grid.HitSequence;
|
||||
|
|
@ -365,8 +395,9 @@ public partial class InventoryGridControl : Control
|
|||
}
|
||||
}
|
||||
|
||||
private void DetectHits(ChassisGrid grid)
|
||||
private bool DetectHits(ChassisGrid grid)
|
||||
{
|
||||
bool changed = false;
|
||||
if (grid.HitSequence != _lastHitSequence)
|
||||
{
|
||||
_lastHitSequence = grid.HitSequence;
|
||||
|
|
@ -374,6 +405,7 @@ public partial class InventoryGridControl : Control
|
|||
{
|
||||
_hitPulse[grid.LastHitX, grid.LastHitY] = 1f;
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
|
||||
for (int y = 0; y < _gridHeight; y++)
|
||||
|
|
@ -384,8 +416,55 @@ public partial class InventoryGridControl : Control
|
|||
if (arm < _prevArmor[x, y] - 0.05f)
|
||||
{
|
||||
_hitPulse[x, y] = 1f;
|
||||
_prevArmor[x, y] = arm;
|
||||
changed = true;
|
||||
}
|
||||
_prevArmor[x, y] = arm;
|
||||
else if (MathF.Abs(arm - _prevArmor[x, y]) > 0.01f)
|
||||
{
|
||||
_prevArmor[x, y] = arm;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
private static int ComputeMountedSignature(ChassisGrid grid)
|
||||
{
|
||||
var hc = new HashCode();
|
||||
hc.Add(grid.Mounted.Count);
|
||||
for (int i = 0; i < grid.Mounted.Count; i++)
|
||||
{
|
||||
var m = grid.Mounted[i];
|
||||
hc.Add(m.HardpointId);
|
||||
hc.Add(m.Spec.Id);
|
||||
hc.Add(m.CurrentPerformance > 0.05f);
|
||||
}
|
||||
return hc.ToHashCode();
|
||||
}
|
||||
|
||||
private bool HasTemperatureChanged(ChassisGrid grid)
|
||||
{
|
||||
for (int y = 0; y < _gridHeight; y++)
|
||||
{
|
||||
for (int x = 0; x < _gridWidth; x++)
|
||||
{
|
||||
if (MathF.Abs(grid.Temperature[x, y] - _prevTemp[x, y]) >= 0.25f)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void SnapshotTemperatures(ChassisGrid grid)
|
||||
{
|
||||
for (int y = 0; y < _gridHeight; y++)
|
||||
{
|
||||
for (int x = 0; x < _gridWidth; x++)
|
||||
{
|
||||
_prevTemp[x, y] = grid.Temperature[x, y];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
201
client/Main.cs
201
client/Main.cs
|
|
@ -1,4 +1,6 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using Godot;
|
||||
using RustToDust.Core;
|
||||
using RustToDust.Ymir;
|
||||
|
|
@ -26,6 +28,29 @@ public partial class Main : Node3D
|
|||
private bool _interactQueued;
|
||||
private int _seed = 42;
|
||||
|
||||
// Temporary Step 1/Step 3 perf probe (enabled only when RTD_PERF_FRAMES is set)
|
||||
private int _perfTargetFrames;
|
||||
private int _perfFrameCount;
|
||||
private int _perfPhysicsTicks;
|
||||
private long _perfLastFrameTick;
|
||||
private int _perfLastDirtyRebakes;
|
||||
private readonly List<double> _perfFrameMs = new();
|
||||
private readonly List<double> _perfPhysicsStepMs = new();
|
||||
private readonly List<double> _perfTerrainSyncMs = new();
|
||||
private readonly List<double> _perfArenaSyncMs = new();
|
||||
private readonly List<double> _perfHudMs = new();
|
||||
private readonly List<int> _perfDirtyRebakeDelta = new();
|
||||
private readonly List<double> _perfDrawCalls = new();
|
||||
private readonly List<double> _perfPrimitives = new();
|
||||
private readonly List<double> _perfObjects = new();
|
||||
private readonly List<double> _perfNodeCount = new();
|
||||
private readonly List<double> _perfTimeProcess = new();
|
||||
private readonly List<double> _perfTimePhysicsProcess = new();
|
||||
private double _perfPendingStepMs;
|
||||
private double _perfPendingTerrainMs;
|
||||
private double _perfPendingArenaMs;
|
||||
private double _perfCamMsSum;
|
||||
|
||||
public ArenaSession Session => _session ?? throw new InvalidOperationException($"No active ArenaSession ({Failure ?? "uninitialized"})");
|
||||
public TerrainRenderer Terrain => _terrain;
|
||||
public ArenaRenderer Arena => _arena;
|
||||
|
|
@ -56,7 +81,15 @@ public partial class Main : Node3D
|
|||
_hud = new Hud(() => _session, OnEquipCargo, () => _cameraYaw) { Name = "Hud" };
|
||||
AddChild(_hud);
|
||||
|
||||
if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_PERF_FRAMES"), out int perfFrames) && perfFrames > 0)
|
||||
{
|
||||
_perfTargetFrames = perfFrames;
|
||||
ArenaSession.PerfEnabled = true;
|
||||
}
|
||||
|
||||
Reset(_seed);
|
||||
_perfLastFrameTick = Stopwatch.GetTimestamp();
|
||||
_perfLastDirtyRebakes = _terrain.DirtyRebakes;
|
||||
}
|
||||
|
||||
public override void _ExitTree()
|
||||
|
|
@ -87,7 +120,7 @@ public partial class Main : Node3D
|
|||
UpdateCamera(1f);
|
||||
_hud.Sync(_session);
|
||||
|
||||
if (DisplayServer.GetName() != "headless" && !_hud.GarageExpanded)
|
||||
if (DisplayServer.GetName() != "headless" && !_hud.GarageExpanded && _perfTargetFrames == 0)
|
||||
{
|
||||
Input.MouseMode = Input.MouseModeEnum.Captured;
|
||||
}
|
||||
|
|
@ -185,9 +218,27 @@ public partial class Main : Node3D
|
|||
var input = _scriptedInput ?? GatherPlayerInput();
|
||||
_interactQueued = false;
|
||||
|
||||
_session.Step(input);
|
||||
_terrain.Sync(_session.State.Terrain);
|
||||
_arena.Sync(_session, _elapsedSeconds, (float)delta);
|
||||
if (_perfTargetFrames > 0)
|
||||
{
|
||||
long t0 = Stopwatch.GetTimestamp();
|
||||
_session.Step(input);
|
||||
long t1 = Stopwatch.GetTimestamp();
|
||||
_terrain.Sync(_session.State.Terrain);
|
||||
long t2 = Stopwatch.GetTimestamp();
|
||||
_arena.Sync(_session, _elapsedSeconds, (float)delta);
|
||||
long t3 = Stopwatch.GetTimestamp();
|
||||
double toMs = 1000.0 / Stopwatch.Frequency;
|
||||
_perfPendingStepMs += (t1 - t0) * toMs;
|
||||
_perfPendingTerrainMs += (t2 - t1) * toMs;
|
||||
_perfPendingArenaMs += (t3 - t2) * toMs;
|
||||
_perfPhysicsTicks++;
|
||||
}
|
||||
else
|
||||
{
|
||||
_session.Step(input);
|
||||
_terrain.Sync(_session.State.Terrain);
|
||||
_arena.Sync(_session, _elapsedSeconds, (float)delta);
|
||||
}
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
|
|
@ -197,8 +248,144 @@ public partial class Main : Node3D
|
|||
return;
|
||||
}
|
||||
|
||||
UpdateCamera((float)delta);
|
||||
_hud.Sync(_session);
|
||||
if (_perfTargetFrames > 0)
|
||||
{
|
||||
long tc0 = Stopwatch.GetTimestamp();
|
||||
UpdateCamera((float)delta);
|
||||
_terrain.UpdateTileLod(_camera.GlobalPosition);
|
||||
long th0 = Stopwatch.GetTimestamp();
|
||||
_hud.Sync(_session);
|
||||
long th1 = Stopwatch.GetTimestamp();
|
||||
_perfCamMsSum += (th0 - tc0) * 1000.0 / Stopwatch.Frequency;
|
||||
double hudMs = (th1 - th0) * 1000.0 / Stopwatch.Frequency;
|
||||
|
||||
long now = Stopwatch.GetTimestamp();
|
||||
double frameMs = (now - _perfLastFrameTick) * 1000.0 / Stopwatch.Frequency;
|
||||
_perfLastFrameTick = now;
|
||||
|
||||
_perfFrameMs.Add(frameMs);
|
||||
_perfPhysicsStepMs.Add(_perfPendingStepMs);
|
||||
_perfTerrainSyncMs.Add(_perfPendingTerrainMs);
|
||||
_perfArenaSyncMs.Add(_perfPendingArenaMs);
|
||||
_perfHudMs.Add(hudMs);
|
||||
_perfPendingStepMs = 0;
|
||||
_perfPendingTerrainMs = 0;
|
||||
_perfPendingArenaMs = 0;
|
||||
|
||||
int rebakesNow = _terrain.DirtyRebakes;
|
||||
_perfDirtyRebakeDelta.Add(rebakesNow - _perfLastDirtyRebakes);
|
||||
_perfLastDirtyRebakes = rebakesNow;
|
||||
|
||||
_perfDrawCalls.Add(Performance.GetMonitor(Performance.Monitor.RenderTotalDrawCallsInFrame));
|
||||
_perfPrimitives.Add(Performance.GetMonitor(Performance.Monitor.RenderTotalPrimitivesInFrame));
|
||||
_perfObjects.Add(Performance.GetMonitor(Performance.Monitor.RenderTotalObjectsInFrame));
|
||||
_perfNodeCount.Add(Performance.GetMonitor(Performance.Monitor.ObjectNodeCount));
|
||||
_perfTimeProcess.Add(Performance.GetMonitor(Performance.Monitor.TimeProcess) * 1000.0);
|
||||
_perfTimePhysicsProcess.Add(Performance.GetMonitor(Performance.Monitor.TimePhysicsProcess) * 1000.0);
|
||||
|
||||
_perfFrameCount++;
|
||||
if (_perfFrameCount >= _perfTargetFrames)
|
||||
{
|
||||
PrintPerfSummaryAndQuit();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
UpdateCamera((float)delta);
|
||||
_terrain.UpdateTileLod(_camera.GlobalPosition);
|
||||
_hud.Sync(_session);
|
||||
}
|
||||
}
|
||||
|
||||
private void PrintPerfSummaryAndQuit()
|
||||
{
|
||||
static double Avg(List<double> v)
|
||||
{
|
||||
if (v.Count == 0) return 0;
|
||||
double s = 0;
|
||||
foreach (double x in v) s += x;
|
||||
return s / v.Count;
|
||||
}
|
||||
static double P95(List<double> v)
|
||||
{
|
||||
if (v.Count == 0) return 0;
|
||||
var sorted = new List<double>(v);
|
||||
sorted.Sort();
|
||||
int idx = Math.Clamp((int)Math.Ceiling(sorted.Count * 0.95) - 1, 0, sorted.Count - 1);
|
||||
return sorted[idx];
|
||||
}
|
||||
double totalMs = 0;
|
||||
foreach (double x in _perfFrameMs) totalMs += x;
|
||||
double fps = totalMs > 0 ? (_perfFrameMs.Count * 1000.0 / totalMs) : 0;
|
||||
double rebakeAvg = 0;
|
||||
int rebakeTotal = 0;
|
||||
foreach (int r in _perfDirtyRebakeDelta) rebakeTotal += r;
|
||||
rebakeAvg = _perfDirtyRebakeDelta.Count > 0 ? (double)rebakeTotal / _perfDirtyRebakeDelta.Count : 0;
|
||||
|
||||
double steadyMs = 0;
|
||||
int steadyCount = Math.Max(0, _perfFrameMs.Count - 10);
|
||||
for (int i = 10; i < _perfFrameMs.Count; i++) steadyMs += _perfFrameMs[i];
|
||||
double steadyAvgMs = steadyCount > 0 ? steadyMs / steadyCount : 0;
|
||||
double steadyFps = steadyAvgMs > 0 ? 1000.0 / steadyAvgMs : 0;
|
||||
|
||||
GD.Print("=== PERF BENCHMARK SUMMARY ===");
|
||||
GD.Print($"Frames={_perfFrameMs.Count} PhysicsTicks={_perfPhysicsTicks} AvgFPS={fps:F2} SteadyFPS(10..59)={steadyFps:F2} EngineFPS={Engine.GetFramesPerSecond():F1}");
|
||||
GD.Print($"frameMs: avg={Avg(_perfFrameMs):F2} steadyAvg={steadyAvgMs:F2} p95={P95(_perfFrameMs):F2}");
|
||||
GD.Print($"physicsStepMs/frame: avg={Avg(_perfPhysicsStepMs):F2} p95={P95(_perfPhysicsStepMs):F2}");
|
||||
GD.Print($"terrainSyncMs/frame: avg={Avg(_perfTerrainSyncMs):F2} p95={P95(_perfTerrainSyncMs):F2} dirtyRebakesTotal={rebakeTotal} dirtyRebakesAvg={rebakeAvg:F2}");
|
||||
GD.Print($"arenaSyncMs/frame: avg={Avg(_perfArenaSyncMs):F2} p95={P95(_perfArenaSyncMs):F2}");
|
||||
GD.Print($"hudMs/frame: avg={Avg(_perfHudMs):F2} p95={P95(_perfHudMs):F2}");
|
||||
GD.Print($"RenderTotalDrawCallsInFrame: avg={Avg(_perfDrawCalls):F0} max={P95(_perfDrawCalls):F0}");
|
||||
GD.Print($"RenderTotalPrimitivesInFrame: avg={Avg(_perfPrimitives):F0}");
|
||||
GD.Print($"RenderTotalObjectsInFrame: avg={Avg(_perfObjects):F0}");
|
||||
GD.Print($"ObjectNodeCount: avg={Avg(_perfNodeCount):F0}");
|
||||
GD.Print($"TimeProcessMs: avg={Avg(_perfTimeProcess):F2}");
|
||||
GD.Print($"TimePhysicsProcessMs: avg={Avg(_perfTimePhysicsProcess):F2}");
|
||||
GD.Print($"UpdateCameraMs/frame: avg={_perfCamMsSum / _perfFrameMs.Count:F2}");
|
||||
GD.Print($"StepBreakdownMs/tick: ring={ArenaSession.PerfRingMs / _perfPhysicsTicks:F2} ai={ArenaSession.PerfAiMs / _perfPhysicsTicks:F2} drive={ArenaSession.PerfDriveMs / _perfPhysicsTicks:F2} world={ArenaSession.PerfWorldMs / _perfPhysicsTicks:F2} sync={ArenaSession.PerfBodySyncMs / _perfPhysicsTicks:F2} detect={ArenaSession.PerfDetectMs / _perfPhysicsTicks:F2} weapons={ArenaSession.PerfWeaponsMs / _perfPhysicsTicks:F2}");
|
||||
foreach (var kv in _arena.AssetCache.Vehicles)
|
||||
{
|
||||
int tris = 0;
|
||||
var bm = kv.Value.BakedStaticMesh;
|
||||
for (int s = 0; s < bm.GetSurfaceCount(); s++)
|
||||
{
|
||||
var arr = bm.SurfaceGetArrays(s);
|
||||
if (arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array)
|
||||
tris += arr[(int)Mesh.ArrayType.Index].AsInt32Array().Length / 3;
|
||||
}
|
||||
int farTris = 0;
|
||||
var fm = kv.Value.BakedLodFarMesh;
|
||||
for (int s = 0; s < fm.GetSurfaceCount(); s++)
|
||||
{
|
||||
var arr = fm.SurfaceGetArrays(s);
|
||||
if (arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array)
|
||||
farTris += arr[(int)Mesh.ArrayType.Index].AsInt32Array().Length / 3;
|
||||
}
|
||||
int nodes = CountSubtreeNodes(kv.Value.SceneTemplate);
|
||||
GD.Print($" Vehicle '{kv.Key}': nodes={nodes} bakedTris={tris} farTris={farTris} surfs={bm.GetSurfaceCount()} farSurfs={fm.GetSurfaceCount()} detachChunks={kv.Value.DetachableParts.Count}");
|
||||
}
|
||||
if (_arena.AssetCache.Vehicles.TryGetValue("paladin", out var palTpl))
|
||||
{
|
||||
var names = new List<string>();
|
||||
CollectNodeNames(palTpl.SceneTemplate, names, 40);
|
||||
GD.Print($" Paladin sample nodes: {string.Join(", ", names)}");
|
||||
}
|
||||
GD.Print("=== END PERF BENCHMARK ===");
|
||||
GetTree().Quit(0);
|
||||
}
|
||||
|
||||
private static void CollectNodeNames(Node cur, List<string> outNames, int limit)
|
||||
{
|
||||
if (outNames.Count >= limit) return;
|
||||
outNames.Add($"{cur.Name}({cur.GetType().Name})");
|
||||
for (int i = 0; i < cur.GetChildCount(); i++) CollectNodeNames(cur.GetChild(i), outNames, limit);
|
||||
}
|
||||
|
||||
private static int CountSubtreeNodes(Node cur)
|
||||
{
|
||||
int n = 1;
|
||||
for (int i = 0; i < cur.GetChildCount(); i++) n += CountSubtreeNodes(cur.GetChild(i));
|
||||
return n;
|
||||
}
|
||||
|
||||
private PlayerInput GatherPlayerInput()
|
||||
|
|
@ -374,6 +561,8 @@ public partial class Main : Node3D
|
|||
LightColor = new Color(1.0f, 0.92f, 0.78f),
|
||||
LightEnergy = 1.45f,
|
||||
ShadowEnabled = true,
|
||||
DirectionalShadowMode = DirectionalLight3D.ShadowMode.Parallel2Splits,
|
||||
DirectionalShadowMaxDistance = 145f,
|
||||
RotationDegrees = new Vector3(-48f, 32f, 0f)
|
||||
};
|
||||
AddChild(sun);
|
||||
|
|
|
|||
|
|
@ -40,13 +40,17 @@ public partial class TerrainRenderer : Node3D
|
|||
}
|
||||
|
||||
private readonly TileNode[,] _tiles = new TileNode[TerrainField.TileGridCount, TerrainField.TileGridCount];
|
||||
private PlaneMesh _nearPlaneMesh = null!;
|
||||
private PlaneMesh _farPlaneMesh = null!;
|
||||
private ImageTexture _white1x1 = null!;
|
||||
private Shader _clearShader = null!;
|
||||
private Shader _brushAddShader = null!;
|
||||
private Shader _brushSubShader = null!;
|
||||
private Shader _brushAlbedoShader = null!;
|
||||
private Shader _surfaceShader = null!;
|
||||
private const int MaxDirtyRebakesPerSync = 2;
|
||||
private TerrainField? _lastTerrain;
|
||||
private int _rebakeCursor;
|
||||
|
||||
public int BakedTileCount { get; private set; }
|
||||
public int DirtyRebakes { get; private set; }
|
||||
|
|
@ -57,6 +61,19 @@ public partial class TerrainRenderer : Node3D
|
|||
whiteImg.SetPixel(0, 0, Colors.White);
|
||||
_white1x1 = ImageTexture.CreateFromImage(whiteImg);
|
||||
|
||||
_nearPlaneMesh = new PlaneMesh
|
||||
{
|
||||
Size = new Vector2(TerrainField.TileSize, TerrainField.TileSize),
|
||||
SubdivideWidth = 64,
|
||||
SubdivideDepth = 64
|
||||
};
|
||||
_farPlaneMesh = new PlaneMesh
|
||||
{
|
||||
Size = new Vector2(TerrainField.TileSize, TerrainField.TileSize),
|
||||
SubdivideWidth = 16,
|
||||
SubdivideDepth = 16
|
||||
};
|
||||
|
||||
_clearShader = new Shader
|
||||
{
|
||||
Code = """
|
||||
|
|
@ -98,28 +115,88 @@ public partial class TerrainRenderer : Node3D
|
|||
_lastTerrain = terrain;
|
||||
}
|
||||
|
||||
const int totalTiles = TerrainField.TileGridCount * TerrainField.TileGridCount;
|
||||
|
||||
// 1. Always bake uninitialized tiles immediately
|
||||
for (int tz = 0; tz < TerrainField.TileGridCount; tz++)
|
||||
{
|
||||
for (int tx = 0; tx < TerrainField.TileGridCount; tx++)
|
||||
{
|
||||
var tile = _tiles[tx, tz];
|
||||
int version = terrain.TileVersions[tx, tz];
|
||||
if (tile.BakedVersion != version)
|
||||
if (tile.BakedVersion < 0 && tile.BakedVersion != version)
|
||||
{
|
||||
BakeTile(tx, tz, tile, terrain);
|
||||
if (tile.BakedVersion < 0)
|
||||
{
|
||||
BakedTileCount++;
|
||||
}
|
||||
else
|
||||
{
|
||||
DirtyRebakes++;
|
||||
}
|
||||
BakedTileCount++;
|
||||
tile.BakedVersion = version;
|
||||
}
|
||||
}
|
||||
}
|
||||
terrain.ClearDirtyMask();
|
||||
|
||||
// 2. Budget dynamic tile rebakes (tracks/craters) to <= 2 per Sync in round-robin order
|
||||
int rebakedThisSync = 0;
|
||||
bool anyRemainingDirty = false;
|
||||
for (int step = 0; step < totalTiles; step++)
|
||||
{
|
||||
int idx = (_rebakeCursor + step) % totalTiles;
|
||||
int tx = idx % TerrainField.TileGridCount;
|
||||
int tz = idx / TerrainField.TileGridCount;
|
||||
var tile = _tiles[tx, tz];
|
||||
int version = terrain.TileVersions[tx, tz];
|
||||
if (tile.BakedVersion != version)
|
||||
{
|
||||
if (rebakedThisSync < MaxDirtyRebakesPerSync)
|
||||
{
|
||||
BakeTile(tx, tz, tile, terrain);
|
||||
DirtyRebakes++;
|
||||
tile.BakedVersion = version;
|
||||
rebakedThisSync++;
|
||||
_rebakeCursor = (idx + 1) % totalTiles;
|
||||
}
|
||||
else
|
||||
{
|
||||
anyRemainingDirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!anyRemainingDirty)
|
||||
{
|
||||
terrain.ClearDirtyMask();
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdateTileLod(Vector3 camPos)
|
||||
{
|
||||
const float nearRadiusSq = 240f * 240f;
|
||||
const float shadowRadiusSq = 220f * 220f;
|
||||
for (int tz = 0; tz < TerrainField.TileGridCount; tz++)
|
||||
{
|
||||
for (int tx = 0; tx < TerrainField.TileGridCount; tx++)
|
||||
{
|
||||
var tile = _tiles[tx, tz];
|
||||
if (tile?.SurfaceMesh is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Vector3 pos = tile.SurfaceMesh.Position;
|
||||
float dx = pos.X - camPos.X;
|
||||
float dz = pos.Z - camPos.Z;
|
||||
float d2 = dx * dx + dz * dz;
|
||||
PlaneMesh desired = d2 <= nearRadiusSq ? _nearPlaneMesh : _farPlaneMesh;
|
||||
if (!ReferenceEquals(tile.SurfaceMesh.Mesh, desired))
|
||||
{
|
||||
tile.SurfaceMesh.Mesh = desired;
|
||||
}
|
||||
var desiredShadow = d2 <= shadowRadiusSq
|
||||
? GeometryInstance3D.ShadowCastingSetting.On
|
||||
: GeometryInstance3D.ShadowCastingSetting.Off;
|
||||
if (tile.SurfaceMesh.CastShadow != desiredShadow)
|
||||
{
|
||||
tile.SurfaceMesh.CastShadow = desiredShadow;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryGetHeightImageFormat(out Image.Format format)
|
||||
|
|
@ -195,13 +272,6 @@ public partial class TerrainRenderer : Node3D
|
|||
tile.AlbedoCanvas = albedoCanvas;
|
||||
AddChild(tile.AlbedoViewport);
|
||||
|
||||
var plane = new PlaneMesh
|
||||
{
|
||||
Size = new Vector2(TerrainField.TileSize, TerrainField.TileSize),
|
||||
SubdivideWidth = 64,
|
||||
SubdivideDepth = 64
|
||||
};
|
||||
|
||||
var mat = new ShaderMaterial { Shader = _surfaceShader };
|
||||
mat.SetShaderParameter("height_tex", tile.HeightViewport.GetTexture());
|
||||
mat.SetShaderParameter("albedo_tex", tile.AlbedoViewport.GetTexture());
|
||||
|
|
@ -218,7 +288,7 @@ public partial class TerrainRenderer : Node3D
|
|||
tile.SurfaceMesh = new MeshInstance3D
|
||||
{
|
||||
Name = $"Tile_{tx}_{tz}_Mesh",
|
||||
Mesh = plane,
|
||||
Mesh = _nearPlaneMesh,
|
||||
MaterialOverride = mat,
|
||||
Position = new Vector3(centerX, 0f, centerZ),
|
||||
CustomAabb = new Aabb(
|
||||
|
|
|
|||
|
|
@ -46,6 +46,8 @@ public sealed class VehicleAssetCache : IDisposable
|
|||
public required VehiclePackage Package { get; init; }
|
||||
public required string GlbPath { get; init; }
|
||||
public required Node3D SceneTemplate { get; init; }
|
||||
public required ArrayMesh BakedStaticMesh { get; init; }
|
||||
public required ArrayMesh BakedLodFarMesh { get; init; }
|
||||
public required float MinY { get; init; }
|
||||
public required float MaxY { get; init; }
|
||||
public required IReadOnlyDictionary<string, GlbAnchorInfo> Anchors { get; init; }
|
||||
|
|
@ -170,6 +172,7 @@ public sealed class VehicleAssetCache : IDisposable
|
|||
generated?.QueueFree();
|
||||
throw new InvalidOperationException($"GltfDocument.GenerateScene did not return a Node3D for '{glbPath}'.");
|
||||
}
|
||||
ClearOwnerRecursive(sceneRoot);
|
||||
|
||||
var gltfNodes = state.GetNodes();
|
||||
var jsonNodes = jsonRoot.GetProperty("nodes");
|
||||
|
|
@ -383,21 +386,89 @@ public sealed class VehicleAssetCache : IDisposable
|
|||
|
||||
ComputeSceneMeshBoundsY(sceneRoot, out float minY, out float maxY);
|
||||
|
||||
// Build full set of protected structural/rig/joint/anchor/mobility Godot nodes
|
||||
var protectedNodes = new HashSet<Node> { sceneRoot };
|
||||
for (int i = 0; i < nodeCount; i++)
|
||||
{
|
||||
if ((protectedIndices.Contains(i) || hasProtectedDesc[i]) && nodeByGltfIndex[i] is { } pn)
|
||||
{
|
||||
MarkNodeAndAncestorsProtected(pn, sceneRoot, protectedNodes);
|
||||
}
|
||||
}
|
||||
foreach (var a in anchors.Values)
|
||||
{
|
||||
if (sceneRoot.GetNodeOrNull(a.RelativePath) is { } an)
|
||||
{
|
||||
MarkNodeAndAncestorsProtected(an, sceneRoot, protectedNodes);
|
||||
}
|
||||
}
|
||||
foreach (var j in joints.Values)
|
||||
{
|
||||
if (sceneRoot.GetNodeOrNull(j.RelativePath) is { } jn)
|
||||
{
|
||||
MarkNodeAndAncestorsProtected(jn, sceneRoot, protectedNodes);
|
||||
}
|
||||
}
|
||||
foreach (var mp in mobilityPaths)
|
||||
{
|
||||
if (sceneRoot.GetNodeOrNull(mp) is { } mn)
|
||||
{
|
||||
MarkNodeAndAncestorsProtected(mn, sceneRoot, protectedNodes);
|
||||
}
|
||||
}
|
||||
|
||||
// Map original detachable MeshInstance3Ds so we can merge them per (rigidParent, CellX, CellY)
|
||||
var detachableByNode = new Dictionary<MeshInstance3D, (int CellX, int CellY, string Kind)>();
|
||||
foreach (var dp in detachableParts)
|
||||
{
|
||||
if (sceneRoot.GetNodeOrNull(dp.RelativePath) is MeshInstance3D mi && !protectedNodes.Contains(mi))
|
||||
{
|
||||
detachableByNode.TryAdd(mi, (dp.CellX, dp.CellY, dp.Kind));
|
||||
}
|
||||
}
|
||||
|
||||
// A & B: Merge detachable armor per (rigidParent, CellX, CellY) and static meshes per rigidParent
|
||||
var mergedDetachableInfos = MergeVehicleSubMeshes(sceneRoot, protectedNodes, detachableByNode);
|
||||
|
||||
// Prune stale nodesByOriginalName entries that were collapsed into merged meshes
|
||||
var survivingNames = new Dictionary<string, NodePath>(StringComparer.Ordinal);
|
||||
foreach (var (origName, relPath) in nodesByOriginalName)
|
||||
{
|
||||
Node? resolved = relPath.ToString() == "." ? sceneRoot : sceneRoot.GetNodeOrNull(relPath);
|
||||
if (resolved is not null)
|
||||
{
|
||||
survivingNames[origName] = relPath;
|
||||
}
|
||||
}
|
||||
|
||||
// C: Build single-node BakedStaticMesh + decimated BakedLodFarMesh (>130m) per template
|
||||
ArrayMesh bakedStaticMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false);
|
||||
ArrayMesh bakedCoarseStatic = BuildBakedStaticMesh(sceneRoot, coarseMaterials: true);
|
||||
ArrayMesh bakedLodFarMesh = DecimateMeshGrid(bakedCoarseStatic, cellSize: 0.45f);
|
||||
|
||||
return new VehicleTemplate
|
||||
{
|
||||
Package = pkg,
|
||||
GlbPath = glbPath,
|
||||
SceneTemplate = sceneRoot,
|
||||
BakedStaticMesh = bakedStaticMesh,
|
||||
BakedLodFarMesh = bakedLodFarMesh,
|
||||
MinY = minY,
|
||||
MaxY = maxY,
|
||||
Anchors = anchors,
|
||||
Joints = joints,
|
||||
NodesByOriginalName = nodesByOriginalName,
|
||||
DetachableParts = detachableParts,
|
||||
NodesByOriginalName = survivingNames,
|
||||
DetachableParts = mergedDetachableInfos,
|
||||
MobilityNodePaths = mobilityPaths
|
||||
};
|
||||
}
|
||||
|
||||
private static readonly HashSet<string> PreservedGearPartNames = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"barrel_inner", "receiver", "muzzle_brake_L", "gun_housing",
|
||||
"sight_tube", "breech_band", "condenser_ring_2", "ivory_cowl"
|
||||
};
|
||||
|
||||
private static GearTemplate LoadGearTemplate(string gearId, string glbPath)
|
||||
{
|
||||
var doc = new GltfDocument();
|
||||
|
|
@ -414,8 +485,10 @@ public sealed class VehicleAssetCache : IDisposable
|
|||
generated?.QueueFree();
|
||||
throw new InvalidOperationException($"GltfDocument.GenerateScene did not return a Node3D for gear '{glbPath}'.");
|
||||
}
|
||||
ClearOwnerRecursive(sceneRoot);
|
||||
|
||||
ComputeSceneMeshBounds(sceneRoot, out Vector3 bMin, out Vector3 bMax);
|
||||
MergeGearSubMeshes(sceneRoot, gearId);
|
||||
Vector3 localFwd = new Vector3(0f, 0f, 1f);
|
||||
|
||||
return new GearTemplate
|
||||
|
|
@ -429,33 +502,35 @@ public sealed class VehicleAssetCache : IDisposable
|
|||
};
|
||||
}
|
||||
|
||||
private static bool IsStructuralNodeName(string name)
|
||||
private static readonly HashSet<string> ExactStructuralNodeNames = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
string low = name.ToLowerInvariant();
|
||||
if (low is "chassis" or "hull" or "pelvis" or "core" or "trunk" or "waist" or "torso.pose" or "aim.turret" or "hull.pose")
|
||||
"chassis", "hull", "pelvis", "core", "trunk", "waist", "torso.pose", "aim.turret", "hull.pose",
|
||||
"legl.hip", "legr.hip", "legl.shin", "legr.shin", "legl.foot", "legr.foot",
|
||||
"legl.upper", "legr.upper", "legl.lower", "legr.lower", "legl.ankle", "legr.ankle",
|
||||
"legl.thigh", "legr.thigh", "legl.cannon", "legr.cannon",
|
||||
"legl.oleo", "legr.oleo", "legl.oleofork", "legr.oleofork",
|
||||
"legl.torqueup", "legr.torqueup", "legl.torquelow", "legr.torquelow",
|
||||
"legl.lug", "legr.lug", "legl.ramluga0", "legl.ramluga1", "legr.ramluga0", "legr.ramluga1",
|
||||
"legl.recessram0", "legl.recessram1", "legr.recessram0", "legr.recessram1",
|
||||
"legfl.s1", "legfr.s1", "legbl.s1", "legbr.s1",
|
||||
"legfl.s2", "legfr.s2", "legbl.s2", "legbr.s2",
|
||||
"footfl", "footfr", "footbl", "footbr",
|
||||
"thigh.fl", "thigh.fr", "thigh.rl", "thigh.rr",
|
||||
"shin.fl", "shin.fr", "shin.rl", "shin.rr",
|
||||
"ankle.fl", "ankle.fr", "ankle.rl", "ankle.rr"
|
||||
};
|
||||
|
||||
private static bool IsStructuralNodeName(string name) =>
|
||||
ExactStructuralNodeNames.Contains(name);
|
||||
|
||||
private static void ClearOwnerRecursive(Node cur)
|
||||
{
|
||||
cur.Owner = null;
|
||||
int count = cur.GetChildCount();
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
return true;
|
||||
ClearOwnerRecursive(cur.GetChild(i));
|
||||
}
|
||||
if (low.StartsWith("slot_frame.", StringComparison.Ordinal) ||
|
||||
low.StartsWith("hp.", StringComparison.Ordinal) ||
|
||||
low.StartsWith("joint.", StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (low.StartsWith("leg", StringComparison.Ordinal) &&
|
||||
!low.Contains("shield") && !low.Contains("armor") && !low.Contains("plate") &&
|
||||
!low.Contains("greave") && !low.Contains("shroud") && !low.Contains("skirt") &&
|
||||
!low.Contains("cheek") && !low.Contains("collar"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return low.Contains("hip") && !low.Contains("cap") && !low.Contains("fender") && !low.Contains("flange") && !low.Contains("guard") && !low.Contains("shroud")
|
||||
|| low.Contains("thigh") && !low.Contains("shield") && !low.Contains("guard") && !low.Contains("shroud") && !low.Contains("lame") && !low.Contains("cuisse")
|
||||
|| low.Contains("shin") && !low.Contains("greave") && !low.Contains("guard") && !low.Contains("cheek") && !low.Contains("shroud")
|
||||
|| low.Contains("oleo") || low.Contains("torque") || low.Contains("recessram")
|
||||
|| low.StartsWith("arm", StringComparison.Ordinal) || low.StartsWith("shoulder", StringComparison.Ordinal)
|
||||
|| low.StartsWith("forearm", StringComparison.Ordinal) || low.StartsWith("elbow", StringComparison.Ordinal)
|
||||
|| low.StartsWith("tail.", StringComparison.Ordinal) || low.StartsWith("foot", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static bool IsDetachablePartKind(string kind, string nodeName, int childCount)
|
||||
|
|
@ -482,6 +557,764 @@ public sealed class VehicleAssetCache : IDisposable
|
|||
return childCount == 0 && (low.Contains("canopy") || low.Contains("hatch") || low.Contains("visor"));
|
||||
}
|
||||
|
||||
private static void MarkNodeAndAncestorsProtected(Node node, Node root, HashSet<Node> protectedNodes)
|
||||
{
|
||||
Node? cur = node;
|
||||
while (cur is not null)
|
||||
{
|
||||
protectedNodes.Add(cur);
|
||||
if (ReferenceEquals(cur, root))
|
||||
{
|
||||
break;
|
||||
}
|
||||
cur = cur.GetParent();
|
||||
}
|
||||
}
|
||||
|
||||
private static Node3D FindNearestProtectedParent(Node node, Node3D sceneRoot, HashSet<Node> protectedNodes)
|
||||
{
|
||||
Node? cur = node.GetParent();
|
||||
while (cur is not null)
|
||||
{
|
||||
if (cur is Node3D n3d && protectedNodes.Contains(cur))
|
||||
{
|
||||
return n3d;
|
||||
}
|
||||
if (ReferenceEquals(cur, sceneRoot))
|
||||
{
|
||||
break;
|
||||
}
|
||||
cur = cur.GetParent();
|
||||
}
|
||||
return sceneRoot;
|
||||
}
|
||||
|
||||
private static Transform3D ComputeRelativeTransform(Node3D ancestor, Node descendant)
|
||||
{
|
||||
Transform3D xf = Transform3D.Identity;
|
||||
Node? cur = descendant;
|
||||
while (cur is not null && !ReferenceEquals(cur, ancestor))
|
||||
{
|
||||
if (cur is Node3D n3d)
|
||||
{
|
||||
xf = n3d.Transform * xf;
|
||||
}
|
||||
cur = cur.GetParent();
|
||||
}
|
||||
return xf;
|
||||
}
|
||||
|
||||
private static bool CanMergeMeshInstance(MeshInstance3D mi)
|
||||
{
|
||||
if (mi.Mesh is null || mi.Mesh.GetSurfaceCount() == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (mi.Mesh is ArrayMesh am)
|
||||
{
|
||||
int surfCount = am.GetSurfaceCount();
|
||||
for (int s = 0; s < surfCount; s++)
|
||||
{
|
||||
if (am.SurfaceGetPrimitiveType(s) != Mesh.PrimitiveType.Triangles)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void CollectAllMeshInstances(Node cur, List<MeshInstance3D> outList)
|
||||
{
|
||||
if (cur is MeshInstance3D mi)
|
||||
{
|
||||
outList.Add(mi);
|
||||
}
|
||||
int count = cur.GetChildCount();
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
CollectAllMeshInstances(cur.GetChild(i), outList);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ReparentChildrenAndRemove(MeshInstance3D mi)
|
||||
{
|
||||
Node? parent = mi.GetParent();
|
||||
if (parent is not null)
|
||||
{
|
||||
for (int i = mi.GetChildCount() - 1; i >= 0; i--)
|
||||
{
|
||||
Node ch = mi.GetChild(i);
|
||||
mi.RemoveChild(ch);
|
||||
if (ch is Node3D ch3d)
|
||||
{
|
||||
ch3d.Transform = mi.Transform * ch3d.Transform;
|
||||
}
|
||||
parent.AddChild(ch);
|
||||
}
|
||||
parent.RemoveChild(mi);
|
||||
}
|
||||
mi.QueueFree();
|
||||
}
|
||||
|
||||
private static List<GlbPartNodeInfo> MergeVehicleSubMeshes(
|
||||
Node3D sceneRoot,
|
||||
HashSet<Node> protectedNodes,
|
||||
Dictionary<MeshInstance3D, (int CellX, int CellY, string Kind)> detachableByNode)
|
||||
{
|
||||
var allMeshes = new List<MeshInstance3D>();
|
||||
CollectAllMeshInstances(sceneRoot, allMeshes);
|
||||
|
||||
var detachableGroups = new Dictionary<(Node3D RigidParent, int CellX, int CellY), (string Kind, List<(MeshInstance3D Mi, Transform3D RelXf)> Items)>();
|
||||
var staticGroups = new Dictionary<Node3D, List<(MeshInstance3D Mi, Transform3D RelXf)>>();
|
||||
var detachResultNodes = new List<(MeshInstance3D Node, int CellX, int CellY, string Kind)>();
|
||||
|
||||
for (int i = 0; i < allMeshes.Count; i++)
|
||||
{
|
||||
MeshInstance3D mi = allMeshes[i];
|
||||
if (!CanMergeMeshInstance(mi))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (detachableByNode.TryGetValue(mi, out var detInfo))
|
||||
{
|
||||
Node3D rigidParent = FindNearestProtectedParent(mi, sceneRoot, protectedNodes);
|
||||
Transform3D relXf = ComputeRelativeTransform(rigidParent, mi);
|
||||
var key = (rigidParent, detInfo.CellX, detInfo.CellY);
|
||||
if (!detachableGroups.TryGetValue(key, out var group))
|
||||
{
|
||||
group = (detInfo.Kind, new List<(MeshInstance3D, Transform3D)>());
|
||||
detachableGroups[key] = group;
|
||||
}
|
||||
group.Items.Add((mi, relXf));
|
||||
}
|
||||
else if (!protectedNodes.Contains(mi))
|
||||
{
|
||||
Node3D rigidParent = FindNearestProtectedParent(mi, sceneRoot, protectedNodes);
|
||||
Transform3D relXf = ComputeRelativeTransform(rigidParent, mi);
|
||||
if (!staticGroups.TryGetValue(rigidParent, out var list))
|
||||
{
|
||||
list = new List<(MeshInstance3D, Transform3D)>();
|
||||
staticGroups[rigidParent] = list;
|
||||
}
|
||||
list.Add((mi, relXf));
|
||||
}
|
||||
}
|
||||
|
||||
// B. Merge detachable armor parts per (rigidParent, CellX, CellY)
|
||||
int detSeq = 0;
|
||||
foreach (var ((rigidParent, cellX, cellY), (kind, items)) in detachableGroups)
|
||||
{
|
||||
if (items.Count == 1 && ReferenceEquals(items[0].Mi.GetParent(), rigidParent))
|
||||
{
|
||||
// Already a single child directly under rigidParent — keep as-is
|
||||
detachResultNodes.Add((items[0].Mi, cellX, cellY, kind));
|
||||
continue;
|
||||
}
|
||||
|
||||
ArrayMesh? merged = BuildMergedArrayMesh(items);
|
||||
if (merged is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var chunkNode = new MeshInstance3D
|
||||
{
|
||||
Name = $"ArmorCell_{cellX}_{cellY}_{detSeq++}",
|
||||
Mesh = merged
|
||||
};
|
||||
rigidParent.AddChild(chunkNode);
|
||||
detachResultNodes.Add((chunkNode, cellX, cellY, kind));
|
||||
|
||||
for (int i = 0; i < items.Count; i++)
|
||||
{
|
||||
ReparentChildrenAndRemove(items[i].Mi);
|
||||
}
|
||||
}
|
||||
|
||||
// A. Merge static non-detachable sub-meshes per rigid articulated parent
|
||||
foreach (var (rigidParent, items) in staticGroups)
|
||||
{
|
||||
if (rigidParent is MeshInstance3D parentMi && CanMergeMeshInstance(parentMi))
|
||||
{
|
||||
var combined = new List<(MeshInstance3D, Transform3D)>(items.Count + 1)
|
||||
{
|
||||
(parentMi, Transform3D.Identity)
|
||||
};
|
||||
combined.AddRange(items);
|
||||
ArrayMesh? merged = BuildMergedArrayMesh(combined);
|
||||
if (merged is not null)
|
||||
{
|
||||
parentMi.MaterialOverride = null;
|
||||
parentMi.Mesh = merged;
|
||||
for (int i = 0; i < items.Count; i++)
|
||||
{
|
||||
ReparentChildrenAndRemove(items[i].Mi);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (items.Count > 1 || (items.Count == 1 && !ReferenceEquals(items[0].Mi.GetParent(), rigidParent)))
|
||||
{
|
||||
ArrayMesh? merged = BuildMergedArrayMesh(items);
|
||||
if (merged is not null)
|
||||
{
|
||||
var staticNode = new MeshInstance3D
|
||||
{
|
||||
Name = $"{rigidParent.Name}_StaticMerged",
|
||||
Mesh = merged
|
||||
};
|
||||
rigidParent.AddChild(staticNode);
|
||||
for (int i = 0; i < items.Count; i++)
|
||||
{
|
||||
ReparentChildrenAndRemove(items[i].Mi);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prune empty non-protected grouping nodes left behind
|
||||
PruneEmptyNonProtectedNodes(sceneRoot, sceneRoot, protectedNodes);
|
||||
|
||||
var result = new List<GlbPartNodeInfo>(detachResultNodes.Count);
|
||||
for (int i = 0; i < detachResultNodes.Count; i++)
|
||||
{
|
||||
var (node, cellX, cellY, kind) = detachResultNodes[i];
|
||||
if (!GodotObject.IsInstanceValid(node) || !sceneRoot.IsAncestorOf(node))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
result.Add(new GlbPartNodeInfo(
|
||||
node.Name,
|
||||
cellX,
|
||||
cellY,
|
||||
kind,
|
||||
BuildRelativeNodePath(sceneRoot, node),
|
||||
HasProtectedDescendant: false));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void MergeGearSubMeshes(Node3D sceneRoot, string gearId)
|
||||
{
|
||||
var keptNodes = new HashSet<Node> { sceneRoot };
|
||||
var allMeshes = new List<MeshInstance3D>();
|
||||
CollectAllMeshInstances(sceneRoot, allMeshes);
|
||||
|
||||
for (int i = 0; i < allMeshes.Count; i++)
|
||||
{
|
||||
MeshInstance3D mi = allMeshes[i];
|
||||
if (PreservedGearPartNames.Contains(mi.Name))
|
||||
{
|
||||
MarkNodeAndAncestorsProtected(mi, sceneRoot, keptNodes);
|
||||
}
|
||||
}
|
||||
|
||||
var mergeList = new List<(MeshInstance3D Mi, Transform3D RelXf)>();
|
||||
for (int i = 0; i < allMeshes.Count; i++)
|
||||
{
|
||||
MeshInstance3D mi = allMeshes[i];
|
||||
if (!keptNodes.Contains(mi) && CanMergeMeshInstance(mi))
|
||||
{
|
||||
mergeList.Add((mi, ComputeRelativeTransform(sceneRoot, mi)));
|
||||
}
|
||||
}
|
||||
|
||||
if (mergeList.Count <= 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
ArrayMesh? merged = BuildMergedArrayMesh(mergeList);
|
||||
if (merged is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var mergedNode = new MeshInstance3D
|
||||
{
|
||||
Name = $"{gearId}_StaticMerged",
|
||||
Mesh = merged
|
||||
};
|
||||
sceneRoot.AddChild(mergedNode);
|
||||
for (int i = 0; i < mergeList.Count; i++)
|
||||
{
|
||||
ReparentChildrenAndRemove(mergeList[i].Mi);
|
||||
}
|
||||
PruneEmptyNonProtectedNodes(sceneRoot, sceneRoot, keptNodes);
|
||||
}
|
||||
|
||||
private static ArrayMesh BuildBakedStaticMesh(Node3D sceneRoot, bool coarseMaterials = false)
|
||||
{
|
||||
var allMeshes = new List<MeshInstance3D>();
|
||||
CollectAllMeshInstances(sceneRoot, allMeshes);
|
||||
|
||||
var items = new List<(MeshInstance3D Mi, Transform3D RelXf)>(allMeshes.Count);
|
||||
for (int i = 0; i < allMeshes.Count; i++)
|
||||
{
|
||||
MeshInstance3D mi = allMeshes[i];
|
||||
if (CanMergeMeshInstance(mi))
|
||||
{
|
||||
items.Add((mi, ComputeRelativeTransform(sceneRoot, mi)));
|
||||
}
|
||||
}
|
||||
|
||||
return BuildMergedArrayMesh(items, coarseMaterials) ?? new ArrayMesh();
|
||||
}
|
||||
|
||||
private static void PruneEmptyNonProtectedNodes(Node cur, Node sceneRoot, HashSet<Node> protectedNodes)
|
||||
{
|
||||
for (int i = cur.GetChildCount() - 1; i >= 0; i--)
|
||||
{
|
||||
Node ch = cur.GetChild(i);
|
||||
PruneEmptyNonProtectedNodes(ch, sceneRoot, protectedNodes);
|
||||
if (!ReferenceEquals(ch, sceneRoot) &&
|
||||
!protectedNodes.Contains(ch) &&
|
||||
ch is not MeshInstance3D &&
|
||||
ch.GetChildCount() == 0)
|
||||
{
|
||||
cur.RemoveChild(ch);
|
||||
ch.QueueFree();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private readonly record struct StandardMatKey(
|
||||
int PaintTag,
|
||||
int R,
|
||||
int G,
|
||||
int B,
|
||||
int A,
|
||||
int Metallic,
|
||||
int Roughness,
|
||||
bool EmissionEnabled,
|
||||
int EmR,
|
||||
int EmG,
|
||||
int EmB,
|
||||
int EmEnergy,
|
||||
int Transparency,
|
||||
int CullMode);
|
||||
|
||||
private static bool TryGetMaterialValueKey(Material mat, bool coarse, out StandardMatKey key)
|
||||
{
|
||||
if (mat is StandardMaterial3D sm &&
|
||||
sm.AlbedoTexture is null &&
|
||||
sm.NormalTexture is null &&
|
||||
sm.RoughnessTexture is null &&
|
||||
sm.MetallicTexture is null &&
|
||||
sm.EmissionTexture is null)
|
||||
{
|
||||
string mName = (sm.ResourceName ?? string.Empty).ToLowerInvariant();
|
||||
int paintTag = (mName.Contains("olive") || mName.Contains("khaki")) ? 1
|
||||
: (mName.Contains("signal") || mName.Contains("orange")) ? 2
|
||||
: 0;
|
||||
float colorScale = coarse ? 6f : 255f;
|
||||
float pbrScale = coarse ? 2f : 100f;
|
||||
key = new StandardMatKey(
|
||||
paintTag,
|
||||
(int)MathF.Round(sm.AlbedoColor.R * colorScale),
|
||||
(int)MathF.Round(sm.AlbedoColor.G * colorScale),
|
||||
(int)MathF.Round(sm.AlbedoColor.B * colorScale),
|
||||
(int)MathF.Round(sm.AlbedoColor.A * 10f),
|
||||
(int)MathF.Round(sm.Metallic * pbrScale),
|
||||
(int)MathF.Round(sm.Roughness * pbrScale),
|
||||
sm.EmissionEnabled,
|
||||
(int)MathF.Round(sm.Emission.R * colorScale),
|
||||
(int)MathF.Round(sm.Emission.G * colorScale),
|
||||
(int)MathF.Round(sm.Emission.B * colorScale),
|
||||
(int)MathF.Round(sm.EmissionEnergyMultiplier * pbrScale),
|
||||
(int)sm.Transparency,
|
||||
(int)sm.CullMode);
|
||||
return true;
|
||||
}
|
||||
key = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
private sealed class MaterialSurfaceBucket
|
||||
{
|
||||
public required Material? Material;
|
||||
public readonly List<(Mesh Mesh, int SurfaceIdx, Transform3D RelXf)> Sources = new();
|
||||
}
|
||||
|
||||
private static ArrayMesh? BuildMergedArrayMesh(List<(MeshInstance3D Mi, Transform3D RelXf)> items, bool coarseMaterials = false)
|
||||
{
|
||||
if (items.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var buckets = new List<MaterialSurfaceBucket>();
|
||||
var bucketByMatId = new Dictionary<ulong, MaterialSurfaceBucket>();
|
||||
var bucketByMatVal = new Dictionary<StandardMatKey, MaterialSurfaceBucket>();
|
||||
MaterialSurfaceBucket? nullMatBucket = null;
|
||||
|
||||
for (int i = 0; i < items.Count; i++)
|
||||
{
|
||||
var (mi, relXf) = items[i];
|
||||
if (mi.Mesh is not { } mesh)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
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;
|
||||
}
|
||||
Material? mat = mi.MaterialOverride ?? mi.GetActiveMaterial(s);
|
||||
MaterialSurfaceBucket bucket;
|
||||
if (mat is null)
|
||||
{
|
||||
nullMatBucket ??= new MaterialSurfaceBucket { Material = null };
|
||||
if (!buckets.Contains(nullMatBucket))
|
||||
{
|
||||
buckets.Add(nullMatBucket);
|
||||
}
|
||||
bucket = nullMatBucket;
|
||||
}
|
||||
else if (TryGetMaterialValueKey(mat, coarseMaterials, out var matKey))
|
||||
{
|
||||
if (!bucketByMatVal.TryGetValue(matKey, out bucket!))
|
||||
{
|
||||
bucket = new MaterialSurfaceBucket { Material = mat };
|
||||
bucketByMatVal[matKey] = bucket;
|
||||
buckets.Add(bucket);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ulong id = mat.GetInstanceId();
|
||||
if (!bucketByMatId.TryGetValue(id, out bucket!))
|
||||
{
|
||||
bucket = new MaterialSurfaceBucket { Material = mat };
|
||||
bucketByMatId[id] = bucket;
|
||||
buckets.Add(bucket);
|
||||
}
|
||||
}
|
||||
bucket.Sources.Add((mesh, s, relXf));
|
||||
}
|
||||
}
|
||||
|
||||
if (buckets.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var outMesh = new ArrayMesh();
|
||||
for (int b = 0; b < buckets.Count; b++)
|
||||
{
|
||||
var bucket = buckets[b];
|
||||
bool anyNormal = false;
|
||||
bool anyTangent = false;
|
||||
bool anyUv = false;
|
||||
bool anyUv2 = false;
|
||||
bool anyColor = false;
|
||||
int totalVerts = 0;
|
||||
int totalIndices = 0;
|
||||
|
||||
var cachedArrays = new List<(Godot.Collections.Array Arrays, Transform3D RelXf, int VertCount, int IndexCount)>(bucket.Sources.Count);
|
||||
for (int s = 0; s < bucket.Sources.Count; s++)
|
||||
{
|
||||
var (mesh, surfIdx, relXf) = bucket.Sources[s];
|
||||
var arr = mesh.SurfaceGetArrays(surfIdx);
|
||||
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;
|
||||
}
|
||||
|
||||
if (arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array) anyNormal = true;
|
||||
if (arr.Count > (int)Mesh.ArrayType.Tangent && arr[(int)Mesh.ArrayType.Tangent].VariantType == Variant.Type.PackedFloat32Array) anyTangent = true;
|
||||
if (arr.Count > (int)Mesh.ArrayType.TexUV && arr[(int)Mesh.ArrayType.TexUV].VariantType == Variant.Type.PackedVector2Array) anyUv = true;
|
||||
if (arr.Count > (int)Mesh.ArrayType.TexUV2 && arr[(int)Mesh.ArrayType.TexUV2].VariantType == Variant.Type.PackedVector2Array) anyUv2 = true;
|
||||
if (arr.Count > (int)Mesh.ArrayType.Color && arr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray) anyColor = true;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
totalVerts += verts.Length;
|
||||
totalIndices += idxCount;
|
||||
cachedArrays.Add((arr, relXf, verts.Length, idxCount));
|
||||
}
|
||||
|
||||
if (totalVerts == 0 || totalIndices == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var outVerts = new Vector3[totalVerts];
|
||||
Vector3[]? outNormals = anyNormal ? new Vector3[totalVerts] : null;
|
||||
float[]? outTangents = anyTangent ? new float[totalVerts * 4] : null;
|
||||
Vector2[]? outUvs = anyUv ? new Vector2[totalVerts] : null;
|
||||
Vector2[]? outUv2s = anyUv2 ? new Vector2[totalVerts] : null;
|
||||
Color[]? outColors = anyColor ? new Color[totalVerts] : null;
|
||||
var outIndices = new int[totalIndices];
|
||||
|
||||
int vOffset = 0;
|
||||
int iOffset = 0;
|
||||
for (int c = 0; c < cachedArrays.Count; c++)
|
||||
{
|
||||
var (arr, relXf, vCount, idxCount) = cachedArrays[c];
|
||||
Vector3[] srcVerts = 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[vOffset + v] = relXf * srcVerts[v];
|
||||
}
|
||||
|
||||
if (outNormals is not null)
|
||||
{
|
||||
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];
|
||||
outNormals[vOffset + v] = n.LengthSquared() > 1e-10f ? n.Normalized() : Vector3.Up;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int v = 0; v < vCount; v++) outNormals[vOffset + v] = Vector3.Up;
|
||||
}
|
||||
}
|
||||
|
||||
if (outTangents is not null)
|
||||
{
|
||||
if (arr.Count > (int)Mesh.ArrayType.Tangent && arr[(int)Mesh.ArrayType.Tangent].VariantType == Variant.Type.PackedFloat32Array)
|
||||
{
|
||||
float[] srcT = arr[(int)Mesh.ArrayType.Tangent].AsFloat32Array();
|
||||
for (int v = 0; v < vCount; v++)
|
||||
{
|
||||
int sBase = v * 4;
|
||||
int dBase = (vOffset + v) * 4;
|
||||
Vector3 t = relXf.Basis * new Vector3(srcT[sBase], srcT[sBase + 1], srcT[sBase + 2]);
|
||||
t = t.LengthSquared() > 1e-10f ? t.Normalized() : Vector3.Right;
|
||||
outTangents[dBase] = t.X;
|
||||
outTangents[dBase + 1] = t.Y;
|
||||
outTangents[dBase + 2] = t.Z;
|
||||
outTangents[dBase + 3] = flipWinding ? -srcT[sBase + 3] : srcT[sBase + 3];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int v = 0; v < vCount; v++)
|
||||
{
|
||||
int dBase = (vOffset + v) * 4;
|
||||
outTangents[dBase] = 1f;
|
||||
outTangents[dBase + 3] = 1f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (outUvs is not null)
|
||||
{
|
||||
if (arr.Count > (int)Mesh.ArrayType.TexUV && arr[(int)Mesh.ArrayType.TexUV].VariantType == Variant.Type.PackedVector2Array)
|
||||
{
|
||||
Array.Copy(arr[(int)Mesh.ArrayType.TexUV].AsVector2Array(), 0, outUvs, vOffset, vCount);
|
||||
}
|
||||
}
|
||||
|
||||
if (outUv2s is not null)
|
||||
{
|
||||
if (arr.Count > (int)Mesh.ArrayType.TexUV2 && arr[(int)Mesh.ArrayType.TexUV2].VariantType == Variant.Type.PackedVector2Array)
|
||||
{
|
||||
Array.Copy(arr[(int)Mesh.ArrayType.TexUV2].AsVector2Array(), 0, outUv2s, vOffset, vCount);
|
||||
}
|
||||
}
|
||||
|
||||
if (outColors is not null)
|
||||
{
|
||||
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, vOffset, vCount);
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int v = 0; v < vCount; v++) outColors[vOffset + v] = Colors.White;
|
||||
}
|
||||
}
|
||||
|
||||
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[iOffset + k] = srcIdx[k] + vOffset;
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int k = 0; k < idxCount; k++) outIndices[iOffset + k] = k + vOffset;
|
||||
}
|
||||
}
|
||||
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[iOffset + k] = a + vOffset;
|
||||
outIndices[iOffset + k + 1] = cIdx + vOffset;
|
||||
outIndices[iOffset + k + 2] = bIdx + vOffset;
|
||||
}
|
||||
}
|
||||
|
||||
vOffset += vCount;
|
||||
iOffset += idxCount;
|
||||
}
|
||||
|
||||
var surfArrays = new Godot.Collections.Array();
|
||||
surfArrays.Resize((int)Mesh.ArrayType.Max);
|
||||
surfArrays[(int)Mesh.ArrayType.Vertex] = outVerts;
|
||||
if (outNormals is not null) surfArrays[(int)Mesh.ArrayType.Normal] = outNormals;
|
||||
if (outTangents is not null) surfArrays[(int)Mesh.ArrayType.Tangent] = outTangents;
|
||||
if (outUvs is not null) surfArrays[(int)Mesh.ArrayType.TexUV] = outUvs;
|
||||
if (outUv2s is not null) surfArrays[(int)Mesh.ArrayType.TexUV2] = outUv2s;
|
||||
if (outColors is not null) surfArrays[(int)Mesh.ArrayType.Color] = outColors;
|
||||
surfArrays[(int)Mesh.ArrayType.Index] = outIndices;
|
||||
|
||||
int newSurf = outMesh.GetSurfaceCount();
|
||||
outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, surfArrays);
|
||||
if (bucket.Material is not null)
|
||||
{
|
||||
outMesh.SurfaceSetMaterial(newSurf, bucket.Material);
|
||||
}
|
||||
}
|
||||
|
||||
return outMesh.GetSurfaceCount() > 0 ? outMesh : null;
|
||||
}
|
||||
|
||||
private static ArrayMesh DecimateMeshGrid(ArrayMesh src, float cellSize)
|
||||
{
|
||||
var outMesh = new ArrayMesh();
|
||||
float invCell = 1f / MathF.Max(0.02f, cellSize);
|
||||
int surfCount = src.GetSurfaceCount();
|
||||
|
||||
for (int s = 0; s < surfCount; s++)
|
||||
{
|
||||
var arr = src.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;
|
||||
}
|
||||
|
||||
bool hasNorm = arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array;
|
||||
Vector3[]? norms = hasNorm ? arr[(int)Mesh.ArrayType.Normal].AsVector3Array() : null;
|
||||
|
||||
bool hasIdx = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array;
|
||||
int[]? indices = hasIdx ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() : null;
|
||||
int triVertCount = indices is not null ? indices.Length : verts.Length;
|
||||
|
||||
var cellToNewIdx = new Dictionary<(int, int, int), int>(verts.Length / 2 + 16);
|
||||
var vertToCellIdx = new int[verts.Length];
|
||||
var accumPos = new List<Vector3>(verts.Length / 2 + 16);
|
||||
var accumNorm = norms is not null ? new List<Vector3>(verts.Length / 2 + 16) : null;
|
||||
var counts = new List<int>(verts.Length / 2 + 16);
|
||||
|
||||
for (int v = 0; v < verts.Length; v++)
|
||||
{
|
||||
Vector3 p = verts[v];
|
||||
var key = (
|
||||
(int)MathF.Floor(p.X * invCell),
|
||||
(int)MathF.Floor(p.Y * invCell),
|
||||
(int)MathF.Floor(p.Z * invCell));
|
||||
|
||||
if (!cellToNewIdx.TryGetValue(key, out int ci))
|
||||
{
|
||||
ci = accumPos.Count;
|
||||
cellToNewIdx[key] = ci;
|
||||
accumPos.Add(p);
|
||||
if (accumNorm is not null) accumNorm.Add(norms![v]);
|
||||
counts.Add(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
accumPos[ci] += p;
|
||||
if (accumNorm is not null) accumNorm[ci] += norms![v];
|
||||
counts[ci]++;
|
||||
}
|
||||
vertToCellIdx[v] = ci;
|
||||
}
|
||||
|
||||
var outIndices = new List<int>(triVertCount / 2 + 12);
|
||||
for (int k = 0; k + 2 < triVertCount; k += 3)
|
||||
{
|
||||
int i0 = indices is not null ? indices[k] : k;
|
||||
int i1 = indices is not null ? indices[k + 1] : k + 1;
|
||||
int i2 = indices is not null ? indices[k + 2] : k + 2;
|
||||
int c0 = vertToCellIdx[i0];
|
||||
int c1 = vertToCellIdx[i1];
|
||||
int c2 = vertToCellIdx[i2];
|
||||
if (c0 != c1 && c1 != c2 && c0 != c2)
|
||||
{
|
||||
outIndices.Add(c0);
|
||||
outIndices.Add(c1);
|
||||
outIndices.Add(c2);
|
||||
}
|
||||
}
|
||||
|
||||
if (outIndices.Count == 0)
|
||||
{
|
||||
// Keep original tiny surface intact if grid collapsed all triangles
|
||||
int fallbackSurf = outMesh.GetSurfaceCount();
|
||||
outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arr);
|
||||
Material? fMat = src.SurfaceGetMaterial(s);
|
||||
if (fMat is not null) outMesh.SurfaceSetMaterial(fallbackSurf, fMat);
|
||||
continue;
|
||||
}
|
||||
|
||||
var outVerts = new Vector3[accumPos.Count];
|
||||
Vector3[]? outNorms = accumNorm is not null ? new Vector3[accumPos.Count] : null;
|
||||
for (int i = 0; i < accumPos.Count; i++)
|
||||
{
|
||||
outVerts[i] = accumPos[i] / counts[i];
|
||||
if (outNorms is not null)
|
||||
{
|
||||
Vector3 n = accumNorm![i];
|
||||
outNorms[i] = n.LengthSquared() > 1e-8f ? n.Normalized() : Vector3.Up;
|
||||
}
|
||||
}
|
||||
|
||||
var newArr = new Godot.Collections.Array();
|
||||
newArr.Resize((int)Mesh.ArrayType.Max);
|
||||
newArr[(int)Mesh.ArrayType.Vertex] = outVerts;
|
||||
if (outNorms is not null) newArr[(int)Mesh.ArrayType.Normal] = outNorms;
|
||||
newArr[(int)Mesh.ArrayType.Index] = outIndices.ToArray();
|
||||
|
||||
int newSurf = outMesh.GetSurfaceCount();
|
||||
outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, newArr);
|
||||
Material? mat = src.SurfaceGetMaterial(s);
|
||||
if (mat is not null)
|
||||
{
|
||||
outMesh.SurfaceSetMaterial(newSurf, mat);
|
||||
}
|
||||
}
|
||||
|
||||
return outMesh.GetSurfaceCount() > 0 ? outMesh : src;
|
||||
}
|
||||
|
||||
private static void MarkAncestorsProtected(int idx, Dictionary<int, int> parentByIndex, HashSet<int> protectedSet)
|
||||
{
|
||||
int cur = idx;
|
||||
|
|
|
|||
|
|
@ -84,6 +84,9 @@ public sealed class VehicleVisualInstance
|
|||
private readonly VehicleRigAnimator.RigState _rigState = new();
|
||||
|
||||
private readonly string _chassisId;
|
||||
private MeshInstance3D? _lodStaticMesh;
|
||||
private bool _isStaticLod;
|
||||
private bool _castShadows = true;
|
||||
|
||||
private VehicleVisualInstance(
|
||||
VehicleAssetCache cache,
|
||||
|
|
@ -120,6 +123,49 @@ public sealed class VehicleVisualInstance
|
|||
public VehicleRigAnimator.RigState RigState => _rigState;
|
||||
public IReadOnlyDictionary<string, BoundJoint> Joints => _joints;
|
||||
public int BoundHardpointCount => _hardpoints.Count;
|
||||
public bool IsStaticLod => _isStaticLod;
|
||||
|
||||
public void SetLodState(bool useStaticLod, bool castShadows)
|
||||
{
|
||||
if (_lodStaticMesh is null)
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (_isStaticLod != useStaticLod)
|
||||
{
|
||||
_isStaticLod = useStaticLod;
|
||||
ModelRoot.Visible = !useStaticLod;
|
||||
ModelRoot.PhysicsInterpolationMode = useStaticLod
|
||||
? Node.PhysicsInterpolationModeEnum.Off
|
||||
: Node.PhysicsInterpolationModeEnum.Inherit;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
public static VehicleVisualInstance Create(
|
||||
VehicleAssetCache cache,
|
||||
|
|
@ -136,18 +182,51 @@ public sealed class VehicleVisualInstance
|
|||
: visualScale;
|
||||
|
||||
var root = new Node3D { Name = $"Actor_{chassisId}" };
|
||||
Vector3 modelScale = new(effectiveScale, effectiveScale, effectiveScale);
|
||||
// Align glTF grounded minY=0 to physics chassis bottom (-halfHeight)
|
||||
Vector3 modelPos = new(0f, -halfHeight - template.MinY * effectiveScale, 0f);
|
||||
|
||||
if (role == VehicleVisualRole.SalvageDrop)
|
||||
{
|
||||
var dropMesh = new MeshInstance3D
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
if (template.SceneTemplate.Duplicate() is not Node3D modelRoot)
|
||||
{
|
||||
throw new InvalidOperationException($"Failed to duplicate GLB scene template for '{pkg.Id}'.");
|
||||
}
|
||||
modelRoot.Name = $"Model_{pkg.Id}";
|
||||
modelRoot.Scale = new Vector3(effectiveScale, effectiveScale, effectiveScale);
|
||||
// Align glTF grounded minY=0 to physics chassis bottom (-halfHeight)
|
||||
modelRoot.Position = new Vector3(0f, -halfHeight - template.MinY * effectiveScale, 0f);
|
||||
modelRoot.Scale = modelScale;
|
||||
modelRoot.Position = modelPos;
|
||||
root.AddChild(modelRoot);
|
||||
|
||||
var instance = new VehicleVisualInstance(cache, template, root, modelRoot, chassisId);
|
||||
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)
|
||||
{
|
||||
_lodStaticMesh = lodMesh
|
||||
};
|
||||
instance.BindAll(role);
|
||||
return instance;
|
||||
}
|
||||
|
|
@ -758,7 +837,7 @@ public sealed class VehicleVisualInstance
|
|||
public float ComputeMountedMaxY()
|
||||
{
|
||||
float maxY = float.NegativeInfinity;
|
||||
AccumulateMaxYRecursive(ModelRoot, Transform3D.Identity, ref maxY);
|
||||
AccumulateMaxYRecursive(ModelRoot, Transform3D.Identity, ref maxY, isRoot: true);
|
||||
if (!float.IsFinite(maxY))
|
||||
{
|
||||
return ModelRoot.Position.Y + _template.MaxY * ModelRoot.Scale.Y;
|
||||
|
|
@ -766,12 +845,12 @@ public sealed class VehicleVisualInstance
|
|||
return maxY;
|
||||
}
|
||||
|
||||
private static void AccumulateMaxYRecursive(Node cur, Transform3D parentToRoot, ref float maxY)
|
||||
private static void AccumulateMaxYRecursive(Node cur, Transform3D parentToRoot, ref float maxY, bool isRoot = false)
|
||||
{
|
||||
Transform3D toRoot = parentToRoot;
|
||||
if (cur is Node3D n3d)
|
||||
{
|
||||
if (!n3d.Visible)
|
||||
if (!isRoot && !n3d.Visible)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -710,7 +710,7 @@ public partial class Smoke : Node
|
|||
debris.QueueFree();
|
||||
}
|
||||
|
||||
// 4. Full Paladin hull + gear strip retains >160 pieces without mid-air eviction (MaxActiveDebris = 256)
|
||||
// 4. Full Paladin hull + gear strip detaches every merged cell armor chunk + mounted gear under 256 cap
|
||||
{
|
||||
var debris = new DebrisSystem { Name = "SmokePaladinDebrisTest" };
|
||||
AddChild(debris);
|
||||
|
|
@ -718,17 +718,26 @@ public partial class Smoke : Node
|
|||
var palVis = VehicleVisualInstance.Create(cache, "paladin", VehicleVisualRole.Player);
|
||||
AddChild(palVis.Root);
|
||||
palVis.SyncMountedGear(palGrid);
|
||||
|
||||
int activeCellCount = 0;
|
||||
int expectedCellChunks = 0;
|
||||
for (int cy = 0; cy < palGrid.Spec.Height; cy++)
|
||||
{
|
||||
for (int cx = 0; cx < palGrid.Spec.Width; cx++)
|
||||
{
|
||||
if (palGrid.Spec.IsActive(cx, cy))
|
||||
{
|
||||
activeCellCount++;
|
||||
expectedCellChunks += palVis.CountDetachablePartsForCell(cx, cy);
|
||||
}
|
||||
palGrid.Armor[cx, cy] = 0f;
|
||||
}
|
||||
}
|
||||
int expectedTotal = expectedCellChunks + palGrid.Mounted.Count;
|
||||
palVis.SyncDamageAndHeat(palGrid, debris, new Vector3(1f, 0f, 3f));
|
||||
GD.Print($"SMOKE INFO: Full Paladin strip debris.ActiveCount={debris.ActiveCount}");
|
||||
Check(debris.ActiveCount > 160 && debris.ActiveCount <= 256,
|
||||
$"Expected full Paladin strip to retain >160 debris pieces under 256 cap, got {debris.ActiveCount}");
|
||||
GD.Print($"SMOKE INFO: Full Paladin strip debris.ActiveCount={debris.ActiveCount} (activeCells={activeCellCount}, cellChunks={expectedCellChunks}, mounted={palGrid.Mounted.Count})");
|
||||
Check(debris.ActiveCount >= activeCellCount && debris.ActiveCount == expectedTotal && debris.ActiveCount <= 256,
|
||||
$"Expected full Paladin strip to detach {expectedTotal} (>= {activeCellCount} active cells) pieces under 256 cap, got {debris.ActiveCount}");
|
||||
palVis.Root.QueueFree();
|
||||
debris.QueueFree();
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue