Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Cg Programming/Unity/Diffuse Reflection

From Wikibooks, open books for an open world
<Cg Programming |Unity
The light reflection from the surface of the moon is (in a good approximation) only diffuse.

This tutorial coversper-vertex diffuse reflection.

It's the first in a series of tutorials about basic lighting in Unity. In this tutorial, we start with diffuse reflection from a single directional light source and then include point light sources and multiple light sources (using multiple passes). Further tutorials cover extensions of this, in particular specular reflection, per-pixel lighting, and two-sided lighting.

Diffuse reflection can be computed using the surface normal vector N and the light vector L, i.e. the vector to the light source.

Diffuse Reflection

[edit |edit source]

The moon exhibits almost exclusively diffuse reflection (also called Lambertian reflection), i.e. light is reflected into all directions without specular highlights. Other examples of such materials are chalk and matte paper; in fact, any surface that appears dull and matte.

In the case of perfect diffuse reflection, the intensity of the observed reflected light depends on the cosine of the angle between the surface normal vector and the ray of the incoming light. As illustrated in the figure to the left, it is common to consider normalized vectors starting in the point of a surface, where the lighting should be computed: the normalized surface normal vectorN is orthogonal to the surface and the normalized light directionL points to the light source.

For the observed diffuse reflected lightIdiffuse{\displaystyle I_{\text{diffuse}}}, we need the cosine of the angle between the normalized surface normal vectorN and the normalized direction to the light sourceL, which is the dot productN·L because the dot producta·b of any two vectorsa andb is:

ab=|a||b|cos(a,b){\displaystyle \mathbf {a} \cdot \mathbf {b} =\left\vert \mathbf {a} \right\vert \left\vert \mathbf {b} \right\vert \cos \measuredangle (\mathbf {a} ,\mathbf {b} )}.

In the case of normalized vectors, the lengths |a| and |b| are both 1.

If the dot productN·L is negative, the light source is on the “wrong” side of the surface and we should set the reflection to 0. This can be achieved by using max(0,N·L), which makes sure that the value of the dot product is clamped to 0 for negative dot products. Furthermore, the reflected light depends on the intensity of the incoming lightIincoming{\displaystyle I_{\text{incoming}}} and a material constantkdiffuse{\displaystyle k_{\text{diffuse}}} for the diffuse reflection: for a black surface, the material constantkdiffuse{\displaystyle k_{\text{diffuse}}} is 0, for a white surface it is 1. The equation for the diffuse reflected intensity is then:

Idiffuse=Iincomingkdiffusemax(0,NL){\displaystyle I_{\text{diffuse}}=I_{\text{incoming}}\,k_{\text{diffuse}}\max(0,\mathbf {N} \cdot \mathbf {L} )}

For colored light, this equation applies to each color component (e.g. red, green, and blue). Thus, if the variablesIdiffuse{\displaystyle I_{\text{diffuse}}},Iincoming{\displaystyle I_{\text{incoming}}}, andkdiffuse{\displaystyle k_{\text{diffuse}}} denote color vectors and the multiplications are performed component-wise (which they are for vectors in Cg), this equation also applies to colored light. This is what we actually use in the shader code.

Shader Code for One Directional Light Source

[edit |edit source]

If we have only one directional light source, the shader code for implementing the equation forIdiffuse{\displaystyle I_{\text{diffuse}}} is relatively small. In order to implement the equation, we follow the questions about implementing equations, which were discussed inSection “Silhouette Enhancement”:

  • Should the equation be implemented in the vertex shader or the fragment shader? We try the vertex shader here. InSection “Smooth Specular Highlights”, we will look at an implementation in the fragment shader.
  • In which coordinate system should the equation be implemented? We try world space by default in Unity. (Which turns out to be a good choice here because Unity provides the light direction in world space.)
  • Where do we get the parameters from? The answer to this is a bit longer:

We use a shader property (seeSection “Shading in World Space”) to let the user specify the diffuse material colorkdiffuse{\displaystyle k_{\text{diffuse}}}. We can get the direction to the light source in world space from the Unity-specific uniform_WorldSpaceLightPos0 and the light colorIincoming{\displaystyle I_{\text{incoming}}} from the Unity-specific uniform_LightColor0. As mentioned inSection “Shading in World Space”, we have to tag the shader pass withTags {"LightMode" = "ForwardBase"} to make sure that these uniforms have the correct values. (Below we will discuss what this tag actually means.) We get the surface normal vector in object coordinates from the vertex input parameter with semanticNORMAL. Since we implement the equation in world space, we have to convert the surface normal vector from object space to world space as discussed inSection “Silhouette Enhancement”.

