Book Image

Unity 3 Game Development HOTSHOT

By : Jate Wittayabundit
Book Image

Unity 3 Game Development HOTSHOT

By: Jate Wittayabundit

Overview of this book

<p>Unity 3d is the game engine of choice for creating professional looking games at no cost. Its combination of powerful tools and outstanding community support make it the natural choice for experienced and aspiring game developers. <br /><br />Unity3D Game Development Hotshot will show you how to exploit the full array of Unity3Dtechnology in order to create an advanced gaming experience for the user. It has eight exciting and challenging projects with step- by-step explanations, diagrams, screenshots, and downloadable materials.<br /><br />Every project is designed to push your Unity skills to the very limits and beyond. You will create a hero/heroine for a role playing game. Create a menu for the RPG game allowing you to customize your character with powerups, armor, and weapons. You will shade, model, rig, and animate your hero/heroine. The end result will be a&nbsp; character on the level of Final Fantasy, far superior to a simple sprite.<br /><br />Now for some damage - rocket launchers! Typically the most powerful weapons in any first person shooter, you will create a rocket launcher that has fire and smoke particles and most importantly causes splash damage for that all important area effect. Create AI controlled enemies for your hero/heroine to eliminate with the rocket launcher. Forge&nbsp; a destructible&nbsp; interactive world so if the rocket launchers miss their target they will at least cause significant damage to the surrounding environment. Learn to save and load your game so you can take a break from the action for life’s necessities like going to the bathroom. Incorporate social gaming by uploading scores online so everyone can see the carnage.</p>
Table of Contents (19 chapters)
Unity 3 Game Development HOTSHT
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Surface shaders


To use the surface shaders, you need to define a surface function (void surf(Input IN, inout SurfaceOutput o)) that takes any UVs or data you need as input, and fills in the output structure SurfaceOutput. The SurfaceOutput structure basically describes properties of the surface (that is albedo color, normal, emission, specularity, and so on). Then, you write this code in Cg/HLSL.

Surface shader compiler then figures out the inputs that are needed, the outputs that are filled, and so on, and generates actual vertex and pixel shaders as well as rendering passes to handle forward and deferred rendering.

The surface shaders placed inside CGPROGRAM...ENDCG block, must be placed inside the SubShader block, and uses the #pragma surface ... directive to indicate that it's a surface shader. You will see that the surface shaders placed inside CGPROGRAM and ENDCG block in the following example:

Shader "My Lambert" {
  Properties {
    _MainTex ("Texture", 2D) = "white" {}
  }
  SubShader {
    Tags { "RenderType"="Opaque" }
    LOD 200 //Optional that allows the script to turned the shader on or off when the player's hardware didn't support your shader.
    CGPROGRAM
    #pragma surface surf Lambert
    sampler2D _MainTex;  

    struct Input {
      float2 uv_MainTex;
    };
    void surf (Input IN, inout SurfaceOutput o) {
      fixed4 c = tex2D (_MainTex, IN.uv_MainTex);
      o.Albedo = c.rgb;
      o.Alpha = c.a;
    }
    ENDCG
  }
  FallBack "Diffuse"
}

#pragma surface

The #pragma surface directive is:

#pragma surface surfaceFunction lightModel [optionalparams] 

Required parameters

