Hello,
I have some issues rotating instances created with Graphics.DrawMeshInstancedIndirect.
I store per-instance position, scale and rotation in ComputeBuffer and apply them to the instances in setup() shader function as described here - Unity - Scripting API: Graphics.DrawMeshInstancedIndirect
The positioning and scaling of the instances works fine, and the rotation also works, in a way.
However, as you can see in the attached image, it seems that the normals of the instance are not rotated along with the object and as a result rotated objects are lit incorrectly.
I’ve attached the relevant portion of the setup() code below that deals with the positioning and rotation of the instances. Possibly I’m going about this all wrong by multiplying unity_ObjectToWorld with a rotation matrix, but I do see correct rotations of the instances, so it kind of works.
I have a hunch that I also need to transform the vertices or normals somehow, but I can’t figure out what transformation to apply there, does anyone have any ideas what could be going wrong here?
void setup()
{
#ifdef UNITY_PROCEDURAL_INSTANCING_ENABLED
int idx = CulledBuffer[unity_InstanceID].index;
int instance = CulledBuffer[unity_InstanceID].instance;
GPUAtom atom = AtomBuffer[idx];
float size = lerp(atom.scaleP, atom.scale, atom.lerpProgress);
float health = lerp(atom.healthP, atom.health, atom.lerpProgress);
float angle = lerp(atom.angleP, atom.angle, atom.lerpProgress);
float3 position = lerp(atom.positionP, atom.position, atom.lerpProgress);
// scale
unity_ObjectToWorld._11_21_31_41 = float4(size, 0, 0, 0);
unity_ObjectToWorld._12_22_32_42 = float4(0, size, 0, 0);
unity_ObjectToWorld._13_23_33_43 = float4(0, 0, size, 0);
// position
unity_ObjectToWorld._14_24_34_44 = float4(position, 1);
// rotation
float c = cos(angle);
float s = sin(angle);
float4x4 rotateYMatrix = float4x4(
c, 0, s, 0,
0, 1, 0, 0,
-s, 0, c, 0,
0, 0, 0, 1);
unity_ObjectToWorld = mul(unity_ObjectToWorld, rotateYMatrix);
unity_WorldToObject = unity_ObjectToWorld;
unity_WorldToObject._14_24_34 *= -1;
unity_WorldToObject._11_22_33 = 1.0f / unity_WorldToObject._11_22_33;
#endif
}