A cat can learn. Unity3d shader Getting Started Guide (i)

Source: Internet
Author: User
a cat can learn. Unity3d shader Getting Started Guide (i)
Original source: https://onevcat.com/2013/07/shader-tutorial-1/

Motive

It's been a while since I've been using Unity3d, but most of the time it's on the surface, and it's much easier to use this engine as a script control, with little understanding of the deeper layers. While the Unity engine design is designed to create a simple 3D engine that does not require the developer to worry about, it is only superficial to use and may not be able to achieve the desired position, so this situation must change. From where to start, seems to have a sentence called will write shader is a master, so, want to see from the beginning of shader can make their own level to reach a bit more, then, with this series (I hope I can persist in writing it, although it should be dragged for about six months or so).

Unity3d All rendering work is inseparable from shaders (Shader), if you and I have recently begun to be interested in Shader programming, perhaps you and I have the same confusion: how to get started. Unity3d provides some shader manuals and documentation (here, here and here), but the content is scattered and the learning ladder is slightly steeper. This is rather unfriendly to newcomers like me who have never been in touch with the content before. Although there are some shader introduction and experience at home and abroad, but also there is the problem of content dispersion, many tutorials in the previous chapter only introduced the basic concepts, and then immediately moved out a super complex example, for many basic usage does not explain. Maybe it's no problem for shader skilled developers, but I believe there are not a few people like me. After a lot of searching without fruit, I felt it necessary to write a tutorial to introduce some basic steps of shader development in the perspective of an introductory person. In fact, rather than a tutorial, rather than a self-summary, hoping to help people in need.

So, the object of this "tutorial" is generally a new contact with shader development people: Maybe you know what is shader, will also use other people's shader, but only to know some basic built shader name, never open them to view its source code. Want to learn more about shader and developers who have a need for shader development, but have not experienced shader development before.

Of course, because I am in shader development is also a no-no big rookie, this article a lot of content is only in their own understanding plus some may not be very reliable verification and summary. The examples in this article should have a better way to implement, so you are a master and happen to pass by, if there is a good way to implement certain content, I implore you to leave a comment, I will continue to update and maintain this article. some basic concepts Shader and material

If you are doing 3D game development, you must not be unfamiliar with the two words. The Shader (shader) is actually a small program that is responsible for combining the input mesh (mesh) in a specified manner with the input map or color, and then outputting it. The drawing unit can draw the image onto the screen based on this output. The input map or color, plus the corresponding shader, as well as the specific parameters of the shader set, the contents (shader and input parameters) are packaged and stored together, resulting in a material (material). We can then assign the material to the appropriate renderer (renderer) for rendering (output).

So there's nothing particularly magical about shader, it's just a program that provides a good input (color, texture, etc.) and output (the point and color that the renderer can read). What the shader developers have to do is to generate the output based on the input and the calculation transformation.

Shader can be broadly divided into two categories, simply speaking surface shader (surface Shader)-doing most of the work for you, with just a few simple tricks to achieve a lot of good results. Analogy card machine, do not need a lot of effort after the good results can be taken. Fragment shader (Fragment Shader)-Can do more things, but it is also more difficult to write. The primary purpose of using fragment shaders is to develop more complex (or more efficient) targets at lower levels.

Since this is an introductory article, the following introduction will be focused on the surface shader. basic structure of shader program

Because shader code can say that specialization is very strong, it artificially prescribes its basic structure. The structure of an ordinary shader should look like this:

First, there are some attribute definitions that specify what input this code will have. Next is one or more sub-shaders, in which case the child shader is used by the running platform as determined by the actual operation. The child shader is the body of the code, and each child shader contains one or more passes. When calculating shading, the platform selects the most preferred shader, then runs the pass in turn, and then gets the result of the output. Finally, a rollback is specified to handle situations where all subshader cannot run (for example, the target device is too old and all subshader have unsupported features).

It should be stated in advance that, in the actual development of the surface shader, we will write the code directly at the Subshader level, and the system will compile our code into a number of appropriate passes. This is the end of the nonsense, let us actually enter the world of shader. Hello Shader

