包含此页的版本:
不含此页的版本:
团结着色器在 GPU 上运行的程序。更多信息
请参阅术语表在此示例中,可视化meshUnity 的主要图形原语。网格体构成了 3D 世界的很大一部分。Unity 支持三角或四边形多边形网格。Nurbs、Nurms、Subdiv 曲面必须转换为多边形。更多信息
请参阅术语表.
使用URP unlit basic shader部分中的Unity着色器源文件,并对ShaderLabUnity 用于定义 Shader 对象结构的语言。更多信息
请参阅术语表法典:
在struct Attributes,这是顶点着色器 渲染模型时在 3D 模型的每个顶点上运行的程序。更多信息
请参阅术语表在此示例中,声明包含每个顶点的法向量的变量。
struct Attributes
{
float4 positionOS : POSITION;
// Declaring the variable containing the normal vector for each vertex.
half3 normal : NORMAL;
};
在struct Varyings,这是本例中片段着色器的输入结构,声明用于存储每个片段的法线向量值的变量:
struct Varyings
{
float4 positionHCS : SV_POSITION;
// The variable for storing the normal vector values.
half3 normal : TEXCOORD0;
};
此示例使用法线向量的三个分量作为每个片段的 RGB 颜色值。
若要在网格上呈现法线向量值,请使用以下代码作为片段着色器:
half4 frag(Varyings IN) : SV_Target
{
half4 color = 0;
color.rgb = IN.normal;
return color;
}
Unity 在网格上渲染法线向量值:
胶囊的一部分是黑色的。这是因为在这些点中,法向量的所有三个分量都是负的。下一步还演示了如何在这些区域中呈现值。
要渲染负法线矢量组件,请使用压缩一种存储数据的方法,可减少所需的存储空间量。请参阅纹理压缩、动画压缩、音频压缩、构建压缩。
请参阅术语表技术。压缩正常组件值的范围(-1..1)到颜色值范围(0..1),请更改以下行:
color.rgb = IN.normal;
到这行:
color.rgb = IN.normal * 0.5 + 0.5;
现在,Unity 将法线矢量值渲染为网格上的颜色。
以下是此示例的完整 ShaderLab 代码。
// This shader visualizes the normal vector values on the mesh.
Shader "Example/URPUnlitShaderNormal"
{
Properties
{ }
SubShader
{
Tags { "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline" }
Pass
{
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
struct Attributes
{
float4 positionOS : POSITION;
// Declaring the variable containing the normal vector for each
// vertex.
half3 normal : NORMAL;
};
struct Varyings
{
float4 positionHCS : SV_POSITION;
half3 normal : TEXCOORD0;
};
Varyings vert(Attributes IN)
{
Varyings OUT;
OUT.positionHCS = TransformObjectToHClip(IN.positionOS.xyz);
// Use the TransformObjectToWorldNormal function to transform the
// normals from object to world space. This function is from the
// SpaceTransforms.hlsl file, which is referenced in Core.hlsl.
OUT.normal = TransformObjectToWorldNormal(IN.normal);
return OUT;
}
half4 frag(Varyings IN) : SV_Target
{
half4 color = 0;
// IN.normal is a 3D vector. Each vector component has the range
// -1..1. To show all vector elements as color, including the
// negative values, compress each value into the range 0..1.
color.rgb = IN.normal * 0.5 + 0.5;
return color;
}
ENDHLSL
}
}
}