Shader,想说爱你不容易。

来源:互联网 发布:c语言函数类型有哪些 编辑:程序博客网 时间:2024/05/18 00:31

这两天开始接触shader,给我的第一感觉是容易,第二感觉是难,第三赶脚是数学不好就先学数学吧

首先我们通过unity自己创建一个shader脚本的时候,其实shader已经给我们搭建好了编写shader基本的框架,我们要做的就是往里面写自己的shader,但是写之前总的先认识这里面有啥子东西吧。先创建一个shader瞅瞅,我使用的unity的版本为5.x,代码如下:

Shader "Custom/BasicDiffuse" {Properties {_Color ("Color", Color) = (1,1,1,1)_MainTex ("Albedo (RGB)", 2D) = "white" {}_Glossiness ("Smoothness", Range(0,1)) = 0.5_Metallic ("Metallic", Range(0,1)) = 0.0}SubShader {Tags { "RenderType"="Opaque" }LOD 200CGPROGRAM// Physically based Standard lighting model, and enable shadows on all light types#pragma surface surf Standard fullforwardshadows// Use shader model 3.0 target, to get nicer looking lighting#pragma target 3.0sampler2D _MainTex;struct Input {float2 uv_MainTex;};half _Glossiness;half _Metallic;fixed4 _Color;void surf (Input IN, inout SurfaceOutputStandard o) {// Albedo comes from a texture tinted by colorfixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;o.Albedo = c.rgb;// Metallic and smoothness come from slider variableso.Metallic = _Metallic;o.Smoothness = _Glossiness;o.Alpha = c.a;}ENDCG} FallBack "Diffuse"}

unity4.x创建的shader代码如下:

Shader "Custom/BasicDiffuse" {      Properties {          _MainTex ("Base (RGB)", 2D) = "white" {}      }      SubShader {          Tags { "RenderType"="Opaque" }          LOD 200                    CGPROGRAM          #pragma surface surf Lambert            sampler2D _MainTex;            struct Input {              float2 uv_MainTex;          };            void surf (Input IN, inout SurfaceOutput o) {              half4 c = tex2D (_MainTex, IN.uv_MainTex);              o.Albedo = c.rgb;              o.Alpha = c.a;          }          ENDCG      }       FallBack "Diffuse"  }  
unity4.x 和5.x是有区别的,我们以5.x为准。

其实shader生成的东西主要由三部分组成:Properties,Subshader和FallBack。

Properties的组成结构为{VariableName(Inspecto Variable Name, Type) = Value},请看Type的类型Type。而该结构中最重要的莫过于VariableName,这个变量的名称在我们之后写shader的过程中要用到,类似于c++中的变量。

subShader则是我们用来渲染对象的主要内容,对于新手什么Tags,LOD可以暂时自己了解,不必深究。而#pragma surface surf Standard fullforwardshadows这句话则相当的重要,它将直接告诉Shader使用哪个光照模型用于计算,这个名叫 Standard fullforwardshadows则是unity默认的光照模型,现在我们自己创建了一个BasicDiffuse的脚本那就将名字替换为BasicDiffuse。_MainTex是与贴图相关,我们可以在unity界面的Inspector中拖入一张图片让如其中就相当于给_MainTex赋值了,也就是Input已经有值了。surf既然有输入的Input的值,在这里那就有输出的值了,不然怎么知道渲染的结果是什么呀,而SurfaceOutputStandard正是扮演者输出值得角色。

FallBack和SurfaceOutputStandard的值将会在后面的内容中讲到



广告之后再回来!

0 0
原创粉丝点击