The shader code then looks like this:

Shader"Cg per-vertex diffuse lighting"{Properties{_Color("Diffuse Material Color",Color)=(1,1,1,1)}SubShader{Pass{Tags{"LightMode"="ForwardBase"}// make sure that all uniforms are correctly setCGPROGRAM#pragma vertex vert#pragma fragment frag#include"UnityCG.cginc"uniformfloat4_LightColor0;// color of light source (from "UnityLightingCommon.cginc")uniformfloat4_Color;// define shader property for shadersstructvertexInput{float4vertex:POSITION;float3normal:NORMAL;};structvertexOutput{float4pos:SV_POSITION;float4col:COLOR;};vertexOutputvert(vertexInputinput){vertexOutputoutput;float4x4modelMatrix=unity_ObjectToWorld;float4x4modelMatrixInverse=unity_WorldToObject;float3normalDirection=normalize(mul(float4(input.normal,0.0),modelMatrixInverse).xyz);// alternative:// float3 normalDirection = UnityObjectToWorldNormal(input.normal);float3lightDirection=normalize(_WorldSpaceLightPos0.xyz);float3diffuseReflection=_LightColor0.rgb*_Color.rgb*max(0.0,dot(normalDirection,lightDirection));output.col=float4(diffuseReflection,1.0);output.pos=UnityObjectToClipPos(input.vertex);returnoutput;}float4frag(vertexOutputinput):COLOR{returninput.col;}ENDCG}}Fallback"Diffuse"}

When you use this shader, make sure that there is only one light source in the scene, which has to be directional. If there is no light source, you can create a directional light source by selectingGame Object > Light > Directional Light from the main menu.

Fallback Shaders

[edit |edit source]

The lineFallback "Diffuse" in the shader code defines a built-in fallback shader in case Unity doesn't find an appropriate subshader. For our example, Unity would use the fallback shader if it doesn't use the “forward rendering path” (see below). By choosing the specific name “_Color” for our shader property, we make sure that this built-in fallback shader can also access it. The source code of the built-in shaders is available atUnity's website. Inspection of this source code appears to be the only way to determine a suitable fallback shader and the names of the properties that it is using.

Shader Code for Multiple Directional (Pixel) Lights

[edit |edit source]

So far we have only considered a single light source. In order to handle multiple light sources, Unity chooses various techniques depending on the rendering and quality settings. In the tutorials here, we will only cover the “Forward Rendering Path”. (Moreover, all cameras should be configured to use the player settings, which they are by default.)

In this tutorial we consider only Unity's so-calledpixel lights. For the first pixel light (which always is a directional light), Unity calls the shader pass tagged withTags { "LightMode" = "ForwardBase" } (as in our code above). For each additional pixel light, Unity calls the shader pass tagged withTags { "LightMode" = "ForwardAdd" }. In order to make sure that all lights are rendered as pixel lights, you have to make sure that the quality settings allow for enough pixel lights: SelectEdit > Project Settings > Quality and then increase the number labeledPixel Light Count in any of the quality settings that you use. If there are more light sources in the scene than pixel light count allows for, Unity renders only the most important lights as pixel lights. Alternatively, you can set theRender Mode of all light sources toImportant in order to render them as pixel lights. (SeeSection “Multiple Lights” for a discussion of the less importantvertex lights.)

Our shader code so far is OK for theForwardBase pass. For theForwardAdd pass, we need to add the reflected light to the light that is already stored in the framebuffer. To this end, we just have to configure the blending to add the new fragment output color to the color in the framebuffer. As discussed inSection “Transparency”, this is achieved by an additive blend equation, which is specified by this line:

Blend One One

Blending automatically clamps all results between 0 and 1; thus, we don't have to worry about colors or alpha values greater than 1.

All in all, our new shader for multiple directional lights becomes:

Shader"Cg per-vertex diffuse lighting"{Properties{_Color("Diffuse Material Color",Color)=(1,1,1,1)}SubShader{Pass{Tags{"LightMode"="ForwardBase"}// pass for first light sourceCGPROGRAM#pragma vertex vert#pragma fragment frag#include"UnityCG.cginc"uniformfloat4_LightColor0;// color of light source (from "UnityLightingCommon.cginc")uniformfloat4_Color;// define shader property for shadersstructvertexInput{float4vertex:POSITION;float3normal:NORMAL;};structvertexOutput{float4pos:SV_POSITION;float4col:COLOR;};vertexOutputvert(vertexInputinput){vertexOutputoutput;float4x4modelMatrix=unity_ObjectToWorld;float4x4modelMatrixInverse=unity_WorldToObject;float3normalDirection=normalize(mul(float4(input.normal,0.0),modelMatrixInverse).xyz);float3lightDirection=normalize(_WorldSpaceLightPos0.xyz);float3diffuseReflection=_LightColor0.rgb*_Color.rgb*max(0.0,dot(normalDirection,lightDirection));output.col=float4(diffuseReflection,1.0);output.pos=UnityObjectToClipPos(input.vertex);returnoutput;}float4frag(vertexOutputinput):COLOR{returninput.col;}ENDCG}Pass{Tags{"LightMode"="ForwardAdd"}// pass for additional light sourcesBlendOneOne// additive blendingCGPROGRAM#pragma vertex vert#pragma fragment frag#include"UnityCG.cginc"uniformfloat4_LightColor0;// color of light source (from "UnityLightingCommon.cginc")uniformfloat4_Color;// define shader property for shadersstructvertexInput{float4vertex:POSITION;float3normal:NORMAL;};structvertexOutput{float4pos:SV_POSITION;float4col:COLOR;};vertexOutputvert(vertexInputinput){vertexOutputoutput;float4x4modelMatrix=unity_ObjectToWorld;float4x4modelMatrixInverse=unity_WorldToObject;float3normalDirection=normalize(mul(float4(input.normal,0.0),modelMatrixInverse).xyz);float3lightDirection=normalize(_WorldSpaceLightPos0.xyz);float3diffuseReflection=_LightColor0.rgb*_Color.rgb*max(0.0,dot(normalDirection,lightDirection));output.col=float4(diffuseReflection,1.0);output.pos=UnityObjectToClipPos(input.vertex);returnoutput;}float4frag(vertexOutputinput):COLOR{returninput.col;}ENDCG}}Fallback"Diffuse"}

This appears to be a rather long shader; however, both passes are identical apart from the tag and theBlend setting in theForwardAdd pass.

Changes for a Point Light Source

[edit |edit source]

In the case of a directional light source_WorldSpaceLightPos0 specifies the direction from where light is coming. In the case of a point light source (or a spot light source), however,_WorldSpaceLightPos0 specifies the position of the light source in world space and we have to compute the direction to the light source as the difference vector from the position of the vertex in world space to the position of the light source. Since the 4th coordinate of a point is 1 and the 4th coordinate of a direction is 0, we can easily distinguish between the two cases:

float3lightDirection;if(0.0==_WorldSpaceLightPos0.w)// directional light?{lightDirection=normalize(_WorldSpaceLightPos0.xyz);}else// point or spot light{lightDirection=normalize(_WorldSpaceLightPos0.xyz-mul(modelMatrix,input.vertex).xyz);}

While there is no attenuation of light for directional light sources, we should add some attenuation with distance to point and spot light source. As light spreads out from a point in three dimensions, it's covering ever larger virtual spheres at larger distances. Since the surface of these spheres increases quadratically with increasing radius and the total amount of light per sphere is the same, the amount of light per area decreases quadratically with increasing distance from the point light source. Thus, we should divide the intensity of the light source by the squared distance to the vertex.

Since a quadratic attenuation is rather rapid, we use a linear attenuation with distance, i.e. we divide the intensity by the distance instead of the squared distance. The code could be:

float3lightDirection;floatattenuation;if(0.0==_WorldSpaceLightPos0.w)// directional light?{attenuation=1.0;// no attenuationlightDirection=normalize(_WorldSpaceLightPos0.xyz);}else// point or spot light{float3vertexToLightSource=_WorldSpaceLightPos0.xyz-mul(modelMatrix,input.vertex).xyz;floatdistance=length(vertexToLightSource);attenuation=1.0/distance;// linear attenuationlightDirection=normalize(vertexToLightSource);}

The factorattenuation should then be multiplied with_LightColor0 to compute the incoming light; see the shader code below. Note that spot light sources have additional features, which are beyond the scope of this tutorial.

Also note that this code is unlikely to give you the best performance because anyif is usually quite costly. Since_WorldSpaceLightPos0.w is either 0 or 1, it is actually not too hard to rewrite the code to avoid the use ofif and optimize a bit further:

float3vertexToLightSource=_WorldSpaceLightPos0.xyz-mul(modelMatrix,input.vertex*_WorldSpaceLightPos0.w).xyz;floatone_over_distance=1.0/length(vertexToLightSource);floatattenuation=lerp(1.0,one_over_distance,_WorldSpaceLightPos0.w);float3lightDirection=vertexToLightSource*one_over_distance;

However, we will use the version withif for clarity. (“Keep it simple, stupid!”)

The complete shader code for multiple directional and point lights is:

Shader"Cg per-vertex diffuse lighting"{Properties{_Color("Diffuse Material Color",Color)=(1,1,1,1)}SubShader{Pass{Tags{"LightMode"="ForwardBase"}// pass for first light sourceCGPROGRAM#pragma vertex vert#pragma fragment frag#include"UnityCG.cginc"uniformfloat4_LightColor0;// color of light source (from "UnityLightingCommon.cginc")uniformfloat4_Color;// define shader property for shadersstructvertexInput{float4vertex:POSITION;float3normal:NORMAL;};structvertexOutput{float4pos:SV_POSITION;float4col:COLOR;};vertexOutputvert(vertexInputinput){vertexOutputoutput;float4x4modelMatrix=unity_ObjectToWorld;float4x4modelMatrixInverse=unity_WorldToObject;float3normalDirection=normalize(mul(float4(input.normal,0.0),modelMatrixInverse).xyz);float3lightDirection;floatattenuation;if(0.0==_WorldSpaceLightPos0.w)// directional light?{attenuation=1.0;// no attenuationlightDirection=normalize(_WorldSpaceLightPos0.xyz);}else// point or spot light{float3vertexToLightSource=_WorldSpaceLightPos0.xyz-mul(modelMatrix,input.vertex).xyz;floatdistance=length(vertexToLightSource);attenuation=1.0/distance;// linear attenuationlightDirection=normalize(vertexToLightSource);}float3diffuseReflection=attenuation*_LightColor0.rgb*_Color.rgb*max(0.0,dot(normalDirection,lightDirection));output.col=float4(diffuseReflection,1.0);output.pos=UnityObjectToClipPos(input.vertex);returnoutput;}float4frag(vertexOutputinput):COLOR{returninput.col;}ENDCG}Pass{Tags{"LightMode"="ForwardAdd"}// pass for additional light sourcesBlendOneOne// additive blendingCGPROGRAM#pragma vertex vert#pragma fragment frag#include"UnityCG.cginc"uniformfloat4_LightColor0;// color of light source (from "UnityLightingCommon.cginc")uniformfloat4_Color;// define shader property for shadersstructvertexInput{float4vertex:POSITION;float3normal:NORMAL;};structvertexOutput{float4pos:SV_POSITION;float4col:COLOR;};vertexOutputvert(vertexInputinput){vertexOutputoutput;float4x4modelMatrix=unity_ObjectToWorld;float4x4modelMatrixInverse=unity_WorldToObject;float3normalDirection=normalize(mul(float4(input.normal,0.0),modelMatrixInverse).xyz);float3lightDirection;floatattenuation;if(0.0==_WorldSpaceLightPos0.w)// directional light?{attenuation=1.0;// no attenuationlightDirection=normalize(_WorldSpaceLightPos0.xyz);}else// point or spot light{float3vertexToLightSource=_WorldSpaceLightPos0.xyz-mul(modelMatrix,input.vertex).xyz;floatdistance=length(vertexToLightSource);attenuation=1.0/distance;// linear attenuationlightDirection=normalize(vertexToLightSource);}float3diffuseReflection=attenuation*_LightColor0.rgb*_Color.rgb*max(0.0,dot(normalDirection,lightDirection));output.col=float4(diffuseReflection,1.0);output.pos=UnityObjectToClipPos(input.vertex);returnoutput;}float4frag(vertexOutputinput):COLOR{returninput.col;}ENDCG}}Fallback"Diffuse"}

Note that the light source in theForwardBase pass always is a directional light; thus, the code for the first pass could actually be simplified. On the other hand, using the same Cg code for both passes, makes it easier to copy & paste the code from one pass to the other in case we have to edit the shader code.

Changes for a Spotlight

[edit |edit source]

Unity implements spotlights with the help of cookie textures as described inSection “Cookies”; however, this is somewhat advanced. Here, we treat spotlights as if they were point lights.

Summary

[edit |edit source]

Congratulations! You just learned how Unity's per-pixel lights work. This is essential for the following tutorials about more advanced lighting. We have also seen:

  • What diffuse reflection is and how to describe it mathematically.
  • How to implement diffuse reflection for a single directional light source in a shader.
  • How to extend the shader for point light sources with linear attenuation.
  • How to further extend the shader to handle multiple per-pixel lights.

Further reading

[edit |edit source]

If you still want to know more

<Cg Programming/Unity

Unless stated otherwise, all example source code on this page is granted to the public domain.
Retrieved from "https://en.wikibooks.org/w/index.php?title=Cg_Programming/Unity/Diffuse_Reflection&oldid=4336523"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp