use*_*963 9 opengl unity-game-engine
这是我的着色器,它将一种颜色替换为另一种颜色:
Shader "Custom/SwapColors"
{
Properties
{
_MainTex("Texture",2D)="white"{}
swap_from("Swap From",COLOR)=(1,1,1,1)
swap_to("Swap To",COLOR)=(1,1,1,1)
threshold("Threshold",Float)=0.00001
}
SubShader
{
Tags
{
"Queue"="Transparent"
}
Pass
{
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
sampler2D _MainTex;
float4 swap_from;
float4 swap_to;
float threshold;
struct VertexInput
{
float4 pos:POSITION;
float2 uv:TEXCOORD0;
};
struct FragmentInput
{
float4 pos:SV_POSITION;
float2 uv:TEXCOORD0;
};
FragmentInput vert(VertexInput data)
{
FragmentInput res;
res.pos=mul(UNITY_MATRIX_MVP,data.pos);
res.uv=data.uv;
return res;
}
bool eq(fixed f,fixed s)
{
return abs(f-s)<threshold;
}
float4 frag(FragmentInput data):COLOR
{
float4 res=tex2D(_MainTex,data.uv.xy).rgba;
if(eq(res.r,swap_from.r)&&eq(res.g,swap_from.g)&&eq(res.b,swap_from.b))
res.rgb=swap_to.rgb;
return res;
}
ENDCG
}
}
Fallback "Diffuse"
}
Run Code Online (Sandbox Code Playgroud)
这是一个附加到gameobject的测试脚本,其中包含主摄像头.在其中我尝试渲染一条线和纹理四边形.
mat被赋予SwapColors纹理.
sprite_mat 使用具有相同纹理的默认精灵着色器指定.
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour
{
[SerializeField]
Material mat;
[SerializeField]
Material sprite_mat;
void OnPostRender()
{
GL.PushMatrix();
GL.LoadProjectionMatrix(Camera.main.projectionMatrix);
GL.modelview=Camera.main.worldToCameraMatrix;
GL.Begin(GL.LINES);
sprite_mat.SetPass(0);
GL.Vertex(new Vector3(0,0));
GL.Vertex(new Vector3(5,0));
GL.End();
GL.Begin(GL.QUADS);
sprite_mat.SetPass(0);
mat.SetPass(0);//<------------------------------------ PROBLEM
GL.TexCoord(new Vector3(0,0));
GL.Vertex(new Vector2(0,0));
GL.TexCoord(new Vector3(1,0));
GL.Vertex(new Vector2(1,0));
GL.TexCoord(new Vector3(1,1));
GL.Vertex(new Vector2(1,1));
GL.TexCoord(new Vector3(0,1));
GL.Vertex(new Vector2(0,1));
GL.End();
GL.PopMatrix();
}
}
Run Code Online (Sandbox Code Playgroud)
当我渲染四边形时sprite_mat,一切都很好.
当我使用时mat,不仅四边形消失了,而且线条也消失了,尽管它被渲染了sprite_mat.
如果我在编辑器中创建另一个四边形并将其材质设置为mat,则会正确呈现.
我的主要问题是如何setPass影响几何渲染后的几何无关setPass.
示例项目:forum.unity3d.com/attachments/errorgl-7z.138105/
编辑:我找到了一个默认的Unity精灵着色器并将其与我的相比较.四边形消失了,因为它面向相机的相反方向.这是固定的Cull Off.
如果我添加线
float4 color:COLOR;
到VertexInput结构,与我的着色材料停止影响与其他材料的几何形状.我不明白发生了什么.
我认为你不能在和SetPass(0)之间两次。GL.Begin(..)GL.End(..)
您可以设置各种通道,SetPass(0); [..] SetPass(1);但看看您的着色器,我认为这不是您想要做的。
那么你想用 2 次绘制四边形吗?一个使用默认的 Sprite 材质,另一个使用您的自定义材质?还是只画两遍?
我不完全明白你想在这里做什么。