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();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -72,7 +72,7 @@ namespace RustToDust.Core
|
|||
}
|
||||
}
|
||||
|
||||
public static void UpdateAiContenders(MatchState state, float dt, LineOfSightCheck? hasLos = null)
|
||||
public static void UpdateAiContenders(MatchState state, float dt, LineOfSightCheck? hasLos = null, int tickIndex = -1)
|
||||
{
|
||||
float safeLimit = MathF.Max(30f, state.Spectators.SafeRadius - 25f);
|
||||
|
||||
|
|
@ -103,34 +103,62 @@ namespace RustToDust.Core
|
|||
hasGoal = true;
|
||||
}
|
||||
|
||||
// 2. Find nearest hostile contender with actual line-of-sight
|
||||
// 2. Find nearest hostile contender with actual line-of-sight (staggered every 3 ticks when tickIndex >= 0)
|
||||
ContenderState? target = null;
|
||||
float bestEnemyDistSq = 215f * 215f;
|
||||
float aiEyeY = GetObserverEyeY(ai.Y, ai.Grid.Spec.HalfHeight);
|
||||
for (int j = 0; j < state.Contenders.Count; j++)
|
||||
bool refreshLos = tickIndex < 0 || ((ai.Id + tickIndex) % 3 == 0);
|
||||
if (refreshLos)
|
||||
{
|
||||
var other = state.Contenders[j];
|
||||
if (other.Id == ai.Id || !other.Alive)
|
||||
float aiEyeY = GetObserverEyeY(ai.Y, ai.Grid.Spec.HalfHeight);
|
||||
for (int j = 0; j < state.Contenders.Count; j++)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
var other = state.Contenders[j];
|
||||
if (other.Id == ai.Id || !other.Alive)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
float dx = other.X - ai.X;
|
||||
float dz = other.Z - ai.Z;
|
||||
float d2 = dx * dx + dz * dz;
|
||||
if (d2 >= bestEnemyDistSq)
|
||||
float dx = other.X - ai.X;
|
||||
float dz = other.Z - ai.Z;
|
||||
float d2 = dx * dx + dz * dz;
|
||||
if (d2 >= bestEnemyDistSq)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (hasLos is not null &&
|
||||
!hasLos(ai.X, aiEyeY, ai.Z, other.X, GetTargetAimY(other.Y, other.Grid.Spec.HalfHeight), other.Z))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
bestEnemyDistSq = d2;
|
||||
target = other;
|
||||
}
|
||||
ai.AiTargetContenderId = target?.Id;
|
||||
}
|
||||
else if (ai.AiTargetContenderId is { } tid && tid >= 0 && tid < state.Contenders.Count)
|
||||
{
|
||||
var cached = state.Contenders[tid];
|
||||
if (cached.Alive && cached.Id != ai.Id)
|
||||
{
|
||||
continue;
|
||||
float dx = cached.X - ai.X;
|
||||
float dz = cached.Z - ai.Z;
|
||||
float d2 = dx * dx + dz * dz;
|
||||
if (d2 < bestEnemyDistSq)
|
||||
{
|
||||
bestEnemyDistSq = d2;
|
||||
target = cached;
|
||||
}
|
||||
else
|
||||
{
|
||||
ai.AiTargetContenderId = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (hasLos is not null &&
|
||||
!hasLos(ai.X, aiEyeY, ai.Z, other.X, GetTargetAimY(other.Y, other.Grid.Spec.HalfHeight), other.Z))
|
||||
else
|
||||
{
|
||||
continue;
|
||||
ai.AiTargetContenderId = null;
|
||||
}
|
||||
|
||||
bestEnemyDistSq = d2;
|
||||
target = other;
|
||||
}
|
||||
|
||||
// 3. Scavenge nearby upgrades when safe
|
||||
|
|
|
|||
|
|
@ -108,6 +108,7 @@ namespace RustToDust.Core
|
|||
public bool FireCmd { get; set; }
|
||||
public bool BrakeCmd { get; set; }
|
||||
public float AiScavengeCooldown { get; set; }
|
||||
public int? AiTargetContenderId { get; set; }
|
||||
public bool AllWeaponsOutOfArc { get; set; }
|
||||
public int OutOfArcWeaponCount { get; set; }
|
||||
public int InArcWeaponCount { get; set; }
|
||||
|
|
|
|||
|
|
@ -125,7 +125,8 @@ namespace RustToDust.Core
|
|||
public void UpdateClearance(
|
||||
ReadOnlySpan<RingContact> contenders,
|
||||
float dt,
|
||||
Func<SpectatorState, RingContact, bool>? hasLos)
|
||||
Func<SpectatorState, RingContact, bool>? hasLos,
|
||||
int tickIndex = -1)
|
||||
{
|
||||
_aliveById.Clear();
|
||||
for (int i = 0; i < contenders.Length; i++)
|
||||
|
|
@ -153,6 +154,10 @@ namespace RustToDust.Core
|
|||
{
|
||||
continue;
|
||||
}
|
||||
if (tickIndex >= 0 && spec.Stance == SpectatorStance.Neutral && ((spec.Id + tickIndex) % 6 != 0))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (hasLos is null || hasLos(spec, contender))
|
||||
{
|
||||
|
|
@ -240,7 +245,7 @@ namespace RustToDust.Core
|
|||
}
|
||||
|
||||
// If full with a stale expired no-LOS watcher while a Neutral watcher has live LOS, rotate one slot.
|
||||
if (currentCleared == allowedCleared && hasLos is not null && AnyNeutralHasLos(contender, hasLos))
|
||||
if (currentCleared == allowedCleared && hasLos is not null && AnyNeutralHasLos(contender, hasLos, tickIndex))
|
||||
{
|
||||
int staleIdx = FindStaleNoLosCleared(contender.Id);
|
||||
if (staleIdx >= 0)
|
||||
|
|
@ -263,6 +268,10 @@ namespace RustToDust.Core
|
|||
{
|
||||
continue;
|
||||
}
|
||||
if (tickIndex >= 0 && ((spec.Id + tickIndex) % 6 != 0))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (hasLos is not null && !hasLos(spec, contender))
|
||||
{
|
||||
|
|
@ -494,12 +503,14 @@ namespace RustToDust.Core
|
|||
return bestIdx;
|
||||
}
|
||||
|
||||
private bool AnyNeutralHasLos(in RingContact contender, Func<SpectatorState, RingContact, bool> hasLos)
|
||||
private bool AnyNeutralHasLos(in RingContact contender, Func<SpectatorState, RingContact, bool> hasLos, int tickIndex)
|
||||
{
|
||||
for (int i = 0; i < _spectators.Count; i++)
|
||||
{
|
||||
var spec = _spectators[i];
|
||||
if (spec.Alive && spec.Stance == SpectatorStance.Neutral && hasLos(spec, contender))
|
||||
if (spec.Alive && spec.Stance == SpectatorStance.Neutral &&
|
||||
(tickIndex < 0 || ((spec.Id + tickIndex) % 6 == 0)) &&
|
||||
hasLos(spec, contender))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,8 +41,29 @@ namespace RustToDust.Core
|
|||
public const float HeightSpan = MaxWorldHeight - MinWorldHeight; // 70m
|
||||
public const int MaxDynamicDecals = 256;
|
||||
|
||||
private readonly record struct BrushPrecomp(
|
||||
float CosR,
|
||||
float SinR,
|
||||
float InvRx,
|
||||
float InvRz,
|
||||
float MaxRadiusSq)
|
||||
{
|
||||
public static BrushPrecomp From(in TerrainBrush b)
|
||||
{
|
||||
float maxR = MathF.Max(0.1f, MathF.Max(b.RadiusX, b.RadiusZ));
|
||||
return new BrushPrecomp(
|
||||
MathF.Cos(b.RotationRad),
|
||||
MathF.Sin(b.RotationRad),
|
||||
1f / MathF.Max(0.1f, b.RadiusX),
|
||||
1f / MathF.Max(0.1f, b.RadiusZ),
|
||||
maxR * maxR);
|
||||
}
|
||||
}
|
||||
|
||||
private readonly List<TerrainBrush> _brushes = new();
|
||||
private readonly List<BrushPrecomp> _brushPrecomps = new();
|
||||
private readonly List<int>[,] _tileBrushIndices = new List<int>[TileGridCount, TileGridCount];
|
||||
private readonly float[,] _tileMaxHeight = new float[TileGridCount, TileGridCount];
|
||||
private readonly Queue<int> _dynamicDecalSlots = new();
|
||||
private int _nextBrushId = 1;
|
||||
|
||||
|
|
@ -350,12 +371,13 @@ namespace RustToDust.Core
|
|||
var indices = _tileBrushIndices[tx, tz];
|
||||
for (int i = 0; i < indices.Count; i++)
|
||||
{
|
||||
var b = _brushes[indices[i]];
|
||||
int idx = indices[i];
|
||||
var b = _brushes[idx];
|
||||
if (b.Kind == TerrainBrushKind.Scorch)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
h += EvaluateBrushHeight(in b, cx, cz);
|
||||
h += EvaluateBrushHeightFast(in b, _brushPrecomps[idx], cx, cz);
|
||||
}
|
||||
|
||||
return Math.Clamp(h, MinWorldHeight, MaxWorldHeight);
|
||||
|
|
@ -404,44 +426,62 @@ namespace RustToDust.Core
|
|||
float px = ox + dx * ct;
|
||||
float py = oy + dy * ct;
|
||||
float pz = oz + dz * ct;
|
||||
float diff = py - SampleHeight(px, pz);
|
||||
|
||||
if (diff <= 0f)
|
||||
float cx = Math.Clamp(px, -HalfExtent, HalfExtent);
|
||||
float cz = Math.Clamp(pz, -HalfExtent, HalfExtent);
|
||||
WorldToTile(cx, cz, out int tx, out int tz);
|
||||
if (py <= _tileMaxHeight[tx, tz])
|
||||
{
|
||||
// Binary refine between prevT and ct
|
||||
float lo = prevT;
|
||||
float hi = ct;
|
||||
for (int iter = 0; iter < 5; iter++)
|
||||
float diff = py - SampleHeight(px, pz);
|
||||
if (diff <= 0f)
|
||||
{
|
||||
float mid = 0.5f * (lo + hi);
|
||||
float mx = ox + dx * mid;
|
||||
float my = oy + dy * mid;
|
||||
float mz = oz + dz * mid;
|
||||
if (my - SampleHeight(mx, mz) > 0f)
|
||||
// Binary refine between prevT and ct
|
||||
float lo = prevT;
|
||||
float hi = ct;
|
||||
for (int iter = 0; iter < 5; iter++)
|
||||
{
|
||||
lo = mid;
|
||||
float mid = 0.5f * (lo + hi);
|
||||
float mx = ox + dx * mid;
|
||||
float my = oy + dy * mid;
|
||||
float mz = oz + dz * mid;
|
||||
if (my - SampleHeight(mx, mz) > 0f)
|
||||
{
|
||||
lo = mid;
|
||||
}
|
||||
else
|
||||
{
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
|
||||
hitDist = 0.5f * (lo + hi);
|
||||
hitX = ox + dx * hitDist;
|
||||
hitZ = oz + dz * hitDist;
|
||||
hitY = SampleHeight(hitX, hitZ);
|
||||
return true;
|
||||
hitDist = 0.5f * (lo + hi);
|
||||
hitX = ox + dx * hitDist;
|
||||
hitZ = oz + dz * hitDist;
|
||||
hitY = SampleHeight(hitX, hitZ);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
prevT = ct;
|
||||
prevDiff = diff;
|
||||
if (ct >= maxDistance)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
t = ct + (ct < 160f ? 1.5f : 2.5f);
|
||||
float step = ct < 160f ? 1.5f : 2.5f;
|
||||
if (py > _tileMaxHeight[tx, tz] + 1.5f)
|
||||
{
|
||||
float farT = MathF.Min(ct + 14f, maxDistance);
|
||||
float fx = Math.Clamp(ox + dx * farT, -HalfExtent, HalfExtent);
|
||||
float fz = Math.Clamp(oz + dz * farT, -HalfExtent, HalfExtent);
|
||||
WorldToTile(fx, fz, out int ftx, out int ftz);
|
||||
float fy = oy + dy * farT;
|
||||
if (ftx == tx && ftz == tz && fy > _tileMaxHeight[tx, tz] + 0.5f)
|
||||
{
|
||||
step = MathF.Max(step, farT - ct);
|
||||
}
|
||||
}
|
||||
t = ct + step;
|
||||
}
|
||||
|
||||
hitX = 0f;
|
||||
|
|
@ -451,6 +491,29 @@ namespace RustToDust.Core
|
|||
return false;
|
||||
}
|
||||
|
||||
private static float EvaluateBrushHeightFast(in TerrainBrush b, in BrushPrecomp p, float worldX, float worldZ)
|
||||
{
|
||||
float dx = worldX - b.X;
|
||||
float dz = worldZ - b.Z;
|
||||
if (dx * dx + dz * dz >= p.MaxRadiusSq)
|
||||
{
|
||||
return 0f;
|
||||
}
|
||||
|
||||
float lx = dx * p.CosR + dz * p.SinR;
|
||||
float lz = -dx * p.SinR + dz * p.CosR;
|
||||
|
||||
float u = lx * p.InvRx;
|
||||
float v = lz * p.InvRz;
|
||||
float r2 = u * u + v * v;
|
||||
if (r2 >= 1f)
|
||||
{
|
||||
return 0f;
|
||||
}
|
||||
|
||||
return EvaluateBrushKernel(in b, u, r2);
|
||||
}
|
||||
|
||||
public static float EvaluateBrushHeight(in TerrainBrush b, float worldX, float worldZ)
|
||||
{
|
||||
float dx = worldX - b.X;
|
||||
|
|
@ -468,6 +531,11 @@ namespace RustToDust.Core
|
|||
return 0f;
|
||||
}
|
||||
|
||||
return EvaluateBrushKernel(in b, u, r2);
|
||||
}
|
||||
|
||||
private static float EvaluateBrushKernel(in TerrainBrush b, float u, float r2)
|
||||
{
|
||||
switch (b.Kind)
|
||||
{
|
||||
case TerrainBrushKind.DuneRidge:
|
||||
|
|
@ -512,6 +580,7 @@ namespace RustToDust.Core
|
|||
var brush = template with { Id = _nextBrushId++ };
|
||||
int index = _brushes.Count;
|
||||
_brushes.Add(brush);
|
||||
_brushPrecomps.Add(BrushPrecomp.From(in brush));
|
||||
RegisterBrushInTiles(index, in brush, incrementTileVersion: true);
|
||||
return brush;
|
||||
}
|
||||
|
|
@ -525,6 +594,7 @@ namespace RustToDust.Core
|
|||
var prev = _brushes[slot];
|
||||
UnregisterBrushFromTiles(slot, in prev);
|
||||
_brushes[slot] = brush;
|
||||
_brushPrecomps[slot] = BrushPrecomp.From(in brush);
|
||||
RegisterBrushInTiles(slot, in brush, incrementTileVersion: true);
|
||||
_dynamicDecalSlots.Enqueue(slot);
|
||||
return brush;
|
||||
|
|
@ -532,19 +602,42 @@ namespace RustToDust.Core
|
|||
|
||||
int index = _brushes.Count;
|
||||
_brushes.Add(brush);
|
||||
_brushPrecomps.Add(BrushPrecomp.From(in brush));
|
||||
RegisterBrushInTiles(index, in brush, incrementTileVersion: true);
|
||||
_dynamicDecalSlots.Enqueue(index);
|
||||
return brush;
|
||||
}
|
||||
|
||||
private static float GetBrushMaxPositiveHeight(in TerrainBrush b) => b.Kind switch
|
||||
{
|
||||
TerrainBrushKind.DuneRidge => b.HeightDelta > 0f ? b.HeightDelta * 1.33f : 0f,
|
||||
TerrainBrushKind.Mesa => b.HeightDelta > 0f ? b.HeightDelta : 0f,
|
||||
TerrainBrushKind.SalvagePad or TerrainBrushKind.Road or TerrainBrushKind.Track => b.HeightDelta > 0f ? b.HeightDelta : 0f,
|
||||
TerrainBrushKind.Crater => 0.33f * MathF.Abs(b.HeightDelta),
|
||||
_ => 0f
|
||||
};
|
||||
|
||||
private void RecomputeTileMaxHeight(int tx, int tz)
|
||||
{
|
||||
float sum = 0f;
|
||||
var indices = _tileBrushIndices[tx, tz];
|
||||
for (int i = 0; i < indices.Count; i++)
|
||||
{
|
||||
sum += GetBrushMaxPositiveHeight(_brushes[indices[i]]);
|
||||
}
|
||||
_tileMaxHeight[tx, tz] = Math.Min(MaxWorldHeight, sum + 0.05f);
|
||||
}
|
||||
|
||||
private void RegisterBrushInTiles(int index, in TerrainBrush brush, bool incrementTileVersion)
|
||||
{
|
||||
float maxPos = GetBrushMaxPositiveHeight(in brush);
|
||||
GetBrushTileBounds(in brush, out int minTx, out int maxTx, out int minTz, out int maxTz);
|
||||
for (int tz = minTz; tz <= maxTz; tz++)
|
||||
{
|
||||
for (int tx = minTx; tx <= maxTx; tx++)
|
||||
{
|
||||
_tileBrushIndices[tx, tz].Add(index);
|
||||
_tileMaxHeight[tx, tz] = Math.Min(MaxWorldHeight, _tileMaxHeight[tx, tz] + maxPos + 0.05f);
|
||||
if (incrementTileVersion)
|
||||
{
|
||||
TileVersions[tx, tz]++;
|
||||
|
|
@ -562,6 +655,7 @@ namespace RustToDust.Core
|
|||
for (int tx = minTx; tx <= maxTx; tx++)
|
||||
{
|
||||
_tileBrushIndices[tx, tz].Remove(index);
|
||||
RecomputeTileMaxHeight(tx, tz);
|
||||
TileVersions[tx, tz]++;
|
||||
DirtyTileMask |= 1UL << (tz * TileGridCount + tx);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Numerics;
|
||||
using RustToDust.Core;
|
||||
using Ymir.Box3D;
|
||||
|
|
@ -22,6 +23,8 @@ namespace RustToDust.Ymir
|
|||
private readonly Dictionary<int, Box3DSoaBodyHandle> _spectatorBodies = new();
|
||||
private readonly Dictionary<ulong, (bool IsContender, int Index)> _entityByStableId = new();
|
||||
private readonly float[] _trackDistAccum = new float[MatchState.ContenderCount];
|
||||
private int _stepTick;
|
||||
private bool _forceFullDetectionRefresh = true;
|
||||
private bool _disposed;
|
||||
|
||||
public ArenaSession(int seed = 42)
|
||||
|
|
@ -41,6 +44,15 @@ namespace RustToDust.Ymir
|
|||
UpdatePlayerDetectionMemory();
|
||||
}
|
||||
|
||||
public static bool PerfEnabled;
|
||||
public static double PerfRingMs;
|
||||
public static double PerfAiMs;
|
||||
public static double PerfDriveMs;
|
||||
public static double PerfWorldMs;
|
||||
public static double PerfBodySyncMs;
|
||||
public static double PerfDetectMs;
|
||||
public static double PerfWeaponsMs;
|
||||
|
||||
public MatchState State { get; }
|
||||
public Box3DSoaWorld World => _world;
|
||||
|
||||
|
|
@ -76,6 +88,7 @@ namespace RustToDust.Ymir
|
|||
{
|
||||
SpawnContenderBody(c);
|
||||
}
|
||||
_forceFullDetectionRefresh = true;
|
||||
}
|
||||
|
||||
public void SetSpectatorPose(int spectatorId, float x, float z, float? yaw = null)
|
||||
|
|
@ -109,6 +122,7 @@ namespace RustToDust.Ymir
|
|||
{
|
||||
SpawnSpectatorBody(index, spec);
|
||||
}
|
||||
_forceFullDetectionRefresh = true;
|
||||
}
|
||||
|
||||
public bool HasLineOfSight(float ax, float ay, float az, float bx, float by, float bz)
|
||||
|
|
@ -130,22 +144,11 @@ namespace RustToDust.Ymir
|
|||
return false;
|
||||
}
|
||||
|
||||
var hit = _world.CastRayClosest((ax, ay, az), (delta.X, delta.Y, delta.Z));
|
||||
if (!hit.Hit)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (hit.StableId >= StaticBoxStableIdBase && hit.StableId < ContenderStableIdBase)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// If a dynamic body caught the single closest ray, verify no static cover wall lies along the segment.
|
||||
return !IntersectsAnyCoverBox(ax, ay, az, dir.X, dir.Y, dir.Z, dist);
|
||||
// Only static cover/boundary boxes block LOS; dynamic vehicles do not occlude terrain/cover sightlines.
|
||||
return !IntersectsAnyStaticBox(ax, ay, az, dir.X, dir.Y, dir.Z, dist);
|
||||
}
|
||||
|
||||
private bool IntersectsAnyCoverBox(float ox, float oy, float oz, float dx, float dy, float dz, float maxDist)
|
||||
private bool IntersectsAnyStaticBox(float ox, float oy, float oz, float dx, float dy, float dz, float maxDist)
|
||||
{
|
||||
var boxes = State.ArenaCoverBoxes;
|
||||
for (int i = 0; i < boxes.Count; i++)
|
||||
|
|
@ -156,6 +159,15 @@ namespace RustToDust.Ymir
|
|||
return true;
|
||||
}
|
||||
}
|
||||
var bounds = State.ArenaBoundaryBoxes;
|
||||
for (int i = 0; i < bounds.Count; i++)
|
||||
{
|
||||
var b = bounds[i];
|
||||
if (RayIntersectsAabb(ox, oy, oz, dx, dy, dz, maxDist, b))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
|
@ -193,23 +205,56 @@ namespace RustToDust.Ymir
|
|||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
|
||||
_stepTick++;
|
||||
State.Time += FixedDt;
|
||||
MatchRules.AdvanceTracers(State, FixedDt);
|
||||
State.Spectators.UpdateSafeRadius(State.Time);
|
||||
State.Spectators.AdvancePerimeterOrbits(FixedDt);
|
||||
|
||||
if (!PerfEnabled)
|
||||
{
|
||||
UpdateRingClearance();
|
||||
MatchRules.ApplyPlayerInput(State, input);
|
||||
MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight, _forceFullDetectionRefresh ? -1 : _stepTick);
|
||||
|
||||
ApplyPhysicsDrives();
|
||||
_world.Step(FixedDt, SubStepCount);
|
||||
SyncBodiesFromWorld();
|
||||
|
||||
UpdatePlayerDetectionMemory();
|
||||
StepThermalAndCooldowns();
|
||||
ProcessWeapons();
|
||||
MatchRules.UpdateMatchOutcome(State);
|
||||
return;
|
||||
}
|
||||
|
||||
double toMs = 1000.0 / Stopwatch.Frequency;
|
||||
long t0 = Stopwatch.GetTimestamp();
|
||||
UpdateRingClearance();
|
||||
long t1 = Stopwatch.GetTimestamp();
|
||||
MatchRules.ApplyPlayerInput(State, input);
|
||||
MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight);
|
||||
|
||||
MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight, _forceFullDetectionRefresh ? -1 : _stepTick);
|
||||
long t2 = Stopwatch.GetTimestamp();
|
||||
ApplyPhysicsDrives();
|
||||
long t3 = Stopwatch.GetTimestamp();
|
||||
_world.Step(FixedDt, SubStepCount);
|
||||
long t4 = Stopwatch.GetTimestamp();
|
||||
SyncBodiesFromWorld();
|
||||
|
||||
long t5 = Stopwatch.GetTimestamp();
|
||||
UpdatePlayerDetectionMemory();
|
||||
long t6 = Stopwatch.GetTimestamp();
|
||||
StepThermalAndCooldowns();
|
||||
ProcessWeapons();
|
||||
long t7 = Stopwatch.GetTimestamp();
|
||||
MatchRules.UpdateMatchOutcome(State);
|
||||
|
||||
PerfRingMs += (t1 - t0) * toMs;
|
||||
PerfAiMs += (t2 - t1) * toMs;
|
||||
PerfDriveMs += (t3 - t2) * toMs;
|
||||
PerfWorldMs += (t4 - t3) * toMs;
|
||||
PerfBodySyncMs += (t5 - t4) * toMs;
|
||||
PerfDetectMs += (t6 - t5) * toMs;
|
||||
PerfWeaponsMs += (t7 - t6) * toMs;
|
||||
}
|
||||
|
||||
private void BuildStaticArena()
|
||||
|
|
@ -293,6 +338,7 @@ namespace RustToDust.Ymir
|
|||
{
|
||||
SpawnContenderBody(c);
|
||||
}
|
||||
_forceFullDetectionRefresh = true;
|
||||
}
|
||||
|
||||
private void SpawnSpectatorBodies()
|
||||
|
|
@ -334,7 +380,7 @@ namespace RustToDust.Ymir
|
|||
var c = State.Contenders[i];
|
||||
contacts[i] = new RingContact(c.Id, c.X, c.Z, c.Alive, c.Y, c.Grid.Spec.HalfHeight);
|
||||
}
|
||||
State.Spectators.UpdateClearance(contacts, FixedDt, HasSpectatorLos);
|
||||
State.Spectators.UpdateClearance(contacts, FixedDt, HasSpectatorLos, _forceFullDetectionRefresh ? -1 : _stepTick);
|
||||
|
||||
for (int i = 0; i < State.Spectators.Spectators.Count; i++)
|
||||
{
|
||||
|
|
@ -1024,6 +1070,23 @@ namespace RustToDust.Ymir
|
|||
continue;
|
||||
}
|
||||
|
||||
float dxC = c.X - p.X;
|
||||
float dzC = c.Z - p.Z;
|
||||
float distSqC = dxC * dxC + dzC * dzC;
|
||||
int rivalPeriod = distSqC > 240f * 240f ? 6 : 3;
|
||||
if (!_forceFullDetectionRefresh && ((c.Id + _stepTick) % rivalPeriod != 0))
|
||||
{
|
||||
if (!mem.VisibleToPlayer && mem.HasEverBeenSeen)
|
||||
{
|
||||
mem.LastSeenAge += FixedDt;
|
||||
}
|
||||
else if (mem.VisibleToPlayer && distSqC <= 240f * 240f)
|
||||
{
|
||||
detectedBy++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
bool playerSees = HasLineOfSight(
|
||||
p.X, pEyeY, p.Z,
|
||||
c.X, MatchRules.GetTargetAimY(c.Y, c.Grid.Spec.HalfHeight), c.Z);
|
||||
|
|
@ -1037,9 +1100,7 @@ namespace RustToDust.Ymir
|
|||
mem.LastSeenZ = c.Z;
|
||||
mem.HasEverBeenSeen = true;
|
||||
|
||||
float dx = c.X - p.X;
|
||||
float dz = c.Z - p.Z;
|
||||
if (dx * dx + dz * dz <= 240f * 240f &&
|
||||
if (distSqC <= 240f * 240f &&
|
||||
HasLineOfSight(c.X, MatchRules.GetObserverEyeY(c.Y, c.Grid.Spec.HalfHeight), c.Z, p.X, pTargetY, p.Z))
|
||||
{
|
||||
detectedBy++;
|
||||
|
|
@ -1068,42 +1129,53 @@ namespace RustToDust.Ymir
|
|||
continue;
|
||||
}
|
||||
|
||||
bool playerSees = HasLineOfSight(
|
||||
p.X, pEyeY, p.Z,
|
||||
s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight), s.Z);
|
||||
bool checkLosThisTick = _forceFullDetectionRefresh ||
|
||||
s.Stance != SpectatorStance.Neutral ||
|
||||
((s.Id + _stepTick) % 12 == 0);
|
||||
|
||||
if (playerSees)
|
||||
if (checkLosThisTick)
|
||||
{
|
||||
mem.VisibleToPlayer = true;
|
||||
mem.FaintHorizonPing = false;
|
||||
mem.LastSeenAge = 0f;
|
||||
mem.LastSeenX = s.X;
|
||||
mem.LastSeenZ = s.Z;
|
||||
mem.HasEverBeenSeen = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
mem.VisibleToPlayer = false;
|
||||
if (mem.HasEverBeenSeen)
|
||||
bool playerSees = HasLineOfSight(
|
||||
p.X, pEyeY, p.Z,
|
||||
s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight), s.Z);
|
||||
|
||||
if (playerSees)
|
||||
{
|
||||
mem.LastSeenAge += FixedDt;
|
||||
mem.VisibleToPlayer = true;
|
||||
mem.FaintHorizonPing = false;
|
||||
mem.LastSeenAge = 0f;
|
||||
mem.LastSeenX = s.X;
|
||||
mem.LastSeenZ = s.Z;
|
||||
mem.HasEverBeenSeen = true;
|
||||
}
|
||||
|
||||
// Spectator wall horizon rule: gaudy Tourists (RadarSignature >= 0.9) ping faintly over moderate crests at medium range;
|
||||
// low-signature Exemplars vanish completely when terrain-occluded.
|
||||
bool horizonPing = false;
|
||||
if (s.RadarSignature >= 0.9f)
|
||||
else
|
||||
{
|
||||
float dx = s.X - p.X;
|
||||
float dz = s.Z - p.Z;
|
||||
if (dx * dx + dz * dz <= MatchState.TouristHorizonMaxRange * MatchState.TouristHorizonMaxRange)
|
||||
mem.VisibleToPlayer = false;
|
||||
if (mem.HasEverBeenSeen)
|
||||
{
|
||||
horizonPing = HasLineOfSight(
|
||||
p.X, pEyeY + 14f, p.Z,
|
||||
s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight) + 14f, s.Z);
|
||||
mem.LastSeenAge += FixedDt;
|
||||
}
|
||||
|
||||
// Spectator wall horizon rule: gaudy Tourists (RadarSignature >= 0.9) ping faintly over moderate crests at medium range;
|
||||
// low-signature Exemplars vanish completely when terrain-occluded.
|
||||
bool horizonPing = false;
|
||||
if (s.RadarSignature >= 0.9f)
|
||||
{
|
||||
float dx = s.X - p.X;
|
||||
float dz = s.Z - p.Z;
|
||||
if (dx * dx + dz * dz <= MatchState.TouristHorizonMaxRange * MatchState.TouristHorizonMaxRange)
|
||||
{
|
||||
horizonPing = HasLineOfSight(
|
||||
p.X, pEyeY + 14f, p.Z,
|
||||
s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight) + 14f, s.Z);
|
||||
}
|
||||
}
|
||||
mem.FaintHorizonPing = horizonPing;
|
||||
}
|
||||
mem.FaintHorizonPing = horizonPing;
|
||||
}
|
||||
else if (!mem.VisibleToPlayer && mem.HasEverBeenSeen)
|
||||
{
|
||||
mem.LastSeenAge += FixedDt;
|
||||
}
|
||||
|
||||
if (s.Stance != SpectatorStance.Neutral &&
|
||||
|
|
@ -1114,6 +1186,7 @@ namespace RustToDust.Ymir
|
|||
}
|
||||
}
|
||||
|
||||
_forceFullDetectionRefresh = false;
|
||||
State.PlayerDetectedByCount = detectedBy;
|
||||
}
|
||||
|
||||
|
|
@ -1192,7 +1265,10 @@ namespace RustToDust.Ymir
|
|||
view.RotationW[lane]);
|
||||
ulong shooterStableId = ContenderStableIdBase + (ulong)c.Id;
|
||||
|
||||
UpdateWeaponArcTelemetry(c, shooterQuat, shooterStableId);
|
||||
if (c.IsPlayer)
|
||||
{
|
||||
UpdateWeaponArcTelemetry(c, shooterQuat, shooterStableId);
|
||||
}
|
||||
|
||||
if (c.FireCmd)
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue