bevy icon indicating copy to clipboard operation
bevy copied to clipboard

Add `VertexBufferLayout::offset_locations`

Open SludgePhD opened this issue 2 years ago • 2 comments

Objective

When using instancing, 2 VertexBufferLayouts are needed, one for per-vertex and one for per-instance data. Shader locations of all attributes must not overlap, so one of the layouts needs to start its locations at an offset. However, VertexBufferLayout::from_vertex_formats will always start locations at 0, requiring manual adjustment, which is currently pretty verbose.

Solution

Add VertexBufferLayout::offset_locations, which adds an offset to all attribute locations.

Code using this method looks like this:

VertexState {
    shader: BACKBUFFER_SHADER_HANDLE.typed(),
    shader_defs: Vec::new(),
    entry_point: "vertex".into(),
    buffers: vec![
        VertexBufferLayout::from_vertex_formats(
            VertexStepMode::Vertex,
            [VertexFormat::Float32x2],
        ),
        VertexBufferLayout::from_vertex_formats(
            VertexStepMode::Instance,
            [VertexFormat::Float32x2, VertexFormat::Float32x3],
        )
        .offset_locations(1),
    ],
}

Alternative solutions include:

  • Pass the starting location to from_vertex_formats – this is a bit simpler than my solution here, but most calls don't need an offset, so they'd always pass 0 there.
  • Do nothing and make the user hand-write this.

Changelog

  • Add VertexBufferLayout::offset_locations to simplify buffer layout construction when using instancing.

SludgePhD avatar Sep 14 '23 10:09 SludgePhD

Yeah need to swap self with mut self in the function signature.

nicopap avatar Sep 19 '23 10:09 nicopap

Small nit actually: I'd rather call this offset_locations_by()

JMS55 avatar Aug 21 '24 19:08 JMS55