How to change UV for Instance?

I’ve found here something like… changing an offset in instanced mesh, as it passes Vector2 and not Vector4 type?
PG: playground

Is it possible to replace UV using Vector4? Not just making some offset but all UV coords: left bottom, right top.

No, an instanced attribute is a single value for the whole instance, that is for all the vertices of an instance. If you want to pass 4 values per instance, you will have to pass 4 attributes. In your case, the values are vec2, so you can pass two values per attribute (which is vec4), so you would need 2 attributes. However, I’m not sure you could achieve to do what you want, as there are 24 vertices in the cube, so 24 coordinates, not 4.

1 Like

Well I’m making it for a plane so I have only 4 numbers in UV: [ left, bottom ] → [ right, top ]. If I would pass two values

mat1.AddAttribute("uv0");
mat1.AddAttribute("uv1");

then how do I pass it in a material?

mat1.Vertex_Definitions(`
  attribute vec2 uv0;
  attribute vec2 uv1;
`);
mat1.Vertex_Before_PositionUpdated(`
  uvUpdated += uv0;

.... something else should goes here? ....

`);
plane.registerInstancedBuffer("uv0", 2);
plane.registerInstancedBuffer("uv1", 2);
plane.instancedBuffers.uv0 = new BABYLON.Vector2( uv_left, uv_bottom );
plane.instancedBuffers.uv1 = new BABYLON.Vector2( uv_right, uv_top );

You can do it like that:

Note that I had to add another attribute (vindex), to know which vertex is currently processed by the vertex shader, so that the right uv value can be set to uvUpdated.

2 Likes

Wow, thanks for a good example here! But why does it use two Vector4 positions when in regular plane’s UV we use only one Vector4? I mean for frontUV or backUV.

Do we actually need to change all 4 vertices for changing frontUV or backUV for a plane?

Not sure what you mean by “frontUV” and “backUV”, but uv coordinates are defined for each vertex, so for a plane you need 4 pair of coordinates. If you want to freely define the uv for each plane instance, you need to pass 4 vec2 to the shader, hence the 2 vec4 (2 vec2 are concatenated into a single vec4).

2 Likes