Unity Shader Getting Started tutorial (i)

Source: Internet
Author: User

Reference:http://www.360doc.com/content/13/0923/15/12282510_316492286.shtml

Unity Shader is a shader, the texture, grid information input, get the material of a program, specifically what things, but also need to practice to know. A Unity great God recommended me: If you want to learn computer graphics programming (the basis of game programming), you can learn unityshader, and then learn OpenGL and DX. Do not say nonsense, according to my style, are directly to see the example, the author of the tutorial is inclined to a fool-style, should be suitable for getting started.

Prerequisite: Install the Unity and VS, and have 3 days of Unity use experience.

First step: Open a new project. Create a Shader in the content browser .

The name is:

Second step: Double-click to open the view:

Shader"custom/shad0"{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 $Cgprogram//physically based standard lighting model, and enable Shadows on all light types        #pragmaSurface Surf Standard Fullforwardshadows//Use Shader Model 3.0 target, to get nicer looking lighting        #pragmaTarget 3.0sampler2d _maintex; structInput {float2 Uv_maintex;        };        Half _glossiness;        Half _metallic;        Fixed4 _color; voidSurf (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"}

Of course, you do not understand at first, please line by line to see my explanation, the following code and the same as above, just added a detailed comment:

/*The first line declares a shader, named Shad0, stored under the path custom (where the path is not the focus, it is categorized in the custom), and appears to be a statement that is not quite like a struct*/Shader"custom/shad0" {    /*before you get to the first piece of content, take a look at the UV texture. Simply put: A is a picture (called A is a texture), B is a coordinate information (called B is UV), B to take a is the essence of texture mapping, for a simple example: a color is as follows: Red yellow blue green B coordinates information as follows: (0,0) (0,1) Then take out to get the texture map is: red green and green yellow like this, is not very boring?    When the above points reach a very large magnitude, it is very meaningful.    No more, you also need to understand the concept of specular highlights and metal degrees, Baidu (or skip this knowledge point to continue to look down). */    /*First Block: attribute declaration*/Properties {_color ("Color", Color) = (1,1,1,1)        /*A variable declared with the _xx declaration method is called a property, the syntax of this sentence is: _xxx (display name, data type) = Default display name is visible in unity, color is actually a data type (like int, but the latter is very simple, is        base data type). What are the data types (refer to the above blog post): Color-a color that is defined by four quantities of rgba (red, green, and transparent); 2D-a map of 2 of the order size (256,512, and so on). This poster will be converted to the corresponding color of each pixel based on the model Uvs after sampling, which is eventually displayed; Rect-a map of a non-2-order size; cube-that is, cube map texture (cubic texture), which is simply the combination of 6 linked 2D maps , mainly used for reflection (such as Sky box and dynamic reflection), will also be converted to the corresponding point of sampling; Range (min, max)-a floating-point number between the minimum and maximum values, typically used as a parameter to adjust some of the shader properties (such as the cutoff value for transparency rendering can be from 0 to 1 value, etc.); float-any one of the floating-point numbers; Vector-a four-dimensional number; look at the default (1,1,1,1), which is the shape (g,b,a,a), where transparency A is 0 o'clock, transparent, and 1 o'clock, which means completely opaque, so it should be called No        Transparency. */_maintex ("Albedo (RGB)", 2D) =" White" {}        /*here is a picture, this picture here is just blank to indicate*/_glossiness ("Smoothness", Range (0,1)) =0.5        /*high light is set to. 5*/_metallic ("Metallic", Range (0,1)) =0.0        /*Metal Degree*/    }    /*The second piece: What is Subshader, if you have used unreal 4, it is easy to understand, in fact, Subshader corresponds to UE4 in the material expression. What are the material expressions in UE4 or the shader nature in unity?    In simple terms, the image is processed to get another picture (such as the process of using a picture to +uv a texture map).    Subshader is actually defining the process of image processing. */Subshader {/*tags specify a hybrid model. What is a hybrid model? See Figure 1 below, of course, the hybrid model is the concept in UE4. 

Fig . 1:

Here's a more accurate explanation than unity: Background-the first called Render, used to render the sky box or background Geometry-This is the default value for rendering non-transparent objects (in general, most of the objects in the scene should be non-transparent) alphatest-To render alpha test pixels, setting a queue for alphatest alone is out of efficiency considerations Transparent-to render a transparent object from a backward forward order Overlay-The effect used to render the overlay is the final stage of the rendering (such as a lens flare and other effects)*/Tags {"Rendertype"="Opaque" }        /*LOD represents the level of detail rendering (also known as quality, coarse/delicate) when the machine is poor, the material is not valid (that is, the shader strike) when the evaluation value is less than 200. When the machine performance is good, greater than 200, the shader continue to work.        That's the way you have personality.        Don't be discouraged, the following content is the most important. */LOD $                /*This is a marker: Cgprogram, which indicates that this is a computer graph programming*/Cgprogram//physically based standard lighting model, and enable Shadows on all light types        #pragmaSurface Surf Standard Fullforwardshadows/*take a look at this strange function declaration: #pragma the code for the surface shader surffunction shader (in this case the surf below) Lightmodel (the concept of lighting, skip first) [Optional parameters] */        //Use Shader Model 3.0 target, to get nicer looking lighting        #pragmaTarget 3.0/*in the words of the author: sampler2d is a picture ...            (Remember, that is the above-mentioned a picture) put a paragraph introduction: The next sentence sampler2d _maintex;,sampler2d is a what?            In fact, in CG, SAMPLER2D is a data container interface that is bound to texture. Wait a minute.. This argument is still too complex, simple to understand, so-called after the texture (map) is just a piece of memory storage, using the RGB (and maybe a) channel, and each channel 8bits of data.            In particular, to know the correspondence between pixels and coordinates, and to get the data, we can not always go to calculate the memory address or offset at once, so it is possible to manipulate the map through sampler2d.            More simply, sampler2d is the type of 2D map in GLSL, corresponding, Sampler1d,sampler3d,samplercube and so on.            After explaining what sampler2d is, you need to explain why you need a statement of _maintex here, and we have not already declared it in the properties as a decal. The answer is that the shader we use for the example is actually made up of two relatively separate blocks, the outer attribute declaration, the rollback, and so on, which unity can use and compile directly shaderlab; now we are in cgprogram ...            Endcg Such a code block, this is a piece of CG program. For this CG program, to access the variables defined in properties, you must declare it with the same name as the previous variable! "Attention here!!!" "So actually sampler2d _maintex, the thing is to re-declare and link _maintex, so that the next CG program can use this variable." */sampler2d _maintex; /*This is a very simple struct, called input, which has a FLOAT2 data type, which is a two-dimensional float vector, i.e. (a, b). */        structInput {float2 Uv_maintex;        }; /*hold on, here are a few variables: half type of two, one of the fixed4 type, half type represents semi-precision floating-point number, good computational performance but low precision, and float and double is the same type of floating-point number; Fixed4 unknown, but the effect is four-dimensional Vector*/half _glossiness;//must be declared with the same name as the previous variable! "Attention here!!!" "half _metallic;//must be declared with the same name as the previous variable! "Attention here!!!" "fixed4 _color;//must be declared with the same name as the previous variable! "Attention here!!!" "        /*the core processing function: Surf, enter a two-dimensional floating point information, that is, the above Uv_maintex, output an O for the material (InOut like C + + in accordance with the introduction, although not returned, but also has the effect of information)*/        voidSurf (Input in, InOut surfaceoutputstandard o) {//Albedo comes from a texture tinted by colorFixed4 C = tex2d (_maintex, In.uv_maintex) *_color; /*look here: tex2d is said before the "use UV to get a picture texture map" approach, and then multiplied by _color, where the multiplication of the color algorithm, their own experience (this _color default value of 1,1,1,1, so the default does not affect) The author here can know: Fixed4 represents a four-dimensional vector (used to represent the color is quite appropriate.) In addition, it is a fixed-point decimal rather than a floating-point decimal.*/O.albedo=C.rgb; /*inout surfaceoutputstandard o What variables are included in this structure: struct Surfaceoutput {half3 Albedo     ;     The color of the pixel half3 Normal;   The normal value of pixels is half3 emission;    The divergence color of pixels half specular;       Pixel specular highlight half Gloss;       The luminous intensity of the pixel half Alpha;            transparency of Pixels}; */            //metallic and smoothness come from slider variablesO.metallic =_metallic; O.smoothness=_glossiness; O.alpha=C.A; } ENDCG/*End CG Encoding*/} FallBack"Diffuse"        //It's not quite clear here, let's go first. }

Step three: Look at the code that has no comments after reading it, organize for 10 minutes, and then continue.

The fourth step: the tutorial of that reference is finished here, I make up the ending:

Import a picture :

Fifth Step: Create a material Material,

Select Shader in the details :

is not very confused, why do you want to do this? Remember, the essence of shader is to convert images into Material algorithms.

Sixth step: Select a picture:

Then see the effect at the bottom right: (Toggle the preview style at the point arrow)

Seventh Step: Create some new objects and put them in this material:

Wait: There seems to be no reaction? Because there is no light, you can see the effect by adding direct light:

--Original small Jiang Cun son of Wen Jie [email protected] , 7 months a day 22:29:44

Unity Shader Getting Started tutorial (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.