- Home /
Vertex Shader and Non-uniformly scaled meshes
I'm having an issue in Unity 5 with a vertex shader where if I have a non-uniformly scaled mesh it will (usually) incorrectly calculate the position in the vertex shader. The shader is intended to offset all the vertices of the object outwards by a set distance (In this example, 0.5 meters). I've seen some questions/answers suggesting a need in U5 to normalize the normals before using them in the vertex shader, but I've done that to no avail.
It seems like this behavior must be related to the batching of objects since it seems to only occur when another object is on screen using the same shader. And given the changes to non-uniform mesh scaling in U5, I assume it's related to that. But I cannot for the life of me see what is happening incorrectly here. Does anyone see a way to fix the shader?
I have simplified my shader down to the following which still exhibits my error:
Shader "Custom/VertexOffsetter" {
Properties {
}
SubShader {
Tags { "RenderType"="Opaque" }
Pass {
Name "FORWARD"
Tags {
"LightMode"="ForwardBase"
}
CGPROGRAM
#include "UnityCG.cginc"
#pragma fragment frag
#pragma vertex vert
#define UNITY_PASS_FORWARDBASE
// Use shader model 3.0 target, to get nicer looking lighting
#pragma target 3.0
struct VertexOutput {
float4 pos : SV_POSITION;
};
VertexOutput vert(appdata_base v) {
VertexOutput o = (VertexOutput)0;
v.vertex.xyz += normalize(v.normal) * 0.5;
o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
return o;
}
float4 frag (VertexOutput i) : COLOR {
return float4(0.5, 0.5, 0, 0);
}
ENDCG
}
}
FallBack "Diffuse"
}
The incorrectly rendered mesh. Note that the wireframe appears to be correct:
The correctly rendered mesh, with the only change that the object which was previously on the left side of the screen is now moved entirely offscreen.
Thanks in advance.
Answer by DuneWalker · Mar 29, 2015 at 02:55 AM
Could it be related to using the ModelViewProjection matrix. Try substituting out it for the ModelView or the Model matrix (the exact names should be found on the Unity documentation under Shader Variables or something similar) and see what happens. If you use the Projection matrix with the ModelView matrix, it may be causing the object to become double-projected, so to speak.
Given that the object draws correctly when it is the only object in the scene, I don't believe the projection matrix could be at fault.