The following are the required parameters for the #pragma surface directive:

  • surfaceFunction —the Cg function that has surface shader code. The function should have the form void surf (Input IN, inout SurfaceOutput o), where Input is a structure you have defined. Input should contain any texture coordinates and extra automatic variables needed by the surface function.

  • lightModel —lighting model to use. Built-in ones are Lambert (diffuse) and BlinnPhong (specular). You can also write your own by using the following custom lighting models:

    • half4 LightingName (SurfaceOutput s, half3 lightDir, half atten);: This is used in a forward rendering path for light models that are not view direction dependent (for example, diffuse).

    • half4 LightingName (SurfaceOutput s, half3 lightDir, half3 viewDir, half atten);: This is used in a forward rendering path for light models that are view direction dependent.

    • half4 LightingName_PrePass (SurfaceOutput s, half4 light);: This is used in a deferred lighting path.

      Tip

      Note that you don't need to declare all functions. A lighting model either uses view direction or it does not. Similarly, if the lighting model will not work in deferred lighting, you just do not declare the _PrePass function. All the shaders that use it will compile to forward rendering only, such as the shader that we did in Chapter 3, The Hero/Heroine Part I—Models and Shaders. We don't need the _PrePass function because our shader needs the view direction(viewDir) and the light direction(lightDir) for our custom lighting function to calculate the ramp effect for the cartoon style shader (Toon Shader/Cel Shader), which is only available in forward rendering.

  • Optional parameters [optionalparams]:

    Type

    Description

    alpha

    Alpha blending mode. Use this for semitransparent shaders.

    alphatest:VariableName

    Alpha testing mode. Use this for transparent-cutout shaders. Cutoff value is in float variable with VariableName.

    vertex:VertexFunction

    Custom vertex modification function. See the Tree Bark shader, for example.

    exclude_path:prepass or exclude_path:forwar d

    Do not generate passes for given rendering path.

    addshadow

    Add shadow caster and collector passes. Commonly used with custom vertex modification, so that shadow casting also gets any procedural vertex animation.

    dualforward

    Use dual lightmaps in forward path.

    fullforwardshadows

    Support all shadow types in forward rendering path.

    decal:add

    Additive decal shader (for example, terrain AddPass).

    decal:blend

    Semitransparent decal shader.

    softvegetation

    Makes the surface shader only be rendered when Soft Vegetation is on.

    Noambient

    Do not apply any ambient lighting or spherical harmonics lights.

    novertexlights

    Do not apply any spherical harmonics or per-vertex lights in forward rendering.

    nolightmap

    Disables lightmap support in this shader (makes a shader smaller).

    Noforwardadd

    Disables forward rendering additive pass. This makes the shader support one full directional light, with all other lights computed per-vertex/SH. Makes shaders smaller as well.

    approxview

    Computes normalized view direction per-vertex instead of per-pixel, for shaders that need it. This is faster, but view direction is not entirely correct when camera gets close to the surface.

    halfasview

    Pass half-direction vector into the lighting function instead of view-direction. Half-direction will be computed and normalized per vertex. This is faster, but not entirely correct.

Additionally, you can write #pragma debug inside the CGPROGRAM block, and then the surface compiler will spit out a lot of comments of the generated code. You can view that using Open Compiled Shader in shader inspector.

Surface shaders input structure

The input structure Input generally has any texture coordinates needed by the shader. Texture coordinates must be named uv followed by a texture name (or start it with uv2 to use the second texture coordinate set).

Example:

Properties {
    _MainTex ("Texture", 2D) = "white" {}
  }
  ......

    sampler2D _MainTex;
   ......
     struct Input {
       float2 uv_MainTex;
     };

We can also have the additional values that can be put into the input structure:

Type

Description

float3 viewDir

Contains view direction, for computing parallax effects, rim lighting, and so on.

float4 with COLOR semantic

Contains interpolated per-vertex color.

float4 screenPos

Contains screen space position for reflection effects. Used by WetStreet shader in Dark Unity, for example.

float3 worldPos

Contains world space position.

float3 worldRefl

Contains world reflection vector if surface shader does not write to o.Normal. See Reflect-Diffuse shader, for example.

float3 worldNormal

Contains world normal vector if surface shader does not write to o.Normal.

float3 worldRefl; INTERNAL_DATA

Contains world reflection vector if surface shader writes to o.Normal. To get the reflection vector based on per-pixel normal map, use WorldReflectionVector (IN, o.Normal). See Reflect-Bumped shader, for example.

float3 worldNormal; INTERNAL_DATA

Contains world normal vector if surface shader writes to o.Normal. To get the normal vector based on per-pixel normal map, use WorldNormalVector (IN, o.Normal).

SurfaceOutput structure

The standard output structure of surface shaders is as follows:

struct SurfaceOutput {     
  fixed3 Albedo;     
  fixed3 Normal;     
  fixed3 Emission;     
  half Specular;     
  fixed Gloss;     
  fixed Alpha; 
};

You can also find it in the Lighting.cginc file inside Unity in {unity install path}/Data/CGIncludes/Lighting.cginc on Windows, and in /Applications/Unity/Unity.app/Contents/CGIncludes/Lighting.cginc on a Mac.