Add MechPaint surface shader, 4x4 POM decal atlas & shader, vertex weathering baker, and live GL3 probe

This commit is contained in:
Meta Vens 2026-12-04 23:30:58 +01:00
commit 81135e9a83
12 changed files with 2419 additions and 0 deletions

553
client/tests/VisualProbe.cs Normal file
View file

@ -0,0 +1,553 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Godot;
namespace RustToDust.Client.Tests;
/// <summary>
/// Live OpenGL 3.3 (gl_compatibility) visual verification probe for:
/// - Baked COLOR_0 vertex weathering (AO, edge curvature, per-island hash, rest height)
/// - Brokkr 6-layer MechPaint spatial shader (mech_paint.gdshader) + INSTANCE_CUSTOM scorch/heat
/// - 4x4 POM MultiMesh decal atlas + decal_pom.gdshader in 1 draw call
/// Captures a 1280x720 preview PNG to tools/decals/previews/visual_substrate_preview.png and %TEMP%.
/// </summary>
public partial class VisualProbe : Node3D
{
private readonly List<string> _failures = new();
private readonly List<IDisposable> _disposables = new();
public override void _Ready() => _ = RunAsync();
public override void _ExitTree()
{
foreach (var d in _disposables)
{
d.Dispose();
}
_disposables.Clear();
}
private void Check(bool cond, string msg)
{
if (!cond)
{
_failures.Add(msg);
GD.PushError("VISUAL_PROBE FAIL: " + msg);
}
}
private async Task RunAsync()
{
int exitCode = 0;
try
{
string repoRoot = Path.GetFullPath(Path.Combine(ProjectSettings.GlobalizePath("res://"), ".."));
string decalsDir = Path.Combine(repoRoot, "assets", "decals");
string previewRepoPath = Path.Combine(repoRoot, "tools", "decals", "previews", "visual_substrate_preview.png");
string previewTempPath = Path.Combine(Path.GetTempPath(), "visual_substrate_preview.png");
SetupEnvironment();
var mechShader = GD.Load<Shader>("res://mech_paint.gdshader");
var decalShader = GD.Load<Shader>("res://decal_pom.gdshader");
Check(mechShader is not null, "Failed to load res://mech_paint.gdshader");
Check(decalShader is not null, "Failed to load res://decal_pom.gdshader");
if (mechShader is null || decalShader is null)
{
Finish(1);
return;
}
ImageTexture albedoTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_albedo.png"));
ImageTexture normalTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_normal.png"));
ImageTexture ormhTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_ormh.png"));
var cache = new VehicleAssetCache();
_disposables.Add(cache);
var paladinTpl = cache.GetOrLoadVehicle("paladin");
var jackalTpl = cache.GetOrLoadVehicle("jackal");
VerifyBakedVertexColors("paladin", paladinTpl.BakedStaticMesh);
VerifyBakedVertexColors("jackal", jackalTpl.BakedStaticMesh);
// Ground desert pad
var groundMesh = new PlaneMesh { Size = new Vector2(48f, 48f) };
var groundMat = new StandardMaterial3D
{
AlbedoColor = new Color(0.42f, 0.34f, 0.24f),
Roughness = 0.94f,
Metallic = 0.02f
};
AddChild(new MeshInstance3D { Name = "DesertPad", Mesh = groundMesh, MaterialOverride = groundMat });
// Shared MechPaint ShaderMaterial variants (zero per-hit cloning)
var paladinArmorMat = MakeMechPaintMat(mechShader, new Color(0.306f, 0.341f, 0.251f), metallic: 0.22f, roughness: 0.58f, wear: 1.05f, grime: 0.95f, mud: 1.15f);
var jackalArmorMat = MakeMechPaintMat(mechShader, new Color(0.388f, 0.345f, 0.255f), metallic: 0.20f, roughness: 0.56f, wear: 1.15f, grime: 0.95f, mud: 1.25f, mudTop: 0.95f);
var gunmetalMat = MakeMechPaintMat(mechShader, new Color(0.173f, 0.188f, 0.180f), metallic: 0.78f, roughness: 0.42f, wear: 0.80f, grime: 1.10f, mud: 1.05f);
var copperMat = MakeMechPaintMat(mechShader, new Color(0.612f, 0.353f, 0.204f), metallic: 0.86f, roughness: 0.34f, wear: 0.65f, grime: 0.90f, mud: 0.80f);
var orangeMat = MakeMechPaintMat(mechShader, new Color(0.851f, 0.424f, 0.153f), metallic: 0.18f, roughness: 0.44f, wear: 1.10f, grime: 0.85f, mud: 0.90f);
var markMat = MakeMechPaintMat(mechShader, new Color(0.760f, 0.730f, 0.640f), metallic: 0.10f, roughness: 0.62f, wear: 0.95f, grime: 0.80f, mud: 0.80f);
// Spawn Paladin (left-center, 3/4 view toward camera)
var paladinMesh = (ArrayMesh)paladinTpl.BakedStaticMesh.Duplicate();
ApplyMechPaintSurfaces(paladinMesh, paladinArmorMat, gunmetalMat, copperMat, orangeMat, markMat);
var paladinXf = new Transform3D(new Basis(Vector3.Up, Mathf.DegToRad(24f)), new Vector3(-2.8f, 0f, -2.4f));
var paladinMi = new MeshInstance3D
{
Name = "PaladinWeathered",
Mesh = paladinMesh,
Transform = paladinXf
};
AddChild(paladinMi);
// Spawn Jackal (right-midground, angled 3/4 toward camera)
var jackalMesh = (ArrayMesh)jackalTpl.BakedStaticMesh.Duplicate();
ApplyMechPaintSurfaces(jackalMesh, jackalArmorMat, gunmetalMat, copperMat, orangeMat, markMat);
var jackalXf = new Transform3D(new Basis(Vector3.Up, Mathf.DegToRad(-38f)), new Vector3(3.4f, 0f, 1.2f));
var jackalMi = new MeshInstance3D
{
Name = "JackalWeathered",
Mesh = jackalMesh,
Transform = jackalXf
};
AddChild(jackalMi);
// Foreground angled Armor Showcase Slab (MechPaint via MultiMesh showing clean vs INSTANCE_CUSTOM scorch+heat)
var slabMesh = BuildBeveledShowcaseSlab(3.2f, 1.26f, 0.14f);
var slabMm = new MultiMesh
{
TransformFormat = MultiMesh.TransformFormatEnum.Transform3D,
UseCustomData = true,
Mesh = slabMesh,
InstanceCount = 2
};
var slabXf0 = new Transform3D(new Basis(Vector3.Up, Mathf.DegToRad(14f)) * new Basis(Vector3.Right, Mathf.DegToRad(-22f)), new Vector3(1.15f, 1.85f, 6.2f));
var slabXf1 = new Transform3D(new Basis(Vector3.Up, Mathf.DegToRad(-18f)) * new Basis(Vector3.Right, Mathf.DegToRad(-18f)) * Basis.FromScale(new Vector3(0.45f, 0.55f, 1.0f)), new Vector3(5.35f, 0.85f, 3.8f));
slabMm.SetInstanceTransform(0, slabXf0);
slabMm.SetInstanceCustomData(0, new Color(0.0f, 0.0f, 0f, 0f)); // clean weathered chest-height plate
slabMm.SetInstanceTransform(1, slabXf1);
slabMm.SetInstanceCustomData(1, new Color(0.90f, 0.48f, 0f, 0f)); // live combat scorch + heat_glow without cloning!
var slabMmi = new MultiMeshInstance3D
{
Name = "ShowcaseArmorPlates",
Multimesh = slabMm,
MaterialOverride = paladinArmorMat
};
AddChild(slabMmi);
// Build 1 single MultiMeshInstance3D batch of POM decals across Paladin, Jackal, and the Showcase Slab
var decalMat = new ShaderMaterial { Shader = decalShader };
decalMat.SetShaderParameter("albedo_tex", albedoTex);
decalMat.SetShaderParameter("normal_tex", normalTex);
decalMat.SetShaderParameter("ormh_tex", ormhTex);
decalMat.SetShaderParameter("use_instance_custom", true);
decalMat.SetShaderParameter("default_depth_scale", 0.06f);
decalMat.SetShaderParameter("normal_offset", 0.004f);
var decalPlacements = new List<(Transform3D Xform, Color Custom)>();
// Showcase slab POM decals (close 3/4 grazing angle so 3D depth & hot rims are unmistakable)
AddSlabDecal(decalPlacements, slabXf0, -1.16f, 0.30f, 0.07f, 0.48f, tile: 0, heat: 0.0f, opacity: 1.0f, depth: 0.080f); // louvered vent
AddSlabDecal(decalPlacements, slabXf0, -0.58f, 0.30f, 0.07f, 0.48f, tile: 1, heat: 0.0f, opacity: 1.0f, depth: 0.080f); // bolted hatch
AddSlabDecal(decalPlacements, slabXf0, 0.00f, 0.30f, 0.07f, 0.48f, tile: 3, heat: 0.0f, opacity: 1.0f, depth: 0.080f); // slotted intake grille
AddSlabDecal(decalPlacements, slabXf0, 0.58f, 0.30f, 0.07f, 0.48f, tile: 5, heat: 0.0f, opacity: 1.0f, depth: 0.070f); // welded patch
AddSlabDecal(decalPlacements, slabXf0, 1.16f, 0.30f, 0.07f, 0.46f, tile: 8, heat: 0.0f, opacity: 0.96f, depth: 0.03f); // stencil "03"
AddSlabDecal(decalPlacements, slabXf0, -1.16f, -0.30f, 0.07f, 0.48f, tile: 6, heat: 0.0f, opacity: 1.0f, depth: 0.085f); // lift-lug pocket
AddSlabDecal(decalPlacements, slabXf0, -0.58f, -0.30f, 0.07f, 0.48f, tile: 7, heat: 0.0f, opacity: 0.96f, depth: 0.04f); // hazard chevron
AddSlabDecal(decalPlacements, slabXf0, 0.00f, -0.30f, 0.07f, 0.50f, tile: 12, heat: 0.95f, opacity: 1.0f, depth: 0.095f); // glowing AP hole
AddSlabDecal(decalPlacements, slabXf0, 0.58f, -0.30f, 0.07f, 0.50f, tile: 13, heat: 0.75f, opacity: 1.0f, depth: 0.085f); // shrapnel gouge
AddSlabDecal(decalPlacements, slabXf0, 1.16f, -0.30f, 0.07f, 0.50f, tile: 14, heat: 0.92f, opacity: 1.0f, depth: 0.090f); // molten plasma crater
// Raycast flush decals directly onto Paladin armor surfaces
TryAddRayDecal(decalPlacements, paladinMesh, paladinXf, new Vector3(-2.6f, 8.2f, 3.0f), new Vector3(0f, -0.05f, -1f), 0.72f, tile: 0, heat: 0.0f, opacity: 1.0f, depth: 0.07f);
TryAddRayDecal(decalPlacements, paladinMesh, paladinXf, new Vector3(-1.5f, 8.8f, 3.0f), new Vector3(-0.2f, -0.05f, -1f), 0.65f, tile: 8, heat: 0.0f, opacity: 0.95f, depth: 0.03f);
TryAddRayDecal(decalPlacements, paladinMesh, paladinXf, new Vector3(-2.8f, 7.1f, 3.0f), new Vector3(0.05f, 0f, -1f), 0.72f, tile: 12, heat: 0.95f, opacity: 1.0f, depth: 0.09f);
TryAddRayDecal(decalPlacements, paladinMesh, paladinXf, new Vector3(-3.6f, 7.8f, 3.0f), new Vector3(0.25f, 0f, -1f), 0.65f, tile: 10, heat: 0.0f, opacity: 0.95f, depth: 0.03f);
// Raycast flush decals onto Jackal armor surfaces
TryAddRayDecal(decalPlacements, jackalMesh, jackalXf, new Vector3(3.4f, 3.0f, 1.5f), new Vector3(0f, -1f, 0.1f), 0.55f, tile: 9, heat: 0.0f, opacity: 0.95f, depth: 0.03f);
TryAddRayDecal(decalPlacements, jackalMesh, jackalXf, new Vector3(3.1f, 2.5f, 2.1f), new Vector3(0.2f, -0.8f, -0.5f), 0.50f, tile: 14, heat: 0.85f, opacity: 1.0f, depth: 0.08f);
var decalQuad = new QuadMesh { Size = Vector2.One };
var decalMm = new MultiMesh
{
TransformFormat = MultiMesh.TransformFormatEnum.Transform3D,
UseCustomData = true,
Mesh = decalQuad,
InstanceCount = decalPlacements.Count
};
for (int i = 0; i < decalPlacements.Count; i++)
{
decalMm.SetInstanceTransform(i, decalPlacements[i].Xform);
decalMm.SetInstanceCustomData(i, decalPlacements[i].Custom);
}
var decalMmi = new MultiMeshInstance3D
{
Name = "PomDecalsBatch",
Multimesh = decalMm,
MaterialOverride = decalMat,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off
};
AddChild(decalMmi);
// Camera framing full Paladin (head to feet) + Jackal + close grazing showcase slab
var cam = new Camera3D
{
Name = "ProbeCamera",
Current = true,
Fov = 48f,
Near = 0.08f,
Far = 200f
};
AddChild(cam);
cam.GlobalPosition = new Vector3(2.8f, 4.3f, 13.4f);
cam.LookAt(new Vector3(0.0f, 4.4f, 0.2f), Vector3.Up);
// Wait several rendered frames so OpenGL 3.3 compiles all shaders and finishes drawing
for (int f = 0; f < 6; f++)
{
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
}
if (DisplayServer.GetName() != "headless")
{
Image? cap = GetViewport().GetTexture()?.GetImage();
Check(cap is not null && cap.GetWidth() == 1280 && cap.GetHeight() == 720,
$"Expected 1280x720 viewport capture, got {cap?.GetWidth()}x{cap?.GetHeight()}");
if (cap is not null)
{
Directory.CreateDirectory(Path.GetDirectoryName(previewRepoPath)!);
cap.SavePng(previewRepoPath);
cap.SavePng(previewTempPath);
GD.Print($"VISUAL_PROBE SAVED: {previewRepoPath}");
GD.Print($"VISUAL_PROBE SAVED: {previewTempPath}");
}
}
double drawCalls = RenderingServer.GetRenderingInfo(RenderingServer.RenderingInfo.TotalDrawCallsInFrame);
GD.Print($"VISUAL_PROBE INFO: renderer={RenderingServer.GetVideoAdapterName()} drawCalls={drawCalls} pomDecals={decalPlacements.Count}");
Check(_failures.Count == 0, $"Encountered {_failures.Count} failures");
}
catch (Exception ex)
{
Check(false, ex.ToString());
}
exitCode = _failures.Count == 0 ? 0 : 1;
GD.Print(exitCode == 0 ? "VISUAL_PROBE RESULT: PASS" : $"VISUAL_PROBE RESULT: FAIL ({_failures.Count})");
Finish(exitCode);
}
private void Finish(int code)
{
GetTree().Quit(code);
}
private void SetupEnvironment()
{
var sun = new DirectionalLight3D
{
Name = "DesertSun",
LightColor = new Color(1.0f, 0.93f, 0.82f),
LightEnergy = 1.85f,
ShadowEnabled = true,
DirectionalShadowMode = DirectionalLight3D.ShadowMode.Parallel2Splits,
RotationDegrees = new Vector3(-38f, 36f, 0f)
};
AddChild(sun);
// Cool oblique fill light so POM recesses & metal rims catch clear specular highlights
var fill = new DirectionalLight3D
{
Name = "SkyFill",
LightColor = new Color(0.68f, 0.80f, 0.98f),
LightEnergy = 0.55f,
ShadowEnabled = false,
RotationDegrees = new Vector3(-25f, -125f, 0f)
};
AddChild(fill);
var skyMat = new ProceduralSkyMaterial
{
SkyTopColor = new Color(0.24f, 0.34f, 0.44f),
SkyHorizonColor = new Color(0.76f, 0.56f, 0.37f),
GroundBottomColor = new Color(0.28f, 0.20f, 0.14f),
GroundHorizonColor = new Color(0.68f, 0.48f, 0.32f)
};
var env = new Godot.Environment
{
BackgroundMode = Godot.Environment.BGMode.Sky,
Sky = new Sky { SkyMaterial = skyMat },
AmbientLightSource = Godot.Environment.AmbientSource.Sky,
AmbientLightEnergy = 0.65f
};
AddChild(new WorldEnvironment { Name = "WorldEnv", Environment = env });
}
private void VerifyBakedVertexColors(string name, ArrayMesh mesh)
{
int surfCount = mesh.GetSurfaceCount();
bool foundColor = false;
float minR = 1f, maxR = 0f, minG = 1f, maxG = 0f, minB = 1f, maxB = 0f, minA = 1f, maxA = 0f;
int totalVerts = 0;
for (int s = 0; s < surfCount; s++)
{
var arrays = mesh.SurfaceGetArrays(s);
if (arrays.Count > (int)Mesh.ArrayType.Color &&
arrays[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray)
{
Color[] cols = arrays[(int)Mesh.ArrayType.Color].AsColorArray();
foundColor = true;
totalVerts += cols.Length;
foreach (Color c in cols)
{
if (c.R < minR) minR = c.R; if (c.R > maxR) maxR = c.R;
if (c.G < minG) minG = c.G; if (c.G > maxG) maxG = c.G;
if (c.B < minB) minB = c.B; if (c.B > maxB) maxB = c.B;
if (c.A < minA) minA = c.A; if (c.A > maxA) maxA = c.A;
}
}
}
GD.Print($"COLOR_0 [{name}]: verts={totalVerts} AO=[{minR:F2},{maxR:F2}] Edge=[{minG:F2},{maxG:F2}] Island=[{minB:F2},{maxB:F2}] Height=[{minA:F2},{maxA:F2}]");
Check(foundColor && totalVerts > 0, $"{name} missing baked COLOR_0 array");
Check(minR < 0.35f && maxR > 0.85f, $"{name} AO range too narrow [{minR:F2},{maxR:F2}]");
Check(maxG > 0.65f, $"{name} Edge curvature max too low ({maxG:F2})");
Check(maxA - minA > 0.15f, $"{name} Rest height span too small [{minA:F2},{maxA:F2}]");
}
private static ImageTexture LoadTextureWithMips(string path)
{
var img = Image.LoadFromFile(path);
if (img is null)
{
throw new FileNotFoundException($"Could not load texture '{path}'", path);
}
img.GenerateMipmaps();
return ImageTexture.CreateFromImage(img);
}
private static ShaderMaterial MakeMechPaintMat(
Shader shader,
Color baseColor,
float metallic,
float roughness,
float wear,
float grime,
float mud,
float mudTop = 1.45f)
{
var mat = new ShaderMaterial { Shader = shader };
mat.SetShaderParameter("base_color", baseColor);
mat.SetShaderParameter("metallic", metallic);
mat.SetShaderParameter("roughness", roughness);
mat.SetShaderParameter("wear", wear);
mat.SetShaderParameter("grime", grime);
mat.SetShaderParameter("mud", mud);
mat.SetShaderParameter("mud_top", mudTop);
return mat;
}
private static void ApplyMechPaintSurfaces(
ArrayMesh mesh,
ShaderMaterial armorMat,
ShaderMaterial gunmetalMat,
ShaderMaterial copperMat,
ShaderMaterial orangeMat,
ShaderMaterial markMat)
{
int n = mesh.GetSurfaceCount();
for (int s = 0; s < n; s++)
{
Material? orig = mesh.SurfaceGetMaterial(s);
string mName = (orig?.ResourceName ?? string.Empty).ToLowerInvariant();
if (mName.Contains("glass") || mName.Contains("lamp") || mName.Contains("glow") || mName.Contains("cyan"))
{
continue;
}
if (mName.Contains("copper"))
{
mesh.SurfaceSetMaterial(s, copperMat);
}
else if (mName.Contains("signal") || mName.Contains("orange"))
{
mesh.SurfaceSetMaterial(s, orangeMat);
}
else if (mName.Contains("mark") || mName.Contains("stencil"))
{
mesh.SurfaceSetMaterial(s, markMat);
}
else if (mName.Contains("gunmetal") || mName.Contains("metal") || mName.Contains("steel") || mName.Contains("socket") || mName.Contains("pit") || mName.Contains("rubber"))
{
mesh.SurfaceSetMaterial(s, gunmetalMat);
}
else
{
mesh.SurfaceSetMaterial(s, armorMat);
}
}
}
private static ArrayMesh BuildBeveledShowcaseSlab(float w, float h, float d)
{
// Build a subdivided box with baked COLOR_0 (flat faces G=0, sharp edges G=1, AO=0.9, island=0.42)
float hw = w * 0.5f, hh = h * 0.5f, hd = d * 0.5f;
var st = new SurfaceTool();
st.Begin(Mesh.PrimitiveType.Triangles);
void AddQuad(Vector3 a, Vector3 b, Vector3 c, Vector3 dPt, Vector3 nrm, float edgeA, float edgeB, float edgeC, float edgeD)
{
void V(Vector3 p, Vector2 uv, float edge)
{
float restH = Math.Clamp((p.Y + 4.2f) / 6.0f, 0f, 1f);
st.SetColor(new Color(0.92f, edge, 0.42f, restH));
st.SetNormal(nrm);
st.SetUV(uv);
st.AddVertex(p);
}
// Clockwise front-face winding for Godot Spatial cull_back
V(a, new Vector2(0, 1), edgeA);
V(c, new Vector2(1, 0), edgeC);
V(b, new Vector2(1, 1), edgeB);
V(a, new Vector2(0, 1), edgeA);
V(dPt, new Vector2(0, 0), edgeD);
V(c, new Vector2(1, 0), edgeC);
}
// Front (+Z) subdivided 3x1 so center interior vertices have edge=0 and outer corners have edge=0.95
float x0 = -hw, x1 = -hw * 0.72f, x2 = hw * 0.72f, x3 = hw;
float y0 = -hh, y1 = -hh * 0.65f, y2 = hh * 0.65f, y3 = hh;
float[] xs = { x0, x1, x2, x3 };
float[] ys = { y0, y1, y2, y3 };
float[,] edges = {
{ 0.95f, 0.85f, 0.85f, 0.95f },
{ 0.85f, 0.00f, 0.00f, 0.85f },
{ 0.85f, 0.00f, 0.00f, 0.85f },
{ 0.95f, 0.85f, 0.85f, 0.95f },
};
for (int iy = 0; iy < 3; iy++)
{
for (int ix = 0; ix < 3; ix++)
{
AddQuad(
new Vector3(xs[ix], ys[iy], hd),
new Vector3(xs[ix + 1], ys[iy], hd),
new Vector3(xs[ix + 1], ys[iy + 1], hd),
new Vector3(xs[ix], ys[iy + 1], hd),
Vector3.Back,
edges[iy, ix], edges[iy, ix + 1], edges[iy + 1, ix + 1], edges[iy + 1, ix]);
}
}
// Back & sides
AddQuad(new Vector3(hw, -hh, -hd), new Vector3(-hw, -hh, -hd), new Vector3(-hw, hh, -hd), new Vector3(hw, hh, -hd), Vector3.Forward, 0.9f, 0.9f, 0.9f, 0.9f);
AddQuad(new Vector3(-hw, hh, hd), new Vector3(hw, hh, hd), new Vector3(hw, hh, -hd), new Vector3(-hw, hh, -hd), Vector3.Up, 0.95f, 0.95f, 0.95f, 0.95f);
AddQuad(new Vector3(-hw, -hh, -hd), new Vector3(hw, -hh, -hd), new Vector3(hw, -hh, hd), new Vector3(-hw, -hh, hd), Vector3.Down, 0.95f, 0.95f, 0.95f, 0.95f);
AddQuad(new Vector3(-hw, -hh, -hd), new Vector3(-hw, -hh, hd), new Vector3(-hw, hh, hd), new Vector3(-hw, hh, -hd), Vector3.Left, 0.95f, 0.95f, 0.95f, 0.95f);
AddQuad(new Vector3(hw, -hh, hd), new Vector3(hw, -hh, -hd), new Vector3(hw, hh, -hd), new Vector3(hw, hh, hd), Vector3.Right, 0.95f, 0.95f, 0.95f, 0.95f);
st.GenerateTangents();
return st.Commit();
}
private static void AddSlabDecal(
List<(Transform3D, Color)> list,
Transform3D slabXf,
float lx,
float ly,
float lz,
float size,
int tile,
float heat,
float opacity,
float depth)
{
var localXf = new Transform3D(Basis.FromScale(new Vector3(size, size, 1f)), new Vector3(lx, ly, lz));
list.Add((slabXf * localXf, new Color(tile, heat, opacity, depth)));
}
private static void TryAddRayDecal(
List<(Transform3D, Color)> list,
ArrayMesh mesh,
Transform3D meshXf,
Vector3 worldOrigin,
Vector3 worldDir,
float size,
int tile,
float heat,
float opacity,
float depth)
{
Transform3D inv = meshXf.AffineInverse();
Vector3 localOrigin = inv * worldOrigin;
Vector3 localDir = (inv.Basis * worldDir).Normalized();
float bestT = float.PositiveInfinity;
Vector3 bestN = Vector3.Back;
for (int s = 0; s < mesh.GetSurfaceCount(); s++)
{
var arr = mesh.SurfaceGetArrays(s);
if (arr.Count <= (int)Mesh.ArrayType.Vertex) continue;
Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array();
int[]? indices = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array
? arr[(int)Mesh.ArrayType.Index].AsInt32Array()
: null;
int triCount = (indices is not null ? indices.Length : verts.Length) / 3;
for (int t = 0; t < triCount; t++)
{
int i0 = indices is not null ? indices[t * 3] : t * 3;
int i1 = indices is not null ? indices[t * 3 + 1] : t * 3 + 1;
int i2 = indices is not null ? indices[t * 3 + 2] : t * 3 + 2;
Vector3 v0 = verts[i0], v1 = verts[i1], v2 = verts[i2];
if (RayTriangle(localOrigin, localDir, v0, v1, v2, out float hitT))
{
if (hitT < bestT)
{
Vector3 fn = (v1 - v0).Cross(v2 - v0);
if (fn.LengthSquared() > 1e-10f)
{
fn = fn.Normalized();
if (fn.Dot(-localDir) < 0f) fn = -fn;
bestT = hitT;
bestN = fn;
}
}
}
}
}
if (!float.IsFinite(bestT))
{
return;
}
Vector3 worldHit = meshXf * (localOrigin + localDir * bestT);
Vector3 worldN = (meshXf.Basis.Inverse().Transposed() * bestN).Normalized();
Vector3 upRef = MathF.Abs(worldN.Y) > 0.92f ? Vector3.Forward : Vector3.Up;
Vector3 right = upRef.Cross(worldN).Normalized();
Vector3 up = worldN.Cross(right).Normalized();
var basis = new Basis(right * size, up * size, worldN);
list.Add((new Transform3D(basis, worldHit), new Color(tile, heat, opacity, depth)));
}
private static bool RayTriangle(Vector3 orig, Vector3 dir, Vector3 v0, Vector3 v1, Vector3 v2, out float t)
{
t = 0f;
Vector3 e1 = v1 - v0;
Vector3 e2 = v2 - v0;
Vector3 pvec = dir.Cross(e2);
float det = e1.Dot(pvec);
if (MathF.Abs(det) < 1e-7f) return false;
float invDet = 1f / det;
Vector3 tvec = orig - v0;
float u = tvec.Dot(pvec) * invDet;
if (u < 0f || u > 1f) return false;
Vector3 qvec = tvec.Cross(e1);
float v = dir.Dot(qvec) * invDet;
if (v < 0f || u + v > 1f) return false;
t = e2.Dot(qvec) * invDet;
return t > 0.01f;
}
}