- Home /
pass value from vertex to fragment without interpolation ?!
Hi, I need to pass the actual vertex coordinate from my vertex to my fragment shader without interpolation. I tried using a uniform variable but for some reason it seems not to hold a valid value at all.
An example:
Shader "Vertex Colored" {
Properties {
_Color ("Main Color", Color) = (1,1,1,1)
}
SubShader {
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
float3 _p1,_p2;
struct v2f {
float4 pos : SV_POSITION;
float3 color : COLOR0;
float3 bc : TEXCOORD2;
float3 p : TEXCOORD3;
};
float PtoLine(float3 a, float3 b, float3 p)
{
return length(cross(p-a, p-b))/length(b-a);
}
v2f vert (appdata_full v)
{
v2f o;
o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
_p1 = v.vertex.xyz;
_p2 = v.tangent.xyz;
o.p = v.vertex;
o.color = v.color;
o.bc = v.tangent.xyz;
return o;
}
half4 frag (v2f i) : COLOR
{
//return half4(i.bc, 1);
return half4(_p1,1);
if(1>0)
return half4(0,0,0,1);
else
return half4 (i.color, 1);
}
ENDCG
}
}
Fallback " VertexLit", 1
}
This will ALWAYS render black, no matter what the vertex coordinate is. What is going on here ?
Answer by Owen-Reynolds · Dec 09, 2014 at 08:53 PM
I think this is impossible. Not just in Unity.
Fragments are created based on the 2 or 3 or 4 or more verts making the face. They never even know how many or which verts made them, much less being able to see their "parent" vert data. Hardware making a single interpolated value works great for this.
The one exception I know of is "flat" shading. where the color is passed straight from the 1st vert in the face (and the rest are ignored.)
Since the vert shader runs for all verts, setting a uniform variable is pointless. It would just be set to the most recently processed vert, probably not one that made this pixel.
Answer by LaireonGames · Sep 01, 2020 at 12:11 PM
Kept coming across this whilst trying to solve this myself and figured out a work around that can work in some situations.
Add more verts so nothing is shared. That way your faces can store data unique to that face and interpolation will always return the same value.
In my situation each triangle had the same central vert and was causing me the interpolation issues. Duplicating that central vert for each face lets me fix this issue (granted with some extra mesh data but its tiny my situation)
Your answer
Follow this Question
Related Questions
Vertex/Fragment shaders - transparency ignoring Render Queue 3 Answers
Refraction Shader. Strange Artifacts 0 Answers
Vertex shader breaks render to texture - camera preview and render texture not the same 1 Answer
How can I make shadows pixelated in fragment function? 1 Answer
Prevent ColorMask obscuring parts of an object's mesh 0 Answers