Contract amendment 1 of three, and V4e's content behind it. Plan section 5.5.16
recorded that both particle pipelines draw with per-instance VERTEX attributes
and that the pinned contract could express instanced DRAWING but not instanced
vertex INPUT: one stride, no divisor, one buffer at VertexInputRate.VERTEX. That
is what stopped V4e. This takes the reviewed option (i) - a second vertex
binding with a per-instance rate.
The amendment. GpuVertexLayout grows a per-binding notion (binding index,
stride, input rate) and GpuVertexAttribute names the binding it is fed from,
defaulting to 0; IGpuPassEncoder.BindVertexBuffer takes a binding index. Every
layout written before this slice keeps its exact meaning through
GpuVertexLayout.Interleaved, which is one vertex-rate binding 0 - and
GpuContractTests asserts that as a requirement rather than trusting it. Both
backends carry the rate natively and at no cost: VK_VERTEX_INPUT_RATE_INSTANCE
on the pipeline, glVertexAttribDivisor recorded once into the pipeline's VAO
where it survives every later attribute rebind.
GpuVertexFormat.UInt1 comes with it, and is necessary to it: particle.vert
declares `layout(location = 6) in uint aTextureIndex` and the amendment's whole
premise is that no shader is edited. Same kind-distinction UByte4UInt was added
for at V4d - GL needs glVertexAttribIPointer, Vulkan needs R32_UINT, and the
float path would reinterpret the value's bits rather than approximate them.
Options (ii) and (iii) were rejected on the record: all ten storage bindings are
spoken for and reusing binding 0 would have the GL particle draw clobber
WbDrawDispatcher's instance array mid-frame (section 5.5.8's hazard in its GL
form); CPU-expanding instances is 5x billboard bandwidth and does not scale to
mesh particles at all.
The arm. ParticleRenderer.Rhi.cs is a SECOND arm per section 5.5.6, not a
replacement - every GL statement in the sibling file is the one it always
issued. Five pipelines replace the imperative glBlendFunc switch (two billboard
blends, three mesh blends) because core Vulkan 1.3 does not make blend dynamic.
The per-flight VAO/VBO pool disappears because every ring allocation inside a
frame is already distinct memory that lives until the frame retires. The
binding-9 table is not bound at all - the device owns the table and the encoder
binds set 2. The pass is BORROWED from IWorldPassScope. Depth tests but does not
write, compare is Less and alpha-to-coverage is off, which is the ambient GL
state particles have always drawn under rather than a choice. Everything above
the submission seam - emitter iteration, retail distance ordering, the
deferred-alpha handoff, billboard axis construction, blend resolution - is the
same CPU code on both arms.
The first Vulkan particle frame threw rather than drew, which is the second
defect of the compiles-clean class this slice found by running:
TextureCache.AcquireParticleTexture is bindless-only, so the standalone particle
texture cache did not exist on a backend without GL. It exists on both arms now.
Everything about it that matters - sharing equivalent surfaces between emitter
owners, the bounded unowned LRU, retirement behind the frame-flight fence - is
already backend-neutral; only how one entry is created and destroyed differs,
which is what IStandaloneBindlessTextureBackend is for. The RHI arm creates the
image through IGpuDevice.CreateTexture with a real sampler and releases the
table slot before the image, which is the GL arm's order and for the same
reason. The composite cache stays GL-only: it serves entity appearance, not
particles.
The durability fix V6k earned. That slice found the sky declaring a 32-byte
stride against a 36-byte AcDream.Core.Terrain.Vertex - the record carries a
TerrainLayer no sky attribute names - and noted that every .Rhi.cs arm restates
a CPU record's footprint from memory while only sky had a test.
RhiVertexLayoutStrideTests is that test for the rest: world mesh, terrain, sky,
retained-UI sprite, debug line, and both particle bindings, each asserted
against the record or the producer's own float count, plus two sweeps over all
seven for attributes that reach past their stride or name an undeclared binding.
Four private layouts became internal to be assertable; nothing else about them
moved.
Gates. Release build green. App tests 4,121/3 skips (4,109 baseline plus three
contract tests and nine layout tests); complete Release suite 9,184/5. Strict GL
offline pixel gate against 08ffe141: 3.20e-05, 18 differing pixels of 563,200,
inside the documented 9-31 band. GL connected -Runs 3: 3/3 RENDERED on the
desktop witness and 3/3 on the client capture. One offline Vulkan run with
VK_LAYER_KHRONOS_validation proven inserted by the loader: zero validation
errors, zero warnings, a captured world frame that still draws terrain,
blending, roads, water, statics, scenery, sky and the complete retained UI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
200 lines
8.1 KiB
C#
200 lines
8.1 KiB
C#
using System.Collections.Generic;
|
|
using System.Numerics;
|
|
using AcDream.App.Rendering.Gpu;
|
|
|
|
namespace AcDream.App.Rendering;
|
|
|
|
/// <summary>
|
|
/// Minimal line renderer for visualizing collision shapes, bounding boxes,
|
|
/// and other debug geometry. Collect lines each frame via
|
|
/// <see cref="AddLine"/> / <see cref="AddCylinder"/>, then call
|
|
/// <see cref="Flush"/> to upload + draw them.
|
|
///
|
|
/// Campaign V slice V4a: the <c>debug_line</c> shader compiles through
|
|
/// <see cref="IGpuDevice.CreatePipeline"/> (<see cref="GpuPrimitiveTopology.LineList"/>
|
|
/// topology, depth disabled to match this renderer's "visible through
|
|
/// geometry" intent), and each Flush's vertex data comes from a per-frame
|
|
/// ring allocation instead of the old single respecialized VBO.
|
|
///
|
|
/// <para>Campaign V slice V6d removed the last GL dependency. The shader's
|
|
/// separate <c>uView</c>/<c>uProjection</c> pair was set directly against the
|
|
/// compiled GL program because the pinned <see cref="GpuPushConstants"/> block
|
|
/// carries one combined matrix and there is no verb for arbitrary named
|
|
/// uniforms. That was never portable — Vulkan has no default uniform block at
|
|
/// all — so the shader converged on <c>uViewProjection</c> and
|
|
/// <see cref="Flush"/> multiplies the two matrices on the CPU. The product
|
|
/// therefore rounds once per frame instead of once per vertex; these lines are
|
|
/// diagnostic-only geometry that draws when collision wireframes are switched
|
|
/// on, so nothing user-visible depends on those bits.</para>
|
|
///
|
|
/// Vertex format is (vec3 pos, vec3 color) = 24 bytes per vertex.
|
|
/// </summary>
|
|
public sealed class DebugLineRenderer : IDisposable
|
|
{
|
|
// internal: slice V6l's stride-equals-the-uploaded-record gate asserts the
|
|
// layout against the producer's own float count rather than a literal.
|
|
internal const int FloatsPerVertex = 6;
|
|
private const int VertexStrideBytes = FloatsPerVertex * sizeof(float);
|
|
|
|
internal static readonly GpuVertexLayout VertexLayout = GpuVertexLayout.Interleaved(
|
|
strideBytes: VertexStrideBytes,
|
|
[
|
|
new GpuVertexAttribute(0, GpuVertexFormat.Float3, 0),
|
|
new GpuVertexAttribute(1, GpuVertexFormat.Float3, 12),
|
|
]);
|
|
|
|
private readonly ICurrentGpuFrameSource _frameSource;
|
|
private readonly IGpuPipeline _pipeline;
|
|
|
|
private readonly List<float> _buffer = new(4096);
|
|
private int _vertexCount;
|
|
|
|
// internal, not public: IGpuDevice/ICurrentGpuFrameSource are internal
|
|
// types (the pinned RHI contract). DebugLineRenderer stays public — only
|
|
// construction is restricted.
|
|
internal DebugLineRenderer(IGpuDevice device, ICurrentGpuFrameSource frameSource, string shaderDir)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(device);
|
|
_frameSource = frameSource ?? throw new ArgumentNullException(nameof(frameSource));
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(shaderDir);
|
|
|
|
_pipeline = device.CreatePipeline(new GpuPipelineDescription
|
|
{
|
|
Name = "debug-line",
|
|
Shaders = new GpuShaderSet("debug_line"),
|
|
VertexLayout = VertexLayout,
|
|
Topology = GpuPrimitiveTopology.LineList,
|
|
Blend = GpuBlendMode.None,
|
|
// Retail debug lines draw through geometry (the old Flush disabled
|
|
// depth testing for the draw and restored whatever was ambient
|
|
// before it — GlGpuPassEncoder now does that restore generically;
|
|
// see its class comment).
|
|
Depth = GpuDepthState.Disabled,
|
|
Cull = GpuCullMode.None,
|
|
AlphaToCoverage = false,
|
|
ColorWrite = true,
|
|
SampleCount = 1,
|
|
});
|
|
}
|
|
|
|
/// <summary>Clear accumulated lines. Call at the start of each frame.</summary>
|
|
public void Begin()
|
|
{
|
|
_buffer.Clear();
|
|
_vertexCount = 0;
|
|
}
|
|
|
|
public void AddLine(Vector3 a, Vector3 b, Vector3 color)
|
|
{
|
|
_buffer.Add(a.X); _buffer.Add(a.Y); _buffer.Add(a.Z);
|
|
_buffer.Add(color.X); _buffer.Add(color.Y); _buffer.Add(color.Z);
|
|
_buffer.Add(b.X); _buffer.Add(b.Y); _buffer.Add(b.Z);
|
|
_buffer.Add(color.X); _buffer.Add(color.Y); _buffer.Add(color.Z);
|
|
_vertexCount += 2;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Draw a cylinder as 2 polygon rings (base + top) connected by 4
|
|
/// vertical line segments at 0/90/180/270 degrees.
|
|
/// </summary>
|
|
public void AddCylinder(Vector3 basePos, float radius, float height, Vector3 color)
|
|
{
|
|
const int segments = 16;
|
|
Vector3 top = basePos + new Vector3(0, 0, height);
|
|
|
|
// Ring vertices
|
|
var baseRing = new Vector3[segments];
|
|
var topRing = new Vector3[segments];
|
|
for (int i = 0; i < segments; i++)
|
|
{
|
|
float theta = i * (MathF.PI * 2f / segments);
|
|
float cx = MathF.Cos(theta) * radius;
|
|
float cy = MathF.Sin(theta) * radius;
|
|
baseRing[i] = new Vector3(basePos.X + cx, basePos.Y + cy, basePos.Z);
|
|
topRing[i] = new Vector3(top.X + cx, top.Y + cy, top.Z);
|
|
}
|
|
|
|
// Base ring
|
|
for (int i = 0; i < segments; i++)
|
|
AddLine(baseRing[i], baseRing[(i + 1) % segments], color);
|
|
// Top ring
|
|
for (int i = 0; i < segments; i++)
|
|
AddLine(topRing[i], topRing[(i + 1) % segments], color);
|
|
// 4 vertical connectors
|
|
for (int i = 0; i < 4; i++)
|
|
{
|
|
int idx = i * (segments / 4);
|
|
AddLine(baseRing[idx], topRing[idx], color);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Draw an axis-aligned box as 12 edges.
|
|
/// </summary>
|
|
public void AddBox(Vector3 min, Vector3 max, Vector3 color)
|
|
{
|
|
Vector3[] c =
|
|
{
|
|
new(min.X, min.Y, min.Z),
|
|
new(max.X, min.Y, min.Z),
|
|
new(max.X, max.Y, min.Z),
|
|
new(min.X, max.Y, min.Z),
|
|
new(min.X, min.Y, max.Z),
|
|
new(max.X, min.Y, max.Z),
|
|
new(max.X, max.Y, max.Z),
|
|
new(min.X, max.Y, max.Z),
|
|
};
|
|
// Bottom
|
|
AddLine(c[0], c[1], color); AddLine(c[1], c[2], color);
|
|
AddLine(c[2], c[3], color); AddLine(c[3], c[0], color);
|
|
// Top
|
|
AddLine(c[4], c[5], color); AddLine(c[5], c[6], color);
|
|
AddLine(c[6], c[7], color); AddLine(c[7], c[4], color);
|
|
// Verticals
|
|
AddLine(c[0], c[4], color); AddLine(c[1], c[5], color);
|
|
AddLine(c[2], c[6], color); AddLine(c[3], c[7], color);
|
|
}
|
|
|
|
/// <summary>Upload + draw all accumulated lines.</summary>
|
|
public void Flush(Matrix4x4 view, Matrix4x4 projection)
|
|
{
|
|
if (_vertexCount == 0) return;
|
|
|
|
IGpuFrame frame = _frameSource.CurrentFrame
|
|
?? throw new InvalidOperationException(
|
|
"DebugLineRenderer.Flush requires an open IGpuFrame (see GpuDeviceFrameLifetime) — " +
|
|
"the host must drive IGpuDevice.BeginFrame() before rendering debug lines.");
|
|
|
|
using IGpuPassEncoder encoder = frame.BeginPass(new GpuPassDescription
|
|
{
|
|
Name = "debug-line",
|
|
Color = new GpuColorAttachment(
|
|
Target: null,
|
|
Load: GpuLoadOp.Load,
|
|
Store: GpuStoreOp.Store,
|
|
ClearColor: default),
|
|
Depth = null,
|
|
SampleCount = 1,
|
|
});
|
|
encoder.BindPipeline(_pipeline);
|
|
|
|
// The GLSL used to evaluate uProjection * uView per vertex. System.Numerics
|
|
// is row-vector convention and GL/Vulkan read the 16 floats as column-major,
|
|
// which transposes; so the CPU-side equivalent of that product is
|
|
// view * projection, in that order.
|
|
GpuPushConstants constants = GpuPushConstants.Default;
|
|
constants.ViewProjection = view * projection;
|
|
encoder.SetPushConstants(constants);
|
|
|
|
int byteCount = _buffer.Count * sizeof(float);
|
|
GpuRingAllocation allocation = frame.AllocateRing(byteCount, GpuRingUsage.Vertex);
|
|
System.Runtime.InteropServices.CollectionsMarshal.AsSpan(_buffer).CopyTo(allocation.AsSpan<float>());
|
|
encoder.BindVertexBuffer(0, allocation.Buffer, allocation.OffsetBytes);
|
|
encoder.Draw((uint)_vertexCount, 1, 0, 0);
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
_pipeline.Dispose();
|
|
}
|
|
}
|