diff --git a/editor/VoxelEditor/VoxelEditorView.axaml.cs b/editor/VoxelEditor/VoxelEditorView.axaml.cs index 53d3f91bb..4b4cbd558 100644 --- a/editor/VoxelEditor/VoxelEditorView.axaml.cs +++ b/editor/VoxelEditor/VoxelEditorView.axaml.cs @@ -12,7 +12,7 @@ public partial class VoxelEditorView : UserControl { public VoxelEditorView() { InitializeComponent(); - AddHandler(KeyDownEvent, OnShortcut, RoutingStrategies.Tunnel, true); + AddHandler(KeyDownEvent, OnShortcut, RoutingStrategies.Tunnel); AddHandler(PointerPressedEvent, (_, _) => m_vm?.EnsureEngine(), RoutingStrategies.Tunnel, true); DataContextChanged += (_, _) => Bind(DataContext as VoxelEditorViewModel); } diff --git a/engine/assets/shaders/gi_sample.slang b/engine/assets/shaders/gi_sample.slang index 5c7ad9213..85b8b2c0f 100644 --- a/engine/assets/shaders/gi_sample.slang +++ b/engine/assets/shaders/gi_sample.slang @@ -481,7 +481,8 @@ float4 giClipAmbientAt(GiClipFrame frame, uint level, float3 worldPosition, floa } /// Empty cells hold nothing so the filtered value is divided by the solid share around the point -bool sampleGiClipAmbient(float3 worldPosition, float3 normal, out float3 irradiance) +/// @p blendLevels false takes the finer level alone, cheaper where a seam is hidden +bool sampleGiClipAmbient(float3 worldPosition, float3 normal, bool blendLevels, out float3 irradiance) { irradiance = float3(0.0, 0.0, 0.0); const GiClipFrame frame = gGiClipFrame[0]; @@ -498,7 +499,7 @@ bool sampleGiClipAmbient(float3 worldPosition, float3 normal, out float3 irradia const float level = min(soft, last); const uint fine = uint(floor(level)); float4 ambient = giClipAmbientAt(frame, fine, worldPosition, normal); - if (level > float(fine)) + if (blendLevels && level > float(fine)) { ambient = lerp(ambient, giClipAmbientAt(frame, fine + 1u, worldPosition, normal), level - float(fine)); } @@ -512,7 +513,17 @@ bool sampleGiClipAmbient(float3 worldPosition, float3 normal, out float3 irradia bool giHitIrradiance(float3 worldPosition, float3 normal, out float3 irradiance) { - if (sampleGiClipAmbient(worldPosition, normal, irradiance)) + if (sampleGiClipAmbient(worldPosition, normal, true, irradiance)) + { + return true; + } + return sampleRadianceCascades(worldPosition, normal, irradiance); +} + +/// For reflected hits off screen where the blur of the lobe hides the step between levels +bool giHitIrradianceNearest(float3 worldPosition, float3 normal, out float3 irradiance) +{ + if (sampleGiClipAmbient(worldPosition, normal, false, irradiance)) { return true; } diff --git a/engine/assets/shaders/scene_trace.slang b/engine/assets/shaders/scene_trace.slang index 1ca4c310f..ae7e73f08 100644 --- a/engine/assets/shaders/scene_trace.slang +++ b/engine/assets/shaders/scene_trace.slang @@ -286,14 +286,11 @@ float3 traceVisibility(float3 origin, float3 segment, float coneSlope, bool tint ray.Direction = segment; ray.TMin = 0.0; ray.TMax = 1.0; - RayQuery query; + // Voxels are AABBs only so triangle instances under the mask never become candidates + RayQuery query; query.TraceRayInline(gScene, RAY_FLAG_NONE, tinted ? kTraceMaskVolume | kTraceMaskGlass : kTraceMaskVolume, ray); while (query.Proceed()) { - if (query.CandidateType() != CANDIDATE_PROCEDURAL_PRIMITIVE) - { - continue; - } const uint custom = query.CandidateInstanceID(); const uint v = custom & kTraceInstanceVolume; bool blocked = false; @@ -336,14 +333,11 @@ float3 traceGlassFilter(float3 origin, float3 segment, float coneSlope) ray.Direction = segment; ray.TMin = 0.0; ray.TMax = 1.0; - RayQuery query; + // Voxels are AABBs only so triangle instances under the mask never become candidates + RayQuery query; query.TraceRayInline(gScene, RAY_FLAG_NONE, kTraceMaskGlass, ray); while (query.Proceed()) { - if (query.CandidateType() != CANDIDATE_PROCEDURAL_PRIMITIVE) - { - continue; - } const uint custom = query.CandidateInstanceID(); const uint v = custom & kTraceInstanceVolume; if ((custom & kTraceInstanceBricks) != 0u) @@ -417,14 +411,11 @@ SceneHit traceScene(float3 origin, float3 direction, float tMin, float tMax, flo ray.Direction = direction; ray.TMin = tMin; ray.TMax = tMax; - RayQuery query; + // Voxels are AABBs only so triangle instances under the mask never become candidates + RayQuery query; query.TraceRayInline(gScene, RAY_FLAG_NONE, kTraceMaskVolume, ray); while (query.Proceed()) { - if (query.CandidateType() != CANDIDATE_PROCEDURAL_PRIMITIVE) - { - continue; - } const uint custom = query.CandidateInstanceID(); const uint v = custom & kTraceInstanceVolume; const RayHit hit = (custom & kTraceInstanceBricks) != 0u diff --git a/engine/assets/shaders/screen_march.slang b/engine/assets/shaders/screen_march.slang new file mode 100644 index 000000000..b09a70675 --- /dev/null +++ b/engine/assets/shaders/screen_march.slang @@ -0,0 +1,178 @@ +// Hi-Z screen march shared by SSR and the traced voxel specular +import depth_convention; + +/// What a march reads besides the depth and its closest depth renderer::HiZPyramid +public struct ScreenMarch +{ + public float4x4 viewProjection; + public float4x4 inverseViewProjection; + /// Meters the ray may travel before the screen edge clips it + public float reach; + /// Meters behind a surface a ray still counts as hitting it, scaled with depth + public float thickness; + public uint maxSteps; + /// Levels of the pyramid + public int levels; +}; + +/// Pixels a finest level step scans along the ray so grazing floors reach as far as steep walls +static const float kScanCell = 8.0; + +/// Clip w from the 1 / w row of the inverse view projection +float marchLinearDepth(ScreenMarch march, float2 uv, float depth) +{ + return 1.0 / max(dot(march.inverseViewProjection[3], float4(uv * 2.0 - 1.0, depth, 1.0)), 1e-8); +} + +/// Full resolution check of the ray against gDepth at @p t, @p behind true when the ray went behind a surface too thick to hit +bool pixelHit(ScreenMarch march, Sampler2D depthTexture, float2 p0, float2 d, float z0, float dz, float t, float2 size, + out bool behind) +{ + behind = false; + const float2 uv = (p0 + d * t) / size; + const float depth = depthTexture.SampleLevel(uv, 0.0).r; + if (isFarDepth(depth) || isCloserDepth(z0 + dz * t, depth)) + { + return false; + } + const float sceneDepth = marchLinearDepth(march, uv, depth); + const float gap = marchLinearDepth(march, uv, z0 + dz * t) - sceneDepth; + behind = gap > march.thickness * (1.0 + 0.025 * sceneDepth); + return !behind; +} + +/// Hi-Z march in screen space clipped to the screen and the reach so a ray goes as far as the screen shows +/// @p fade drops reach limited rays near their end so they fade out instead of cutting off +public bool marchScreenHiz(ScreenMarch march, Sampler2D depthTexture, Sampler2D hiz, float3 origin, float3 direction, float jitter, + out float2 hitUv, out float fade) +{ + hitUv = float2(0.0, 0.0); + fade = 1.0; + + uint width; + uint height; + depthTexture.GetDimensions(width, height); + const float2 size = float2(float(width), float(height)); + + float reach = march.reach; + const float4 start = mul(march.viewProjection, float4(origin, 1.0)); + float4 end = mul(march.viewProjection, float4(origin + direction * reach, 1.0)); + + // Stops short of the near plane so 1 / w stays finite + const float minW = 1e-3; + if (end.w < minW) + { + reach *= (start.w - minW) / max(start.w - end.w, 1e-6); + end = mul(march.viewProjection, float4(origin + direction * reach, 1.0)); + } + + const float2 p0 = (start.xy / start.w * 0.5 + 0.5) * size; + const float2 p1 = (end.xy / end.w * 0.5 + 0.5) * size; + const float z0 = start.z / start.w; + const float dz = end.z / end.w - z0; + const float2 d = p1 - p0; + const float pixels = length(d); + if (pixels < 1.0) + { + return false; + } + + // Clipped to the screen edge so the reach is only a cap + float tEnd = 1.0; + [unroll] + for (int axis = 0; axis < 2; ++axis) + { + if (abs(d[axis]) > 1e-6) + { + tEnd = min(tEnd, ((d[axis] > 0.0 ? size[axis] - 0.5 : 0.5) - p0[axis]) / d[axis]); + } + } + if (tEnd <= 0.0) + { + return false; + } + const bool reachLimited = tEnd >= 1.0; + + const float2 inverseD = float2(abs(d.x) > 1e-6 ? 1.0 / d.x : 1e30, abs(d.y) > 1e-6 ? 1.0 / d.y : 1e30); + const float2 forward = step(float2(0.0, 0.0), d); + const float tPixel = 1.0 / pixels; + const int topLevel = max(march.levels - 1, 0); + const uint maxSteps = max(march.maxSteps, 1u); + + float t = tPixel * (1.0 + jitter); + int level = 0; + for (uint i = 0u; i < maxSteps && t < tEnd; ++i) + { + const float2 p = p0 + d * t; + const float cellSize = float(2u << uint(level)); + const float2 cell = floor(p / cellSize); + const float cellDepth = hiz.Load(int3(int2(cell), level)).r; + const float2 exits = ((cell + forward) * cellSize - p0) * inverseD; + // A hair past the boundary so the next cell is the one the ray enters + const float tCell = min(min(exits.x, exits.y) + 0.01 * tPixel, tEnd); + + if (!isCloserDepth(z0 + dz * t, cellDepth)) + { + if (level > 0) + { + --level; + continue; + } + // The 2x2 cell holds something at least as close as the ray so test pixels at full resolution + // on to the edge of the 8x8 cell around it since a grazing ray otherwise spends a step every 2 pixels + const float2 scanCell = floor(p / kScanCell); + const float2 scanExits = ((scanCell + forward) * kScanCell - p0) * inverseD; + const float tScan = max(min(min(scanExits.x, scanExits.y) + 0.01 * tPixel, tEnd), tCell); + float previous = t - tPixel; + // Two pixels a step with both reads issued before either is tested so their latency overlaps + for (float x = t; x < tScan; x += 2.0 * tPixel) + { + const float next = x + tPixel; + bool behind; + bool behindNext; + const bool hitHere = pixelHit(march, depthTexture, p0, d, z0, dz, x, size, behind); + const bool hitNext = pixelHit(march, depthTexture, p0, d, z0, dz, next, size, behindNext) && next < tScan; + if (hitHere || hitNext) + { + float lo = max(hitHere ? previous : x, 0.0); + float hi = hitHere ? x : next; + [unroll] + for (uint j = 0u; j < 4u; ++j) + { + const float mid = 0.5 * (lo + hi); + const float2 midUv = (p0 + d * mid) / size; + const float midDepth = depthTexture.SampleLevel(midUv, 0.0).r; + if (!isFarDepth(midDepth) && !isCloserDepth(z0 + dz * mid, midDepth)) + { + hi = mid; + } + else + { + lo = mid; + } + } + hitUv = (p0 + d * hi) / size; + fade = reachLimited ? 1.0 - smoothstep(0.7, 1.0, hi) : 1.0; + return true; + } + previous = next; + } + t = tScan; + continue; + } + + if (isCloserDepth(z0 + dz * tCell, cellDepth)) + { + // Wholly in front of everything in the cell + t = tCell; + level = min(level + 1, topLevel); + } + else + { + // Reaches the closest depth inside the cell so refine from there + t = max(t + 0.01 * tPixel, (cellDepth - z0) / dz); + level = max(level - 1, 0); + } + } + return false; +} diff --git a/engine/assets/shaders/screen_march.slang.meta b/engine/assets/shaders/screen_march.slang.meta new file mode 100644 index 000000000..9d49194de --- /dev/null +++ b/engine/assets/shaders/screen_march.slang.meta @@ -0,0 +1,4 @@ +uid = "Bc6AR02k44u" +type = "slang_module" +created_at = "2026-11-18T19:45:00.0000000Z" +modified_at = "2026-11-18T19:45:00.0000000Z" diff --git a/engine/assets/shaders/ssr.slang b/engine/assets/shaders/ssr.slang index a5099ca42..a61b77cc6 100644 --- a/engine/assets/shaders/ssr.slang +++ b/engine/assets/shaders/ssr.slang @@ -3,6 +3,7 @@ import fullscreen; import depth_convention; import scene_normal; import ggx_sampling; +import screen_march; struct SsrParams { @@ -58,9 +59,6 @@ Sampler2D gHiz; [[vk::binding(10, 0)]] Sampler2D gAmbientSpecular; -/// Pixels a finest level step scans along the ray so grazing floors reach as far as steep walls -static const float kScanCell = 8.0; - /// Below this a surface is a mirror and gets one ray with no reuse static const float kMirrorRoughness = 0.05; @@ -158,150 +156,16 @@ float planeWeight(SurfaceSample surface, float3 position) return exp(-abs(dot(surface.normal, position - surface.position)) / (0.005 * surface.linearDepth + 0.01)); } -/// Full resolution check of the ray against gDepth at @p t, @p behind true when the ray went behind a surface too thick to hit -bool pixelHit(float2 p0, float2 d, float z0, float dz, float t, float2 size, out bool behind) -{ - behind = false; - const float2 uv = (p0 + d * t) / size; - const float depth = gDepth.SampleLevel(uv, 0.0).r; - if (isFarDepth(depth) || isCloserDepth(z0 + dz * t, depth)) - { - return false; - } - const float sceneDepth = linearDepth(uv, depth); - const float gap = linearDepth(uv, z0 + dz * t) - sceneDepth; - behind = gap > gParams.tuning.z * (1.0 + 0.025 * sceneDepth); - return !behind; -} - -/// Hi-Z march in screen space clipped to the screen and the reach so a ray goes as far as the screen shows -/// @p fade drops reach limited rays near their end so they fade out instead of cutting off bool marchScreen(float3 origin, float3 direction, float jitter, out float2 hitUv, out float fade) { - hitUv = float2(0.0, 0.0); - fade = 1.0; - - uint width; - uint height; - gDepth.GetDimensions(width, height); - const float2 size = float2(float(width), float(height)); - - float reach = gParams.marching.x; - const float4 start = mul(gParams.viewProjection, float4(origin, 1.0)); - float4 end = mul(gParams.viewProjection, float4(origin + direction * reach, 1.0)); - - // Stops short of the near plane so 1 / w stays finite - const float minW = 1e-3; - if (end.w < minW) - { - reach *= (start.w - minW) / max(start.w - end.w, 1e-6); - end = mul(gParams.viewProjection, float4(origin + direction * reach, 1.0)); - } - - const float2 p0 = (start.xy / start.w * 0.5 + 0.5) * size; - const float2 p1 = (end.xy / end.w * 0.5 + 0.5) * size; - const float z0 = start.z / start.w; - const float dz = end.z / end.w - z0; - const float2 d = p1 - p0; - const float pixels = length(d); - if (pixels < 1.0) - { - return false; - } - - // Clipped to the screen edge so the reach is only a cap - float tEnd = 1.0; - [unroll] - for (int axis = 0; axis < 2; ++axis) - { - if (abs(d[axis]) > 1e-6) - { - tEnd = min(tEnd, ((d[axis] > 0.0 ? size[axis] - 0.5 : 0.5) - p0[axis]) / d[axis]); - } - } - if (tEnd <= 0.0) - { - return false; - } - const bool reachLimited = tEnd >= 1.0; - - const float2 inverseD = float2(abs(d.x) > 1e-6 ? 1.0 / d.x : 1e30, abs(d.y) > 1e-6 ? 1.0 / d.y : 1e30); - const float2 forward = step(float2(0.0, 0.0), d); - const float tPixel = 1.0 / pixels; - const int topLevel = max(int(gParams.pyramid.x) - 1, 0); - const uint maxSteps = max(uint(gParams.tuning.w), 1u); - - float t = tPixel * (1.0 + jitter); - int level = 0; - for (uint i = 0u; i < maxSteps && t < tEnd; ++i) - { - const float2 p = p0 + d * t; - const float cellSize = float(2u << uint(level)); - const float2 cell = floor(p / cellSize); - const float cellDepth = gHiz.Load(int3(int2(cell), level)).r; - const float2 exits = ((cell + forward) * cellSize - p0) * inverseD; - // A hair past the boundary so the next cell is the one the ray enters - const float tCell = min(min(exits.x, exits.y) + 0.01 * tPixel, tEnd); - - if (!isCloserDepth(z0 + dz * t, cellDepth)) - { - if (level > 0) - { - --level; - continue; - } - // The 2x2 cell holds something at least as close as the ray so test pixels at full resolution - // on to the edge of the 8x8 cell around it since a grazing ray otherwise spends a step every 2 pixels - const float2 scanCell = floor(p / kScanCell); - const float2 scanExits = ((scanCell + forward) * kScanCell - p0) * inverseD; - const float tScan = max(min(min(scanExits.x, scanExits.y) + 0.01 * tPixel, tEnd), tCell); - float previous = t - tPixel; - for (float x = t; x < tScan; x += tPixel) - { - bool behind; - if (pixelHit(p0, d, z0, dz, x, size, behind)) - { - float lo = max(previous, 0.0); - float hi = x; - [unroll] - for (uint j = 0u; j < 4u; ++j) - { - const float mid = 0.5 * (lo + hi); - const float2 midUv = (p0 + d * mid) / size; - const float midDepth = gDepth.SampleLevel(midUv, 0.0).r; - if (!isFarDepth(midDepth) && !isCloserDepth(z0 + dz * mid, midDepth)) - { - hi = mid; - } - else - { - lo = mid; - } - } - hitUv = (p0 + d * hi) / size; - fade = reachLimited ? 1.0 - smoothstep(0.7, 1.0, hi) : 1.0; - return true; - } - previous = x; - } - t = tScan; - continue; - } - - if (isCloserDepth(z0 + dz * tCell, cellDepth)) - { - // Wholly in front of everything in the cell - t = tCell; - level = min(level + 1, topLevel); - } - else - { - // Reaches the closest depth inside the cell so refine from there - t = max(t + 0.01 * tPixel, (cellDepth - z0) / dz); - level = max(level - 1, 0); - } - } - return false; + ScreenMarch march; + march.viewProjection = gParams.viewProjection; + march.inverseViewProjection = gParams.inverseViewProjection; + march.reach = gParams.marching.x; + march.thickness = gParams.tuning.z; + march.maxSteps = uint(gParams.tuning.w); + march.levels = int(gParams.pyramid.x); + return marchScreenHiz(march, gDepth, gHiz, origin, direction, jitter, hitUv, fade); } /// Stratum fixed to the surface on its dominant axis plane so rough reflections hold still as the camera moves diff --git a/engine/assets/shaders/volumetrics.slang b/engine/assets/shaders/volumetrics.slang index 1a5e417c9..f4dab83de 100644 --- a/engine/assets/shaders/volumetrics.slang +++ b/engine/assets/shaders/volumetrics.slang @@ -508,14 +508,27 @@ float4 temporalMain(VSOutput input) : SV_Target0 return lerp(history, current, kTemporalBlend); } +/// View depth capped like rayEnd, a single dot product since composite only compares texels with their neighbours +float compositeDepth(int2 pixel, float2 size) +{ + const float depth = gDepth.Load(int3(pixel, 0)).r; + if (isFarDepth(depth)) + { + return marchLimit(); + } + const float2 uv = (float2(pixel) + 0.5) / size; + const float w = dot(gParams.inverseViewProjection[3], float4(uv * 2.0 - 1.0, depth, 1.0)); + return min(1.0 / max(w, 1e-8), marchLimit()); +} + /// Bilinear among texels whose rays ended about as far away [shader("fragment")] float4 compositeMain(VSOutput input) : SV_Target0 { const int2 pixel = int2(input.position.xy); + const float2 size = fullSize(); const float3 scene = gSceneColour.Load(int3(pixel, 0)).rgb; - float distance; - rayEnd(pixel, distance); + const float distance = compositeDepth(pixel, size); uint width; uint height; @@ -525,28 +538,33 @@ float4 compositeMain(VSOutput input) : SV_Target0 const int2 base = int2(floor(low)); const float2 fraction = low - float2(base); + // All eight reads first so they overlap + float4 values[4]; + float texelDistances[4]; + [unroll] + for (int i = 0; i < 4; ++i) + { + const int2 texel = clamp(base + int2(i & 1, i >> 1), int2(0, 0), last); + values[i] = gTemporal.Load(int3(texel, 0)); + texelDistances[i] = compositeDepth(texel * int(gParams.quality.x), size); + } + float4 fog = float4(0.0, 0.0, 0.0, 0.0); float weightSum = 0.0; float4 nearest = float4(0.0, 0.0, 0.0, 1.0); float nearestError = 1e30; - for (int y = 0; y < 2; ++y) + [unroll] + for (int i = 0; i < 4; ++i) { - for (int x = 0; x < 2; ++x) + const float error = abs(texelDistances[i] - distance); + const float2 bilinear = lerp(1.0 - fraction, fraction, float2(float(i & 1), float(i >> 1))); + const float weight = bilinear.x * bilinear.y * exp(-error / (0.05 * distance + 0.05)); + fog += values[i] * weight; + weightSum += weight; + if (error < nearestError) { - const int2 texel = clamp(base + int2(x, y), int2(0, 0), last); - const float4 value = gTemporal.Load(int3(texel, 0)); - float texelDistance; - rayEnd(texel * int(gParams.quality.x), texelDistance); - const float error = abs(texelDistance - distance); - const float2 bilinear = lerp(1.0 - fraction, fraction, float2(float(x), float(y))); - const float weight = bilinear.x * bilinear.y * exp(-error / (0.05 * distance + 0.05)); - fog += value * weight; - weightSum += weight; - if (error < nearestError) - { - nearestError = error; - nearest = value; - } + nearestError = error; + nearest = values[i]; } } fog = weightSum > 1e-4 ? fog / weightSum : nearest; diff --git a/engine/assets/shaders/voxel.slang b/engine/assets/shaders/voxel.slang index e679d0af6..944576515 100644 --- a/engine/assets/shaders/voxel.slang +++ b/engine/assets/shaders/voxel.slang @@ -263,7 +263,6 @@ float gridLine(float2 position, float2 voxelsPerPixel, float period, float halfW static const uint kOverlayUnitGrid = 1u; static const uint kOverlayVoxelGrid = 2u; static const uint kOverlayVoxelEdges = 4u; -static const float3 kSelectionTint = float3(1.0, 0.366, 0.0); /// Voxel contour thing float voxelEdgeCoverage(uint recordIndex, RayHit hit, float3 cellPosition, float3 voxelsPerPixel, int3 outward) @@ -384,10 +383,6 @@ float3 applyEditorOverlays(float3 color, VoxelInstance instance, RayHit hit, flo } } - if (instance.highlightRecord != 0u && voxelMaterialAt(instance.highlightRecord - 1u, hit.voxel) != 0u) - { - color = lerp(color, kSelectionTint, 0.55); - } return color; } diff --git a/engine/assets/shaders/voxel_dda.slang b/engine/assets/shaders/voxel_dda.slang index aabebf161..c4f69a65d 100644 --- a/engine/assets/shaders/voxel_dda.slang +++ b/engine/assets/shaders/voxel_dda.slang @@ -33,7 +33,7 @@ struct VoxelInstance float4x4 worldToVoxel; float4x4 previousVoxelToWorld; uint recordIndex; - uint highlightRecord; /// this is for selection tint + uint pad0; /// Bit 0 no real previous frame and bit 1 a mirrored transform uint flags; /// First global coarse cell of this instance in the cell cull dispatch diff --git a/engine/assets/shaders/voxel_glass.slang b/engine/assets/shaders/voxel_glass.slang index d0e594d29..dcc634332 100644 --- a/engine/assets/shaders/voxel_glass.slang +++ b/engine/assets/shaders/voxel_glass.slang @@ -424,18 +424,17 @@ bool compositeGlass(VSOutput input, bool surfaceOnly, out GlassComposite result) // Surfaces the walk entered within the lit budget, shaded after it so the walk loop stays small // Written by constant index so they stay in registers float slotT[kMaxLitSurfaces]; - int slotAxis[kMaxLitSurfaces]; - uint slotMaterial[kMaxLitSurfaces]; + /// Material with the axis in the top two bits + uint slotKey[kMaxLitSurfaces]; float3 slotWeight[kMaxLitSurfaces]; - float slotFresnel[kMaxLitSurfaces]; + // Only the first surface can reflect so only its fresnel is kept + float firstFresnel = 0.0; [unroll] for (uint k = 0u; k < kMaxLitSurfaces; ++k) { slotT[k] = 0.0; - slotAxis[k] = 0; - slotMaterial[k] = 0u; + slotKey[k] = 0u; slotWeight[k] = float3(0.0, 0.0, 0.0); - slotFresnel[k] = 0.0; } // A run of glass is nearly always one palette entry @@ -578,10 +577,12 @@ bool compositeGlass(VSOutput input, bool surfaceOnly, out GlassComposite result) if (k == litInterfaces) { slotT[k] = t; - slotAxis[k] = axis; - slotMaterial[k] = material; + slotKey[k] = material | (uint(axis) << 30u); slotWeight[k] = result.transmittance; - slotFresnel[k] = fresnel; + if (k == 0u) + { + firstFresnel = fresnel; + } } } ++litInterfaces; @@ -637,27 +638,43 @@ bool compositeGlass(VSOutput input, bool surfaceOnly, out GlassComposite result) [loop] for (uint k = 0u; k < kMaxLitSurfaces; ++k) { + // Picked by constant index since a slot array read at k would move the arrays to local memory + float slotTk = 0.0; + uint slotKeyK = 0u; + float3 slotWeightK = float3(0.0, 0.0, 0.0); + [unroll] + for (uint j = 0u; j < kMaxLitSurfaces; ++j) + { + if (j == k) + { + slotTk = slotT[j]; + slotKeyK = slotKey[j]; + slotWeightK = slotWeight[j]; + } + } + const int slotAxisK = int(slotKeyK >> 30u); + const uint slotMaterialK = slotKeyK & 0x3FFFFFFFu; // Weights only fall so nothing past a dim surface shows either - if (k >= litInterfaces || max(slotWeight[k].x, max(slotWeight[k].y, slotWeight[k].z)) < kContributionCutoff) + if (k >= litInterfaces || max(slotWeightK.x, max(slotWeightK.y, slotWeightK.z)) < kContributionCutoff) { break; } - if (lightCached && slotAxis[k] == lightAxis && slotMaterial[k] == lightMaterial) + if (lightCached && slotAxisK == lightAxis && slotMaterialK == lightMaterial) { - result.color += slotWeight[k] * cachedLight; + result.color += slotWeightK * cachedLight; continue; } float3 voxelNormal = float3(0.0, 0.0, 0.0); - voxelNormal[slotAxis[k]] = direction[slotAxis[k]] > 0.0 ? -1.0 : 1.0; + voxelNormal[slotAxisK] = direction[slotAxisK] > 0.0 ? -1.0 : 1.0; const float3 normal = normalize(mul(transpose((float3x3)worldToVoxel), voxelNormal)); // The first surface of each brick reflects so glass seen through glass shows the scene and not the bare sky, unless what // it reflects is too dim to show past the glass in front - const bool reflects = k == 0u && max(slotWeight[k].x, max(slotWeight[k].y, slotWeight[k].z)) * slotFresnel[k] >= kReflectionCutoff; + const bool reflects = k == 0u && max(slotWeightK.x, max(slotWeightK.y, slotWeightK.z)) * firstFresnel >= kReflectionCutoff; float fresnel; bool debugView = false; - const float3 light = shadeInterface(camera + worldDirection * slotT[k], normal, view, input.position.xy, - samplePalette(record, slotMaterial[k]), reflects, fresnel, debugView); + const float3 light = shadeInterface(camera + worldDirection * slotTk, normal, view, input.position.xy, + samplePalette(record, slotMaterialK), reflects, fresnel, debugView); if (debugView) { result.color = light; @@ -665,13 +682,13 @@ bool compositeGlass(VSOutput input, bool surfaceOnly, out GlassComposite result) result.debugView = true; return true; } - result.color += slotWeight[k] * light; + result.color += slotWeightK * light; ++result.shaded; result.reflected = result.reflected || (reflects && kSpecReflection != kReflectionNone); // Never a reflecting surface whose reflection belongs to it alone lightCached = !reflects; - lightAxis = slotAxis[k]; - lightMaterial = slotMaterial[k]; + lightAxis = slotAxisK; + lightMaterial = slotMaterialK; cachedLight = light; } return true; diff --git a/engine/assets/shaders/voxel_lighting.slang b/engine/assets/shaders/voxel_lighting.slang index 8b0c6c252..414a2112a 100644 --- a/engine/assets/shaders/voxel_lighting.slang +++ b/engine/assets/shaders/voxel_lighting.slang @@ -107,14 +107,18 @@ VSOutput vertexMain(uint vertexId : SV_VertexID) return fullscreenTriangle(vertexId); } -float3 positionAt(int2 pixel) +float3 positionFrom(int2 pixel, float depth) { const float2 uv = (float2(pixel) + 0.5) / gPush.viewport.xy; - const float depth = gDepth.Load(int3(pixel, 0)).r; const float4 world = mul(gPush.inverseViewProjection, float4(uv * 2.0 - 1.0, depth, 1.0)); return world.xyz / world.w; } +float3 positionAt(int2 pixel) +{ + return positionFrom(pixel, gDepth.Load(int3(pixel, 0)).r); +} + bool isLitVoxelAt(int2 pixel, out float3 faceNormal) { const float4 encoded = gFaceNormal.Load(int3(pixel, 0)); @@ -846,25 +850,37 @@ float4 giGatherAt(int2 pixel, float3 position, float3 normal) const float2 at = float2(pixel) * 0.5; const int2 base = int2(floor(at)); const float2 blend = at - float2(base); + // Every load of the four taps is issued before any test so they overlap instead of waiting one by one + float4 gathered[4]; + float4 sourceEncoded[4]; + float sourceDepth[4]; + int2 source[4]; + [unroll] + for (int tap = 0; tap < 4; ++tap) + { + const int2 half = clamp(base + int2(tap & 1, tap >> 1), int2(0, 0), size - 1); + source[tap] = giGatherPixel(half); + gathered[tap] = gGiGather.Load(int3(half, 0)); + sourceEncoded[tap] = gFaceNormal.Load(int3(source[tap], 0)); + sourceDepth[tap] = gDepth.Load(int3(source[tap], 0)).r; + } float4 sum = float4(0.0, 0.0, 0.0, 0.0); float total = 0.0; + [unroll] for (int tap = 0; tap < 4; ++tap) { const int2 corner = int2(tap & 1, tap >> 1); - const int2 half = clamp(base + corner, int2(0, 0), size - 1); - const float4 gathered = gGiGather.Load(int3(half, 0)); - const int2 source = giGatherPixel(half); - float3 sourceNormal; - if (gathered.a < 0.0 || !isLitVoxelAt(source, sourceNormal)) + if (gathered[tap].a < 0.0 || sourceEncoded[tap].a <= 0.5) { continue; } + const float3 sourceNormal = decodeFaceNormal(sourceEncoded[tap]); const float2 side = lerp(1.0 - blend, blend, float2(corner)); const float facing = saturate(dot(normal, sourceNormal)); - const float plane = saturate(1.0 - abs(dot(positionAt(source) - position, normal)) / kGiGatherPlane); + const float plane = saturate(1.0 - abs(dot(positionFrom(source[tap], sourceDepth[tap]) - position, normal)) / kGiGatherPlane); // A floor so a pixel right on a gather pixel still takes its neighbours when that one is rejected const float weight = (side.x * side.y + 0.01) * facing * facing * facing * facing * plane; - sum += gathered * weight; + sum += gathered[tap] * weight; total += weight; } return total > 1e-4 ? sum / total : float4(0.0, 0.0, 0.0, -1.0); @@ -876,6 +892,11 @@ FSOutput fragmentMain(VSOutput input) const int2 pixel = int2(input.position.xy); const int3 texel = int3(pixel, 0); const float4 albedo = gAlbedo.Load(texel); + // Above the discard so all five gbuffer reads are in flight together + const float depth = gDepth.Load(texel).r; + const float4 faceEncoded = gFaceNormal.Load(texel); + const float4 detailEncoded = gDetailNormal.Load(texel); + const float4 material = gMaterial.Load(texel); if (!isVoxelCoverage(albedo.a)) { discard; @@ -892,12 +913,10 @@ FSOutput fragmentMain(VSOutput input) return output; } - const float3 position = positionAt(pixel); - const float3 faceNormal = decodeFaceNormal(gFaceNormal.Load(texel)); - const float4 detailEncoded = gDetailNormal.Load(texel); + const float3 position = positionFrom(pixel, depth); + const float3 faceNormal = decodeFaceNormal(faceEncoded); // Shading and every later pass reading the scene normal take the bumped one and rays keep the face const float3 normal = detailEncoded.a > 0.5 ? decodeFaceNormal(detailEncoded) : faceNormal; - const float4 material = gMaterial.Load(texel); const float roughness = clamp(material.b, 0.045, 1.0); const float tracedRoughness = float((gPush.reuse.x >> 8) & 0xffu) / 255.0; diff --git a/engine/assets/shaders/voxel_specular.slang b/engine/assets/shaders/voxel_specular.slang index 7ba1fdcc4..9a489633f 100644 --- a/engine/assets/shaders/voxel_specular.slang +++ b/engine/assets/shaders/voxel_specular.slang @@ -9,6 +9,7 @@ import gi_sample; import scene_trace; import trace_shading; import ggx_sampling; +import screen_march; // Mirrors TracedSpecularPass::Params struct SpecularParams @@ -19,6 +20,8 @@ struct SpecularParams float4 tracing; /// x 1 when gPreviousColour holds last frame resolve float4 resolve; + /// x levels of gHiz y most screen march steps with 0 off z SSR thickness w 1 when off screen hits take local lights + float4 march; }; [[vk::push_constant]] @@ -73,6 +76,14 @@ Sampler2D gSurface; [[vk::binding(13, 2)]] Sampler2D gColourPyramid; +/// Closest depth renderer::HiZPyramid of gDepth for the screen march +[[vk::binding(14, 2)]] +Sampler2D gHiz; + +/// gTemporal filtered over the lobe footprint +[[vk::binding(15, 2)]] +Sampler2D gFiltered; + /// Mirrors voxel_lighting.slang static const float kTracedMark = 2.0; static const float kVoxelSize = 0.1; @@ -188,6 +199,27 @@ TracedPixel tracedPixelAt(int2 pixel) return surface; } +/// Last frame colour at a pixel blurred to the width the cone of a ray spans at @p distance from the camera +float3 screenColour(int2 pixel, float distance, float coneWidth) +{ + uint width; + uint height; + gDepth.GetDimensions(width, height); + float3 radiance = gSceneColour.Load(int3(pixel, 0)).rgb; + const float4 motion = gMotion.Load(int3(pixel, 0)); + const float2 previousUv = (float2(pixel) + 0.5) / float2(float(width), float(height)) - (motion.w > 0.5 ? motion.xy : float2(0.0, 0.0)); + if (gParams.resolve.x > 0.5 && motion.z <= 0.5 && all(previousUv >= float2(0.0, 0.0)) && all(previousUv < float2(1.0, 1.0))) + { + // Pixels across the cone at the hit and level 0 of the pyramid spans two + const float pixels = coneWidth * abs(gCamera.projection[1][1]) * float(height) / (2.0 * distance); + const float level = log2(max(pixels, 1e-4)) - 1.0; + // By uv since TAA output is output sized + radiance = level > 0.0 ? gColourPyramid.SampleLevel(previousUv, min(level, kPyramidLevels - 1.0)).rgb + : gPreviousColour.SampleLevel(previousUv, 0.0).rgb; + } + return radiance; +} + /// False unless the pixel the hit projects to shows the same face. The pyramid level matches the cone of this ray at the hit bool screenRadiance(float3 position, float3 normal, float coneWidth, out float3 radiance) { @@ -222,21 +254,11 @@ bool screenRadiance(float3 position, float3 normal, float coneWidth, out float3 { return false; } - radiance = gSceneColour.Load(int3(pixel, 0)).rgb; - const float4 motion = gMotion.Load(int3(pixel, 0)); - const float2 previousUv = (float2(pixel) + 0.5) / float2(float(width), float(height)) - (motion.w > 0.5 ? motion.xy : float2(0.0, 0.0)); - if (gParams.resolve.x > 0.5 && motion.z <= 0.5 && all(previousUv >= float2(0.0, 0.0)) && all(previousUv < float2(1.0, 1.0))) - { - // Pixels across the cone at the hit and level 0 of the pyramid spans two - const float pixels = coneWidth * abs(gCamera.projection[1][1]) * float(height) / (2.0 * distance); - const float level = log2(max(pixels, 1e-4)) - 1.0; - // By uv since TAA output is output sized - radiance = level > 0.0 ? gColourPyramid.SampleLevel(previousUv, min(level, kPyramidLevels - 1.0)).rgb - : gPreviousColour.SampleLevel(previousUv, 0.0).rgb; - } + radiance = screenColour(pixel, distance, coneWidth); return true; } + /// rayTan is the cone half angle tangent each of the strata rays stands for float3 hitRadiance(SceneHit hit, float3 origin, float3 direction, float coneSlope, float rayTan, float2 pixel, inout uint random) { @@ -250,7 +272,7 @@ float3 hitRadiance(SceneHit hit, float3 origin, float3 direction, float coneSlop const PaletteSample palette = samplePalette(gTraceVolumes[hit.volume].recordIndex, hit.material); float3 irradiance; - if (!giHitIrradiance(position, normal, irradiance)) + if (!giHitIrradianceNearest(position, normal, irradiance)) { irradiance = gCamera.ambientColorIntensity.rgb * gCamera.ambientColorIntensity.a; if (gCamera.environmentParams.x >= 0.5) @@ -258,7 +280,9 @@ float3 hitRadiance(SceneHit hit, float3 origin, float3 direction, float coneSlop irradiance += gIrradianceMap.SampleLevel(normal, 0.0).rgb; } } - return palette.albedo * (palette.emissive + irradiance) + traceLocalLight(position, normal, palette.albedo, coneSlope, random) + + const float3 local = + gParams.march.w > 0.5 ? traceLocalLight(position, normal, palette.albedo, coneSlope, random) : float3(0.0, 0.0, 0.0); + return palette.albedo * (palette.emissive + irradiance) + local + traceSunLight(position, normal, palette.albedo, coneSlope, gParams.tracing.w, pixel); } @@ -432,6 +456,39 @@ float4 traceMain(VSOutput input) : SV_Target0 // Rough lobes blur what they hit so their marches take a cone floor const float coneSlope = 0.25 * surface.roughness * surface.roughness; const float3 origin = surface.position + surface.face * (kOriginOffset * kVoxelSize); + // Each stratum ray covers its share of the lobe so its screen hit reads a matching blur + const float rayTan = surface.roughness > kMirrorRoughness ? lobeTanHalf(surface.roughness) / sqrt(float(kLobeStrata)) : 0.0; + + // Screen first so a hit the depth buffer shows skips the voxel trace and the hit lighting + if (gParams.march.y > 0.5) + { + ScreenMarch march; + march.viewProjection = gCamera.jitteredViewProjection; + march.inverseViewProjection = gParams.inverseViewProjection; + march.reach = gParams.tracing.x; + march.thickness = gParams.march.z; + march.maxSteps = uint(gParams.march.y); + march.levels = int(gParams.march.x); + // Fixed per texel so the stable strata stay stable + const float jitter = float(giHash(uint(texel.x) | (uint(texel.y) << 16)) & 0xffffu) / 65536.0; + float2 hitUv; + float fade; + if (marchScreenHiz(march, gDepth, gHiz, origin, L, jitter, hitUv, fade)) + { + uint width; + uint height; + gDepth.GetDimensions(width, height); + const int2 hitPixel = clamp(int2(hitUv * float2(float(width), float(height))), int2(0, 0), int2(int(width), int(height)) - 1); + const float3 hitPosition = worldAt(hitPixel, gDepth.Load(int3(hitPixel, 0)).r); + // A ray reaching the back of what the screen shows hit something hidden so the voxel trace decides + if (dot(gSceneNormal.Load(int3(hitPixel, 0)).xyz, L) < 0.0) + { + const float t = length(hitPosition - origin); + return float4(screenColour(hitPixel, length(gCamera.position - hitPosition), 2.0 * rayTan * t), t); + } + } + } + const SceneHit hit = traceScene(origin, L, 0.0, gParams.tracing.x, coneSlope); if (!hit.hit) { @@ -439,8 +496,6 @@ float4 traceMain(VSOutput input) : SV_Target0 } // Frame in the seed so history averages the light pick instead of freezing it uint random = giHash((uint(texel.x) | (uint(texel.y) << 16)) ^ giHash(uint(gCamera.noiseParams.z))); - // Each stratum ray covers its share of the lobe so its screen hit reads a matching blur - const float rayTan = surface.roughness > kMirrorRoughness ? lobeTanHalf(surface.roughness) / sqrt(float(kLobeStrata)) : 0.0; return float4(hitRadiance(hit, origin, L, coneSlope, rayTan, float2(pixel), random), hit.t); } @@ -748,53 +803,42 @@ float2 fullPixelOf(float3 position, float2 fullSize, out bool visible) return (clip.xy / max(clip.w, 1e-6) * 0.5 + 0.5) * fullSize; } -/// Bilinear core plus disk taps over the GGX lobe footprint at the hit distance projected on the surface plane +/// Plane distance and normal agreement of a half resolution texel from its packed surface +float packedWeight(TracedPixel surface, int2 texel, float distance) +{ + const uint4 packed = gSurface.Load(int3(texel, 0)); + const float3 normal = giOctDecode(float2(packed.w & 2047u, (packed.w >> 11) & 2047u) / 2047.0); + return planeWeight(surface, asfloat(packed.xyz), distance) * pow(saturate(dot(normal, surface.normal)), 16.0); +} + +/// Disk taps over the GGX lobe footprint at the hit distance projected on the surface plane, at half resolution so the +/// composite only upsamples [shader("fragment")] -float4 compositeMain(VSOutput input) : SV_Target0 +float4 filterMain(VSOutput input) : SV_Target0 { - const int2 pixel = int2(input.position.xy); - const float3 scene = gSceneColour.Load(int3(pixel, 0)).rgb; - const TracedPixel surface = tracedPixelAt(pixel); + const int2 texel = int2(input.position.xy); + const float4 own = gTemporal.Load(int3(texel, 0)); + if (own.a < 0.0) + { + return own; + } + const TracedPixel surface = tracedPixelAt(texel * 2); if (!surface.traced) { - return float4(scene, 1.0); + return own; } uint width; uint height; gTemporal.GetDimensions(width, height); const int2 last = int2(int(width), int(height)) - 1; - const float2 low = (float2(pixel) + 0.5) * 0.5 - 0.5; - const int2 base = int2(floor(low)); const float distance = length(gCamera.position - surface.position); - - float3 reflection = float3(0.0, 0.0, 0.0); - float weightSum = 0.0; - for (int y = 0; y <= 1; ++y) - { - for (int x = 0; x <= 1; ++x) - { - const int2 texel = base + int2(x, y); - if (any(texel < int2(0, 0)) || any(texel > last)) - { - continue; - } - const float4 value = gTemporal.Load(int3(texel, 0)); - if (value.a < 0.0) - { - continue; - } - const float2 offset = float2(texel) - low; - const float weight = - exp(-dot(offset, offset) / (2.0 * kBilinearSigma * kBilinearSigma)) * sourceWeight(surface, texel, distance); - reflection += compress(value.rgb) * weight; - weightSum += weight; - } - } + float3 reflection = compress(own.rgb); + float weightSum = 1.0; // Lobe radius on the plane is its tangent times the distance to the virtual image seen from the camera const float3 V = normalize(gCamera.position - surface.position); - float radius = lobeTanHalf(surface.roughness) * distance * footprintHitFactor(surface, base, last, distance); + float radius = lobeTanHalf(surface.roughness) * distance * footprintHitFactor(surface, texel, last, distance); const float3 N = surface.face; float3 along = V - N * dot(V, N); float3 across; @@ -819,23 +863,69 @@ float4 compositeMain(VSOutput input) : SV_Target0 if (pixels > kMinFootprintPixels) { radius *= min(1.0, kMaxFootprintPixels / pixels); - const float turn = interleavedGradientNoise(float2(pixel)) * 6.28318530718; + const float turn = interleavedGradientNoise(float2(texel)) * 6.28318530718; for (int i = 0; i < kFootprintTaps; ++i) { const float r = sqrt((float(i) + 0.5) / float(kFootprintTaps)); const float angle = float(i) * 2.39996323 + turn; const float3 position = surface.position + (along * (cos(angle) * stretch) + across * sin(angle)) * (r * radius); - const int2 texel = int2(floor(fullPixelOf(position, fullSize, visible) * 0.5)); - if (!visible || any(texel < int2(0, 0)) || any(texel > last)) + const int2 tap = int2(floor(fullPixelOf(position, fullSize, visible) * 0.5)); + if (!visible || any(tap < int2(0, 0)) || any(tap > last)) { continue; } - const float4 value = gTemporal.Load(int3(texel, 0)); + const float4 value = gTemporal.Load(int3(tap, 0)); if (value.a < 0.0 || abs(historyRoughness(value.a) - surface.roughness) > kRoughnessChange) { continue; } - const float weight = exp(-2.0 * r * r) * sourceWeight(surface, texel, distance); + const float weight = exp(-2.0 * r * r) * packedWeight(surface, tap, distance); + reflection += compress(value.rgb) * weight; + weightSum += weight; + } + } + return float4(expand(reflection / weightSum), own.a); +} + +/// Bilinear upsample of the footprint filtered reflection kept on the surface by plane distance and normal +[shader("fragment")] +float4 compositeMain(VSOutput input) : SV_Target0 +{ + const int2 pixel = int2(input.position.xy); + const float3 scene = gSceneColour.Load(int3(pixel, 0)).rgb; + const TracedPixel surface = tracedPixelAt(pixel); + if (!surface.traced) + { + return float4(scene, 1.0); + } + + uint width; + uint height; + gFiltered.GetDimensions(width, height); + const int2 last = int2(int(width), int(height)) - 1; + const float2 low = (float2(pixel) + 0.5) * 0.5 - 0.5; + const int2 base = int2(floor(low)); + const float distance = length(gCamera.position - surface.position); + + float3 reflection = float3(0.0, 0.0, 0.0); + float weightSum = 0.0; + for (int y = 0; y <= 1; ++y) + { + for (int x = 0; x <= 1; ++x) + { + const int2 texel = base + int2(x, y); + if (any(texel < int2(0, 0)) || any(texel > last)) + { + continue; + } + const float4 value = gFiltered.Load(int3(texel, 0)); + if (value.a < 0.0) + { + continue; + } + const float2 offset = float2(texel) - low; + const float weight = + exp(-dot(offset, offset) / (2.0 * kBilinearSigma * kBilinearSigma)) * sourceWeight(surface, texel, distance); reflection += compress(value.rgb) * weight; weightSum += weight; } @@ -854,7 +944,7 @@ float4 compositeMain(VSOutput input) : SV_Target0 { continue; } - const float4 value = gTemporal.Load(int3(texel, 0)); + const float4 value = gFiltered.Load(int3(texel, 0)); if (value.a < 0.0 || abs(historyRoughness(value.a) - surface.roughness) > kRoughnessChange) { continue; @@ -870,6 +960,7 @@ float4 compositeMain(VSOutput input) : SV_Target0 } } + const float3 V = normalize(gCamera.position - surface.position); reflection = weightSum > 1e-4 ? expand(reflection / weightSum) : ambientSpecularRadiance(surface.position, reflect(-V, surface.normal), surface.roughness); diff --git a/engine/src/toast/crash_handler.cpp b/engine/src/toast/crash_handler.cpp index 447ab5e62..b9ba11022 100644 --- a/engine/src/toast/crash_handler.cpp +++ b/engine/src/toast/crash_handler.cpp @@ -64,10 +64,10 @@ auto enabled() noexcept -> bool { if (length > 0 && length < 4) { return value[0] != L'0'; } -#ifdef NDEBUG - return false; -#else +#ifdef TOAST_DEV_TOOLS return true; +#else + return false; #endif } diff --git a/engine/src/toast/physics/broad_phase.cpp b/engine/src/toast/physics/broad_phase.cpp index f1b7827c3..6d0e087c9 100644 --- a/engine/src/toast/physics/broad_phase.cpp +++ b/engine/src/toast/physics/broad_phase.cpp @@ -345,7 +345,6 @@ void BroadPhase::updateTree(CollisionWorldView world, std::span std::vector { - ZoneScopedN("physics::QueryBounds"); return m_tree.query(bounds); } diff --git a/engine/src/toast/physics/manifold.cpp b/engine/src/toast/physics/manifold.cpp index 9cc18b85b..439b38995 100644 --- a/engine/src/toast/physics/manifold.cpp +++ b/engine/src/toast/physics/manifold.cpp @@ -1098,9 +1098,6 @@ auto contactGroup(const glm::vec3& normal) -> uint8_t { } auto collideSpheres(BroadPhasePair pair, CollisionElement a, CollisionElement b) -> std::optional { - ZoneScoped; - ZoneValue((static_cast(pair.a.shape.slot) << 32) | static_cast(pair.b.shape.slot)); - const Shape& shape_a = a.shape; const Body& body_a = a.body; const Shape& shape_b = b.shape; @@ -1147,9 +1144,6 @@ auto collideSpheres(BroadPhasePair pair, CollisionElement a, CollisionElement b) auto collideSphereBox(BroadPhasePair pair, CollisionElement sphere_element, CollisionElement box_element) -> std::optional { - ZoneScoped; - ZoneValue((static_cast(pair.a.shape.slot) << 32) | static_cast(pair.b.shape.slot)); - const Shape& sph_shape = sphere_element.shape; const Body& sph_body = sphere_element.body; const Shape& box_shape = box_element.shape; @@ -1257,9 +1251,6 @@ auto collideSphereBox(BroadPhasePair pair, CollisionElement sphere_element, Coll auto collideSphereCapsule(BroadPhasePair pair, CollisionElement sphere_element, CollisionElement capsule_element) -> std::optional { - ZoneScoped; - ZoneValue((static_cast(pair.a.shape.slot) << 32) | static_cast(pair.b.shape.slot)); - const Shape& sph_shape = sphere_element.shape; const Body& sph_body = sphere_element.body; const Shape& caps_shape = capsule_element.shape; @@ -1332,12 +1323,6 @@ auto collideSphereCapsule(BroadPhasePair pair, CollisionElement sphere_element, } namespace { -[[nodiscard]] -auto queryVolumeInVoxels(const AABB& bounds) -> uint64_t { - const glm::vec3 extent = glm::max(bounds.max - bounds.min, glm::vec3(0.0f)) / voxel::k_voxel_size; - return static_cast(extent.x) * static_cast(extent.y) * static_cast(extent.z); -} - // Surface area not volume since queryVoxelSurface only ever visits surface-classified voxels [[nodiscard]] auto querySurfaceAreaInVoxels(const AABB& bounds) -> uint64_t { @@ -1352,9 +1337,6 @@ void collideSphereVoxel( BroadPhasePair pair, CollisionElement sphere_element, CollisionElement voxel_element, const VoxelShapeData& voxel_data, std::vector& output ) { - ZoneScoped; - ZoneValue((static_cast(pair.a.shape.slot) << 32) | static_cast(pair.b.shape.slot)); - const Shape& sph_shape = sphere_element.shape; const Body& sph_body = sphere_element.body; const Shape& voxel_shape = voxel_element.shape; @@ -1371,7 +1353,6 @@ void collideSphereVoxel( .min = local_center - glm::vec3(radius), .max = local_center + glm::vec3(radius), }; - ZoneValue(queryVolumeInVoxels(local_bounds)); const VoxelQueryContext context { .volume = *voxel_data.volume, .surface = voxel_data.surface, .palette = voxel_data.palette, .materials = voxel_data.materials @@ -1390,7 +1371,6 @@ void collideSphereVoxel( std::array, voxel::k_normal_direction_count> best_per_normal; { - ZoneScopedN("physics::VoxelQueryWalk"); queryVoxelSurface(context, local_bounds, [&](const VoxelCandidate& candidate) { if (candidate.normal_index >= best_per_normal.size()) { return; @@ -1436,7 +1416,6 @@ void collideSphereVoxel( } { - ZoneScopedN("physics::BuildManifolds"); for (size_t normal_index = 0; normal_index < best_per_normal.size(); ++normal_index) { const std::optional& best = best_per_normal[normal_index]; if (not best.has_value()) { @@ -1467,9 +1446,6 @@ void collideSphereVoxel( } auto collideBoxes(BroadPhasePair pair, CollisionElement a, CollisionElement b) -> std::optional { - ZoneScoped; - ZoneValue((static_cast(pair.a.shape.slot) << 32) | static_cast(pair.b.shape.slot)); - const Shape& shape_a = a.shape; const Body& body_a = a.body; const Shape& shape_b = b.shape; @@ -1505,9 +1481,6 @@ auto collideBoxes(BroadPhasePair pair, CollisionElement a, CollisionElement b) - auto collideCapsuleBox(BroadPhasePair pair, CollisionElement capsule_element, CollisionElement box_element) -> std::optional { - ZoneScoped; - ZoneValue((static_cast(pair.a.shape.slot) << 32) | static_cast(pair.b.shape.slot)); - const Shape& capsule_shape = capsule_element.shape; const Body& capsule_body = capsule_element.body; const Shape& box_shape = box_element.shape; @@ -1603,9 +1576,6 @@ auto collideCapsuleBox(BroadPhasePair pair, CollisionElement capsule_element, Co } auto collideCapsules(BroadPhasePair pair, CollisionElement a, CollisionElement b) -> std::optional { - ZoneScoped; - ZoneValue((static_cast(pair.a.shape.slot) << 32) | static_cast(pair.b.shape.slot)); - const Shape& shape_a = a.shape; const Body& body_a = a.body; const Shape& shape_b = b.shape; @@ -1687,6 +1657,8 @@ auto collideCapsules(BroadPhasePair pair, CollisionElement a, CollisionElement b namespace { +constexpr size_t k_voxel_pair_test_budget = 4096; + struct VoxelVoxelScratch { std::array, voxel::k_normal_direction_count> candidates_per_normal; std::array normal_per_group {}; @@ -1816,8 +1788,6 @@ auto classifyVoxelVoxelSplit(const VoxelVoxelPairView& view) -> std::optional VoxelPairPartial { - ZoneScoped; - VoxelPairPartial partial; const auto setup = voxelVoxelSetup(view); if (not setup) { @@ -1828,7 +1798,7 @@ auto collideVoxelVoxelRegion(const VoxelVoxelPairView& view, const AABB& probe_r const glm::mat3 probe_basis = setup->probe_basis; const glm::mat3 ref_basis_inv = setup->ref_basis_inv; const glm::vec3 ref_origin = setup->ref_origin; - size_t remaining_budget = 256; + size_t remaining_budget = k_voxel_pair_test_budget; queryVoxelSurface(setup->probe_context, probe_region, [&](const VoxelCandidate& probe_c) -> bool { if (remaining_budget == 0) { @@ -1983,9 +1953,6 @@ void collideVoxelVoxel( BroadPhasePair pair, CollisionElement a, const VoxelShapeData& data_a, CollisionElement b, const VoxelShapeData& data_b, std::vector& output ) { - ZoneScoped; - ZoneValue((static_cast(pair.a.shape.slot) << 32) | static_cast(pair.b.shape.slot)); - bool a_is_probe = data_a.solid_voxel_count <= data_b.solid_voxel_count; auto probe = a_is_probe ? a : b; const VoxelShapeData& probe_data = a_is_probe ? data_a : data_b; @@ -2035,9 +2002,6 @@ void collideVoxelVoxel( if (glm::any(glm::greaterThan(probe_search_bounds.min, probe_search_bounds.max))) { return; } - ZoneValue(queryVolumeInVoxels(probe_search_bounds)); - ZoneValue(queryVolumeInVoxels(probe.shape.voxel.local_bounds)); - ZoneValue(queryVolumeInVoxels(ref.shape.voxel.local_bounds)); static thread_local VoxelVoxelScratch scratch; scratch.reset(); @@ -2046,10 +2010,9 @@ void collideVoxelVoxel( auto& normal_sum_per_group = scratch.normal_sum_per_group; auto& material_per_group = scratch.material_per_group; auto& group_started = scratch.group_started; - size_t remaining_budget = 256; + size_t remaining_budget = k_voxel_pair_test_budget; { - ZoneScopedN("physics::VoxelQueryWalk"); queryVoxelSurface(probe_context, probe_search_bounds, [&](const VoxelCandidate& probe_c) -> bool { if (remaining_budget == 0) { return false; @@ -2138,7 +2101,6 @@ void collideVoxelVoxel( } { - ZoneScopedN("physics::BuildManifolds"); for (size_t i = 0; i < candidates_per_normal.size(); ++i) { std::vector<_detail::ContactCandidate>& bucket = candidates_per_normal[i]; if (bucket.empty()) { @@ -2176,9 +2138,6 @@ void collideCapsuleVoxel( BroadPhasePair pair, CollisionElement capsule_element, CollisionElement voxel_element, const VoxelShapeData& voxel_data, std::vector& output ) { - ZoneScoped; - ZoneValue((static_cast(pair.a.shape.slot) << 32) | static_cast(pair.b.shape.slot)); - const Shape& caps_shape = capsule_element.shape; const Body& caps_body = capsule_element.body; const Shape& voxel_shape = voxel_element.shape; @@ -2199,7 +2158,6 @@ void collideCapsuleVoxel( .min = glm::min(local_a, local_b) - glm::vec3(radius), .max = glm::max(local_a, local_b) + glm::vec3(radius), }; - ZoneValue(queryVolumeInVoxels(local_bounds)); const VoxelQueryContext context { .volume = *voxel_data.volume, .surface = voxel_data.surface, .palette = voxel_data.palette, .materials = voxel_data.materials }; @@ -2218,7 +2176,6 @@ void collideCapsuleVoxel( std::array, voxel::k_normal_direction_count> best_per_normal; { - ZoneScopedN("physics::VoxelQueryWalk"); queryVoxelSurface(context, local_bounds, [&](const VoxelCandidate& candidate) { if (candidate.normal_index >= best_per_normal.size()) { return; @@ -2250,7 +2207,6 @@ void collideCapsuleVoxel( } { - ZoneScopedN("physics::BuildManifolds"); for (size_t normal_index = 0; normal_index < best_per_normal.size(); ++normal_index) { const std::optional& best = best_per_normal[normal_index]; if (not best.has_value()) { @@ -2408,8 +2364,6 @@ auto splitVoxelRegions(const AABB& local_bounds, size_t region_count) -> std::ve } auto collideBoxVoxelRegion(const BoxVoxelPairView& view, const AABB& region) -> VoxelPairPartial { - ZoneScoped; - const _detail::WorldBox local_box = boxVoxelLocalBox(view); const VoxelQueryContext context { .volume = *view.voxel_data.volume, @@ -2536,9 +2490,6 @@ void collideBoxVoxel( BroadPhasePair pair, CollisionElement box_element, CollisionElement voxel_element, const VoxelShapeData& voxel_data, std::vector& output ) { - ZoneScoped; - ZoneValue((static_cast(pair.a.shape.slot) << 32) | static_cast(pair.b.shape.slot)); - const Shape& box_shape = box_element.shape; const Body& box_body = box_element.body; const Shape& voxel_shape = voxel_element.shape; @@ -2564,8 +2515,6 @@ void collideBoxVoxel( .min = local_box.center - local_world_extents, .max = local_box.center + local_world_extents, }; - ZoneValue(queryVolumeInVoxels(local_bounds)); - ZoneValue(queryVolumeInVoxels(voxel_shape.voxel.local_bounds)); const VoxelQueryContext context { .volume = *voxel_data.volume, .surface = voxel_data.surface, .palette = voxel_data.palette, .materials = voxel_data.materials }; @@ -2579,7 +2528,6 @@ void collideBoxVoxel( auto& group_started = scratch.group_started; { - ZoneScopedN("physics::VoxelQueryWalk"); queryVoxelSurface(context, local_bounds, [&](const VoxelCandidate& candidate) { if (candidate.normal_index >= candidates_per_normal.size()) { return; @@ -2591,7 +2539,6 @@ void collideBoxVoxel( .half_extents = (candidate.max - candidate.min) * 0.5f, }; - ZoneScopedN("physics::BoxVoxelSAT"); // NOLINT auto sat = _detail::collideWorldBoxes(local_box, voxel_box, voxel::k_all_faces_exposed, candidate.exposure); if (not sat.has_value()) { return; @@ -2624,7 +2571,6 @@ void collideBoxVoxel( } { - ZoneScopedN("physics::BuildManifolds"); for (size_t normal_index = 0; normal_index < candidates_per_normal.size(); ++normal_index) { std::vector<_detail::ContactCandidate>& bucket = candidates_per_normal[normal_index]; if (bucket.empty()) { diff --git a/engine/src/toast/physics/narrow_phase.cpp b/engine/src/toast/physics/narrow_phase.cpp index 14beae054..bed3fa510 100644 --- a/engine/src/toast/physics/narrow_phase.cpp +++ b/engine/src/toast/physics/narrow_phase.cpp @@ -43,7 +43,8 @@ auto pairType(ShapeType a, ShapeType b) -> NarrowPhasePairType { } -auto NarrowPhase::generateManifolds(CollisionWorldView world, std::span candidates) const -> ManifoldQueue { +auto NarrowPhase::generateManifolds(CollisionWorldView world, std::span candidates, bool time_pairs) const + -> ManifoldQueue { ZoneScopedN("physics::RecordManifoldQueue"); ZoneValue(static_cast(candidates.size())); @@ -61,11 +62,13 @@ auto NarrowPhase::generateManifolds(CollisionWorldView world, std::span(std::chrono::steady_clock::now() - pair_start).count(); + } else { + collide(world, pair, pair_manifolds); } accumulate(pair_manifolds, world, queue); @@ -87,9 +90,6 @@ void NarrowPhase::accumulate(std::span manifolds, CollisionWorldView w } auto NarrowPhase::validate(CollisionWorldView world, Manifold& manifold) const -> bool { - ZoneScopedN("physics::ValidateManifold"); - ZoneValue((static_cast(manifold.pair.a.shape.slot) << 32) | static_cast(manifold.pair.b.shape.slot)); - const Body* body_a = world.body(manifold.pair.a.body); const Body* body_b = world.body(manifold.pair.b.body); const Shape* shape_a = world.shape(manifold.pair.a.shape); @@ -132,9 +132,6 @@ void NarrowPhase::flip(Manifold& manifold) { } void NarrowPhase::collide(CollisionWorldView world, BroadPhasePair pair, std::vector& output) const { - ZoneScopedN("physics::DispatchCollisionPair"); - ZoneValue((static_cast(pair.a.shape.slot) << 32) | static_cast(pair.b.shape.slot)); - const Shape* shape_a = world.shape(pair.a.shape); const Shape* shape_b = world.shape(pair.b.shape); const Body* body_a = world.body(pair.a.body); diff --git a/engine/src/toast/physics/narrow_phase.hpp b/engine/src/toast/physics/narrow_phase.hpp index 982eca663..b41ea82aa 100644 --- a/engine/src/toast/physics/narrow_phase.hpp +++ b/engine/src/toast/physics/narrow_phase.hpp @@ -43,7 +43,8 @@ struct ManifoldQueue { class NarrowPhase { public: [[nodiscard]] - auto generateManifolds(CollisionWorldView world, std::span candidates) const -> ManifoldQueue; + auto generateManifolds(CollisionWorldView world, std::span candidates, bool time_pairs) const + -> ManifoldQueue; /// Same validate/count/keep-or-reject step generateManifolds runs so a split pair can fold results in too void accumulate(std::span manifolds, CollisionWorldView world, ManifoldQueue& queue) const; diff --git a/engine/src/toast/physics/nodes/collider.cpp b/engine/src/toast/physics/nodes/collider.cpp index 8c40402bc..18b90b3ae 100644 --- a/engine/src/toast/physics/nodes/collider.cpp +++ b/engine/src/toast/physics/nodes/collider.cpp @@ -90,7 +90,6 @@ void Collider::clearColorOverride() { } void Collider::drawDebug() { - ZoneScoped; if (!m_debug_visible) { return; } diff --git a/engine/src/toast/physics/nodes/joint3d.cpp b/engine/src/toast/physics/nodes/joint3d.cpp index 7b899ede7..9ab78d094 100644 --- a/engine/src/toast/physics/nodes/joint3d.cpp +++ b/engine/src/toast/physics/nodes/joint3d.cpp @@ -142,7 +142,6 @@ auto Joint3D::frameRotation() const -> glm::quat { } void Joint3D::drawDebug() { - ZoneScoped; if (not draw_debug) { return; } diff --git a/engine/src/toast/physics/physics_settings.cpp b/engine/src/toast/physics/physics_settings.cpp index a279d9ea4..e84391f18 100644 --- a/engine/src/toast/physics/physics_settings.cpp +++ b/engine/src/toast/physics/physics_settings.cpp @@ -72,6 +72,16 @@ void registerPhysicsSettings() { .step = 1.0f}, &Tunables::wind_shelter_distance); + flt("physics.world.kill_plane_z", + -50.0f, + {.label = "Kill plane Z", + .category = "World", + .description = "Rigidbodies that fall below this height are destroyed", + .min = -100000.0f, + .max = 100000.0f, + .step = 1.0f}, + &Tunables::kill_plane_z); + uint_setting( "physics.solver.iterations", 8, @@ -656,6 +666,14 @@ void registerPhysicsSettings() { .step = 1.0}, &Tunables::voxel_pair_split_regions ); + toast::settings::declareBool( + "physics.debug.time_narrow_pairs", + false, + {.label = "Time narrow phase pairs", + .category = "Debug", + .description = "Times every narrow phase pair per shape type for the debug overlay"} + ) + .onChange([](bool v) { g_tunables.time_narrow_pairs = v; }); uint_setting( "physics.character.sweep_refine_iterations", 6, diff --git a/engine/src/toast/physics/physics_settings.hpp b/engine/src/toast/physics/physics_settings.hpp index 48dc48675..303b4ae96 100644 --- a/engine/src/toast/physics/physics_settings.hpp +++ b/engine/src/toast/physics/physics_settings.hpp @@ -81,6 +81,8 @@ struct Tunables { float air_density = 1.225f; glm::vec3 wind = {0.0f, 0.0f, 0.0f}; float wind_shelter_distance = 64.0f; + float kill_plane_z = -50.0f; + bool time_narrow_pairs = false; [[nodiscard]] auto fixedDelta() const noexcept -> double { diff --git a/engine/src/toast/physics/simulator.cpp b/engine/src/toast/physics/simulator.cpp index 398ae3087..290386c48 100644 --- a/engine/src/toast/physics/simulator.cpp +++ b/engine/src/toast/physics/simulator.cpp @@ -20,6 +20,7 @@ #include "voxel_data_lock.hpp" #include "voxel_smash.hpp" +#include #include #include #include @@ -705,8 +706,6 @@ auto Simulator::nodeFor(BodyID body) -> toast::Box { return {}; } - ZoneScoped; - const auto rigidbody_binding = std::ranges::find_if(instance->m_node_bindings, [body](const NodeBinding& candidate) { return candidate.body == body; }); if (rigidbody_binding != instance->m_node_bindings.end()) { @@ -728,8 +727,6 @@ auto Simulator::colliderFor(BodyID body, ShapeID shape) -> toast::Boxm_node_bindings) { if (binding.body != body) { continue; @@ -797,6 +794,7 @@ void Simulator::tick() { spawnBudgetedFragments(); enforceFragmentBudget(dt); despawnSettledFragments(dt); + destroyFallenBodies(); checkJointAnchors(); integrate(dt); checkTriggers(); @@ -849,13 +847,21 @@ void Simulator::tick() { m_profile.voxel_shape_count = static_cast(std::ranges::count_if(m_shapes, [](const ShapeSlot& s) { return s.occupied && s.shape.type == ShapeType::voxel; })); + size_t rigidbody_count = 0; + size_t awake_rigidbody_count = 0; for (const BodySlot& b : m_bodies) { if (!b.occupied) { continue; } ++m_profile.body_count; m_profile.awake_body_count += b.body.awake ? 1 : 0; + if (b.body.type == BodyType::dynamic_body && b.body.enabled) { + ++rigidbody_count; + awake_rigidbody_count += b.body.awake ? 1 : 0; + } } + TracyPlot("physics::Rigidbodies", static_cast(rigidbody_count)); + TracyPlot("physics::Awake rigidbodies", static_cast(awake_rigidbody_count)); const voxel::BrickPool& pool = voxel::runtimeBrickPool(); m_profile.brick_pool_allocated = pool.allocatedCount(); m_profile.brick_pool_capacity = pool.capacity(); @@ -1703,7 +1709,6 @@ auto Simulator::spawnFragmentBody(ShapeID source_shape_id, const DetachedCompone .voxels = extracted.voxels, }; - const glm::uvec3 extracted_brick_dims = extracted.volume.brickDims(); glm::vec3 origin_local = glm::vec3(extracted.offset) * static_cast(voxel::k_brick_dim) * voxel::k_voxel_size; glm::quat frag_rotation = glm::normalize(rotation * local_rotation); glm::vec3 frag_pos = position + rotation * (local_center + local_rotation * origin_local); @@ -1766,28 +1771,6 @@ auto Simulator::spawnFragmentBody(ShapeID source_shape_id, const DetachedCompone ++m_profile.fragments_spawned; - TOAST_TRACE( - "Physics", - "Fragment body {} broke off shape {}: {} voxels across {} pieces, extracted volume {}x{}x{} bricks ({}x{}x{} voxels, " - "{:.2f}x{:.2f}x{:.2f} m) at brick offset {} {} {}", - frag_body.slot, - source_shape_id.slot, - component.voxel_count, - component.pieces.size(), - extracted_brick_dims.x, - extracted_brick_dims.y, - extracted_brick_dims.z, - extracted_brick_dims.x * voxel::k_brick_dim, - extracted_brick_dims.y * voxel::k_brick_dim, - extracted_brick_dims.z * voxel::k_brick_dim, - static_cast(extracted_brick_dims.x) * voxel::k_brick_size, - static_cast(extracted_brick_dims.y) * voxel::k_brick_size, - static_cast(extracted_brick_dims.z) * voxel::k_brick_size, - extracted.offset.x, - extracted.offset.y, - extracted.offset.z - ); - if (auto* b = tryGetBody(frag_body)) { glm::vec3 frag_com_world = b->worldCenterOfMass(); glm::vec3 r = frag_com_world - world_com; @@ -1918,15 +1901,6 @@ auto Simulator::spawnStaticSplitBody(ShapeID source_shape_id, const DetachedComp ++m_profile.static_splits_spawned; - TOAST_TRACE( - "Physics", - "Static body {} split off shape {}: {} voxels across {} pieces, still anchored", - split_body.slot, - source_shape_id.slot, - component.voxel_count, - component.pieces.size() - ); - return true; } @@ -1964,6 +1938,43 @@ void Simulator::despawnSettledFragments(float dt) { m_profile.fragments_despawned = doomed.size(); } +void Simulator::destroyFallenBodies() { + ZoneScopedN("physics::DestroyFallenBodies"); + + const float kill_z = tunables().kill_plane_z; + if (not std::isfinite(kill_z)) { + return; + } + + std::erase_if(m_scheduled_kills, [this](BodyID id) { return not valid(id); }); + + std::vector> fallen_nodes; + for (const NodeBinding& binding : m_node_bindings) { + const Body* body = tryGetBody(binding.body); + if (body != nullptr && body->enabled && body->type == BodyType::dynamic_body && body->position.z < kill_z && + binding.node.exists() && std::ranges::find(m_scheduled_kills, binding.body) == m_scheduled_kills.end()) { + fallen_nodes.push_back(binding.node); + m_scheduled_kills.push_back(binding.body); + } + } + + std::vector fallen_fragments; + for (const FragmentRecord& fragment : m_fragments) { + const Body* body = tryGetBody(fragment.body); + if (body != nullptr && body->position.z < kill_z) { + fallen_fragments.push_back(fragment.body); + } + } + + for (toast::Box& node : fallen_nodes) { + event::send(*node); + event::send(*node); + } + for (const BodyID id : fallen_fragments) { + destroyBody(id); + } +} + void Simulator::syncEnabledState() { ZoneScopedN("physics::SyncEnabledState"); @@ -2475,9 +2486,6 @@ void Simulator::publishTransforms() { } auto Simulator::publishTransform(NodeBinding& binding) -> bool { - ZoneScoped; - ZoneValue(static_cast(binding.body.slot)); - Body* body = tryGetBody(binding.body); if (not binding.node.exists() || not body) { return false; @@ -2494,9 +2502,6 @@ auto Simulator::publishTransform(NodeBinding& binding) -> bool { } auto Simulator::publishVoxelTransform(VoxelNodeBinding& binding) -> bool { - ZoneScoped; - ZoneValue(static_cast(binding.body.slot)); - Body* body = tryGetBody(binding.body); if (not binding.node.exists() || not body) { return false; @@ -2761,8 +2766,6 @@ auto Simulator::velocityAtPoint(const Body& body, const glm::vec3& r) -> glm::ve auto Simulator::effectiveMassAlong( const Body& body_a, const Body& body_b, const glm::vec3& r_a, const glm::vec3& r_b, const glm::vec3& direction ) -> std::optional { - ZoneScopedN("physics::EffectiveMass"); - const bool a_moves = movable(body_a); const bool b_moves = movable(body_b); glm::vec3 angular_a = a_moves ? body_a.inverse_inertia_world * glm::cross(r_a, direction) : glm::vec3 {0.0f}; @@ -3088,6 +3091,7 @@ auto Simulator::generateManifoldsAsync(CollisionWorldView world, std::span> futures; futures.reserve(job_count); @@ -3096,10 +3100,10 @@ auto Simulator::generateManifoldsAsync(CollisionWorldView world, std::span {active_candidates}.subspan(begin, end - begin); - futures.emplace_back(toast::ThreadPool::push([this, world, batch] { + futures.emplace_back(toast::ThreadPool::push([this, world, batch, time_pairs] { ZoneScopedN("physics::NarrowPhaseBatch"); // NOLINT ZoneValue(static_cast(batch.size())); - return m_narrow_phase.generateManifolds(world, batch); + return m_narrow_phase.generateManifolds(world, batch, time_pairs); })); } @@ -3189,44 +3193,9 @@ auto Simulator::generateManifoldsAsync(CollisionWorldView world, std::span(NarrowPhasePairType::box_voxel)]; - const double split_ms = std::chrono::duration(std::chrono::steady_clock::now() - split_start).count(); - m_profile.narrow_pair_time_ms[static_cast(NarrowPhasePairType::box_voxel)] += split_ms; - if (split_ms > 2.0) { - // diagnostic, remove; body type 0 static 1 dynamic 2 kinematic - const Body& box_body = split.view.box.body; - const Body& voxel_body = split.view.voxel.body; - const glm::vec3 box_size = split.view.box.shape.box.size; - const glm::uvec3 voxel_dims = split.view.voxel_data.volume->brickDims(); - size_t candidates = 0; - for (const VoxelPairPartial& partial : partials) { - for (const auto& per_normal : partial.candidates_per_normal) { - candidates += per_normal.size(); - } - } - TOAST_WARN( - "Physics", - "[box-voxel slow] {:.2f} ms, {} regions, {} candidates, local extent {:.1f}x{:.1f}x{:.1f} m | box type {} awake {} " - "size {:.1f}x{:.1f}x{:.1f} | " - "voxel type {} awake {} bricks {}x{}x{} solid {} fragment {}", - split_ms, - partials.size(), - candidates, - split.local_bounds.max.x - split.local_bounds.min.x, - split.local_bounds.max.y - split.local_bounds.min.y, - split.local_bounds.max.z - split.local_bounds.min.z, - static_cast(box_body.type), - box_body.awake, - box_size.x, - box_size.y, - box_size.z, - static_cast(voxel_body.type), - voxel_body.awake, - voxel_dims.x, - voxel_dims.y, - voxel_dims.z, - split.view.voxel_data.solid_voxel_count, - valid(split.view.voxel_data.fragment_origin) - ); + if (time_pairs) { + m_profile.narrow_pair_time_ms[static_cast(NarrowPhasePairType::box_voxel)] += + std::chrono::duration(std::chrono::steady_clock::now() - split_start).count(); } merged.insert_range(merged.end(), std::move(queue.manifolds)); } @@ -3255,8 +3224,10 @@ auto Simulator::generateManifoldsAsync(CollisionWorldView world, std::span(NarrowPhasePairType::voxel_voxel)]; - m_profile.narrow_pair_time_ms[static_cast(NarrowPhasePairType::voxel_voxel)] += - std::chrono::duration(std::chrono::steady_clock::now() - split_start).count(); + if (time_pairs) { + m_profile.narrow_pair_time_ms[static_cast(NarrowPhasePairType::voxel_voxel)] += + std::chrono::duration(std::chrono::steady_clock::now() - split_start).count(); + } merged.insert_range(merged.end(), std::move(queue.manifolds)); } } @@ -3605,8 +3576,6 @@ void Simulator::integrate(float dt) { void Simulator::integrateBody( BodyID id, Body& body, const glm::vec3& gravity, float air_density, const glm::vec3& wind, float dt ) { - ZoneScopedN("physics::IntegrateBody"); - ZoneValue(static_cast(id.slot)); if (not body.enabled) { return; } @@ -4423,8 +4392,6 @@ void Simulator::checkTriggers() { if (not trigger.exists()) { continue; } - ZoneScopedN("physics::CheckTrigger"); - // Trigger::onDisable already sent the exits if (not trigger->enabled()) { continue; @@ -4999,7 +4966,6 @@ auto Simulator::setLinearVelocity(BodyID body, const glm::vec3& velocity) -> boo } void Simulator::recordDamage(DamageCommand&& command) { - ZoneScopedN("physics::RecordDamage"); std::scoped_lock lock {m_damage_mutex}; m_damage_commands.emplace_back(command); } @@ -5116,21 +5082,6 @@ void Simulator::applyDamageCommand(const DamageCommand& c) { // cracks in the band around the crater const ShatterPlan shatter = planShatter(volume, data->palette, data->materials, crater, c.max_hardness); - TOAST_INFO( - "Physics", - "Shatter: pattern {} shatter_energy {:.3f} kJ density {:.2f} kJ/m3 radius {:.3f} m band_voxels {} width {:.3f} m cells " - "{} cracks {} | stop: " - "{}", - fracturePatternName(crater.pattern), - crater.shatter_energy, - shatter.density, - crater.radius, - shatter.band_voxels, - shatter.width, - shatter.cells, - shatter.crack.size(), - shatter.stop - ); const float seal_floor = glm::max(craterMinRadius(crater) - voxel::k_voxel_size, 0.0f); const float seal_floor_squared = seal_floor * seal_floor; @@ -5240,15 +5191,6 @@ void Simulator::applyDamageCommand(const DamageCommand& c) { // fragmenting const CoreSplit core_split = planCoreSplit(core, crater); - TOAST_INFO( - "Physics", - "Fragment: energy {:.3f} kJ density {:.2f} kJ/m3 core_voxels {} parts {} cracks {}", - crater.fragment_energy, - core_split.density, - core.size(), - core_split.parts, - core_split.crack.size() - ); for (const glm::ivec3& v : core_split.crack) { const uint8_t palette_index = volume.materialAt(v); if (palette_index == voxel::k_empty_palette_index) { @@ -5692,7 +5634,6 @@ auto Simulator::explodeShape(ShapeID shape_id, const ExplosionDamage& explosion) glm::vec3 debris_index_sum {0.0f}; glm::vec3 chunk_index_sum {0.0f}; uint32_t chunk_voxels = 0; - uint32_t crack_voxels = 0; float debris_energy = 0.0f; float reach = 0.0f; @@ -5902,7 +5843,6 @@ auto Simulator::explodeShape(ShapeID shape_id, const ExplosionDamage& explosion) continue; } debris = true; - ++crack_voxels; } else if (not loose) { continue; } @@ -5962,7 +5902,6 @@ auto Simulator::explodeShape(ShapeID shape_id, const ExplosionDamage& explosion) } const AABB bounds {.min = explosion.point - glm::vec3(reach), .max = explosion.point + glm::vec3(reach)}; - size_t chunk_count = 0; { ZoneNamedN(chunks_zone, "physics::ExplodeShape::Chunks", true); // NOLINT SmashPieces chunks; @@ -5977,7 +5916,6 @@ auto Simulator::explodeShape(ShapeID shape_id, const ExplosionDamage& explosion) } chunks.pieces.push_back(std::move(piece)); } - chunk_count = chunks.pieces.size(); breakPieces( shape_id, chunks, @@ -6000,18 +5938,6 @@ auto Simulator::explodeShape(ShapeID shape_id, const ExplosionDamage& explosion) unlockSleep(shape->owner); wakeBodiesInBounds(bounds); - TOAST_INFO( - "Physics", - "Explosion: force {:.1f} reach {:.2f} m debris_voxels {} (cracks {}) chunk_voxels {} chunks {} debris_energy {:.3f} kJ", - explosion.force, - reach, - debris_voxels.size(), - crack_voxels, - chunk_voxels, - chunk_count, - debris_energy - ); - const uint32_t solid_after = data->solid_voxel_count; return solid_before - std::min(solid_before, solid_after); } @@ -6354,8 +6280,6 @@ auto Simulator::tryGetBody(BodyID body) const -> const Body* { auto Simulator::findCachedContact( const BroadPhasePair& pair, uint8_t normal_index, ContactFeatureID feature_a, ContactFeatureID feature_b ) -> CachedContact* { - ZoneScopedN("physics::FindCachedContact"); - const CachedManifoldKey key {.pair = pair, .normal_index = normal_index}; const auto manifold = std::lower_bound( m_cached_manifolds.begin(), m_cached_manifolds.end(), key, [](const CachedManifold& cached, CachedManifoldKey candidate) { @@ -6377,8 +6301,6 @@ auto Simulator::findCachedContact( auto Simulator::findCachedContact( const BroadPhasePair& pair, uint8_t normal_index, ContactFeatureID feature_a, ContactFeatureID feature_b ) const -> const CachedContact* { - ZoneScopedN("physics::FindCachedContact"); - const CachedManifoldKey key {.pair = pair, .normal_index = normal_index}; const auto manifold = std::lower_bound( m_cached_manifolds.begin(), m_cached_manifolds.end(), key, [](const CachedManifold& cached, CachedManifoldKey candidate) { @@ -6474,9 +6396,6 @@ auto Simulator::prepareConstraints(const std::vector& manifolds) -> st constraints.insert(constraints.end(), m_prepare_chunks[job_index].begin(), m_prepare_chunks[job_index].end()); } - if (rejected_contact_count > 0) { - TOAST_WARN("Physics", "Rejected {} invalid contact(s) while preparing constraints", rejected_contact_count); - } m_profile.constraints = constraints.size(); m_profile.rejected_constraints = rejected_contact_count; m_profile.warm_started_constraints = std::ranges::count_if(constraints, [](const Constraint& constraint) { @@ -6651,7 +6570,10 @@ auto Simulator::buildIslands(std::span manifolds, const std::vec } // Shared across islands since none share a dynamic body so never reset between them, only once per call - m_island_next_free_batch.assign(m_bodies.size(), 0); + // A body holds a bit per colour it already uses, a body past every mask colour falls back to batches above it + constexpr uint32_t k_mask_colors = 64; + m_island_color_mask.assign(m_bodies.size(), 0); + m_island_next_free_batch.assign(m_bodies.size(), k_mask_colors); for (SimulationIsland& island : islands) { // Load bearing: makes the greedy coloring below deterministic, not just the final storage order @@ -6673,7 +6595,6 @@ auto Simulator::buildIslands(std::span manifolds, const std::vec return lhs.feature_b < rhs.feature_b; }); - // Greedy list coloring per body pair not per contact m_island_constraint_batch.resize(island.constraints.size()); uint32_t batch_count = island.constraints.empty() ? 0 : 1; size_t group_begin = 0; @@ -6689,25 +6610,46 @@ auto Simulator::buildIslands(std::span manifolds, const std::vec const bool a_dynamic = body_a != nullptr && movable(*body_a); const bool b_dynamic = body_b != nullptr && movable(*body_b); - uint32_t batch = 0; + uint64_t used = 0; if (a_dynamic) { - batch = std::max(batch, m_island_next_free_batch[constraint.body_a.slot]); + used |= m_island_color_mask[constraint.body_a.slot]; } if (b_dynamic) { - batch = std::max(batch, m_island_next_free_batch[constraint.body_b.slot]); + used |= m_island_color_mask[constraint.body_b.slot]; } + + uint32_t batch = 0; + if (used != ~uint64_t {0}) { + batch = static_cast(std::countr_one(used)); + const uint64_t bit = uint64_t {1} << batch; + if (a_dynamic) { + m_island_color_mask[constraint.body_a.slot] |= bit; + } + if (b_dynamic) { + m_island_color_mask[constraint.body_b.slot] |= bit; + } + } else { + batch = k_mask_colors; + if (a_dynamic) { + batch = std::max(batch, m_island_next_free_batch[constraint.body_a.slot]); + } + if (b_dynamic) { + batch = std::max(batch, m_island_next_free_batch[constraint.body_b.slot]); + } + if (a_dynamic) { + m_island_next_free_batch[constraint.body_a.slot] = batch + 1; + } + if (b_dynamic) { + m_island_next_free_batch[constraint.body_b.slot] = batch + 1; + } + } + std::fill( m_island_constraint_batch.begin() + static_cast(group_begin), m_island_constraint_batch.begin() + static_cast(group_end), batch ); batch_count = std::max(batch_count, batch + 1); - if (a_dynamic) { - m_island_next_free_batch[constraint.body_a.slot] = batch + 1; - } - if (b_dynamic) { - m_island_next_free_batch[constraint.body_b.slot] = batch + 1; - } group_begin = group_end; } @@ -6786,9 +6728,6 @@ auto Simulator::buildIslands(std::span manifolds, const std::vec } auto Simulator::prepareConstraint(const Manifold& manifold, const ContactPoint& contact) const -> std::optional { - ZoneScopedN("physics::PrepareConstraint"); - ZoneValue((static_cast(manifold.pair.a.body.slot) << 32) | static_cast(manifold.pair.b.body.slot)); - const Body* body_a = tryGetBody(manifold.pair.a.body); const Body* body_b = tryGetBody(manifold.pair.b.body); if (not body_a || not body_b) { @@ -7215,9 +7154,6 @@ void Simulator::solveIslands(std::vector& islands) { } } - if (invalid_constraint_count > 0) { - TOAST_WARN("Physics", "Skipped {} invalid solver constraint(s)", invalid_constraint_count); - } m_profile.invalid_constraints = invalid_constraint_count; // Position correction is one pass over each island manifolds same reasoning as warm start above diff --git a/engine/src/toast/physics/simulator.hpp b/engine/src/toast/physics/simulator.hpp index 4d27dacb0..33474d9a6 100644 --- a/engine/src/toast/physics/simulator.hpp +++ b/engine/src/toast/physics/simulator.hpp @@ -17,7 +17,6 @@ #include "joint_solver.hpp" #include "manifold.hpp" #include "narrow_phase.hpp" -#include "physics_material.hpp" #include "shape.hpp" #include "shape_query.hpp" #include "toast/physics/raycast.hpp" @@ -684,6 +683,7 @@ class TOAST_API Simulator { [[nodiscard]] auto spawnStaticSplitBody(ShapeID source_shape_id, const DetachedComponent& component) -> bool; void despawnSettledFragments(float dt); + void destroyFallenBodies(); void retireVoxelBody(BodyID id); auto debrisIfSmall(ShapeID shape) -> bool; void destroyFragmentsOf(BodyID origin); @@ -773,6 +773,7 @@ class TOAST_API Simulator { std::vector m_island_parents; std::vector m_island_participates; std::vector m_island_by_root; + std::vector m_island_color_mask; std::vector m_island_next_free_batch; std::vector m_island_constraint_batch; std::vector m_island_batch_cursor; @@ -822,6 +823,7 @@ class TOAST_API Simulator { std::unordered_map m_fragment_index; std::vector m_pending_fragments; std::vector m_doomed_fragments; + std::vector m_scheduled_kills; /// Round robin start so a connectivity job cap does not starve the same shapes size_t m_connectivity_cursor = 0; diff --git a/engine/src/toast/renderer/debug/editor_overlays.hpp b/engine/src/toast/renderer/debug/editor_overlays.hpp index f2bf2ba6d..1fa16b4f6 100644 --- a/engine/src/toast/renderer/debug/editor_overlays.hpp +++ b/engine/src/toast/renderer/debug/editor_overlays.hpp @@ -24,8 +24,6 @@ struct EditorOverlays { bool volume_edges = false; ///< Lines along the AABB volume for the voxels bool projections = false; ///< 2D diedrico projections peak dibujo tecnico - toast::UID selected; ///< Focused node - toast::UID cut_root; ///< The voxel the Split and Slice preview is on bool cut_active = false; glm::vec4 cut_plane {0.0f}; ///< red is where the normal points diff --git a/engine/src/toast/renderer/passes/debug/debug_pass.cpp b/engine/src/toast/renderer/passes/debug/debug_pass.cpp index 3b97bc41f..07bf900bf 100644 --- a/engine/src/toast/renderer/passes/debug/debug_pass.cpp +++ b/engine/src/toast/renderer/passes/debug/debug_pass.cpp @@ -831,7 +831,11 @@ void DebugPass::update(uint32_t frame_index, float dt) { ImGui::TableNextColumn(); ImGui::TextDisabled("%zu", phys.narrow_pair_candidates[static_cast(type)]); ImGui::TableNextColumn(); - ImGui::TextDisabled("%.2f ms", phys.narrow_pair_time_ms[static_cast(type)]); + if (physics::tunables().time_narrow_pairs) { + ImGui::TextDisabled("%.2f ms", phys.narrow_pair_time_ms[static_cast(type)]); + } else { + ImGui::TextDisabled("timing off"); + } } ImGui::EndTable(); } diff --git a/engine/src/toast/renderer/passes/debug/selection_outline.cpp b/engine/src/toast/renderer/passes/debug/selection_outline.cpp index f2fa7bd4b..bef24518a 100644 --- a/engine/src/toast/renderer/passes/debug/selection_outline.cpp +++ b/engine/src/toast/renderer/passes/debug/selection_outline.cpp @@ -103,6 +103,18 @@ auto unite(const vk::Rect2D& a, const vk::Rect2D& b) -> vk::Rect2D { }; } +template +void forEachOutlinedVolume(const RenderFrame& frame, Visit&& visit) { + for (const VoxelVolumeProxy& proxy : frame.voxel_instances) { + if (proxy.outlined && proxy.visible) { + visit(proxy); + } + } + for (const VoxelVolumeProxy& proxy : frame.voxel_outline_only) { + visit(proxy); + } +} + auto outlinedMesh(const MeshInstanceProxy& proxy) -> bool { return proxy.outlined && proxy.visible && proxy.mesh != nullptr && proxy.mesh->isReady(); } @@ -346,19 +358,16 @@ auto SelectionOutline::prepareVolumes(uint32_t frame_index) -> uint32_t { } uint32_t count = 0; - for (const auto& proxy : frame->voxel_instances) { - if (!proxy.outlined || !proxy.visible) { - continue; - } + forEachOutlinedVolume(*frame, [&](const VoxelVolumeProxy& proxy) { if (count == k_max_volumes) { - break; + return; } instances[count] = makeVoxelInstance(proxy.model, proxy.inverse_model, proxy.model, true, proxy.record_index); if (proxy.mirrored) { instances[count].flags |= k_voxel_instance_mirrored; } ++count; - } + }); if (count == 0) { return 0; } @@ -393,11 +402,9 @@ void SelectionOutline::recordMask(vk::CommandBuffer cmd, uint32_t frame_index, v } const uint32_t volumes = prepareVolumes(frame_index); if (volumes > 0) { - for (const auto& proxy : frame->voxel_instances) { - if (proxy.outlined && proxy.visible) { - rect = unite(rect, sphereRect(view_projection, proxy.bounds_center, proxy.bounds_radius, m_extent)); - } - } + forEachOutlinedVolume(*frame, [&](const VoxelVolumeProxy& proxy) { + rect = unite(rect, sphereRect(view_projection, proxy.bounds_center, proxy.bounds_radius, m_extent)); + }); } if ((!any_mesh && volumes == 0) || rect.extent.width == 0 || rect.extent.height == 0) { m_history_valid = false; @@ -411,11 +418,7 @@ void SelectionOutline::recordMask(vk::CommandBuffer cmd, uint32_t frame_index, v models.push_back(proxy.model); } } - for (const auto& proxy : frame->voxel_instances) { - if (proxy.outlined && proxy.visible) { - models.push_back(proxy.model); - } - } + forEachOutlinedVolume(*frame, [&](const VoxelVolumeProxy& proxy) { models.push_back(proxy.model); }); const bool reset = !m_history_valid || !frame->taa_active || frame->frame_data.view_projection != m_history_view_projection || models != m_history_models; m_history_view_projection = frame->frame_data.view_projection; @@ -443,12 +446,19 @@ void SelectionOutline::recordMask(vk::CommandBuffer cmd, uint32_t frame_index, v stencil_info.storeOp = vk::AttachmentStoreOp::eStore; stencil_info.clearValue = vk::ClearValue(vk::ClearDepthStencilValue {0.0f, 0}); - const vk::Rect2D full { - {0, 0}, - m_extent + // The resolve reads the mask up to k_outline_reach past the rect, outside that the stale mask is never read + const int32_t mask_x0 = std::max(rect.offset.x - k_outline_reach, 0); + const int32_t mask_y0 = std::max(rect.offset.y - k_outline_reach, 0); + const int32_t mask_x1 = + std::min(rect.offset.x + static_cast(rect.extent.width) + k_outline_reach, static_cast(m_extent.width)); + const int32_t mask_y1 = + std::min(rect.offset.y + static_cast(rect.extent.height) + k_outline_reach, static_cast(m_extent.height)); + const vk::Rect2D mask_rect { + { mask_x0, mask_y0}, + {static_cast(mask_x1 - mask_x0), static_cast(mask_y1 - mask_y0)} }; vk::RenderingInfo rendering_info {}; - rendering_info.renderArea = full; + rendering_info.renderArea = mask_rect; rendering_info.layerCount = 1; rendering_info.pStencilAttachment = &stencil_info; @@ -457,7 +467,7 @@ void SelectionOutline::recordMask(vk::CommandBuffer cmd, uint32_t frame_index, v 0, std::array {vk::Viewport(0.0f, 0.0f, static_cast(m_extent.width), static_cast(m_extent.height), 0.0f, 1.0f)} ); - cmd.setScissor(0, std::array {full}); + cmd.setScissor(0, std::array {mask_rect}); const vk::PipelineLayout layout = *m_mask_layout.getPipelineLayout(); cmd.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, layout, 0, std::array {*m_mask_sets[frame_index]}, {}); diff --git a/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp b/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp index d8dccf3cc..8ae6852fb 100644 --- a/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp +++ b/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp @@ -952,7 +952,6 @@ auto VoxelPass::prepare(uint32_t frame_index) -> bool { const auto index = static_cast(m_draws.size()); VoxelInstanceGpu instance = makeVoxelInstance(proxy.model, proxy.inverse_model, proxy.previous_model, proxy.has_previous, proxy.record_index); - instance.pad0 = proxy.highlight_record; instance.cell_base = m_total_cells; if (proxy.mirrored) { instance.flags |= k_voxel_instance_mirrored; diff --git a/engine/src/toast/renderer/passes/lighting/gi_pass.cpp b/engine/src/toast/renderer/passes/lighting/gi_pass.cpp index d9ee1a044..09a54d6d3 100644 --- a/engine/src/toast/renderer/passes/lighting/gi_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/gi_pass.cpp @@ -182,13 +182,14 @@ struct QualityLevel { /// Scalability constexpr std::array k_quality_levels { { - {.ray_budget = 150'000, - .cascades = 4, - .spacing = 0.2f, - .lod_distance = 4.0f, - .multibounce = false, - .points = 8192, - .interval = 2}, + // Cheapest since the Low preset without ray tracing runs it on software traces + {.ray_budget = 100'000, + .cascades = 4, + .spacing = 0.25f, + .lod_distance = 4.0f, + .multibounce = false, + .points = 8192, + .interval = 2}, {.ray_budget = 300'000, .cascades = 4, .spacing = 0.15f, diff --git a/engine/src/toast/renderer/passes/lighting/ssr_pass.cpp b/engine/src/toast/renderer/passes/lighting/ssr_pass.cpp index 1ecf79b32..7fffa5972 100644 --- a/engine/src/toast/renderer/passes/lighting/ssr_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/ssr_pass.cpp @@ -125,6 +125,11 @@ void SsrPass::onResize(vk::Extent2D extent) { auto SsrPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView source_view) -> vk::ImageView { ZoneScoped; + // Traced specular owns reflections on its frames and the rest keep the environment specular already in the colour + if (VulkanRenderer::instance->tracedSpecularFrame()) { + m_history_valid = false; + return source_view; + } const bool pipelines_ready = m_trace_pipeline.isReady() && m_resolve_pipeline.isReady() && m_temporal_pipeline.isReady() && m_composite_pipeline.isReady(); const bool targets_ready = m_target.isReady() && m_hit_target.isReady() && m_resolve_target.isReady() && diff --git a/engine/src/toast/renderer/passes/lighting/traced_specular_pass.cpp b/engine/src/toast/renderer/passes/lighting/traced_specular_pass.cpp index 7f99a1152..524f19e1c 100644 --- a/engine/src/toast/renderer/passes/lighting/traced_specular_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/traced_specular_pass.cpp @@ -89,6 +89,7 @@ TracedSpecularPass::TracedSpecularPass(const VulkanCore& core, vk::Format scene_ build_pipeline(m_temporal_pipeline, k_trace_format, half, "temporalMain", "TracedSpecular Temporal"); build_pipeline(m_composite_pipeline, scene_format, extent, "compositeMain", "TracedSpecular Composite"); build_pipeline(m_pyramid_pipeline, k_pyramid_format, half, "pyramidMain", "TracedSpecular Pyramid"); + build_pipeline(m_filter_pipeline, k_trace_format, half, "filterMain", "TracedSpecular Filter"); m_scene_sets.create(core, shader->reflection, *layouts[k_specular_scene_set], "TracedSpecular"); m_instances_bound = std::ranges::any_of(shader->reflection.bindings, [](const ShaderBinding& binding) { @@ -99,7 +100,7 @@ TracedSpecularPass::TracedSpecularPass(const VulkanCore& core, vk::Format scene_ m_ready = m_surface_pipeline.isReady() && m_trace_pipeline.isReady() && m_resolve_pipeline.isReady() && m_temporal_pipeline.isReady() && m_composite_pipeline.isReady() && m_pyramid_pipeline.isReady() && - !m_scene_sets.empty() && !m_storage_sets.empty(); + m_filter_pipeline.isReady() && !m_scene_sets.empty() && !m_storage_sets.empty(); if (m_ready) { TOAST_INFO("Render", "TracedSpecularPass ready (GGX rays traced at half resolution)"); } @@ -166,6 +167,7 @@ void TracedSpecularPass::createTargets(const VulkanCore& core, vk::Extent2D exte m_resolved.create(core, half, k_trace_format, "TracedSpecular Resolved"); m_history[0].create(core, half, k_trace_format, "TracedSpecular History0"); m_history[1].create(core, half, k_trace_format, "TracedSpecular History1"); + m_filtered.create(core, half, k_trace_format, "TracedSpecular Filtered"); createPyramid(core, half); m_image_bound.invalidate(); m_history_valid = false; @@ -290,6 +292,16 @@ auto TracedSpecularPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk: writeVoxelStorageDescriptors(m_core->getDevice(), *m_storage_sets[frame_index], *frame->voxel_storage); } + // Views only change on a resize after a wait for idle so recreating here never frees a pyramid in flight + const vk::ImageView depth_view = renderer->getOpaqueDepthView(); + const vk::Extent2D depth_extent = renderer->renderExtent(); + if (depth_view && m_hiz.source() != depth_view) { + m_hiz.create(*m_core, depth_view, depth_extent, HiZPyramid::Reduction::closest); + } + if (!m_hiz.isReady()) { + return source_view; + } + const PostProcessTarget& history_write = m_history[m_parity]; const PostProcessTarget& history_read = m_history[1 - m_parity]; const uint32_t set_index = (frame_index * 2) + m_parity; @@ -310,6 +322,8 @@ auto TracedSpecularPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk: m_resolved.view(), m_surface.view(), m_pyramid_view.has_value() ? **m_pyramid_view : vk::ImageView {}, + m_hiz.view(), + m_filtered.view(), }; if (std::ranges::any_of(views, [](vk::ImageView view) { return !view; })) { return source_view; @@ -346,9 +360,25 @@ auto TracedSpecularPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk: ); params.resolve = glm::vec4(previous_view ? 1.0f : 0.0f, 0.0f, 0.0f, 0.0f); + { + const GpuScope scope(renderer->gpuTimer(), frame_index, cmd, "TracedSpecular depth pyramid"); + m_hiz.record(cmd, depth_extent, frame->frame_data.jittered_view_projection); + sync::BarrierBatch barriers; + m_hiz.beforeFragmentRead(barriers); + barriers.flush(cmd); + } + const auto ssr = renderer->ssrSettings(); + params.march = glm::vec4( + static_cast(m_hiz.builtLevels()), + static_cast(ssr.max_steps), + ssr.thickness, + renderer->voxelSpecularHitLights() ? 1.0f : 0.0f + ); + const vk::PipelineLayout layout = *m_layout.getPipelineLayout(); const std::array sets {m_scene_sets.get(frame_index), *m_storage_sets[frame_index], image_set}; - const auto draw = [&](const PostProcessTarget& target, const VulkanPipeline& pipeline) { + const auto draw = [&](const PostProcessTarget& target, const VulkanPipeline& pipeline, std::string_view scope_name) { + const GpuScope scope(renderer->gpuTimer(), frame_index, cmd, scope_name); target.beginScope(cmd); cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline.getPipeline()); cmd.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, layout, k_specular_scene_set, sets, {}); @@ -358,15 +388,17 @@ auto TracedSpecularPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk: }; if (previous_view) { + const GpuScope scope(renderer->gpuTimer(), frame_index, cmd, "TracedSpecular colour pyramid"); recordPyramid(cmd, layout, sets, params); } else if (m_pyramid_state.usage == sync::Usage::none) { sync::transition(cmd, m_pyramid_state, sync::Usage::shader_sampled); } - draw(m_surface, m_surface_pipeline); - draw(m_trace, m_trace_pipeline); - draw(m_resolved, m_resolve_pipeline); - draw(history_write, m_temporal_pipeline); - draw(m_target, m_composite_pipeline); + draw(m_surface, m_surface_pipeline, "TracedSpecular surface"); + draw(m_trace, m_trace_pipeline, "TracedSpecular trace"); + draw(m_resolved, m_resolve_pipeline, "TracedSpecular resolve"); + draw(history_write, m_temporal_pipeline, "TracedSpecular temporal"); + draw(m_filtered, m_filter_pipeline, "TracedSpecular filter"); + draw(m_target, m_composite_pipeline, "TracedSpecular composite"); m_parity = 1 - m_parity; m_history_valid = true; diff --git a/engine/src/toast/renderer/passes/lighting/traced_specular_pass.hpp b/engine/src/toast/renderer/passes/lighting/traced_specular_pass.hpp index 375c59c1b..59ad1c210 100644 --- a/engine/src/toast/renderer/passes/lighting/traced_specular_pass.hpp +++ b/engine/src/toast/renderer/passes/lighting/traced_specular_pass.hpp @@ -9,6 +9,7 @@ #include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/core/vulkan_common.hpp" #include "toast/renderer/passes/post_process_pass_base.hpp" +#include "toast/renderer/resources/hiz_pyramid.hpp" #include "toast/renderer/resources/post_process_target.hpp" #include "toast/renderer/resources/scene_descriptor_set.hpp" #include "toast/renderer/shaders/shader_layout.hpp" @@ -52,6 +53,9 @@ class TracedSpecularPass : public IPostProcessPass { glm::vec4 tracing {0.0f}; /// x 1 when binding 10 holds last frame resolve glm::vec4 resolve {0.0f}; + /// x levels of the closest depth pyramid y most screen march steps with 0 off z SSR thickness w 1 when off screen + /// hits take local lights + glm::vec4 march {0.0f}; }; /// rgb radiance a hit distance then history and -1 where nothing was traced @@ -64,7 +68,7 @@ class TracedSpecularPass : public IPostProcessPass { /// Mirrors voxel_specular.slang kPyramidLevels static constexpr uint32_t k_pyramid_levels = 6; - static constexpr uint32_t k_image_bindings = 14; + static constexpr uint32_t k_image_bindings = 16; void createSets(const VulkanCore& core); void createTargets(const VulkanCore& core, vk::Extent2D extent); @@ -85,6 +89,7 @@ class TracedSpecularPass : public IPostProcessPass { VulkanPipeline m_temporal_pipeline; VulkanPipeline m_composite_pipeline; VulkanPipeline m_pyramid_pipeline; + VulkanPipeline m_filter_pipeline; SceneDescriptorSets m_scene_sets; bool m_instances_bound = false; @@ -104,7 +109,11 @@ class TracedSpecularPass : public IPostProcessPass { PostProcessTarget m_resolved; /// The temporal pass reads one and writes the other std::array m_history; + /// Footprint filtered history at half resolution so the full resolution composite only upsamples it + PostProcessTarget m_filtered; PostProcessTarget m_target; + /// Closest depth so a ray the screen shows skips the voxel trace + HiZPyramid m_hiz; std::optional m_pyramid; /// Every level for sampling and level 0 alone for drawing diff --git a/engine/src/toast/renderer/render_frame.hpp b/engine/src/toast/renderer/render_frame.hpp index bb2bd99ce..6def72e6e 100644 --- a/engine/src/toast/renderer/render_frame.hpp +++ b/engine/src/toast/renderer/render_frame.hpp @@ -86,7 +86,6 @@ struct VoxelVolumeProxy { float bounds_radius = 0.0f; float view_distance = 0.0f; - uint32_t highlight_record = 0; /// False the first frame this node_uid is drawn so the shader reports motion as not written instead of zero bool has_previous = false; @@ -178,6 +177,7 @@ struct RenderFrame { /// Sorted front to back std::vector voxel_instances; + std::vector voxel_outline_only; std::shared_ptr voxel_storage; diff --git a/engine/src/toast/renderer/settings/renderer_settings.cpp b/engine/src/toast/renderer/settings/renderer_settings.cpp index ec60bdc30..e54d569b5 100644 --- a/engine/src/toast/renderer/settings/renderer_settings.cpp +++ b/engine/src/toast/renderer/settings/renderer_settings.cpp @@ -22,6 +22,8 @@ struct PresetKnobs { bool traced_specular = true; float specular_roughness = 0.6f; float specular_reach = 32.0f; + /// Off screen traced specular hits take a local light and its shadow ray + bool specular_hit_lights = true; uint32_t light_candidates = 8; bool ambient_rays = true; bool glass_shadows = true; @@ -42,7 +44,7 @@ struct PresetKnobs { float glass_reflection_reach = 32.0f; }; -/// Low Medium High Epic without ray tracing, then Low RT Medium RT High RT Epic RT +/// Low Medium High Epic without ray tracing, then Low RT Medium RT High RT Epic RT. Radiance cascades run in every tier constexpr std::array k_preset_tiers { { // Without ray tracing @@ -56,7 +58,7 @@ constexpr std::array k_preset_tiers { .glass_shadows = false, .volumetric_quality = 0, .gi_quality = 0, - .gi_enabled = false, + .gi_enabled = true, .render_scale = 0.65f, .shadow_distance = 60.0f, .spot_budget = 4, @@ -74,7 +76,7 @@ constexpr std::array k_preset_tiers { .glass_shadows = false, .volumetric_quality = 0, .gi_quality = 0, - .gi_enabled = false, + .gi_enabled = true, .render_scale = 0.75f, .shadow_distance = 100.0f, .spot_budget = 6, @@ -93,7 +95,7 @@ constexpr std::array k_preset_tiers { .ambient_rays = false, .glass_shadows = true, .volumetric_quality = 1, - .gi_quality = 0, + .gi_quality = 1, .gi_enabled = true, .render_scale = 0.85f, .shadow_distance = 150.0f, @@ -114,7 +116,7 @@ constexpr std::array k_preset_tiers { .ambient_rays = false, .glass_shadows = true, .volumetric_quality = 1, - .gi_quality = 1, + .gi_quality = 2, .gi_enabled = true, .render_scale = 1.0f, .shadow_distance = 250.0f, @@ -137,9 +139,12 @@ constexpr std::array k_preset_tiers { .glass_shadows = false, .volumetric_quality = 0, .gi_quality = 0, + .gi_enabled = true, + .render_scale = 0.75f, .shadow_distance = 60.0f, .spot_budget = 4, .point_budget = 2, + .shadow_maps_only = true, .glass_lit_surfaces = 1, .glass_reflection_reach = 8.0f}, {.ssr = true, @@ -152,6 +157,8 @@ constexpr std::array k_preset_tiers { .glass_shadows = true, .volumetric_quality = 1, .gi_quality = 1, + .gi_enabled = true, + .render_scale = 0.85f, .shadow_distance = 100.0f, .spot_budget = 8, .point_budget = 4, @@ -162,13 +169,15 @@ constexpr std::array k_preset_tiers { {.ssr = true, .ssao = true, .traced_specular = true, - .specular_roughness = 0.5f, - .specular_reach = 32.0f, + .specular_roughness = 0.45f, + .specular_reach = 24.0f, + .specular_hit_lights = false, .light_candidates = 8, .ambient_rays = true, .glass_shadows = true, .volumetric_quality = 2, .gi_quality = 2, + .gi_enabled = true, .shadow_distance = 150.0f, .spot_budget = 16, .point_budget = 8, @@ -181,12 +190,13 @@ constexpr std::array k_preset_tiers { .ssao = true, .traced_specular = true, .specular_roughness = 0.6f, - .specular_reach = 48.0f, + .specular_reach = 32.0f, .light_candidates = 16, .ambient_rays = true, .glass_shadows = true, .volumetric_quality = 3, .gi_quality = 3, + .gi_enabled = true, .shadow_distance = 250.0f, .spot_budget = shadows::k_max_spot_shadows, .point_budget = shadows::k_max_point_shadows, @@ -238,6 +248,7 @@ void applyPreset() { renderer.setVoxelTracedSpecular(knobs.traced_specular); renderer.setVoxelSpecularRoughness(knobs.specular_roughness); renderer.setVoxelSpecularReach(knobs.specular_reach); + renderer.setVoxelSpecularHitLights(knobs.specular_hit_lights); renderer.setVoxelLightCandidates(knobs.light_candidates); renderer.setVoxelAmbientRays(knobs.ambient_rays); renderer.setVoxelGlassShadows(knobs.glass_shadows); @@ -257,7 +268,7 @@ struct DrivenSetting { Value (*get)(const PresetKnobs&); }; -const std::array k_driven { +const std::array k_driven { { {"renderer.voxels.shadow_maps_only", [](const PresetKnobs& k) { return Value {k.shadow_maps_only}; }}, {"renderer.quality.ssr_reach", [](const PresetKnobs& k) { return Value {static_cast(k.ssr_reach)}; }}, @@ -270,6 +281,7 @@ const std::array k_driven { {"renderer.voxels.specular_roughness", [](const PresetKnobs& k) { return Value {static_cast(k.specular_roughness)}; }}, {"renderer.voxels.specular_reach", [](const PresetKnobs& k) { return Value {static_cast(k.specular_reach)}; }}, + {"renderer.voxels.specular_hit_lights", [](const PresetKnobs& k) { return Value {k.specular_hit_lights}; }}, {"renderer.voxels.light_candidates", [](const PresetKnobs& k) { return Value {static_cast(k.light_candidates)}; }}, {"renderer.voxels.ambient_rays", [](const PresetKnobs& k) { return Value {k.ambient_rays}; }}, {"renderer.voxels.glass_shadows", [](const PresetKnobs& k) { return Value {k.glass_shadows}; }}, @@ -886,6 +898,16 @@ void registerVoxels(VulkanRenderer& renderer) { ) .onChange(presetKnob(&PresetKnobs::specular_reach, k_to_float)); + toast::settings::declareBool( + "renderer.voxels.specular_hit_lights", + true, + {.label = "Traced specular hit lights", + .category = "Voxels", + .description = "Reflection rays that hit off screen take a local light and its shadow ray on top of the sun and GI. " + "Preset Custom only"} + ) + .onChange(presetKnob(&PresetKnobs::specular_hit_lights, k_same_bool)); + toast::settings::declareInt( "renderer.voxels.glass_lit_surfaces", 4, diff --git a/engine/src/toast/renderer/vulkan_renderer.hpp b/engine/src/toast/renderer/vulkan_renderer.hpp index fb0b567b2..a821317a7 100644 --- a/engine/src/toast/renderer/vulkan_renderer.hpp +++ b/engine/src/toast/renderer/vulkan_renderer.hpp @@ -563,6 +563,14 @@ class VulkanRenderer { return m_voxel_specular_roughness.load(std::memory_order_relaxed); } + void setVoxelSpecularHitLights(bool enabled) noexcept { m_voxel_specular_hit_lights.store(enabled, std::memory_order_relaxed); } + + /// Off screen reflection hits take a local light with its shadow ray on top of the sun and GI + [[nodiscard]] + auto voxelSpecularHitLights() const noexcept -> bool { + return m_voxel_specular_hit_lights.load(std::memory_order_relaxed); + } + void setVoxelSpecularReach(float meters) noexcept { m_voxel_specular_reach.store(std::max(meters, 0.1f), std::memory_order_relaxed); } @@ -1134,6 +1142,11 @@ class VulkanRenderer { m_outlined_rids = std::move(rids); } + [[nodiscard]] + auto isNodeOutlined(uint64_t node_rid) const -> bool { + return isOutlined(node_rid); + } + void setDebugDrawEnabled(bool enabled) noexcept { m_debug_draw_enabled.store(enabled, std::memory_order_relaxed); } [[nodiscard]] @@ -1280,24 +1293,6 @@ class VulkanRenderer { cancelIrradianceBake(); } - /** - * Tints the voxels of node that are solid in highlight - * @note nullptr clears it - */ - void setVoxelHighlight(const toast::VoxelNode* node, const voxel::Volume* highlight, uint64_t part_key = 0) { - std::scoped_lock lock(m_voxel_proxy_mutex); - if (highlight == nullptr) { - m_voxel_highlights.erase(VoxelHighlightKey {node, part_key}); - } else { - m_voxel_highlights[VoxelHighlightKey {node, part_key}] = highlight; - } - } - - void clearVoxelHighlights(const toast::VoxelNode* node) { - std::scoped_lock lock(m_voxel_proxy_mutex); - std::erase_if(m_voxel_highlights, [node](const auto& entry) { return entry.first.node == node; }); - } - void setSecondaryOwner(const toast::INodeOwner* owner, const glm::mat4& transform, const toast::Node* hidden) { m_secondary_owner = owner; m_secondary_transform = transform; @@ -1632,6 +1627,7 @@ class VulkanRenderer { std::atomic m_volumetric_distance {100.0f}; std::atomic m_voxel_specular_roughness {0.6f}; std::atomic m_voxel_specular_reach {32.0f}; + std::atomic_bool m_voxel_specular_hit_lights {true}; std::atomic m_voxel_glass_lit_surfaces {4}; std::atomic m_voxel_glass_reflection_reach {32.0f}; std::atomic m_glass_glow_scale {1.0f}; @@ -1734,20 +1730,6 @@ class VulkanRenderer { const toast::INodeOwner* m_render_owner_filter = nullptr; - struct VoxelHighlightKey { - const toast::VoxelNode* node = nullptr; - uint64_t part = 0; - - auto operator==(const VoxelHighlightKey&) const noexcept -> bool = default; - }; - - struct VoxelHighlightKeyHash { - auto operator()(const VoxelHighlightKey& key) const noexcept -> size_t { - return std::hash {}(key.node) ^ (std::hash {}(key.part) * 0x9E3779B97F4A7C15ull); - } - }; - - std::unordered_map m_voxel_highlights; const toast::INodeOwner* m_secondary_owner = nullptr; glm::mat4 m_secondary_transform {1.0f}; const toast::Node* m_secondary_hidden = nullptr; diff --git a/engine/src/toast/renderer/vulkan_renderer_record.cpp b/engine/src/toast/renderer/vulkan_renderer_record.cpp index 67d9a9ef5..5051b6d48 100644 --- a/engine/src/toast/renderer/vulkan_renderer_record.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_record.cpp @@ -533,7 +533,7 @@ auto VulkanRenderer::recordVoxelScopes( specular_frame->irradiance_capture_index < 0; // Read here since glass records under m_pass_mutex m_ssr_frame = specular_frame != nullptr && specular_frame->render_mode == 0 && specular_frame->probe_capture_index < 0 && - specular_frame->irradiance_capture_index < 0 && isPostProcessPassEnabled("SSR"); + specular_frame->irradiance_capture_index < 0 && isPostProcessPassEnabled("SSR") && !m_traced_specular_frame; const vk::CommandBuffer cmd = *frame.command_buffer; { diff --git a/engine/src/toast/renderer/vulkan_renderer_scene.cpp b/engine/src/toast/renderer/vulkan_renderer_scene.cpp index aa817b0d2..f75c433d3 100644 --- a/engine/src/toast/renderer/vulkan_renderer_scene.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_scene.cpp @@ -560,6 +560,7 @@ void VulkanRenderer::resetFrameBuild(RenderFrame& frame) { frame.mesh_instances.clear(); frame.material_ranges.clear(); frame.voxel_instances.clear(); + frame.voxel_outline_only.clear(); frame.voxel_storage.reset(); frame.probe_capture_index = -1; frame.probe_capture_face = 0; @@ -1269,7 +1270,7 @@ void VulkanRenderer::logLightingInputs(const RenderFrame& frame, glm::vec3 ambie static std::optional last_state; if (!last_state.has_value() || *last_state != state) { last_state = state; - TOAST_TRACE( + /*TOAST_TRACE( "Render", "Lighting inputs: ambient=({:.3f}, {:.3f}, {:.3f}), {} directional, {} punctual, environment={}, " "{} mesh instances, render mode {}, exposure {:.3f}, {} probes (baked mask {:#x}),", @@ -1284,7 +1285,7 @@ void VulkanRenderer::logLightingInputs(const RenderFrame& frame, glm::vec3 ambie frame.post_process.tonemap.exposure, frame.frame_data.reflection_probe_count_pad.x, frame.frame_data.reflection_probe_count_pad.z - ); + );*/ } } diff --git a/engine/src/toast/renderer/vulkan_renderer_voxel.cpp b/engine/src/toast/renderer/vulkan_renderer_voxel.cpp index 492a0d9d8..773fb45ed 100644 --- a/engine/src/toast/renderer/vulkan_renderer_voxel.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_voxel.cpp @@ -1,36 +1,12 @@ -/// @file vulkan_renderer_voxel.cpp -/// @author dario -/// @date 16/05/2026 - -#include "toast/renderer/debug/editor_overlays.hpp" -#include "toast/renderer/debug/voxel_debug.hpp" -#include "toast/renderer/lighting/clustered_lighting_constants.hpp" -#include "toast/renderer/lighting/cube_face_basis.hpp" -#include "toast/renderer/lighting/frustum.hpp" -#include "toast/renderer/lighting/light_culling.hpp" -#include "toast/renderer/lighting/shadow_slots.hpp" -#include "toast/renderer/passes/debug/selection_outline.hpp" -#include "toast/renderer/passes/geometry/debris_pass.hpp" -#include "toast/renderer/passes/geometry/depth_prepass.hpp" -#include "toast/renderer/passes/geometry/material_pass.hpp" -#include "toast/renderer/passes/geometry/skinning_pass.hpp" -#include "toast/renderer/passes/geometry/voxel_pass.hpp" -#include "toast/renderer/passes/lighting/environment_pass.hpp" -#include "toast/renderer/passes/lighting/reflection_probe_pass.hpp" -#include "toast/renderer/passes/lighting/shadow_pass.hpp" -#include "toast/renderer/passes/lighting/traced_specular_pass.hpp" -#include "toast/renderer/passes/post/taa_pass.hpp" -#include "toast/renderer/raytracing/ray_tracing_scene.hpp" -#include "toast/renderer/raytracing/skinned_blas_pool.hpp" -#include "toast/renderer/resources/blue_noise.hpp" -#include "toast/renderer/settings/renderer_settings.hpp" -#include "toast/renderer/shaders/shader_compiler.hpp" -#include "toast/renderer/vulkan_renderer.hpp" -#include "toast/renderer/vulkan_renderer_detail.hpp" +#include "debug/voxel_debug.hpp" +#include "passes/debug/selection_outline.hpp" +#include "passes/geometry/voxel_pass.hpp" +#include "passes/lighting/shadow_pass.hpp" +#include "passes/lighting/traced_specular_pass.hpp" +#include "settings/renderer_settings.hpp" +#include "vulkan_renderer.hpp" #include -#include -#include #include #include #include @@ -202,10 +178,10 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { std::string_view debug_suffix; uint32_t fragment_slot = ~0u; bool data_only = false; - uint64_t highlight_id = 0; const toast::VoxelNode* node = nullptr; - uint64_t part_key = 0; uint64_t outline_id = 0; + bool piece_outlined = false; + bool outline_only = false; }; // chatty vibed this @@ -215,9 +191,6 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { return (mixed & 0x3FFFFFFFFFFFFFFFull) | (uint64_t {1} << 62); }; - // Highlights share the voxel grid of their node so the shader looks up the same voxel - constexpr uint64_t k_highlight_id_bit = uint64_t {1} << 63; - std::vector gathered; std::vector key; gathered.reserve(nodes.size()); @@ -229,9 +202,41 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { if (node == nullptr || !node->enabled()) { continue; } - const glm::mat4* owner_transform = ownerTransform(*node); - if (owner_transform == nullptr) { - continue; + static const glm::mat4 k_identity(1.0f); + const glm::mat4* drawn_transform = ownerTransform(*node); + const bool hidden = drawn_transform == nullptr; + const glm::mat4* owner_transform = hidden ? &k_identity : drawn_transform; + + // volumes that doesn't ahve any voxels + for (const toast::VoxelOutlineGhost& ghost : node->outlineGhosts()) { + if (ghost.volume == nullptr) { + continue; + } + const voxel::Palette* ghost_palette = node->resolvedPalette(); + if (ghost_palette == nullptr) { + ghost_palette = &defaultVoxelPalette(); + } + const uint64_t id = part_render_id(node->rid(), ghost.piece_rid ^ 0x6F75'746C'696E'6500ull); + // clang-format off + gathered.push_back(Gathered { + .id = id, + .volume = ghost.volume.get(), + .palette = ghost_palette, + .model = *owner_transform * node->getWorldTransform() * ghost.localTransform(), + .debug_name = node->name(), + .debug_suffix = " outline", + .data_only = true, + .node = node, + .outline_only = !hidden + }); + key.push_back({ + .node_rid = id, + .revision = ghost.generation, + .content = ghost.volume->revision(), + .palette = ghost_palette, + .palette_revision = ghost_palette->revision + }); + // clang-format on } if (node->usesParts()) { @@ -255,9 +260,10 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { .palette = parts_palette, .model = *owner_transform * physics::Simulator::renderPoseDelta(part) * pose * part.localTransform(), .debug_name = node->name(), + .data_only = hidden, .node = node, - .part_key = part.key, - .outline_id = node->rid() + .outline_id = node->rid(), + .piece_outlined = std::ranges::any_of(part.outline_rids, [this](uint64_t rid) { return isOutlined(rid); }) }); key.push_back({ .node_rid = id, @@ -287,6 +293,7 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { .palette = palette, .model = *owner_transform * physics::Simulator::renderPoseDelta(*node) * node->getWorldTransform() * node->volumeLocalTransform(), .debug_name = node->name(), + .data_only = hidden, .node = node }); key.push_back({ @@ -299,36 +306,6 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { // clang-format on } - { - std::scoped_lock lock(m_voxel_proxy_mutex); - const size_t drawn = gathered.size(); - for (size_t i = 0; i < drawn; ++i) { - auto it = m_voxel_highlights.find(VoxelHighlightKey {gathered[i].node, gathered[i].part_key}); - if (gathered[i].node == nullptr || it == m_voxel_highlights.end() || - it->second->brickDims() != gathered[i].volume->brickDims()) { - continue; - } - const uint64_t id = gathered[i].id ^ k_highlight_id_bit; - gathered[i].highlight_id = id; - gathered.push_back({ - .id = id, - .volume = it->second, - .palette = gathered[i].palette, - .model = gathered[i].model, - .debug_name = gathered[i].debug_name, - .debug_suffix = " highlight", - .data_only = true, - }); - key.push_back( - {.node_rid = id, - .revision = 0, - .content = it->second->revision(), - .palette = gathered[i].palette, - .palette_revision = gathered[i].palette->revision} - ); - } - } - // Fragments of one blast share an origin and part entries repeat their node so each origin is checked once per node std::vector> origin_owned; const auto owned_by_gathered = [&](physics::BodyID origin) { @@ -339,7 +316,7 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { bool owned = false; const toast::VoxelNode* checked = nullptr; for (const Gathered& g : gathered) { - if (g.node == nullptr || g.node == checked) { + if (g.node == nullptr || g.data_only || g.node == checked) { continue; } checked = g.node; @@ -497,6 +474,20 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { m_voxel_storage = std::move(storage); m_voxel_change_tracker.published(); } else { + if (m_voxel_storage != nullptr) { + const char* reason; + if (keep_mirror) { + reason = "a voxel debug view keeps a CPU mirror"; + } else if (not m_voxel_storage->isReady()) { + reason = "the previous upload is not ready"; + } else if (not patched.has_value()) { + reason = "dead records or the edit outweigh half the scene"; + } else { + reason = "the GPU buffers ran out of spare room"; + } + + TOAST_INFO("Render", "Voxel scene uploads every brick again: {}", reason); + } auto packed = std::make_shared(VoxelPackedScene { .pool = voxel::gpu::packPool(voxel::runtimeBrickPool()), .scene = voxel::gpu::packScene(scene_volumes) }); @@ -554,12 +545,6 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { return; } - // 1 + the packed record of a highlight so 0 stays none - const auto highlight_record_of = [this](uint64_t id) -> uint32_t { - const std::optional record = id != 0 ? m_voxel_storage->recordIndexOf(id) : std::nullopt; - return record.has_value() ? *record + 1u : 0u; - }; - // Existing keys are rewritten in place so a steady scene allocates nothing here const uint64_t proxy_frame = ++m_voxel_proxy_frame; frame.voxel_instances.reserve(gathered.size()); @@ -567,6 +552,27 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { for (const Gathered& entry : gathered) { const uint64_t node_rid = entry.id; + if (entry.outline_only) { + if (const std::optional record = m_voxel_storage->recordIndexOf(node_rid)) { + const glm::uvec3 dims = m_voxel_storage->recordBrickDims(*record); + const glm::vec4 sphere = voxel::worldBoundingSphere(entry.model, dims); + frame.voxel_outline_only.push_back( + VoxelVolumeProxy { + .model = entry.model, + .inverse_model = glm::inverse(entry.model), + .previous_model = entry.model, + .node_rid = node_rid, + .brick_dims = dims, + .record_index = *record, + .bounds_center = glm::vec3(sphere), + .bounds_radius = sphere.w, + .mirrored = glm::determinant(entry.model) < 0.0f, + .outlined = true, + } + ); + } + continue; + } if (entry.data_only) { continue; } @@ -603,10 +609,9 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { .record_index = *record, .bounds_center = glm::vec3(math.sphere), .bounds_radius = math.sphere.w, - .highlight_record = highlight_record_of(entry.highlight_id), .has_previous = has_previous, .mirrored = math.mirrored, - .outlined = isOutlined(entry.outline_id != 0 ? entry.outline_id : node_rid), + .outlined = entry.piece_outlined || isOutlined(entry.outline_id != 0 ? entry.outline_id : node_rid), } ); m_voxel_drawn_models.insert_or_assign(node_rid, VoxelDrawnModel {.model = model, .frame = proxy_frame}); diff --git a/engine/src/toast/voxel/brick_pool.hpp b/engine/src/toast/voxel/brick_pool.hpp index 1ba3140ec..1b593f595 100644 --- a/engine/src/toast/voxel/brick_pool.hpp +++ b/engine/src/toast/voxel/brick_pool.hpp @@ -65,6 +65,11 @@ class TOAST_API BrickPool { return m_capacity - allocatedCount(); } + [[nodiscard]] + auto slotsInUse() const noexcept -> uint32_t { + return m_next_unused.load(std::memory_order_acquire); + } + [[nodiscard]] auto isValid(uint32_t id) const noexcept -> bool { return id < m_next_unused.load(std::memory_order_acquire); diff --git a/engine/src/toast/voxel/gpu_layout.cpp b/engine/src/toast/voxel/gpu_layout.cpp index e83b614bd..ebe99f474 100644 --- a/engine/src/toast/voxel/gpu_layout.cpp +++ b/engine/src/toast/voxel/gpu_layout.cpp @@ -1,5 +1,6 @@ #include "gpu_layout.hpp" +#include #include namespace voxel::gpu { @@ -8,11 +9,7 @@ namespace { [[nodiscard]] auto poolSlotsInUse(const BrickPool& pool) -> uint32_t { - uint32_t used = 0; - while (used < pool.capacity() && pool.isValid(used)) { - ++used; - } - return used; + return std::min(pool.slotsInUse(), pool.capacity()); } [[nodiscard]] diff --git a/engine/src/toast/voxel/nodes/procedural_compose.cpp b/engine/src/toast/voxel/nodes/procedural_compose.cpp new file mode 100644 index 000000000..e5e86c2e5 --- /dev/null +++ b/engine/src/toast/voxel/nodes/procedural_compose.cpp @@ -0,0 +1,823 @@ +#include "procedural_compose.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace toast::procedural { + +namespace { + +struct ProjectionAxes { + int h; + int v; + int depth; + int toward; +}; + +constexpr std::array k_projection_views { + ProjectionAxes {0, 2, 1, 1}, + ProjectionAxes {1, 2, 0, -1}, + ProjectionAxes {0, 1, 2, -1} +}; + +void projectShape( + const voxel::Volume& shape, glm::ivec3 origin, const voxel::Palette& palette, std::vector& out +) { + ZoneScoped; + glm::ivec3 dims = glm::ivec3(shape.voxelDims()); + + for (const auto& view : k_projection_views) { + event::VoxelProjectionData projection; + projection.min_h = origin[view.h]; + projection.min_v = origin[view.v]; + projection.width = static_cast(dims[view.h]); + projection.height = static_cast(dims[view.v]); + projection.colors.assign(static_cast(projection.width) * projection.height * 4, 0); + projection.depths.assign(static_cast(projection.width) * projection.height, std::numeric_limits::max()); + projection.edges_h.assign(static_cast(projection.width + 1) * projection.height * 4, 0); + projection.edges_v.assign(static_cast(projection.width) * (projection.height + 1) * 4, 0); + out.push_back(std::move(projection)); + } + + // Outlines + for (uint32_t index = 0; index < shape.brickCount(); ++index) { + glm::ivec3 brick = shape.brickAtIndex(index); + voxel::BrickEntry entry = shape.entryAt(brick); + + if (entry.tag() == voxel::BrickTag::empty) { + continue; + } + const auto& occupancy = *shape.occupancyPointer(brick); + voxel::BrickNeighbourhood around = shape.neighbourhoodOf(brick); + std::array, 3> exposed { + { + {occupancy & ~voxel::neighboursNegX(occupancy, around.neg_x), + occupancy & ~voxel::neighboursPosX(occupancy, around.pos_x)}, + {occupancy & ~voxel::neighboursNegY(occupancy, around.neg_y), + occupancy & ~voxel::neighboursPosY(occupancy, around.pos_y)}, + {occupancy & ~voxel::neighboursNegZ(occupancy, around.neg_z), + occupancy & ~voxel::neighboursPosZ(occupancy, around.pos_z)}, + } + }; + bool uniform = entry.tag() == voxel::BrickTag::uniform; + const uint8_t* materials = uniform ? nullptr : std::as_const(*shape.pool()).material(entry.payload()).data(); + glm::ivec3 corner = brick * static_cast(voxel::k_brick_dim); + + for (size_t v = 0; v < k_projection_views.size(); ++v) { + event::VoxelProjectionData& projection = out[v]; + const auto& view = k_projection_views[v]; + const auto& across = exposed[static_cast(view.h)]; + const auto& up = exposed[static_cast(view.v)]; + for (uint32_t z = 0; z < voxel::k_brick_dim; ++z) { + uint64_t bits = across[0][z] | across[1][z] | up[0][z] | up[1][z]; + while (bits != 0) { + auto bit = static_cast(std::countr_zero(bits)); + uint64_t mask = uint64_t {1} << bit; + bits &= bits - 1; + + uint32_t local = (z * 64) + bit; + uint8_t id = uniform ? static_cast(entry.payload()) : materials[local]; + const voxel::PaletteEntry& color = palette.entries[id]; + glm::ivec3 cell = + corner + glm::ivec3(static_cast(bit & 7), static_cast(bit >> 3), static_cast(z)); + auto h = static_cast(cell[view.h]); + auto row = static_cast(cell[view.v]); + + // See through + auto mark = [&](std::vector& edges, size_t at) { + edges[(at * 4) + 0] = color.albedo_r; + edges[(at * 4) + 1] = color.albedo_g; + edges[(at * 4) + 2] = color.albedo_b; + edges[(at * 4) + 3] = 255; + }; + if ((across[0][z] & mask) != 0) { + mark(projection.edges_h, h + (row * (projection.width + 1))); + } + if ((across[1][z] & mask) != 0) { + mark(projection.edges_h, h + 1 + (row * (projection.width + 1))); + } + if ((up[0][z] & mask) != 0) { + mark(projection.edges_v, h + (row * projection.width)); + } + if ((up[1][z] & mask) != 0) { + mark(projection.edges_v, h + ((row + 1) * projection.width)); + } + } + } + } + } + + // See through fill + constexpr float k_layer_alpha = 0.1f; + constexpr int32_t k_dim = static_cast(voxel::k_brick_dim); + for (size_t v = 0; v < k_projection_views.size(); ++v) { + event::VoxelProjectionData& projection = out[v]; + const auto& view = k_projection_views[v]; + int length = dims[view.depth]; + for (uint32_t row = 0; row < projection.height; ++row) { + for (uint32_t h = 0; h < projection.width; ++h) { + glm::vec3 color(0.0f); + float alpha = 0.0f; + uint8_t previous = voxel::k_empty_palette_index; + int nearest = -1; + glm::ivec3 cell; + cell[view.h] = static_cast(h); + cell[view.v] = static_cast(row); + auto layer = [&](uint8_t id) { + const voxel::PaletteEntry& entry = palette.entries[id]; + glm::vec3 tint = glm::vec3(entry.albedo_r, entry.albedo_g, entry.albedo_b) / 255.0f; + color = tint * k_layer_alpha + color * (1.0f - k_layer_alpha); + alpha = k_layer_alpha + (alpha * (1.0f - k_layer_alpha)); + }; + int step = 0; + while (step < length) { + cell[view.depth] = view.toward > 0 ? length - 1 - step : step; + voxel::BrickEntry entry = shape.entryAt({cell.x >> 3, cell.y >> 3, cell.z >> 3}); + int along = cell[view.depth] & (k_dim - 1); + int rest = view.toward > 0 ? along + 1 : k_dim - along; + if (entry.tag() == voxel::BrickTag::empty) { + step += rest; + previous = voxel::k_empty_palette_index; + continue; + } + if (entry.tag() == voxel::BrickTag::uniform) { + auto id = static_cast(entry.payload()); + if (id != previous) { + layer(id); + } + previous = id; + nearest = view.toward > 0 ? cell[view.depth] - (rest - 1) : cell[view.depth] + (rest - 1); + step += rest; + continue; + } + uint8_t id = shape.materialAt(cell); + if (id != voxel::k_empty_palette_index) { + if (id != previous) { + layer(id); + } + nearest = cell[view.depth]; + } + previous = id; + ++step; + } + if (alpha <= 0.0f) { + continue; + } + // color is premultiplied + size_t slot = static_cast(h) + (static_cast(row) * projection.width); + for (int c = 0; c < 3; ++c) { + projection.colors[(slot * 4) + c] = + static_cast(std::lround(glm::clamp(color[c] / alpha, 0.0f, 1.0f) * 255.0f)); + } + projection.colors[(slot * 4) + 3] = static_cast(std::lround(alpha * 255.0f)); + projection.depths[slot] = static_cast(view.toward * (nearest + origin[view.depth])); + } + } + } +} + +template +void visitSolid(const voxel::Volume& volume, glm::ivec3 brick, Visit&& visit) { + voxel::BrickEntry entry = volume.entryAt(brick); + if (entry.tag() == voxel::BrickTag::empty) { + return; + } + glm::ivec3 corner = brick * static_cast(voxel::k_brick_dim); + if (entry.tag() == voxel::BrickTag::uniform) { + auto id = static_cast(entry.payload()); + for (int32_t z = 0; std::cmp_less(z, voxel::k_brick_dim); ++z) { + for (int32_t y = 0; std::cmp_less(y, voxel::k_brick_dim); ++y) { + for (int32_t x = 0; std::cmp_less(x, voxel::k_brick_dim); ++x) { + visit(corner + glm::ivec3(x, y, z), id); + } + } + } + return; + } + const voxel::BrickOccupancy& occupancy = *volume.occupancyPointer(brick); + const uint8_t* materials = std::as_const(*volume.pool()).material(entry.payload()).data(); + for (uint32_t z = 0; z < voxel::k_brick_dim; ++z) { + uint64_t bits = occupancy[z]; + while (bits != 0) { + auto bit = static_cast(std::countr_zero(bits)); + bits &= bits - 1; + visit( + corner + glm::ivec3(static_cast(bit & 7), static_cast(bit >> 3), static_cast(z)), + materials[(z * 64) + bit] + ); + } + } +} + +template +auto splitByOwner( + const voxel::Volume& shape, const voxel::Volume& owner, glm::ivec3 origin, const std::vector& keys, + bool& pool_exhausted +) -> std::vector { + ZoneScopedN("voxel::SplitByOwner"); // NOLINT + + struct Extent { + glm::ivec3 min {std::numeric_limits::max()}; + glm::ivec3 max {std::numeric_limits::min()}; + bool any = false; + }; + + std::vector extents(keys.size()); + + // Every owner number in a brick + auto owners_in = [&](glm::ivec3 brick) { + std::bitset<256> seen; + voxel::BrickEntry entry = owner.entryAt(brick); + if (entry.tag() == voxel::BrickTag::uniform) { + seen.set(static_cast(entry.payload())); + } else if (entry.tag() != voxel::BrickTag::empty) { + const voxel::BrickOccupancy& occupancy = *owner.occupancyPointer(brick); + const uint8_t* materials = std::as_const(*owner.pool()).material(entry.payload()).data(); + for (uint32_t z = 0; z < voxel::k_brick_dim; ++z) { + uint64_t bits = occupancy[z]; + while (bits != 0) { + auto bit = static_cast(std::countr_zero(bits)); + bits &= bits - 1; + seen.set(materials[(z * 64) + bit]); + } + } + } + seen.reset(0); + return seen; + }; + + std::vector>> bricks; + for (uint32_t index = 0; index < owner.brickCount(); ++index) { + glm::ivec3 brick = owner.brickAtIndex(index); + if (owner.entryAt(brick).tag() == voxel::BrickTag::empty) { + continue; + } + std::bitset<256> seen = owners_in(brick); + for (size_t id = 1; id <= keys.size(); ++id) { + if (seen.test(id)) { + Extent& extent = extents[id - 1]; + extent.min = glm::min(extent.min, brick); + extent.max = glm::max(extent.max, brick); + extent.any = true; + } + } + bricks.emplace_back(brick, seen); + } + + std::vector parts; + std::vector part_of(keys.size(), -1); + for (size_t id = 1; id <= keys.size(); ++id) { + const Extent& extent = extents[id - 1]; + if (!extent.any) { + continue; + } + Part part; + part.key = keys[id - 1]; + part.origin = origin + (extent.min * static_cast(voxel::k_brick_dim)); + part.volume = std::make_unique(voxel::proceduralBrickPool(), glm::uvec3(extent.max - extent.min + 1)); + part_of[id - 1] = static_cast(parts.size()); + parts.push_back(std::move(part)); + } + + for (const auto& [brick, seen] : bricks) { + if (seen.count() == 1) { + // Whole brick moves + size_t id = 1; + while (!seen.test(id)) { + ++id; + } + if (id <= keys.size()) { + const Extent& extent = extents[id - 1]; + parts[static_cast(part_of[id - 1])].volume->copyBrickFrom(brick - extent.min, shape, brick); + } + continue; + } + visitSolid(owner, brick, [&](glm::ivec3 cell, uint8_t id) { + if (id == 0 || id > keys.size()) { + return; + } + const Extent& extent = extents[id - 1]; + voxel::Volume::VoxelWrite write = parts[static_cast(part_of[id - 1])].volume->setVoxel( + cell - (extent.min * static_cast(voxel::k_brick_dim)), shape.materialAt(cell) + ); + pool_exhausted = pool_exhausted || !write.changed; + }); + } + return parts; +} + +} + +namespace { + +constexpr auto k_dim = static_cast(voxel::k_brick_dim); + +[[nodiscard]] +auto intersects(const voxel::EditBounds& a, const voxel::EditBounds& b) noexcept -> bool { + return !a.empty() && !b.empty() && glm::all(glm::lessThanEqual(a.min, b.max)) && glm::all(glm::lessThanEqual(b.min, a.max)); +} + +[[nodiscard]] +auto partBricks(const VoxelPart& part) -> std::pair { + glm::ivec3 first = brickFloor(part.origin); + return {first, first + glm::ivec3(part.volume->brickDims()) - 1}; +} + +auto growPart(VoxelPart& part, const voxel::EditBounds& bounds) -> bool { + constexpr int32_t k_max_bricks_per_axis = 512; + constexpr int64_t k_max_bricks = int64_t {1} << 21; + + glm::ivec3 first = brickFloor(bounds.min); + glm::ivec3 dims = brickFloor(bounds.max) - first + 1; + if (glm::any(glm::greaterThan(dims, glm::ivec3(k_max_bricks_per_axis))) || + static_cast(dims.x) * dims.y * dims.z > k_max_bricks) { + return false; + } + + // Physics use the old volume until it builds the new one + if (part.volume != nullptr && part.body != physics::BodyID {}) { + part.retired.push_back(std::move(part.volume)); + } + part.volume = std::make_unique(voxel::runtimeBrickPool(), glm::uvec3(dims)); + part.origin = first * k_dim; + ++part.revision; + return true; +} + +[[nodiscard]] +auto slackAround(glm::ivec3 min, glm::ivec3 max, bool slack) -> glm::ivec3 { + return slack ? glm::max(glm::ivec3(2 * k_dim), (max - min + 1) / 4) : glm::ivec3(0); +} + +auto growKeeping(VoxelPart& part, const voxel::EditBounds& wanted, bool slack) -> bool { + voxel::EditBounds bounds = wanted; + if (part.volume != nullptr) { + const auto [first, last] = partBricks(part); + bounds = voxel::boundsUnion(bounds, {first * k_dim, ((last + 1) * k_dim) - 1}); + } + glm::ivec3 room = slackAround(bounds.min, bounds.max, slack); + VoxelPart grown; + if (!growPart(grown, {bounds.min - room, bounds.max + room}) && !growPart(grown, bounds)) { + return false; + } + + // Physics use the old volume until it builds the new one + if (part.volume != nullptr) { + glm::ivec3 shift = brickFloor(part.origin) - brickFloor(grown.origin); + for (uint32_t index = 0; index < part.volume->brickCount(); ++index) { + glm::ivec3 brick = part.volume->brickAtIndex(index); + if (part.volume->entryAt(brick).tag() != voxel::BrickTag::empty) { + grown.volume->copyBrickFrom(brick + shift, *part.volume, brick); + } + } + if (part.body != physics::BodyID {}) { + part.retired.push_back(std::move(part.volume)); + } + } + part.volume = std::move(grown.volume); + part.origin = grown.origin; + ++part.revision; + return true; +} + +void retirePart(VoxelPart& part, std::vector>& retired) { + if (part.body == physics::BodyID {}) { + return; + } + for (std::unique_ptr& volume : part.retired) { + retired.push_back(std::move(volume)); + } + retired.push_back(std::move(part.volume)); +} + +auto copyBricks(VoxelPart& part, const Part* source, glm::ivec3 first, glm::ivec3 last) -> bool { + glm::ivec3 part_first = brickFloor(part.origin); + glm::ivec3 source_first = source != nullptr ? brickFloor(source->origin) : glm::ivec3(0); + bool changed = false; + for (int32_t z = first.z; z <= last.z; ++z) { + for (int32_t y = first.y; y <= last.y; ++y) { + for (int32_t x = first.x; x <= last.x; ++x) { + glm::ivec3 shape_brick {x, y, z}; + glm::ivec3 brick = shape_brick - part_first; + glm::ivec3 from = shape_brick - source_first; + if (source != nullptr && source->volume->containsBrick(from)) { + changed = part.volume->copyBrickFrom(brick, *source->volume, from) || changed; + } else if (part.volume->entryAt(brick).tag() != voxel::BrickTag::empty) { + part.volume->setBrickUniform(brick, voxel::k_empty_palette_index); + changed = true; + } + } + } + } + return changed; +} + +} + +auto Stamp::bounds() const noexcept -> voxel::EditBounds { + return grid != nullptr ? voxel::placedBounds(grid->brickDims(), placement) : voxel::EditBounds {}; +} + +auto Stamp::sameAs(const Stamp& other) const noexcept -> bool { + return grid == other.grid && placement == other.placement && kind == other.kind && mode == other.mode && + match_id == other.match_id && key == other.key && remap == other.remap; +} + +void assignPartKeys(Request& request) { + std::vector seen; + const auto lump = [&](uint64_t key) -> uint64_t { + if (std::ranges::contains(seen, key)) { + return key; + } + if (seen.size() < k_max_part_keys) { + seen.push_back(key); + return key; + } + request.too_many_parts = true; + return seen.back(); + }; + + // order a compose claims them + if (request.base != nullptr) { + lump(0); + } + for (Stamp& stamp : request.stamps) { + if (stamp.kind == PieceKind::fill) { + stamp.key = lump(stamp.key); + } + } + if (request.preview.has_value() && request.preview->kind == PieceKind::fill) { + request.preview->key = lump(request.preview->key); + } +} + +auto compose(const Request& request) -> Result { + ZoneScopedN("voxel::ComposeProcedural"); // NOLINT + Result out; + out.region = request.region; + out.too_many_parts = request.too_many_parts; + bool full = !request.region.has_value(); + out.has_projections = full && request.projections; + + voxel::EditBounds bounds {}; + if (full) { + if (request.base != nullptr) { + bounds = {glm::ivec3(0), glm::ivec3(request.base->voxelDims()) - 1}; + } + for (const Stamp& stamp : request.stamps) { + if (stamp.kind == PieceKind::fill) { + bounds = voxel::boundsUnion(bounds, stamp.bounds()); + } + } + if (request.preview.has_value() && request.preview->kind == PieceKind::fill) { + bounds = voxel::boundsUnion(bounds, request.preview->bounds()); + } + } else { + bounds = *request.region; + } + if (bounds.empty()) { + return out; + } + + glm::ivec3 first = brickFloor(bounds.min); + glm::ivec3 last = brickFloor(bounds.max); + glm::ivec3 origin = first * k_dim; + voxel::EditBounds covered {origin, ((last + 1) * k_dim) - 1}; + voxel::Volume target(voxel::proceduralBrickPool(), glm::uvec3(last - first + 1)); + + voxel::Volume owner(voxel::proceduralBrickPool(), target.brickDims()); + std::vector owner_keys; + auto claim = [&](uint64_t key) -> uint8_t { + if (const auto found = std::ranges::find(owner_keys, key); found != owner_keys.end()) { + return static_cast((found - owner_keys.begin()) + 1); + } + if (owner_keys.size() >= k_max_part_keys) { + out.too_many_parts = true; + return static_cast(k_max_part_keys); + } + owner_keys.push_back(key); + return static_cast(owner_keys.size()); + }; + + auto claim_table = [](const voxel::PaletteRemapTable& remap, uint8_t id) { + voxel::PaletteRemapTable table {}; + for (uint32_t i = 1; i < voxel::k_palette_size; ++i) { + table[i] = remap[i] != voxel::k_empty_palette_index ? id : voxel::k_empty_palette_index; + } + return table; + }; + + auto claim_mode = [](voxel::WriteMode mode, uint8_t match_id) -> std::optional { + switch (mode) { + case voxel::WriteMode::replace: return voxel::WriteMode::replace; + case voxel::WriteMode::empty_only: return voxel::WriteMode::empty_only; + case voxel::WriteMode::match: + return match_id == voxel::k_empty_palette_index ? std::optional {voxel::WriteMode::empty_only} : std::nullopt; + case voxel::WriteMode::solid_only: return std::nullopt; + } + return std::nullopt; + }; + + voxel::EditResult result; + auto write = [&](const Stamp& stamp) { + voxel::LatticePlacement indexed = stamp.placement; + indexed.offset -= origin; + const voxel::Volume& grid = *stamp.grid; + switch (stamp.kind) { + case PieceKind::fill: { + result += voxel::stampVolume(target, grid, indexed, stamp.remap, stamp.mode, stamp.match_id); + uint8_t id = claim(stamp.key); + if (const std::optional mode = claim_mode(stamp.mode, stamp.match_id)) { + result += voxel::stampVolume(owner, grid, indexed, claim_table(stamp.remap, id), *mode, 0); + } + break; + } + case PieceKind::carve: + result += voxel::carveVolume(target, grid, indexed); + result += voxel::carveVolume(owner, grid, indexed); + break; + case PieceKind::paint: + result += voxel::stampVolume(target, grid, indexed, stamp.remap, voxel::WriteMode::solid_only, 0); + break; + } + }; + + // A region only needs the pieces reaching into it + auto reaches = [&](const Stamp& stamp) { return stamp.grid != nullptr && (full || intersects(stamp.bounds(), covered)); }; + + if (request.base != nullptr) { + voxel::LatticePlacement at_zero {.offset = -origin}; + result += voxel::stampVolume(target, *request.base, at_zero, voxel::identityRemap(), voxel::WriteMode::replace, 0); + uint8_t id = claim(0); + result += + voxel::stampVolume(owner, *request.base, at_zero, claim_table(voxel::identityRemap(), id), voxel::WriteMode::replace, 0); + } + for (const Stamp& stamp : request.stamps) { + if (reaches(stamp)) { + write(stamp); + } + } + + // changedRegion never asks for a region with buckets + if (full) { + for (const auto& [seed, id] : request.buckets) { + result += voxel::floodFill(target, seed - origin, id); + } + } + + if (request.preview.has_value() && reaches(*request.preview)) { + write(*request.preview); + } + + if (out.has_projections) { + projectShape(target, origin, request.palette, out.projections); + } + + bool split_exhausted = false; + out.parts = splitByOwner(target, owner, origin, owner_keys, split_exhausted); + out.pool_exhausted = result.pool_exhausted || split_exhausted; + return out; +} + +auto changedRegion(const Request& before, const Request& after) -> std::optional { + if (!before.buckets.empty() || !after.buckets.empty() || after.projections) { + return std::nullopt; + } + if (before.base_source != after.base_source || (before.base == nullptr) != (after.base == nullptr)) { + return std::nullopt; + } + + std::unordered_map old_by_id; + old_by_id.reserve(before.stamps.size()); + for (const Stamp& stamp : before.stamps) { + if (!old_by_id.emplace(stamp.id, &stamp).second) { + return std::nullopt; + } + } + + voxel::EditBounds changed {}; + std::unordered_map in_both; + std::vector kept_after; + in_both.reserve(after.stamps.size()); + for (const Stamp& stamp : after.stamps) { + auto found = old_by_id.find(stamp.id); + if (found == old_by_id.end()) { + changed = voxel::boundsUnion(changed, stamp.bounds()); + continue; + } + bool same = stamp.sameAs(*found->second); + if (!in_both.emplace(stamp.id, same).second) { + return std::nullopt; + } + if (same) { + kept_after.push_back(stamp.id); + } else { + changed = voxel::boundsUnion(changed, voxel::boundsUnion(found->second->bounds(), stamp.bounds())); + } + } + std::vector kept_before; + for (const Stamp& stamp : before.stamps) { + auto found = in_both.find(stamp.id); + if (found == in_both.end()) { + changed = voxel::boundsUnion(changed, stamp.bounds()); + } else if (found->second) { + kept_before.push_back(stamp.id); + } + } + if (kept_before != kept_after) { + return std::nullopt; + } + + bool same_preview = before.preview.has_value() == after.preview.has_value() && + (!after.preview.has_value() || after.preview->sameAs(*before.preview)); + if (!same_preview) { + if (before.preview.has_value()) { + changed = voxel::boundsUnion(changed, before.preview->bounds()); + } + if (after.preview.has_value()) { + changed = voxel::boundsUnion(changed, after.preview->bounds()); + } + } + if (changed.empty()) { + return voxel::EditBounds {}; + } + + glm::ivec3 first = brickFloor(changed.min); + glm::ivec3 last = brickFloor(changed.max); + voxel::EditBounds region {first * k_dim, ((last + 1) * k_dim) - 1}; + + // Rebuilding most of the shape costs the same as all of it + voxel::EditBounds whole = + after.base != nullptr ? voxel::EditBounds {glm::ivec3(0), glm::ivec3(after.base->voxelDims()) - 1} : voxel::EditBounds {}; + for (const Stamp& stamp : after.stamps) { + if (stamp.kind == PieceKind::fill) { + whole = voxel::boundsUnion(whole, stamp.bounds()); + } + } + auto bricks = [](const voxel::EditBounds& box) -> int64_t { + if (box.empty()) { + return 0; + } + glm::ivec3 dims = brickFloor(box.max) - brickFloor(box.min) + 1; + return static_cast(dims.x) * dims.y * dims.z; + }; + if (bricks(region) * 2 > bricks(whole)) { + return std::nullopt; + } + return region; +} + +auto applyFull(std::vector& parts, Result& result, bool slack, std::vector>& retired) + -> ApplyStats { + ApplyStats stats; + for (size_t i = parts.size(); i-- > 0;) { + VoxelPart& part = parts[i]; + if (std::ranges::any_of(result.parts, [&](const Part& incoming) { return incoming.key == part.key; })) { + continue; + } + retirePart(part, retired); + parts.erase(parts.begin() + static_cast(i)); + stats.parts_changed = true; + } + + for (Part& incoming : result.parts) { + auto found = std::ranges::find(parts, incoming.key, &VoxelPart::key); + if (found == parts.end()) { + parts.emplace_back(); + parts.back().key = incoming.key; + found = parts.end() - 1; + stats.parts_changed = true; + } + VoxelPart& part = *found; + + const voxel::Volume& source = *incoming.volume; + glm::ivec3 wanted_min = incoming.origin; + glm::ivec3 wanted_max = incoming.origin + glm::ivec3(source.voxelDims()) - 1; + bool fits = part.volume != nullptr && glm::all(glm::greaterThanEqual(wanted_min, part.origin)) && + glm::all(glm::lessThan(wanted_max, part.origin + glm::ivec3(part.volume->voxelDims()))); + if (!fits) { + // Growing makes a new volume + glm::ivec3 room = slackAround(wanted_min, wanted_max, slack); + ++stats.grown; + bool grown = growPart(part, {wanted_min - room, wanted_max + room}); + if (!grown) { + grown = growPart(part, {wanted_min, wanted_max}); + } + if (!grown && part.volume == nullptr) { + ++stats.left_out; + parts.erase(found); + continue; + } + if (!grown) { + ++stats.clipped; + } + } + + const auto [part_first, part_last] = partBricks(part); + if (copyBricks(part, &incoming, part_first, part_last)) { + ++part.revision; + part.split_pending = true; + ++stats.changed; + } + } + // bricks go back to the pool + result.parts.clear(); + return stats; +} + +auto applyRegion(std::vector& parts, Result& result, bool slack, std::vector>& retired) + -> ApplyStats { + ApplyStats stats; + if (!result.region.has_value() || result.region->empty()) { + result.parts.clear(); + return stats; + } + glm::ivec3 region_first = brickFloor(result.region->min); + glm::ivec3 region_last = brickFloor(result.region->max); + + auto incoming_of = [&](uint64_t key) -> const Part* { + const auto found = std::ranges::find(result.parts, key, &Part::key); + return found != result.parts.end() ? &*found : nullptr; + }; + + std::vector touched(parts.size(), false); + for (size_t i = 0; i < parts.size(); ++i) { + VoxelPart& part = parts[i]; + if (part.volume == nullptr) { + continue; + } + const Part* incoming = incoming_of(part.key); + auto [part_first, part_last] = partBricks(part); + bool overlaps = + glm::all(glm::lessThanEqual(part_first, region_last)) && glm::all(glm::lessThanEqual(region_first, part_last)); + if (!overlaps && incoming == nullptr) { + continue; + } + + if (incoming != nullptr) { + glm::ivec3 wanted_min = incoming->origin; + glm::ivec3 wanted_max = incoming->origin + glm::ivec3(incoming->volume->voxelDims()) - 1; + bool fits = glm::all(glm::greaterThanEqual(wanted_min, part.origin)) && + glm::all(glm::lessThan(wanted_max, part.origin + glm::ivec3(part.volume->voxelDims()))); + if (!fits) { + ++stats.grown; + if (!growKeeping(part, {wanted_min, wanted_max}, slack)) { + ++stats.clipped; + } + std::tie(part_first, part_last) = partBricks(part); + } + } + + glm::ivec3 first = glm::max(part_first, region_first); + glm::ivec3 last = glm::min(part_last, region_last); + if (glm::all(glm::lessThanEqual(first, last)) && copyBricks(part, incoming, first, last)) { + ++part.revision; + part.split_pending = true; + ++stats.changed; + touched[i] = true; + } + } + + for (Part& incoming : result.parts) { + if (std::ranges::contains(parts, incoming.key, &VoxelPart::key)) { + continue; + } + VoxelPart part; + part.key = incoming.key; + glm::ivec3 wanted_min = incoming.origin; + glm::ivec3 wanted_max = incoming.origin + glm::ivec3(incoming.volume->voxelDims()) - 1; + glm::ivec3 room = slackAround(wanted_min, wanted_max, slack); + ++stats.grown; + if (!growPart(part, {wanted_min - room, wanted_max + room}) && !growPart(part, {wanted_min, wanted_max})) { + ++stats.left_out; + continue; + } + auto [part_first, part_last] = partBricks(part); + copyBricks(part, &incoming, part_first, part_last); + part.split_pending = true; + ++stats.changed; + parts.push_back(std::move(part)); + touched.push_back(false); + stats.parts_changed = true; + } + + for (size_t i = touched.size(); i-- > 0;) { + if (!touched[i] || parts[i].volume == nullptr || parts[i].volume->solidVoxelCount() != 0) { + continue; + } + retirePart(parts[i], retired); + parts.erase(parts.begin() + static_cast(i)); + stats.parts_changed = true; + } + + result.parts.clear(); + return stats; +} + +} diff --git a/engine/src/toast/voxel/nodes/procedural_compose.hpp b/engine/src/toast/voxel/nodes/procedural_compose.hpp new file mode 100644 index 000000000..72a9cb314 --- /dev/null +++ b/engine/src/toast/voxel/nodes/procedural_compose.hpp @@ -0,0 +1,104 @@ +/** + * @file procedural_compose.hpp + * @author Xein + * @date 19 Nov 2026 + * @brief Builds only the modified parts of a ProceduralVoxel + */ + +#pragma once +#include "voxel_node.hpp" +#include "voxel_piece.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace toast::procedural { + +inline constexpr uint64_t k_preview_key = std::numeric_limits::max(); +inline constexpr size_t k_max_part_keys = 255; + +[[nodiscard]] +inline auto brickFloor(glm::ivec3 voxel) noexcept -> glm::ivec3 { + return {voxel.x >> 3, voxel.y >> 3, voxel.z >> 3}; +} + +struct Stamp { + uint64_t id = 0; + std::shared_ptr grid; + voxel::LatticePlacement placement; + voxel::PaletteRemapTable remap {}; + PieceKind kind = PieceKind::fill; + voxel::WriteMode mode = voxel::WriteMode::replace; + uint8_t match_id = 0; + uint64_t key = 0; + + /// Voxels the grid can write + [[nodiscard]] + TOAST_API auto bounds() const noexcept -> voxel::EditBounds; + + /// Writes exactly the same voxels as @p other + [[nodiscard]] + TOAST_API auto sameAs(const Stamp& other) const noexcept -> bool; +}; + +struct Request { + std::vector stamps; + std::optional preview; + std::vector> buckets; + std::shared_ptr base; + const void* base_source = nullptr; + bool projections = false; + voxel::Palette palette; + bool too_many_parts = false; + std::optional region; +}; + +struct Part { + uint64_t key = 0; + glm::ivec3 origin {0}; + std::unique_ptr volume; +}; + +struct Result { + std::vector parts; + std::optional region; + std::vector projections; + bool has_projections = false; + bool pool_exhausted = false; + bool too_many_parts = false; +}; + +TOAST_API void assignPartKeys(Request& request); + +[[nodiscard]] +TOAST_API auto compose(const Request& request) -> Result; + +[[nodiscard]] +TOAST_API auto changedRegion(const Request& before, const Request& after) -> std::optional; + +struct ApplyStats { + bool parts_changed = false; + uint32_t changed = 0; + uint32_t grown = 0; + uint32_t left_out = 0; + uint32_t clipped = 0; +}; + +/** Makes @p parts match a full result */ +TOAST_API auto + applyFull(std::vector& parts, Result& result, bool slack, std::vector>& retired) + -> ApplyStats; + +/** Makes the region of @p parts match and leaves the rest alone */ +TOAST_API auto + applyRegion(std::vector& parts, Result& result, bool slack, std::vector>& retired) + -> ApplyStats; + +} diff --git a/engine/src/toast/voxel/nodes/procedural_voxel.cpp b/engine/src/toast/voxel/nodes/procedural_voxel.cpp index 8ff102cd6..42b6fb400 100644 --- a/engine/src/toast/voxel/nodes/procedural_voxel.cpp +++ b/engine/src/toast/voxel/nodes/procedural_voxel.cpp @@ -1,8 +1,9 @@ #include "procedural_voxel.hpp" +#include "procedural_compose.hpp" +#include "toast/voxel/nodes/voxel_piece.hpp" #include "voxel_node_utils.hpp" -#include #include #include #include @@ -17,6 +18,7 @@ namespace toast { namespace { using _detail::assetOfType; +using procedural::brickFloor; // moved to hash.hpp 16 Oct // void hashCombine(uint64_t& seed, uint64_t value) noexcept { @@ -167,368 +169,17 @@ auto insideProceduralVoxel(Node& node) -> bool { // ProceduralVoxel struct ProceduralVoxel::ComposeInput { - struct Preview { - VoxelPiece::GridRef grid; - uint8_t kind = 0; - voxel::EditBounds box; - voxel::WriteMode mode = voxel::WriteMode::replace; ///< How a fill preview lands - }; - std::vector landings; - std::vector> buckets; - std::unique_ptr base; ///< The model the shape starts from - std::optional preview; - std::optional highlight; ///< The landing of the selected piece - bool projections = false; - voxel::Palette palette; + std::shared_ptr request; + std::vector> outline_rids; }; struct ProceduralVoxel::ComposeOutput { - struct Part { - uint64_t key = 0; - glm::ivec3 origin {0}; - std::unique_ptr volume; - std::unique_ptr highlight; - }; - - std::vector parts; - std::vector projections; - bool has_projections = false; - bool pool_exhausted = false; - bool too_many_parts = false; + procedural::Result result; + std::shared_ptr request; + std::vector> outline_rids; }; -namespace { - -struct ProjectionAxes { - int h; - int v; - int depth; - int toward; -}; - -constexpr std::array k_projection_views { - ProjectionAxes {0, 2, 1, 1}, - ProjectionAxes {1, 2, 0, -1}, - ProjectionAxes {0, 1, 2, -1} -}; - -void projectShape( - const voxel::Volume& shape, glm::ivec3 origin, const voxel::Palette& palette, std::vector& out -) { - ZoneScoped; - const glm::ivec3 dims = glm::ivec3(shape.voxelDims()); - - for (const ProjectionAxes& view : k_projection_views) { - event::VoxelProjectionData projection; - projection.min_h = origin[view.h]; - projection.min_v = origin[view.v]; - projection.width = static_cast(dims[view.h]); - projection.height = static_cast(dims[view.v]); - projection.colors.assign(static_cast(projection.width) * projection.height * 4, 0); - projection.depths.assign(static_cast(projection.width) * projection.height, std::numeric_limits::max()); - projection.edges_h.assign(static_cast(projection.width + 1) * projection.height * 4, 0); - projection.edges_v.assign(static_cast(projection.width) * (projection.height + 1) * 4, 0); - out.push_back(std::move(projection)); - } - - // Outlines - for (uint32_t index = 0; index < shape.brickCount(); ++index) { - const glm::ivec3 brick = shape.brickAtIndex(index); - const voxel::BrickEntry entry = shape.entryAt(brick); - if (entry.tag() == voxel::BrickTag::empty) { - continue; - } - const voxel::BrickOccupancy& occupancy = *shape.occupancyPointer(brick); - const voxel::BrickNeighbourhood around = shape.neighbourhoodOf(brick); - // exposed[axis][0] has a voxel when the one before it on axis is empty - const std::array, 3> exposed { - { - {occupancy & ~voxel::neighboursNegX(occupancy, around.neg_x), - occupancy & ~voxel::neighboursPosX(occupancy, around.pos_x)}, - {occupancy & ~voxel::neighboursNegY(occupancy, around.neg_y), - occupancy & ~voxel::neighboursPosY(occupancy, around.pos_y)}, - {occupancy & ~voxel::neighboursNegZ(occupancy, around.neg_z), - occupancy & ~voxel::neighboursPosZ(occupancy, around.pos_z)}, - } - }; - const bool uniform = entry.tag() == voxel::BrickTag::uniform; - const uint8_t* materials = uniform ? nullptr : std::as_const(*shape.pool()).material(entry.payload()).data(); - const glm::ivec3 corner = brick * static_cast(voxel::k_brick_dim); - - for (size_t v = 0; v < k_projection_views.size(); ++v) { - event::VoxelProjectionData& projection = out[v]; - const ProjectionAxes& view = k_projection_views[v]; - const auto& across = exposed[static_cast(view.h)]; - const auto& up = exposed[static_cast(view.v)]; - for (uint32_t z = 0; z < voxel::k_brick_dim; ++z) { - uint64_t bits = across[0][z] | across[1][z] | up[0][z] | up[1][z]; - while (bits != 0) { - const auto bit = static_cast(std::countr_zero(bits)); - const uint64_t mask = uint64_t {1} << bit; - bits &= bits - 1; - - const uint32_t local = (z * 64) + bit; - const uint8_t id = uniform ? static_cast(entry.payload()) : materials[local]; - const voxel::PaletteEntry& color = palette.entries[id]; - const glm::ivec3 cell = - corner + glm::ivec3(static_cast(bit & 7), static_cast(bit >> 3), static_cast(z)); - const auto h = static_cast(cell[view.h]); - const auto row = static_cast(cell[view.v]); - - // See through - const auto mark = [&](std::vector& edges, size_t at) { - edges[(at * 4) + 0] = color.albedo_r; - edges[(at * 4) + 1] = color.albedo_g; - edges[(at * 4) + 2] = color.albedo_b; - edges[(at * 4) + 3] = 255; - }; - if ((across[0][z] & mask) != 0) { - mark(projection.edges_h, h + (row * (projection.width + 1))); - } - if ((across[1][z] & mask) != 0) { - mark(projection.edges_h, h + 1 + (row * (projection.width + 1))); - } - if ((up[0][z] & mask) != 0) { - mark(projection.edges_v, h + (row * projection.width)); - } - if ((up[1][z] & mask) != 0) { - mark(projection.edges_v, h + ((row + 1) * projection.width)); - } - } - } - } - } - - // See through fill - constexpr float k_layer_alpha = 0.1f; - constexpr int32_t k_dim = static_cast(voxel::k_brick_dim); - for (size_t v = 0; v < k_projection_views.size(); ++v) { - event::VoxelProjectionData& projection = out[v]; - const ProjectionAxes& view = k_projection_views[v]; - const int length = dims[view.depth]; - for (uint32_t row = 0; row < projection.height; ++row) { - for (uint32_t h = 0; h < projection.width; ++h) { - glm::vec3 color(0.0f); - float alpha = 0.0f; - uint8_t previous = voxel::k_empty_palette_index; - int nearest = -1; - glm::ivec3 cell; - cell[view.h] = static_cast(h); - cell[view.v] = static_cast(row); - const auto layer = [&](uint8_t id) { - const voxel::PaletteEntry& entry = palette.entries[id]; - const glm::vec3 tint = glm::vec3(entry.albedo_r, entry.albedo_g, entry.albedo_b) / 255.0f; - color = tint * k_layer_alpha + color * (1.0f - k_layer_alpha); - alpha = k_layer_alpha + (alpha * (1.0f - k_layer_alpha)); - }; - int step = 0; - while (step < length) { - cell[view.depth] = view.toward > 0 ? length - 1 - step : step; - const voxel::BrickEntry entry = shape.entryAt({cell.x >> 3, cell.y >> 3, cell.z >> 3}); - // Empty and uniform bricks are one run, the march jumps to the next brick - const int along = cell[view.depth] & (k_dim - 1); - const int rest = view.toward > 0 ? along + 1 : k_dim - along; - if (entry.tag() == voxel::BrickTag::empty) { - step += rest; - previous = voxel::k_empty_palette_index; - continue; - } - if (entry.tag() == voxel::BrickTag::uniform) { - const auto id = static_cast(entry.payload()); - if (id != previous) { - layer(id); - } - previous = id; - nearest = view.toward > 0 ? cell[view.depth] - (rest - 1) : cell[view.depth] + (rest - 1); - step += rest; - continue; - } - const uint8_t id = shape.materialAt(cell); - if (id != voxel::k_empty_palette_index) { - if (id != previous) { - layer(id); - } - nearest = cell[view.depth]; - } - previous = id; - ++step; - } - if (alpha <= 0.0f) { - continue; - } - // color is premultiplied - const size_t slot = static_cast(h) + (static_cast(row) * projection.width); - for (int c = 0; c < 3; ++c) { - projection.colors[(slot * 4) + c] = - static_cast(std::lround(glm::clamp(color[c] / alpha, 0.0f, 1.0f) * 255.0f)); - } - projection.colors[(slot * 4) + 3] = static_cast(std::lround(alpha * 255.0f)); - projection.depths[slot] = static_cast(view.toward * (nearest + origin[view.depth])); - } - } - } -} - -[[nodiscard]] -auto brickFloor(glm::ivec3 voxel) noexcept -> glm::ivec3 { - return {voxel.x >> 3, voxel.y >> 3, voxel.z >> 3}; -} - -constexpr uint64_t k_preview_key = ~uint64_t {0}; - -template -void visitSolid(const voxel::Volume& volume, glm::ivec3 brick, Visit&& visit) { - const voxel::BrickEntry entry = volume.entryAt(brick); - if (entry.tag() == voxel::BrickTag::empty) { - return; - } - const glm::ivec3 corner = brick * static_cast(voxel::k_brick_dim); - if (entry.tag() == voxel::BrickTag::uniform) { - const auto id = static_cast(entry.payload()); - for (int32_t z = 0; std::cmp_less(z, voxel::k_brick_dim); ++z) { - for (int32_t y = 0; std::cmp_less(y, voxel::k_brick_dim); ++y) { - for (int32_t x = 0; std::cmp_less(x, voxel::k_brick_dim); ++x) { - visit(corner + glm::ivec3(x, y, z), id); - } - } - } - return; - } - const voxel::BrickOccupancy& occupancy = *volume.occupancyPointer(brick); - const uint8_t* materials = std::as_const(*volume.pool()).material(entry.payload()).data(); - for (uint32_t z = 0; z < voxel::k_brick_dim; ++z) { - uint64_t bits = occupancy[z]; - while (bits != 0) { - const auto bit = static_cast(std::countr_zero(bits)); - bits &= bits - 1; - visit( - corner + glm::ivec3(static_cast(bit & 7), static_cast(bit >> 3), static_cast(z)), - materials[(z * 64) + bit] - ); - } - } -} - -/** - * Splits a built shape into one volume per owner - */ -template -auto splitByOwner( - const voxel::Volume& shape, const voxel::Volume& owner, const voxel::Volume* highlight, glm::ivec3 origin, - const std::vector& keys, bool& pool_exhausted -) -> std::vector { - ZoneScopedN("voxel::SplitByOwner"); // NOLINT - - struct Extent { - glm::ivec3 min {std::numeric_limits::max()}; - glm::ivec3 max {std::numeric_limits::min()}; - bool any = false; - }; - - std::vector extents(keys.size()); - - // Every owner number in a brick - const auto owners_in = [&](glm::ivec3 brick) { - std::bitset<256> seen; - const voxel::BrickEntry entry = owner.entryAt(brick); - if (entry.tag() == voxel::BrickTag::uniform) { - seen.set(static_cast(entry.payload())); - } else if (entry.tag() != voxel::BrickTag::empty) { - const voxel::BrickOccupancy& occupancy = *owner.occupancyPointer(brick); - const uint8_t* materials = std::as_const(*owner.pool()).material(entry.payload()).data(); - for (uint32_t z = 0; z < voxel::k_brick_dim; ++z) { - uint64_t bits = occupancy[z]; - while (bits != 0) { - const auto bit = static_cast(std::countr_zero(bits)); - bits &= bits - 1; - seen.set(materials[(z * 64) + bit]); - } - } - } - seen.reset(0); - return seen; - }; - - std::vector>> bricks; - for (uint32_t index = 0; index < owner.brickCount(); ++index) { - const glm::ivec3 brick = owner.brickAtIndex(index); - if (owner.entryAt(brick).tag() == voxel::BrickTag::empty) { - continue; - } - const std::bitset<256> seen = owners_in(brick); - for (size_t id = 1; id <= keys.size(); ++id) { - if (seen.test(id)) { - Extent& extent = extents[id - 1]; - extent.min = glm::min(extent.min, brick); - extent.max = glm::max(extent.max, brick); - extent.any = true; - } - } - bricks.emplace_back(brick, seen); - } - - std::vector parts; - std::vector part_of(keys.size(), -1); - for (size_t id = 1; id <= keys.size(); ++id) { - const Extent& extent = extents[id - 1]; - if (!extent.any) { - continue; - } - Part part; - part.key = keys[id - 1]; - part.origin = origin + (extent.min * static_cast(voxel::k_brick_dim)); - part.volume = std::make_unique(voxel::proceduralBrickPool(), glm::uvec3(extent.max - extent.min + 1)); - part_of[id - 1] = static_cast(parts.size()); - parts.push_back(std::move(part)); - } - - for (const auto& [brick, seen] : bricks) { - if (seen.count() == 1) { - // Whole brick moves - size_t id = 1; - while (!seen.test(id)) { - ++id; - } - if (id <= keys.size()) { - const Extent& extent = extents[id - 1]; - parts[static_cast(part_of[id - 1])].volume->copyBrickFrom(brick - extent.min, shape, brick); - } - continue; - } - visitSolid(owner, brick, [&](glm::ivec3 cell, uint8_t id) { - if (id == 0 || id > keys.size()) { - return; - } - const Extent& extent = extents[id - 1]; - const voxel::Volume::VoxelWrite write = parts[static_cast(part_of[id - 1])].volume->setVoxel( - cell - (extent.min * static_cast(voxel::k_brick_dim)), shape.materialAt(cell) - ); - pool_exhausted = pool_exhausted || !write.changed; - }); - } - - if (highlight != nullptr) { - for (uint32_t index = 0; index < highlight->brickCount(); ++index) { - visitSolid(*highlight, highlight->brickAtIndex(index), [&](glm::ivec3 cell, uint8_t tint) { - const uint8_t id = owner.materialAt(cell); - if (id == 0 || id > keys.size() || part_of[id - 1] < 0) { - return; - } - Part& part = parts[static_cast(part_of[id - 1])]; - if (part.highlight == nullptr) { - part.highlight = std::make_unique(voxel::proceduralBrickPool(), part.volume->brickDims()); - } - const Extent& extent = extents[id - 1]; - part.highlight->setVoxel(cell - (extent.min * static_cast(voxel::k_brick_dim)), tint); - }); - } - } - return parts; -} - -} - void ProceduralVoxel::rebuild() { if (buildsAsync()) { m_compose_wanted = true; @@ -748,9 +399,12 @@ void ProceduralVoxel::buildShape() { std::vector pieces; collect(*this, glm::mat4(1.0f), pieces); const std::shared_ptr input = makeComposeInput(pieces, true); + finishComposeInput(*input); m_pending_layout = layoutOf(input->landings); - const std::shared_ptr output = compose(*input); - applyComposed(*output); + ComposeOutput output { + .result = procedural::compose(*input->request), .request = input->request, .outline_rids = input->outline_rids + }; + applyComposed(output); // In game the shape is only built once and destruction owns it after that if (!m_keep_grids) { @@ -783,12 +437,13 @@ void ProceduralVoxel::tickAsyncBuild() { if (const uint64_t key = keyOf(pieces); key != m_shape_key || m_rebuild_requested) { m_shape_key = key; + m_compose_full = m_compose_full || m_rebuild_requested; m_rebuild_requested = false; m_compose_wanted = true; } const bool projections_missing = - overlays.projections && (m_last_compose == nullptr || !m_last_compose->has_projections) && !m_pending_projections; - if (projections_missing || overlays.selected != m_highlight_for) { + overlays.projections && (m_last_compose == nullptr || !m_last_compose->result.has_projections) && !m_pending_projections; + if (projections_missing) { m_compose_wanted = true; } @@ -805,26 +460,119 @@ void ProceduralVoxel::tickAsyncBuild() { if (m_compose_wanted && !m_compose_job.valid()) { launchCompose(pieces); } + + refreshOutlineGhosts(); +} + +void ProceduralVoxel::refreshOutlineGhosts() { + struct Wanted { + uint64_t rid = 0; + VoxelPiece::GridRef grid; + voxel::LatticePlacement placement; + }; + + // The whole shape already outlines when the root itself is selected + std::vector wanted; + const renderer::VulkanRenderer* renderer = renderer::VulkanRenderer::instance; + if (renderer != nullptr && !renderer->isNodeOutlined(rid())) { + for (const PieceLayout& layout : m_layout) { + auto* piece = layout.node.exists() ? reflect_cast(&const_cast(*layout.node)) : nullptr; + if (piece == nullptr || !renderer->isNodeOutlined(piece->rid())) { + continue; + } + const bool owns = std::ranges::any_of(m_parts, [&](const VoxelPart& part) { + return std::ranges::contains(part.outline_rids, piece->rid()); + }); + if (owns) { + continue; + } + if (VoxelPiece::GridRef grid = piece->readyGrid(); grid != nullptr && grid->volume != nullptr) { + wanted.push_back({.rid = piece->rid(), .grid = std::move(grid), .placement = layout.placement}); + } + } + } + + const auto matches = [](const VoxelOutlineGhost& ghost, const Wanted& want) { + return ghost.piece_rid == want.rid && ghost.source == want.grid.get() && ghost.source_offset == want.placement.offset; + }; + if (wanted.size() == m_outline_ghosts.size() && std::ranges::equal(m_outline_ghosts, wanted, matches)) { + return; + } + + constexpr auto k_dim = static_cast(voxel::k_brick_dim); + std::vector ghosts; + std::scoped_lock lock(voxel::runtimePoolMutex()); + for (Wanted& want : wanted) { + if (auto kept = std::ranges::find_if(m_outline_ghosts, [&](const VoxelOutlineGhost& ghost) { return matches(ghost, want); }); + kept != m_outline_ghosts.end()) { + ghosts.push_back(std::move(*kept)); + continue; + } + const voxel::Volume& grid = *want.grid->volume; + const voxel::EditBounds placed = voxel::placedBounds(grid.brickDims(), want.placement); + const glm::ivec3 first = brickFloor(placed.min); + const glm::ivec3 last = brickFloor(placed.max); + + VoxelOutlineGhost ghost; + ghost.piece_rid = want.rid; + ghost.source = want.grid.get(); + ghost.source_offset = want.placement.offset; + ghost.generation = ++m_ghost_generation; + ghost.origin = first * k_dim; + ghost.volume = std::make_unique(voxel::runtimeBrickPool(), glm::uvec3(last - first + 1)); + voxel::LatticePlacement indexed = want.placement; + indexed.offset -= ghost.origin; + voxel::stampVolume(*ghost.volume, grid, indexed, voxel::identityRemap(), voxel::WriteMode::replace, 0); + ghosts.push_back(std::move(ghost)); + } + // The old copies free their bricks here while the renderer cannot be reading them + m_outline_ghosts = std::move(ghosts); } auto ProceduralVoxel::makeComposeInput(const std::vector& pieces, bool wait) -> std::shared_ptr { auto input = std::make_shared(); input->landings = land(pieces, wait); + input->request = std::make_shared(); + procedural::Request& request = *input->request; + + request.stamps.reserve(input->landings.size()); + for (const Landing& landing : input->landings) { + request.stamps.push_back({ + .id = landing.piece->rid(), + .grid = std::shared_ptr(landing.grid, landing.grid->volume.get()), + .placement = landing.placement, + .remap = landing.remap, + .kind = landing.kind, + .mode = landing.mode, + .match_id = landing.match_id, + .key = landing.key, + }); + } std::vector buckets; collectBuckets(*this, glm::mat4(1.0f), buckets); for (const BucketFill& fill : buckets) { - input->buckets.emplace_back(fill.seed, fill.bucket->colorId()); + request.buckets.emplace_back(fill.seed, fill.bucket->colorId()); } if (const assets::VoxelModel* model = resolvedModel()) { if (std::optional instance = model->instantiate(voxel::proceduralBrickPool())) { - input->base = std::make_unique(std::move(*instance)); + request.base = std::make_shared(std::move(*instance)); + request.base_source = model; } } return input; } +void ProceduralVoxel::finishComposeInput(ComposeInput& input) { + procedural::assignPartKeys(*input.request); + for (const procedural::Stamp& stamp : input.request->stamps) { + if (stamp.kind == PieceKind::fill) { + input.outline_rids.emplace_back(stamp.key, stamp.id); + } + } +} + void ProceduralVoxel::launchCompose(const std::vector& pieces) { ZoneScopedN("voxel::LaunchCompose"); // NOLINT m_compose_wanted = false; @@ -833,224 +581,62 @@ void ProceduralVoxel::launchCompose(const std::vector& pieces) { std::shared_ptr input = makeComposeInput(pieces, false); m_pending_layout = layoutOf(input->landings); - // The selected piece gets tinted where it still shows - m_highlight_for = overlays.selected; - for (size_t i = 0; i < input->landings.size(); ++i) { - const Landing& landing = input->landings[i]; - if (landing.kind != PieceKind::carve && landing.piece->uid() == m_highlight_for) { - input->highlight = i; - } - } - + procedural::Request& request = *input->request; // The preview draws with the script the new volume will get if (VoxelPiece* tool = toolPiece()) { if (VoxelPiece::GridRef grid = tool->readyGrid()) { - input->preview = ComposeInput::Preview { - .grid = std::move(grid), - .kind = overlays.tool_box_kind, - .box = {glm::min(overlays.tool_box_min, overlays.tool_box_max), glm::max(overlays.tool_box_min, overlays.tool_box_max)}, - .mode = tool->writeMode(), - }; - } - } - - input->projections = overlays.projections; - input->palette = resolvedPalette() != nullptr ? *resolvedPalette() : voxel::defaultPalette(); - m_pending_projections = input->projections; - - m_compose_job = ThreadPool::push([input] { return compose(*input); }); -} - -auto ProceduralVoxel::compose(const ComposeInput& input) -> std::shared_ptr { - ZoneScopedN("voxel::ComposeProcedural"); // NOLINT - auto out = std::make_shared(); - out->has_projections = input.projections; + const glm::ivec3 box_min = glm::min(overlays.tool_box_min, overlays.tool_box_max); - voxel::EditBounds grows {}; - if (input.base != nullptr) { - grows = {glm::ivec3(0), glm::ivec3(input.base->voxelDims()) - 1}; - } - for (const Landing& landing : input.landings) { - if (landing.kind == PieceKind::fill) { - grows = voxel::boundsUnion(grows, voxel::placedBounds(landing.grid->volume->brickDims(), landing.placement)); - } - } - // Fill grows the shape like a real volume would - if (input.preview.has_value() && input.preview->kind == 0) { - grows = voxel::boundsUnion(grows, input.preview->box); - } - if (grows.empty()) { - return out; - } - - const glm::ivec3 first = brickFloor(grows.min); - const glm::ivec3 last = brickFloor(grows.max); - const glm::ivec3 origin = first * static_cast(voxel::k_brick_dim); - voxel::Volume target(voxel::proceduralBrickPool(), glm::uvec3(last - first + 1)); - - // Which piece every voxel belongs to - voxel::Volume owner(voxel::proceduralBrickPool(), target.brickDims()); - std::vector owner_keys; - const auto claim = [&](uint64_t key) -> uint8_t { - if (const auto found = std::ranges::find(owner_keys, key); found != owner_keys.end()) { - return static_cast((found - owner_keys.begin()) + 1); - } - if (owner_keys.size() >= 255) { - out->too_many_parts = true; - return 255; - } - owner_keys.push_back(key); - return static_cast(owner_keys.size()); - }; - // Where the piece draws - const auto claim_table = [](const voxel::PaletteRemapTable& remap, uint8_t id) { - voxel::PaletteRemapTable table {}; - for (uint32_t i = 1; i < voxel::k_palette_size; ++i) { - table[i] = remap[i] != voxel::k_empty_palette_index ? id : voxel::k_empty_palette_index; - } - return table; - }; - // Painting only recolors so its not a volume - const auto claim_mode = [](voxel::WriteMode mode, uint8_t match_id) -> std::optional { - switch (mode) { - case voxel::WriteMode::replace: return voxel::WriteMode::replace; - case voxel::WriteMode::empty_only: return voxel::WriteMode::empty_only; - case voxel::WriteMode::match: - return match_id == voxel::k_empty_palette_index ? std::optional {voxel::WriteMode::empty_only} : std::nullopt; - case voxel::WriteMode::solid_only: return std::nullopt; - } - return std::nullopt; - }; - - voxel::EditResult result; - if (input.base != nullptr) { - const voxel::LatticePlacement at_zero {.offset = -origin}; - result += voxel::stampVolume(target, *input.base, at_zero, voxel::identityRemap(), voxel::WriteMode::replace, 0); - const uint8_t id = claim(0); - result += - voxel::stampVolume(owner, *input.base, at_zero, claim_table(voxel::identityRemap(), id), voxel::WriteMode::replace, 0); - } - for (const Landing& landing : input.landings) { - result += apply(target, landing, origin); - - voxel::LatticePlacement indexed = landing.placement; - indexed.offset -= origin; - const voxel::Volume& grid = *landing.grid->volume; - switch (landing.kind) { - case PieceKind::fill: { - const uint8_t id = claim(landing.key); - if (const std::optional mode = claim_mode(landing.mode, landing.match_id)) { - result += voxel::stampVolume(owner, grid, indexed, claim_table(landing.remap, id), *mode, 0); - } - break; + PieceKind kind = PieceKind::paint; + if (overlays.tool_box_kind == 0) { + kind = PieceKind::fill; + } else if (overlays.tool_box_kind == 1) { + kind = PieceKind::carve; } - case PieceKind::carve: result += voxel::carveVolume(owner, grid, indexed); break; - case PieceKind::paint: break; - } - } - for (const auto& [seed, id] : input.buckets) { - result += voxel::floodFill(target, seed - origin, id); - } - - if (input.preview.has_value()) { - const voxel::Volume& grid = *input.preview->grid->volume; - const voxel::LatticePlacement placement {.offset = input.preview->box.min - origin}; - switch (input.preview->kind) { - case 0: { - result += voxel::stampVolume(target, grid, placement, voxel::identityRemap(), input.preview->mode, 0); - const uint8_t id = claim(k_preview_key); - if (const std::optional mode = claim_mode(input.preview->mode, 0)) { - result += voxel::stampVolume(owner, grid, placement, claim_table(voxel::identityRemap(), id), *mode, 0); - } - break; - } - case 1: - result += voxel::carveVolume(target, grid, placement); - result += voxel::carveVolume(owner, grid, placement); - break; - default: - result += voxel::stampVolume(target, grid, placement, voxel::identityRemap(), voxel::WriteMode::solid_only, 0); - break; + request.preview = procedural::Stamp { + .id = procedural::k_preview_key, + .grid = std::shared_ptr(grid, grid->volume.get()), + .placement = {.offset = box_min}, + .remap = voxel::identityRemap(), + .kind = kind, + .mode = kind == PieceKind::fill ? tool->writeMode() : voxel::WriteMode::solid_only, + .key = procedural::k_preview_key, + }; } } - std::unique_ptr highlight; - if (input.highlight.has_value()) { - ZoneScopedN("voxel::ProceduralHighlight"); // NOLINT - const Landing& selected = input.landings[*input.highlight]; - highlight = std::make_unique(voxel::proceduralBrickPool(), target.brickDims()); - voxel::LatticePlacement indexed = selected.placement; - indexed.offset -= origin; - voxel::stampVolume(*highlight, *selected.grid->volume, indexed, voxel::identityRemap(), voxel::WriteMode::replace, 0); - - // Only where the finished shape still has voxels - for (uint32_t index = 0; index < highlight->brickCount(); ++index) { - const glm::ivec3 brick = highlight->brickAtIndex(index); - const voxel::BrickOccupancy* mine = highlight->occupancyPointer(brick); - if (mine == nullptr) { - continue; - } - const voxel::BrickOccupancy* shown = target.occupancyPointer(brick); - if (shown == nullptr) { - highlight->setBrickUniform(brick, voxel::k_empty_palette_index); - continue; - } - const voxel::BrickOccupancy hidden = *mine & ~*shown; - if (voxel::isEmpty(hidden)) { - continue; - } - const std::optional write = highlight->beginBrickWrite(brick); - if (!write.has_value()) { - continue; - } - for (uint32_t z = 0; z < voxel::k_brick_dim; ++z) { - uint64_t bits = hidden[z]; - while (bits != 0) { - const auto bit = static_cast(std::countr_zero(bits)); - write->material[(z * 64) + bit] = voxel::k_empty_palette_index; - bits &= bits - 1; - } - (*write->occupancy)[z] &= ~hidden[z]; + request.projections = overlays.projections; + request.palette = resolvedPalette() != nullptr ? *resolvedPalette() : voxel::defaultPalette(); + finishComposeInput(*input); + + if (m_composed != nullptr && !m_compose_full && m_composed_parts_revision == m_parts_revision) { + if (const std::optional region = procedural::changedRegion(*m_composed, request)) { + if (region->empty()) { + m_composed = input->request; + m_layout = std::move(m_pending_layout); + m_pending_layout.clear(); + return; } - highlight->finishBrickWrite(brick, true); + request.region = region; } } + m_compose_full = false; + m_pending_projections = request.projections && !request.region.has_value(); - if (input.projections) { - projectShape(target, origin, input.palette, out->projections); - } - - bool split_exhausted = false; - out->parts = splitByOwner(target, owner, highlight.get(), origin, owner_keys, split_exhausted); - out->pool_exhausted = result.pool_exhausted || split_exhausted; - return out; -} - -auto ProceduralVoxel::growPart(VoxelPart& part, const voxel::EditBounds& bounds) -> bool { - constexpr int32_t k_max_bricks_per_axis = 512; - constexpr int64_t k_max_bricks = int64_t {1} << 21; - - const glm::ivec3 first = brickFloor(bounds.min); - const glm::ivec3 dims = brickFloor(bounds.max) - first + 1; - if (glm::any(glm::greaterThan(dims, glm::ivec3(k_max_bricks_per_axis))) || - static_cast(dims.x) * dims.y * dims.z > k_max_bricks) { - return false; - } - - // Physics keeps reading the old volume until it builds the new one - if (part.volume != nullptr && part.body != physics::BodyID {}) { - part.retired.push_back(std::move(part.volume)); - } - part.volume = std::make_unique(voxel::runtimeBrickPool(), glm::uvec3(dims)); - part.origin = first * static_cast(voxel::k_brick_dim); - ++part.revision; - return true; + m_compose_job = ThreadPool::push([request = input->request, outline_rids = input->outline_rids] { + auto out = std::make_shared(); + out->result = procedural::compose(*request); + out->request = request; + out->outline_rids = outline_rids; + return out; + }); } void ProceduralVoxel::applyComposed(ComposeOutput& output) { ZoneScopedN("voxel::ApplyProcedural"); // NOLINT - if (output.pool_exhausted) { + procedural::Result& result = output.result; + if (result.pool_exhausted) { TOAST_WARN( "Voxel", "'{}' is missing voxels: the procedural brick pool is out of its {} bricks", @@ -1058,127 +644,44 @@ void ProceduralVoxel::applyComposed(ComposeOutput& output) { voxel::k_procedural_brick_capacity ); } - if (output.too_many_parts) { + if (result.too_many_parts && !result.region.has_value()) { TOAST_WARN("Voxel", "'{}' has more than 255 solid pieces, the last ones share one body", name()); } - renderer::VulkanRenderer* renderer = renderer::VulkanRenderer::instance; - constexpr auto k_dim = static_cast(voxel::k_brick_dim); - bool parts_changed = false; + procedural::ApplyStats stats; { std::scoped_lock lock(voxel::runtimePoolMutex()); - - for (size_t i = m_parts.size(); i-- > 0;) { - VoxelPart& part = m_parts[i]; - if (std::ranges::any_of(output.parts, [&](const ComposeOutput::Part& incoming) { return incoming.key == part.key; })) { - continue; - } - if (renderer != nullptr) { - renderer->setVoxelHighlight(this, nullptr, part.key); - } - - if (part.body != physics::BodyID {}) { - for (std::unique_ptr& retired : part.retired) { - m_retired_volumes.push_back(std::move(retired)); - } - m_retired_volumes.push_back(std::move(part.volume)); - } - m_parts.erase(m_parts.begin() + static_cast(i)); - parts_changed = true; - } - - for (ComposeOutput::Part& incoming : output.parts) { - auto found = std::ranges::find(m_parts, incoming.key, &VoxelPart::key); - if (found == m_parts.end()) { - m_parts.emplace_back(); - m_parts.back().key = incoming.key; - found = m_parts.end() - 1; - parts_changed = true; - } - VoxelPart& part = *found; - - const voxel::Volume& source = *incoming.volume; - const glm::ivec3 wanted_min = incoming.origin; - const glm::ivec3 wanted_max = incoming.origin + glm::ivec3(source.voxelDims()) - 1; - const bool fits = part.volume != nullptr && glm::all(glm::greaterThanEqual(wanted_min, part.origin)) && - glm::all(glm::lessThan(wanted_max, part.origin + glm::ivec3(part.volume->voxelDims()))); - if (!fits) { - // Growing makes a new volume the renderer uploads whole - const glm::ivec3 slack = participatesIn(NodeOwnerParticipation::gameplay_tick) - ? glm::ivec3(0) - : glm::max(glm::ivec3(2 * k_dim), (wanted_max - wanted_min + 1) / 4); - bool grown = growPart(part, {wanted_min - slack, wanted_max + slack}); - if (!grown) { - grown = growPart(part, {wanted_min, wanted_max}); - } - if (!grown && part.volume == nullptr) { - TOAST_WARN("Voxel", "'{}' has a piece that is too big for one volume, it is left out", name()); - m_parts.erase(found); - continue; - } - if (!grown) { - TOAST_WARN("Voxel", "'{}' has a piece that is too big for one volume, it is clipped to the current one", name()); - } - } - - // Both origins sit on bricks - const glm::ivec3 shift = (part.origin - incoming.origin) / k_dim; - bool changed = false; - for (uint32_t index = 0; index < part.volume->brickCount(); ++index) { - const glm::ivec3 brick = part.volume->brickAtIndex(index); - const glm::ivec3 from = brick + shift; - if (source.containsBrick(from)) { - changed = part.volume->copyBrickFrom(brick, source, from) || changed; - } else if (part.volume->entryAt(brick).tag() != voxel::BrickTag::empty) { - part.volume->setBrickUniform(brick, voxel::k_empty_palette_index); - changed = true; - } - } - if (changed) { - ++part.revision; - part.split_pending = true; - } - - // The tint has the same bricks as the volume - if (part.highlight != nullptr && - (incoming.highlight == nullptr || part.highlight->brickDims() != part.volume->brickDims())) { - if (renderer != nullptr) { - renderer->setVoxelHighlight(this, nullptr, part.key); - } - part.highlight.reset(); - } - if (incoming.highlight != nullptr) { - if (part.highlight == nullptr) { - part.highlight = std::make_unique(voxel::runtimeBrickPool(), part.volume->brickDims()); - } - for (uint32_t index = 0; index < part.highlight->brickCount(); ++index) { - const glm::ivec3 brick = part.highlight->brickAtIndex(index); - const glm::ivec3 from = brick + shift; - if (incoming.highlight->containsBrick(from)) { - part.highlight->copyBrickFrom(brick, *incoming.highlight, from); - } else if (part.highlight->entryAt(brick).tag() != voxel::BrickTag::empty) { - part.highlight->setBrickUniform(brick, voxel::k_empty_palette_index); - } - } - if (renderer != nullptr) { - renderer->setVoxelHighlight(this, part.highlight.get(), part.key); + const bool slack = !participatesIn(NodeOwnerParticipation::gameplay_tick); + stats = result.region.has_value() ? procedural::applyRegion(m_parts, result, slack, m_retired_volumes) + : procedural::applyFull(m_parts, result, slack, m_retired_volumes); + + for (VoxelPart& part : m_parts) { + part.outline_rids.clear(); + for (const auto& [key, rid] : output.outline_rids) { + if (key == part.key) { + part.outline_rids.push_back(rid); } } } - - if (parts_changed) { + if (stats.parts_changed) { ++m_parts_revision; } + m_composed = output.request; + m_composed_parts_revision = m_parts_revision; } - // The bricks go back to the pool - output.parts.clear(); + if (stats.left_out > 0) { + TOAST_WARN("Voxel", "'{}' has a piece that is too big for one volume, it is left out", name()); + } + if (stats.clipped > 0) { + TOAST_WARN("Voxel", "'{}' has a piece that is too big for one volume, it is clipped to the current one", name()); + } m_layout = std::move(m_pending_layout); m_pending_layout.clear(); // Bodies exist per part // We need to build them agains - if (parts_changed) { + if (stats.parts_changed) { reregisterPhysics(); } } @@ -1187,15 +690,18 @@ auto ProceduralVoxel::bakeParts() -> std::vector { std::vector pieces; collect(*this, glm::mat4(1.0f), pieces); const std::shared_ptr input = makeComposeInput(pieces, true); - const std::shared_ptr output = compose(*input); + finishComposeInput(*input); + procedural::Result result = procedural::compose(*input->request); + // Stamps are made one per landing in the same order + const std::vector& stamps = input->request->stamps; std::vector out; - out.reserve(output->parts.size()); - for (ComposeOutput::Part& part : output->parts) { + out.reserve(result.parts.size()); + for (procedural::Part& part : result.parts) { uint64_t lead = 0; - for (const Landing& landing : input->landings) { - if (landing.key == part.key && landing.kind == PieceKind::fill) { - lead = landing.piece->uid().data(); + for (size_t i = 0; i < stamps.size(); ++i) { + if (stamps[i].key == part.key && stamps[i].kind == PieceKind::fill) { + lead = input->landings[i].piece->uid().data(); break; } } @@ -1280,13 +786,14 @@ auto ProceduralVoxel::pieceAt(glm::ivec3 voxel) -> VoxelPiece* { } void ProceduralVoxel::end() { - if (renderer::VulkanRenderer::instance != nullptr) { - renderer::VulkanRenderer::instance->clearVoxelHighlights(this); + { + std::scoped_lock lock(voxel::runtimePoolMutex()); + m_outline_ghosts.clear(); } - m_highlight_for = {}; // The compose only reads its own snapshot so it is left to finish on its own m_compose_job = {}; m_last_compose.reset(); + m_composed.reset(); m_pending_projections = false; } @@ -1321,8 +828,8 @@ void ProceduralVoxel::sendLayout() { } layout.palette_uid = UID(paletteUid()); // The projections come from the last compose - if (renderer::editorOverlays().projections && m_last_compose != nullptr && m_last_compose->has_projections) { - layout.projections = m_last_compose->projections; + if (renderer::editorOverlays().projections && m_last_compose != nullptr && m_last_compose->result.has_projections) { + layout.projections = m_last_compose->result.projections; } event::send(std::move(layout)); } @@ -1393,13 +900,6 @@ void ProceduralVoxel::drawDebug() { ); } - // The selected piece - const glm::vec4 k_selection_orange {1.0f, 0.639f, 0.0f, 1.0f}; - for (const PieceLayout& piece : m_layout) { - if (piece.node.exists() && piece.node->uid() == overlays.selected) { - debug::drawShapeBox(box(glm::vec3(piece.bounds.min), glm::vec3(piece.bounds.max + 1)), k_selection_orange, false); - } - } if (!overlays.volume_edges && !cutting) { return; } @@ -1442,5 +942,4 @@ void ProceduralVoxel::drawDebug() { slab(-extent * 0.5f, 0.0f, {0.15f, 0.45f, 1.0f, 0.12f}); slab(-0.05f, 0.05f, {1.0f, 1.0f, 1.0f, 0.5f}); } - } diff --git a/engine/src/toast/voxel/nodes/procedural_voxel.hpp b/engine/src/toast/voxel/nodes/procedural_voxel.hpp index 264e57c46..1350d7c08 100644 --- a/engine/src/toast/voxel/nodes/procedural_voxel.hpp +++ b/engine/src/toast/voxel/nodes/procedural_voxel.hpp @@ -32,6 +32,10 @@ namespace event { struct ProceduralVoxelLayout; } +namespace toast::procedural { +struct Request; +} + namespace toast { /** @@ -186,10 +190,6 @@ class [[ToastNode, Color("Magenta")]] TOAST_API ProceduralVoxel : public VoxelNo /** Writes one piece into target whose first voxel is the shape voxel origin */ static auto apply(voxel::Volume& target, const Landing& landing, glm::ivec3 origin) -> voxel::EditResult; - /** Builds the whole shape into a fresh volume, async */ - [[nodiscard]] - static auto compose(const ComposeInput& input) -> std::shared_ptr; - [[nodiscard]] auto keyOf(const std::vector& pieces) -> uint64_t; @@ -200,15 +200,18 @@ class [[ToastNode, Color("Magenta")]] TOAST_API ProceduralVoxel : public VoxelNo /** Start building the piece async */ void launchCompose(const std::vector& pieces); + void refreshOutlineGhosts(); + + uint32_t m_ghost_generation = 0; + /** Copies the volumes of a finished compose into the parts */ void applyComposed(ComposeOutput& output); - /** Makes the volume of part cover bounds */ - auto growPart(VoxelPart& part, const voxel::EditBounds& bounds) -> bool; - [[nodiscard]] auto makeComposeInput(const std::vector& pieces, bool wait) -> std::shared_ptr; + static void finishComposeInput(ComposeInput& input); + [[nodiscard]] auto averageColor(const Landing& landing) -> glm::vec3; @@ -218,8 +221,6 @@ class [[ToastNode, Color("Magenta")]] TOAST_API ProceduralVoxel : public VoxelNo [[nodiscard]] auto toolPiece() -> VoxelPiece*; - UID m_highlight_for; - std::vector m_layout; std::vector m_pending_layout; bool m_keep_grids = false; @@ -229,6 +230,10 @@ class [[ToastNode, Color("Magenta")]] TOAST_API ProceduralVoxel : public VoxelNo bool m_compose_wanted = false; bool m_pending_projections = false; + std::shared_ptr m_composed; + uint32_t m_composed_parts_revision = 0; + bool m_compose_full = false; + struct CachedRemap { voxel::PaletteRemapTable table {}; uint64_t target_uid = 0; diff --git a/engine/src/toast/voxel/nodes/voxel_node.hpp b/engine/src/toast/voxel/nodes/voxel_node.hpp index 98392c106..de39c357e 100644 --- a/engine/src/toast/voxel/nodes/voxel_node.hpp +++ b/engine/src/toast/voxel/nodes/voxel_node.hpp @@ -75,7 +75,7 @@ struct VoxelPart { bool split_pending = false; physics::BodyID body; physics::ShapeID shape; - std::unique_ptr highlight; + std::vector outline_rids; bool has_pose = false; glm::vec3 pose_position {0.0f}; @@ -88,6 +88,20 @@ struct VoxelPart { } }; +struct VoxelOutlineGhost { + uint64_t piece_rid = 0; + std::unique_ptr volume; + glm::ivec3 origin {0}; + const void* source = nullptr; + glm::ivec3 source_offset {0}; + uint32_t generation = 0; + + [[nodiscard]] + auto localTransform() const -> glm::mat4 { + return glm::translate(glm::mat4(1.0f), glm::vec3(origin) * voxel::k_voxel_size); + } +}; + /** * A shape made of voxels that renders and collides * @@ -336,6 +350,8 @@ class [[ToastNode, Icon("BoxMesh")]] TOAST_API VoxelNode : public Voxel { signals::Signal<> went_to_sleep; ///< Sent when the body falls asleep signals::Signal<> woke_up; ///< Sent when the body wakes up + signals::Signal<> grabbed; ///< Triggered when an object is grabbed + /** Puts the physics body to sleep */ [[Reflect]] void sleep(); @@ -396,6 +412,11 @@ class [[ToastNode, Icon("BoxMesh")]] TOAST_API VoxelNode : public Voxel { return m_parts_revision; } + [[nodiscard]] + auto outlineGhosts() const noexcept -> const std::vector& { + return m_outline_ghosts; + } + [[nodiscard]] auto ownsBody(physics::BodyID body) const noexcept -> bool; @@ -652,6 +673,7 @@ class [[ToastNode, Icon("BoxMesh")]] TOAST_API VoxelNode : public Voxel { std::vector> m_retired_volumes; std::vector m_parts; uint32_t m_parts_revision = 0; + std::vector m_outline_ghosts; bool m_warned_part_edit = false; glm::ivec3 m_voxel_origin {0}; uint32_t m_revision = 0; diff --git a/engine/src/toast/voxel/runtime_pool.hpp b/engine/src/toast/voxel/runtime_pool.hpp index 64e9ceb1b..704e01dad 100644 --- a/engine/src/toast/voxel/runtime_pool.hpp +++ b/engine/src/toast/voxel/runtime_pool.hpp @@ -14,7 +14,7 @@ namespace voxel { -inline constexpr uint32_t k_runtime_brick_capacity = 1u << 18; +inline constexpr uint32_t k_runtime_brick_capacity = 1u << 20; /// @note Main thread only [[nodiscard]] diff --git a/engine/src/toast/world/workspace.cpp b/engine/src/toast/world/workspace.cpp index 32dce6d85..fb987098f 100644 --- a/engine/src/toast/world/workspace.cpp +++ b/engine/src/toast/world/workspace.cpp @@ -2105,8 +2105,6 @@ void Workspace::eventSubscriptions() { return false; } m_focused_node = findFrom(m_root_node, e.node); - // The VoxelEditor tints the selected piece - renderer::editorOverlays().selected = m_focused_node.exists() ? m_focused_node->uid() : UID {}; return false; }); diff --git a/engine/src/toast/world/workspace_voxel.cpp b/engine/src/toast/world/workspace_voxel.cpp index 42830d72c..620fd849a 100644 --- a/engine/src/toast/world/workspace_voxel.cpp +++ b/engine/src/toast/world/workspace_voxel.cpp @@ -545,7 +545,6 @@ auto Workspace::voxelToolMouseButton(uint32_t button, bool pressed, int mods) -> } VoxelPiece* piece = shape->pickPiece(local.origin, local.direction); m_focused_node = piece != nullptr ? piece->box() : Box {}; - renderer::editorOverlays().selected = piece != nullptr ? piece->uid() : UID {}; event::NodePicked picked; picked.workspace_handle = m_handle.data(); picked.node = piece != nullptr ? piece->uid() : UID {}; @@ -798,7 +797,6 @@ void Workspace::subscribeVoxelEditing() { return; } m_focused_node = node; - renderer::editorOverlays().selected = node->uid(); event::NodePicked picked; picked.workspace_handle = m_handle.data(); picked.node = node->uid();