The Hundred-line document is not as good as an instance, the following is a simple shader code, and then according to the code to verify the above mentioned structure and the elaboration of some basic shader syntax. Because this article is for Unity3d to write shader, so also use Unity3d to demonstrate it. First, create a new shader, you can find it in the project panel, create, select Shader, and then name it diffuse Texture:

Just use a text editor to open the newly created shader:

Shader "Custom/diffuse Texture" {
    Properties {
        _maintex ("Base (RGB)", 2D) = "White" {}
    }
    subshader {
  
   tags {"Rendertype" = "Opaque"}
        LOD

        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"
}


  

If you haven't seen the shader code before, the details will not be understood. But with the introduction of the basic structure above, you should be able to identify the composition of the shader, such as a Properties section, a Subshader, and a fallback. In addition, the first line is just this shader declaration and assigns it a name, such as our instance shader, you can find the shader in the corresponding position when you select shader in the material panel.

Next we talk about the shader, in order to understand the meaning of each statement. Properties

The shader properties are defined in properties{}, and the properties defined here are provided as input to all child shaders. The syntax for the definition of each property is this:

_name ("Display name", type) = Defaultvalue[{options}] _name-The name of the property, simply said to be the variable name, after which the entire shader code will use this name to get the contents of the property Display Name-This string will be displayed in Unity's material editor as the user-readable content of shader-the type of this property, the possible type is represented by the following: color-a color defined by the RGBA (red-green-blue and transparency) four quantities; 2D- A map with a 2 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-the cube map texture (cube texture), which is simply a combination of 6 linked 2D maps, It is mainly used for reflection effects (such as sky boxes and dynamic reflections) and is also converted to the corresponding point sampling; Range (min, max)-a floating-point number between the minimum and maximum values, Generally used as a parameter to adjust shader certain characteristics (such as the cutoff value of transparency rendering can be from 0 to 1, etc.); float-any one floating point; Vector-a four-dimensional number; DefaultValue defines the default value for this property. Specify the initial value of the corresponding property by entering a default value that conforms to the format (some effects may require some specific parameter values to achieve the desired effect, although these values can be adjusted later, but if you specify the desired value by default, it is much easier to do so without having to adjust the time.) Color-an RGBA color defined in 0~1, such as (1,1,1,1); 2d/rect/cube-For a map, the default value can be a string representing the default tint color, either an empty string or "white", "black", "gray", " Bump "One float,range-a specified floating-point Vector-a 4-dimensional number, written as (x,y,z,w) there is another {option}, which is only relevant for 2d,rect or cube maps. At least we have to write a pair of blank {} with nothing after the map when we write the input, and we can write it in the curly braces when we need to open the specific option. If you need to open more than one option at the same time, you can use whitespace delimited. Possible options are objectlinear, Eyelinear, SphereMap, Cubereflect, CubenormaOne of these is the Texgen pattern in OpenGL, which is left in the back for a chance to talk about.

So, the statement of a set of attributes might look like this.

Define a color with a default value of semi-transparent blue
_maincolor ("Main color", color) = (0,0,1,0.5)
//de Fine a texture with a default of white
_texture ("texture", 2D) = ' White ' {}

Now you can see that the Properties section of the shader (and all the other shader) above should have no problem. The next step is the Subshader section. Tags

Surface shaders can be modified by a number of tags, and the hardware determines when the shader is invoked by determining the tags. For example, the first sentence of Subshader in our example

Tags {"Rendertype" = "Opaque"}

Tells the system to call us when rendering non-transparent objects. Unity defines a number of columns such as the rendering process, and rendertype is opaque the obvious is "rendertype" = "Transparent", which is called when rendering objects containing transparent effects. Here tags in fact implies that your shader output is what, if the output is non-transparent objects, that is written in opaque, if you want to render transparent or translucent pixels, it should be written in transparent.

Other useful tags are "ignoreprojector" = "true" (not affected by projectors), "forcenoshadowcasting" = "true" (never produce Shadows) and "Queue" = "xxx" (Specify the render order queue). The point here is that the queue is the label, and if you've ever used unity to mix transparent and opaque objects, you've probably already had a situation where opaque objects can't appear behind a transparent object. This situation is most likely due to incorrect rendering order of shader. The queue specifies the order in which the objects are rendered, and the predefined queue has: Background-the first called Render, used to render the sky box or the back

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.