SlideShare une entreprise Scribd logo
1  sur  58
Beginning Direct3D Game Programming:
10. Shader Detail
jintaeks@gmail.com
Division of Digital Contents, DongSeo University.
May 2016
Decompose a vector
 d=(a·n)
 a⊥=(a·n)n
 a∥=a-a⊥=a-(a·n)n
2
Coordinate Transform
(a·n, a·t, a·b)
3
a
Step1 : Diffuse Light
4
Diffuse Lighting
 The diffuse lighting model following Lambert’s law is
described with the help of two vectors—the light vector L and
the normal vector N.
 The diffuse reflection has its peak (cos(θ) ≡ 1) when L and N
are aligned.
5
Diffuse Lighting
 This diffuse lighting component is usually added to the
ambient lighting component like this:
I = Aintensity * Acolor + Dintensity * Dcolor * N·L + Specular
6
Effect File: Declare Global Variables
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
float4 g_MaterialAmbientColor; // Material's ambient color
float4 g_MaterialDiffuseColor; // Material's diffuse color
float3 g_LightDir; // Light's direction in world space
float4 g_LightDiffuse; // Light's diffuse color
float4 g_LightAmbient = float4(0.5,0.5,0.5,0.5); // Light's ambient color
texture g_MeshTexture; // Color texture for mesh
float g_fTime; // App's time in seconds
float4x4 g_mWorld; // World matrix for object
float4x4 g_mWorldViewProjection; // World * View * Projection matrix
7
Vertex Shader Output Structure
//--------------------------------------------------------------------------------------
// Vertex shader output structure
//--------------------------------------------------------------------------------------
struct VS_OUTPUT
{
float4 Position : POSITION; // vertex position
float4 Diffuse : COLOR0; // vertex diffuse color (note that COLOR0 is clamped
from 0..1)
float2 TextureUV : TEXCOORD0; // vertex texture coords
};
8
Vertex Shader
VS_OUTPUT RenderSceneVS( float4 vPos : POSITION, float3 vNormal : NORMAL, float2
vTexCoord0 : TEXCOORD0, uniform int nUnused, uniform bool bTexture, uniform bool
bAnimate )
{
VS_OUTPUT Output;
float3 vNormalWorldSpace;
float4 vAnimatedPos = vPos;
// Transform the position from object space to homogeneous projection space
Output.Position = mul(vAnimatedPos, g_mWorldViewProjection);
// Transform the normal from object space to world space
vNormalWorldSpace = normalize(mul(vNormal, (float3x3)g_mWorld));
9
Vertex Shader
VS_OUTPUT RenderSceneVS( float4 vPos : POSITION, float3 vNormal : NORMAL, float2
vTexCoord0 : TEXCOORD0, uniform int nUnused, uniform bool bTexture, uniform bool
bAnimate )
{
VS_OUTPUT Output;
…
// Compute simple directional lighting equation
float3 vTotalLightDiffuse = float3(0,0,0);
vTotalLightDiffuse += g_LightDiffuse * max( 0, dot( vNormalWorldSpace,
g_LightDir ) );
Output.Diffuse.rgb = g_MaterialDiffuseColor * vTotalLightDiffuse +
g_MaterialAmbientColor * g_LightAmbient;
Output.Diffuse.a = 1.0f;
// Just copy the texture coordinate through
Output.TextureUV = vTexCoord0;
return Output;
}
10
Pixel Shader
struct PS_OUTPUT
{
float4 RGBColor : COLOR0; // Pixel color
};
PS_OUTPUT RenderScenePS( VS_OUTPUT In, uniform bool bTexture )
{
PS_OUTPUT Output;
// Lookup mesh texture and modulate it with diffuse
if( bTexture )
Output.RGBColor = tex2D(MeshTextureSampler, In.TextureUV) * In.Diffuse;
else
Output.RGBColor = In.Diffuse;
return Output;
}
11
Technique
technique RenderSceneWithTexture1Light
{
pass P0
{
VertexShader = compile vs_2_0 RenderSceneVS( 1, false, false );
PixelShader = compile ps_2_0 RenderScenePS( false );
}
}
12
Client : Declare Global Variables
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
ID3DXFont* g_pFont = NULL; // Font for drawing text
ID3DXSprite* g_pSprite = NULL; // Sprite for batching draw text calls
bool g_bShowHelp = true; // If true, it renders the UI control text
CModelViewerCamera g_Camera; // A model viewing camera
ID3DXEffect* g_pEffect = NULL; // D3DX effect interface
ID3DXMesh* g_pMesh = NULL; // Mesh object
IDirect3DTexture9* g_pMeshTexture = NULL; // Mesh texture
CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared
resources of dialogs
13
OnCreateDevice()
// Read the D3DX effect file
WCHAR str[MAX_PATH];
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"BasicHLSL.fx" ) );
// If this fails, there should be debug output as to
// why the .fx file failed to compile
V_RETURN( D3DXCreateEffectFromFile( pd3dDevice, str, NULL, NULL, dwShaderFlags, NULL,
&g_pEffect, NULL ) );
// Create the mesh texture from a file
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"earthearth.bmp" ) );
V_RETURN( D3DXCreateTextureFromFileEx( pd3dDevice, str, D3DX_DEFAULT, D3DX_DEFAULT,
D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED,
D3DX_DEFAULT, D3DX_DEFAULT, 0,
NULL, NULL, &g_pMeshTexture ) );
14
OnCreateDevice()
// Set effect variables as needed
D3DXCOLOR colorMtrlDiffuse( 1.0f, 1.0f, 1.0f, 1.0f );
D3DXCOLOR colorMtrlAmbient( 0.35f, 0.35f, 0.35f, 0 );
V_RETURN( g_pEffect->SetValue( "g_MaterialAmbientColor", &colorMtrlAmbient, sizeof(
D3DXCOLOR ) ) );
V_RETURN( g_pEffect->SetValue( "g_MaterialDiffuseColor", &colorMtrlDiffuse, sizeof(
D3DXCOLOR ) ) );
V_RETURN( g_pEffect->SetTexture( "g_MeshTexture", g_pMeshTexture ) );
15
OnResetDevice()
HRESULT hr;
V_RETURN( g_DialogResourceManager.OnD3D9ResetDevice() );
V_RETURN( g_SettingsDlg.OnD3D9ResetDevice() );
if( g_pFont )
V_RETURN( g_pFont->OnResetDevice() );
if( g_pEffect )
V_RETURN( g_pEffect->OnResetDevice() );
// Create a sprite to help batch calls when drawing many lines of text
V_RETURN( D3DXCreateSprite( pd3dDevice, &g_pSprite ) );
16
OnFrameRender()
// Render the scene
if( SUCCEEDED( pd3dDevice->BeginScene() ) )
{
// Get the projection & view matrix from the camera class
mWorld = g_mCenterWorld * *g_Camera.GetWorldMatrix();
mProj = *g_Camera.GetProjMatrix();
mView = *g_Camera.GetViewMatrix();
mWorldViewProjection = mWorld * mView * mProj;
D3DXCOLOR arrowColor = D3DXCOLOR( 1, 1, 0, 1 );
V( g_LightControl.OnRender9( arrowColor, &mView, &mProj, g_Camera.GetEyePt() )
);
vLightDir = g_LightControl.GetLightDirection();
vLightDiffuse = g_fLightScale * D3DXCOLOR( 1, 1, 1, 1 );
17
V( g_pEffect->SetValue( "g_LightDir", &vLightDir, sizeof( D3DXVECTOR3 ) ) );
V( g_pEffect->SetValue( "g_LightDiffuse", &vLightDiffuse, sizeof( D3DXVECTOR4 ) )
);
// Update the effect's variables. Instead of using strings, it would
// be more efficient to cache a handle to the parameter by calling
// ID3DXEffect::GetParameterByName
V( g_pEffect->SetMatrix( "g_mWorldViewProjection", &mWorldViewProjection ) );
V( g_pEffect->SetMatrix( "g_mWorld", &mWorld ) );
V( g_pEffect->SetFloat( "g_fTime", ( float )fTime ) );
D3DXCOLOR vWhite = D3DXCOLOR( 1, 1, 1, 1 );
V( g_pEffect->SetValue( "g_MaterialDiffuseColor", &vWhite, sizeof( D3DXCOLOR )
) );
V( g_pEffect->SetFloat( "g_fTime", ( float )fTime ) );
18
V( g_pEffect->SetTechnique( "RenderSceneWithTexture1Light" ) );
// Apply the technique contained in the effect
V( g_pEffect->Begin( &cPasses, 0 ) );
for( iPass = 0; iPass < cPasses; iPass++ )
{
V( g_pEffect->BeginPass( iPass ) );
V( g_pEffect->CommitChanges() );
// Render the mesh with the applied technique
V( g_pMesh->DrawSubset( 0 ) );
V( g_pEffect->EndPass() );
}
V( g_pEffect->End() );
19
OnLostDevice()
void CALLBACK OnLostDevice( void* pUserContext )
{
g_DialogResourceManager.OnD3D9LostDevice();
g_SettingsDlg.OnD3D9LostDevice();
CDXUTDirectionWidget::StaticOnD3D9LostDevice();
if( g_pFont )
g_pFont->OnLostDevice();
if( g_pEffect )
g_pEffect->OnLostDevice();
SAFE_RELEASE( g_pSprite );
}
20
OnDestroyDevice()
void CALLBACK OnDestroyDevice( void* pUserContext )
{
g_DialogResourceManager.OnD3D9DestroyDevice();
g_SettingsDlg.OnD3D9DestroyDevice();
CDXUTDirectionWidget::StaticOnD3D9DestroyDevice();
SAFE_RELEASE( g_pEffect );
SAFE_RELEASE( g_pFont );
SAFE_RELEASE( g_pMesh );
SAFE_RELEASE( g_pMeshTexture );
}
21
Practice: Build and Run BasicHLSL Step1
22
Step2 : Diffuse Light in Local Space
 Use Object space
uniform variables in
Shader to speed
up.
23
Client: OnFrameRender() Differences
24
25
Vertex Shader Differences
26
Practice: Build and Run BasicHLSL Step2
27
Step3 : Specular Light
28
Reflection vector
 r = a - 2(a·n)n
29
Specular Reflection
 Two vectors are used to calculate the specular component—
the Light vector L and the reflection vector R.
 The more L is aligned with R, the brighter the specular light
should be.
30
Half Vector
 If one calculates a halfway vector between the viewer and
light-source vectors we can replace L·R with H·N.
31
Shader Differences
32
Shader Differences
33
34
Client: OnFrameRender() Differences
 Prepare WorldView and WorldViewInv matrices.
35
 Get Object space eye position.
36
 Set Object space eye position.
37
Practice: Build and Run BasicHLSL Step3
38
Step4 : Specular Light in Pixel Shader
 Specular light
calculation in pixel
shader to get more
precise result.
39
Effect Differences
 Add Normal and Eye vector to VS_OUTPUT.
40
Vertex Shader Differences
 Pass Normal and Eye vector to Pixel shader.
41
Pixel Shader Differences
42
Practice: Build and Run BasicHLSL Step4
43
Step5 : Normal Mapping
44
Normal Map
 In 3D computer graphics, normal mapping is a technique
used for faking the lighting of bumps and dents – an
implementation of bump mapping.
 It is used to add details without using more polygons.
• Example of a normal map (center) with the scene it was
calculated from (left) and the result when applied to a flat
surface (right).
45
Diffuse Map
46
Normal Map
 RGB color of pixel in image file is a direction (x,y,z) in tangent
space.
47
Effect Differences: Added normal map texture
48
Added Light vector in tangent space
49
Vertex Shader Differences
50
 Eye and Light vectors must be transformed to tangent space.
51
Pixel Shader
PS_OUTPUT RenderScenePS( VS_OUTPUT In, uniform bool bTexture )
{
PS_OUTPUT Output;
float3 N = 2.0f * tex2D( MeshBumpTextureSampler, In.TextureUV ).xyz - 1.0f;
float3 L = normalize( In.L );
float3 R = reflect( -normalize( In.Eye ), N ); // reflection vector
// Lookup mesh texture and modulate it with diffuse
if( bTexture ) {
Output.RGBColor = tex2D( MeshTextureSampler, In.TextureUV ) *In.Diffuse * max(
0, dot( N, L ) );
} else {
Output.RGBColor = In.Diffuse * max( 0, dot( N, L ) );
}//if.. else..
Output.RGBColor += pow( max( 0, dot( R, L ) ), 10 );
return Output;
}
52
Client: Added normal map texture
53
OnCreateDevice() Differences
54
OnResetDevice() Differences()
D3DVERTEXELEMENT9 decl[] =
{
{ 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
{ 0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 },
{ 0, 24, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0 },
{ 0, 36, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
D3DDECL_END()
};//decl[]
if( g_pMesh ) {
LPD3DXMESH pMesh;
g_pMesh->CloneMesh(
g_pMesh->GetOptions(), decl,
pd3dDevice, &pMesh );
D3DXComputeNormals( pMesh, NULL );
D3DXComputeTangent( pMesh, 0, 0, 0, TRUE, NULL );
SAFE_RELEASE( g_pMesh );
g_pMesh = pMesh;
}//if
55
OnDestroyDevice() Differences
56
References
57
Beginning direct3d gameprogramming10_shaderdetail_20160506_jintaeks

Contenu connexe

Tendances

Tendances (20)

Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeksBeginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
 
Shadow Volumes on Programmable Graphics Hardware
Shadow Volumes on Programmable Graphics HardwareShadow Volumes on Programmable Graphics Hardware
Shadow Volumes on Programmable Graphics Hardware
 
Dsp lecture vol 4 digital filters
Dsp lecture vol 4 digital filtersDsp lecture vol 4 digital filters
Dsp lecture vol 4 digital filters
 
Deep learning with C++ - an introduction to tiny-dnn
Deep learning with C++  - an introduction to tiny-dnnDeep learning with C++  - an introduction to tiny-dnn
Deep learning with C++ - an introduction to tiny-dnn
 
CS 354 Transformation, Clipping, and Culling
CS 354 Transformation, Clipping, and CullingCS 354 Transformation, Clipping, and Culling
CS 354 Transformation, Clipping, and Culling
 
Maximizing performance of 3 d user generated assets in unity
Maximizing performance of 3 d user generated assets in unityMaximizing performance of 3 d user generated assets in unity
Maximizing performance of 3 d user generated assets in unity
 
Show, Attend and Tell: Neural Image Caption Generation with Visual Attention
Show, Attend and Tell: Neural Image Caption Generation with Visual AttentionShow, Attend and Tell: Neural Image Caption Generation with Visual Attention
Show, Attend and Tell: Neural Image Caption Generation with Visual Attention
 
Introducton to Convolutional Nerural Network with TensorFlow
Introducton to Convolutional Nerural Network with TensorFlowIntroducton to Convolutional Nerural Network with TensorFlow
Introducton to Convolutional Nerural Network with TensorFlow
 
CS 354 Graphics Math
CS 354 Graphics MathCS 354 Graphics Math
CS 354 Graphics Math
 
CS 354 Understanding Color
CS 354 Understanding ColorCS 354 Understanding Color
CS 354 Understanding Color
 
Lecture 11 (Digital Image Processing)
Lecture 11 (Digital Image Processing)Lecture 11 (Digital Image Processing)
Lecture 11 (Digital Image Processing)
 
Epsrcws08 campbell isvm_01
Epsrcws08 campbell isvm_01Epsrcws08 campbell isvm_01
Epsrcws08 campbell isvm_01
 
Mathematical tools in dip
Mathematical tools in dipMathematical tools in dip
Mathematical tools in dip
 
2.5D Clip-Surfaces for Technical Visualization
2.5D Clip-Surfaces for Technical Visualization2.5D Clip-Surfaces for Technical Visualization
2.5D Clip-Surfaces for Technical Visualization
 
Automatic Gain Tuning based on Gaussian Process Global Optimization (= Bayesi...
Automatic Gain Tuning based on Gaussian Process Global Optimization (= Bayesi...Automatic Gain Tuning based on Gaussian Process Global Optimization (= Bayesi...
Automatic Gain Tuning based on Gaussian Process Global Optimization (= Bayesi...
 
(Paper Review)3D shape reconstruction from sketches via multi view convolutio...
(Paper Review)3D shape reconstruction from sketches via multi view convolutio...(Paper Review)3D shape reconstruction from sketches via multi view convolutio...
(Paper Review)3D shape reconstruction from sketches via multi view convolutio...
 
Geometry Batching Using Texture-Arrays
Geometry Batching Using Texture-ArraysGeometry Batching Using Texture-Arrays
Geometry Batching Using Texture-Arrays
 
Otsu
OtsuOtsu
Otsu
 
[MIRU2018] Global Average Poolingの特性を用いたAttention Branch Network
[MIRU2018] Global Average Poolingの特性を用いたAttention Branch Network[MIRU2018] Global Average Poolingの特性を用いたAttention Branch Network
[MIRU2018] Global Average Poolingの特性を用いたAttention Branch Network
 
Vgg
VggVgg
Vgg
 

En vedette

Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeksBeginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
JinTaek Seo
 
Email Classifier using Spark 1.3 Mlib / ML Pipeline
Email Classifier using Spark 1.3 Mlib / ML PipelineEmail Classifier using Spark 1.3 Mlib / ML Pipeline
Email Classifier using Spark 1.3 Mlib / ML Pipeline
leorick lin
 

En vedette (20)

Beginning direct3d gameprogrammingmath06_transformations_20161019_jintaeks
Beginning direct3d gameprogrammingmath06_transformations_20161019_jintaeksBeginning direct3d gameprogrammingmath06_transformations_20161019_jintaeks
Beginning direct3d gameprogrammingmath06_transformations_20161019_jintaeks
 
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeksBeginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
 
Beginning direct3d gameprogrammingmath04_calculus_20160324_jintaeks
Beginning direct3d gameprogrammingmath04_calculus_20160324_jintaeksBeginning direct3d gameprogrammingmath04_calculus_20160324_jintaeks
Beginning direct3d gameprogrammingmath04_calculus_20160324_jintaeks
 
Beginning direct3d gameprogramming01_20161102_jintaeks
Beginning direct3d gameprogramming01_20161102_jintaeksBeginning direct3d gameprogramming01_20161102_jintaeks
Beginning direct3d gameprogramming01_20161102_jintaeks
 
Beginning direct3d gameprogramming02_overviewofhalandcom_20160408_jintaeks
Beginning direct3d gameprogramming02_overviewofhalandcom_20160408_jintaeksBeginning direct3d gameprogramming02_overviewofhalandcom_20160408_jintaeks
Beginning direct3d gameprogramming02_overviewofhalandcom_20160408_jintaeks
 
Beginning direct3d gameprogrammingmath03_vectors_20160328_jintaeks
Beginning direct3d gameprogrammingmath03_vectors_20160328_jintaeksBeginning direct3d gameprogrammingmath03_vectors_20160328_jintaeks
Beginning direct3d gameprogrammingmath03_vectors_20160328_jintaeks
 
Beginning direct3d gameprogramming01_thehistoryofdirect3dgraphics_20160407_ji...
Beginning direct3d gameprogramming01_thehistoryofdirect3dgraphics_20160407_ji...Beginning direct3d gameprogramming01_thehistoryofdirect3dgraphics_20160407_ji...
Beginning direct3d gameprogramming01_thehistoryofdirect3dgraphics_20160407_ji...
 
Beginning direct3d gameprogramming03_programmingconventions_20160414_jintaeks
Beginning direct3d gameprogramming03_programmingconventions_20160414_jintaeksBeginning direct3d gameprogramming03_programmingconventions_20160414_jintaeks
Beginning direct3d gameprogramming03_programmingconventions_20160414_jintaeks
 
Beginning direct3d gameprogramming04_3dfundamentals_20160414_jintaeks
Beginning direct3d gameprogramming04_3dfundamentals_20160414_jintaeksBeginning direct3d gameprogramming04_3dfundamentals_20160414_jintaeks
Beginning direct3d gameprogramming04_3dfundamentals_20160414_jintaeks
 
Beginning direct3d gameprogramming05_thebasics_20160421_jintaeks
Beginning direct3d gameprogramming05_thebasics_20160421_jintaeksBeginning direct3d gameprogramming05_thebasics_20160421_jintaeks
Beginning direct3d gameprogramming05_thebasics_20160421_jintaeks
 
Beginning direct3d gameprogramming08_usingtextures_20160428_jintaeks
Beginning direct3d gameprogramming08_usingtextures_20160428_jintaeksBeginning direct3d gameprogramming08_usingtextures_20160428_jintaeks
Beginning direct3d gameprogramming08_usingtextures_20160428_jintaeks
 
Beginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeks
Beginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeksBeginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeks
Beginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeks
 
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
Beginning direct3d gameprogrammingcpp02_20160324_jintaeksBeginning direct3d gameprogrammingcpp02_20160324_jintaeks
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
 
Spark Data Streaming Pipeline
Spark Data Streaming PipelineSpark Data Streaming Pipeline
Spark Data Streaming Pipeline
 
Pixel shaders
Pixel shadersPixel shaders
Pixel shaders
 
Big Data Logging Pipeline with Apache Spark and Kafka
Big Data Logging Pipeline with Apache Spark and KafkaBig Data Logging Pipeline with Apache Spark and Kafka
Big Data Logging Pipeline with Apache Spark and Kafka
 
Email Classifier using Spark 1.3 Mlib / ML Pipeline
Email Classifier using Spark 1.3 Mlib / ML PipelineEmail Classifier using Spark 1.3 Mlib / ML Pipeline
Email Classifier using Spark 1.3 Mlib / ML Pipeline
 
Intro to Shader
Intro to ShaderIntro to Shader
Intro to Shader
 
Shaders - Claudia Doppioslash - Unity With the Best
Shaders - Claudia Doppioslash - Unity With the BestShaders - Claudia Doppioslash - Unity With the Best
Shaders - Claudia Doppioslash - Unity With the Best
 
Unity Surface Shader for Artist 02
Unity Surface Shader for Artist 02Unity Surface Shader for Artist 02
Unity Surface Shader for Artist 02
 

Similaire à Beginning direct3d gameprogramming10_shaderdetail_20160506_jintaeks

CD504 CGM_Lab Manual_004e08d3838702ed11fc6d03cc82f7be.pdf
CD504 CGM_Lab Manual_004e08d3838702ed11fc6d03cc82f7be.pdfCD504 CGM_Lab Manual_004e08d3838702ed11fc6d03cc82f7be.pdf
CD504 CGM_Lab Manual_004e08d3838702ed11fc6d03cc82f7be.pdf
RajJain516913
 
Advanced Lighting Techniques Dan Baker (Meltdown 2005)
Advanced Lighting Techniques   Dan Baker (Meltdown 2005)Advanced Lighting Techniques   Dan Baker (Meltdown 2005)
Advanced Lighting Techniques Dan Baker (Meltdown 2005)
mobius.cn
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]
Palak Sanghani
 
Tao Fayan_Iso and Full_volume rendering
Tao Fayan_Iso and Full_volume renderingTao Fayan_Iso and Full_volume rendering
Tao Fayan_Iso and Full_volume rendering
Fayan TAO
 
Lecture03 p1
Lecture03 p1Lecture03 p1
Lecture03 p1
aa11bb11
 
Parallel Evaluation of Multi-Semi-Joins
Parallel Evaluation of Multi-Semi-JoinsParallel Evaluation of Multi-Semi-Joins
Parallel Evaluation of Multi-Semi-Joins
Jonny Daenen
 
20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilers20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilers
Computer Science Club
 

Similaire à Beginning direct3d gameprogramming10_shaderdetail_20160506_jintaeks (20)

Trident International Graphics Workshop 2014 1/5
Trident International Graphics Workshop 2014 1/5Trident International Graphics Workshop 2014 1/5
Trident International Graphics Workshop 2014 1/5
 
CD504 CGM_Lab Manual_004e08d3838702ed11fc6d03cc82f7be.pdf
CD504 CGM_Lab Manual_004e08d3838702ed11fc6d03cc82f7be.pdfCD504 CGM_Lab Manual_004e08d3838702ed11fc6d03cc82f7be.pdf
CD504 CGM_Lab Manual_004e08d3838702ed11fc6d03cc82f7be.pdf
 
Advanced Lighting Techniques Dan Baker (Meltdown 2005)
Advanced Lighting Techniques   Dan Baker (Meltdown 2005)Advanced Lighting Techniques   Dan Baker (Meltdown 2005)
Advanced Lighting Techniques Dan Baker (Meltdown 2005)
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]
 
Graph Neural Network in practice
Graph Neural Network in practiceGraph Neural Network in practice
Graph Neural Network in practice
 
Subquad multi ff
Subquad multi ffSubquad multi ff
Subquad multi ff
 
Tao Fayan_Iso and Full_volume rendering
Tao Fayan_Iso and Full_volume renderingTao Fayan_Iso and Full_volume rendering
Tao Fayan_Iso and Full_volume rendering
 
Games 3 dl4-example
Games 3 dl4-exampleGames 3 dl4-example
Games 3 dl4-example
 
Lecture03 p1
Lecture03 p1Lecture03 p1
Lecture03 p1
 
Trident International Graphics Workshop2014 3/5
Trident International Graphics Workshop2014 3/5Trident International Graphics Workshop2014 3/5
Trident International Graphics Workshop2014 3/5
 
SA09 Realtime education
SA09 Realtime educationSA09 Realtime education
SA09 Realtime education
 
Rendering Techniques in Rise of the Tomb Raider
Rendering Techniques in Rise of the Tomb RaiderRendering Techniques in Rise of the Tomb Raider
Rendering Techniques in Rise of the Tomb Raider
 
Parallel Evaluation of Multi-Semi-Joins
Parallel Evaluation of Multi-Semi-JoinsParallel Evaluation of Multi-Semi-Joins
Parallel Evaluation of Multi-Semi-Joins
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentation
 
Algorithm
AlgorithmAlgorithm
Algorithm
 
20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilers20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilers
 
Deep Learning, Keras, and TensorFlow
Deep Learning, Keras, and TensorFlowDeep Learning, Keras, and TensorFlow
Deep Learning, Keras, and TensorFlow
 
Explanation on Tensorflow example -Deep mnist for expert
Explanation on Tensorflow example -Deep mnist for expertExplanation on Tensorflow example -Deep mnist for expert
Explanation on Tensorflow example -Deep mnist for expert
 
From RNN to neural networks for cyclic undirected graphs
From RNN to neural networks for cyclic undirected graphsFrom RNN to neural networks for cyclic undirected graphs
From RNN to neural networks for cyclic undirected graphs
 
CS 354 More Graphics Pipeline
CS 354 More Graphics PipelineCS 354 More Graphics Pipeline
CS 354 More Graphics Pipeline
 

Plus de JinTaek Seo

Beginning direct3d gameprogrammingmath01_primer_20160324_jintaeks
Beginning direct3d gameprogrammingmath01_primer_20160324_jintaeksBeginning direct3d gameprogrammingmath01_primer_20160324_jintaeks
Beginning direct3d gameprogrammingmath01_primer_20160324_jintaeks
JinTaek Seo
 

Plus de JinTaek Seo (14)

Neural network 20161210_jintaekseo
Neural network 20161210_jintaekseoNeural network 20161210_jintaekseo
Neural network 20161210_jintaekseo
 
05 heap 20161110_jintaeks
05 heap 20161110_jintaeks05 heap 20161110_jintaeks
05 heap 20161110_jintaeks
 
02 linked list_20160217_jintaekseo
02 linked list_20160217_jintaekseo02 linked list_20160217_jintaekseo
02 linked list_20160217_jintaekseo
 
Hermite spline english_20161201_jintaeks
Hermite spline english_20161201_jintaeksHermite spline english_20161201_jintaeks
Hermite spline english_20161201_jintaeks
 
01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo
 
03 fsm how_toimplementai_state_20161006_jintaeks
03 fsm how_toimplementai_state_20161006_jintaeks03 fsm how_toimplementai_state_20161006_jintaeks
03 fsm how_toimplementai_state_20161006_jintaeks
 
Beginning direct3d gameprogrammingmath01_primer_20160324_jintaeks
Beginning direct3d gameprogrammingmath01_primer_20160324_jintaeksBeginning direct3d gameprogrammingmath01_primer_20160324_jintaeks
Beginning direct3d gameprogrammingmath01_primer_20160324_jintaeks
 
Boost pp 20091102_서진택
Boost pp 20091102_서진택Boost pp 20091102_서진택
Boost pp 20091102_서진택
 
아직도가야할길 훈련 20090722_서진택
아직도가야할길 훈련 20090722_서진택아직도가야할길 훈련 20090722_서진택
아직도가야할길 훈련 20090722_서진택
 
3ds maxscript 튜토리얼_20151206_서진택
3ds maxscript 튜토리얼_20151206_서진택3ds maxscript 튜토리얼_20151206_서진택
3ds maxscript 튜토리얼_20151206_서진택
 
Multithread programming 20151206_서진택
Multithread programming 20151206_서진택Multithread programming 20151206_서진택
Multithread programming 20151206_서진택
 
03동물 로봇그리고사람 public_20151125_서진택
03동물 로봇그리고사람 public_20151125_서진택03동물 로봇그리고사람 public_20151125_서진택
03동물 로봇그리고사람 public_20151125_서진택
 
20150605 홀트입양예비부모모임 서진택
20150605 홀트입양예비부모모임 서진택20150605 홀트입양예비부모모임 서진택
20150605 홀트입양예비부모모임 서진택
 
Boost라이브러리의내부구조 20151111 서진택
Boost라이브러리의내부구조 20151111 서진택Boost라이브러리의내부구조 20151111 서진택
Boost라이브러리의내부구조 20151111 서진택
 

Dernier

VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Christo Ananth
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
Tonystark477637
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 

Dernier (20)

Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 

Beginning direct3d gameprogramming10_shaderdetail_20160506_jintaeks

  • 1. Beginning Direct3D Game Programming: 10. Shader Detail jintaeks@gmail.com Division of Digital Contents, DongSeo University. May 2016
  • 2. Decompose a vector  d=(a·n)  a⊥=(a·n)n  a∥=a-a⊥=a-(a·n)n 2
  • 4. Step1 : Diffuse Light 4
  • 5. Diffuse Lighting  The diffuse lighting model following Lambert’s law is described with the help of two vectors—the light vector L and the normal vector N.  The diffuse reflection has its peak (cos(θ) ≡ 1) when L and N are aligned. 5
  • 6. Diffuse Lighting  This diffuse lighting component is usually added to the ambient lighting component like this: I = Aintensity * Acolor + Dintensity * Dcolor * N·L + Specular 6
  • 7. Effect File: Declare Global Variables //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- float4 g_MaterialAmbientColor; // Material's ambient color float4 g_MaterialDiffuseColor; // Material's diffuse color float3 g_LightDir; // Light's direction in world space float4 g_LightDiffuse; // Light's diffuse color float4 g_LightAmbient = float4(0.5,0.5,0.5,0.5); // Light's ambient color texture g_MeshTexture; // Color texture for mesh float g_fTime; // App's time in seconds float4x4 g_mWorld; // World matrix for object float4x4 g_mWorldViewProjection; // World * View * Projection matrix 7
  • 8. Vertex Shader Output Structure //-------------------------------------------------------------------------------------- // Vertex shader output structure //-------------------------------------------------------------------------------------- struct VS_OUTPUT { float4 Position : POSITION; // vertex position float4 Diffuse : COLOR0; // vertex diffuse color (note that COLOR0 is clamped from 0..1) float2 TextureUV : TEXCOORD0; // vertex texture coords }; 8
  • 9. Vertex Shader VS_OUTPUT RenderSceneVS( float4 vPos : POSITION, float3 vNormal : NORMAL, float2 vTexCoord0 : TEXCOORD0, uniform int nUnused, uniform bool bTexture, uniform bool bAnimate ) { VS_OUTPUT Output; float3 vNormalWorldSpace; float4 vAnimatedPos = vPos; // Transform the position from object space to homogeneous projection space Output.Position = mul(vAnimatedPos, g_mWorldViewProjection); // Transform the normal from object space to world space vNormalWorldSpace = normalize(mul(vNormal, (float3x3)g_mWorld)); 9
  • 10. Vertex Shader VS_OUTPUT RenderSceneVS( float4 vPos : POSITION, float3 vNormal : NORMAL, float2 vTexCoord0 : TEXCOORD0, uniform int nUnused, uniform bool bTexture, uniform bool bAnimate ) { VS_OUTPUT Output; … // Compute simple directional lighting equation float3 vTotalLightDiffuse = float3(0,0,0); vTotalLightDiffuse += g_LightDiffuse * max( 0, dot( vNormalWorldSpace, g_LightDir ) ); Output.Diffuse.rgb = g_MaterialDiffuseColor * vTotalLightDiffuse + g_MaterialAmbientColor * g_LightAmbient; Output.Diffuse.a = 1.0f; // Just copy the texture coordinate through Output.TextureUV = vTexCoord0; return Output; } 10
  • 11. Pixel Shader struct PS_OUTPUT { float4 RGBColor : COLOR0; // Pixel color }; PS_OUTPUT RenderScenePS( VS_OUTPUT In, uniform bool bTexture ) { PS_OUTPUT Output; // Lookup mesh texture and modulate it with diffuse if( bTexture ) Output.RGBColor = tex2D(MeshTextureSampler, In.TextureUV) * In.Diffuse; else Output.RGBColor = In.Diffuse; return Output; } 11
  • 12. Technique technique RenderSceneWithTexture1Light { pass P0 { VertexShader = compile vs_2_0 RenderSceneVS( 1, false, false ); PixelShader = compile ps_2_0 RenderScenePS( false ); } } 12
  • 13. Client : Declare Global Variables //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- ID3DXFont* g_pFont = NULL; // Font for drawing text ID3DXSprite* g_pSprite = NULL; // Sprite for batching draw text calls bool g_bShowHelp = true; // If true, it renders the UI control text CModelViewerCamera g_Camera; // A model viewing camera ID3DXEffect* g_pEffect = NULL; // D3DX effect interface ID3DXMesh* g_pMesh = NULL; // Mesh object IDirect3DTexture9* g_pMeshTexture = NULL; // Mesh texture CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs 13
  • 14. OnCreateDevice() // Read the D3DX effect file WCHAR str[MAX_PATH]; V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"BasicHLSL.fx" ) ); // If this fails, there should be debug output as to // why the .fx file failed to compile V_RETURN( D3DXCreateEffectFromFile( pd3dDevice, str, NULL, NULL, dwShaderFlags, NULL, &g_pEffect, NULL ) ); // Create the mesh texture from a file V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"earthearth.bmp" ) ); V_RETURN( D3DXCreateTextureFromFileEx( pd3dDevice, str, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, &g_pMeshTexture ) ); 14
  • 15. OnCreateDevice() // Set effect variables as needed D3DXCOLOR colorMtrlDiffuse( 1.0f, 1.0f, 1.0f, 1.0f ); D3DXCOLOR colorMtrlAmbient( 0.35f, 0.35f, 0.35f, 0 ); V_RETURN( g_pEffect->SetValue( "g_MaterialAmbientColor", &colorMtrlAmbient, sizeof( D3DXCOLOR ) ) ); V_RETURN( g_pEffect->SetValue( "g_MaterialDiffuseColor", &colorMtrlDiffuse, sizeof( D3DXCOLOR ) ) ); V_RETURN( g_pEffect->SetTexture( "g_MeshTexture", g_pMeshTexture ) ); 15
  • 16. OnResetDevice() HRESULT hr; V_RETURN( g_DialogResourceManager.OnD3D9ResetDevice() ); V_RETURN( g_SettingsDlg.OnD3D9ResetDevice() ); if( g_pFont ) V_RETURN( g_pFont->OnResetDevice() ); if( g_pEffect ) V_RETURN( g_pEffect->OnResetDevice() ); // Create a sprite to help batch calls when drawing many lines of text V_RETURN( D3DXCreateSprite( pd3dDevice, &g_pSprite ) ); 16
  • 17. OnFrameRender() // Render the scene if( SUCCEEDED( pd3dDevice->BeginScene() ) ) { // Get the projection & view matrix from the camera class mWorld = g_mCenterWorld * *g_Camera.GetWorldMatrix(); mProj = *g_Camera.GetProjMatrix(); mView = *g_Camera.GetViewMatrix(); mWorldViewProjection = mWorld * mView * mProj; D3DXCOLOR arrowColor = D3DXCOLOR( 1, 1, 0, 1 ); V( g_LightControl.OnRender9( arrowColor, &mView, &mProj, g_Camera.GetEyePt() ) ); vLightDir = g_LightControl.GetLightDirection(); vLightDiffuse = g_fLightScale * D3DXCOLOR( 1, 1, 1, 1 ); 17
  • 18. V( g_pEffect->SetValue( "g_LightDir", &vLightDir, sizeof( D3DXVECTOR3 ) ) ); V( g_pEffect->SetValue( "g_LightDiffuse", &vLightDiffuse, sizeof( D3DXVECTOR4 ) ) ); // Update the effect's variables. Instead of using strings, it would // be more efficient to cache a handle to the parameter by calling // ID3DXEffect::GetParameterByName V( g_pEffect->SetMatrix( "g_mWorldViewProjection", &mWorldViewProjection ) ); V( g_pEffect->SetMatrix( "g_mWorld", &mWorld ) ); V( g_pEffect->SetFloat( "g_fTime", ( float )fTime ) ); D3DXCOLOR vWhite = D3DXCOLOR( 1, 1, 1, 1 ); V( g_pEffect->SetValue( "g_MaterialDiffuseColor", &vWhite, sizeof( D3DXCOLOR ) ) ); V( g_pEffect->SetFloat( "g_fTime", ( float )fTime ) ); 18
  • 19. V( g_pEffect->SetTechnique( "RenderSceneWithTexture1Light" ) ); // Apply the technique contained in the effect V( g_pEffect->Begin( &cPasses, 0 ) ); for( iPass = 0; iPass < cPasses; iPass++ ) { V( g_pEffect->BeginPass( iPass ) ); V( g_pEffect->CommitChanges() ); // Render the mesh with the applied technique V( g_pMesh->DrawSubset( 0 ) ); V( g_pEffect->EndPass() ); } V( g_pEffect->End() ); 19
  • 20. OnLostDevice() void CALLBACK OnLostDevice( void* pUserContext ) { g_DialogResourceManager.OnD3D9LostDevice(); g_SettingsDlg.OnD3D9LostDevice(); CDXUTDirectionWidget::StaticOnD3D9LostDevice(); if( g_pFont ) g_pFont->OnLostDevice(); if( g_pEffect ) g_pEffect->OnLostDevice(); SAFE_RELEASE( g_pSprite ); } 20
  • 21. OnDestroyDevice() void CALLBACK OnDestroyDevice( void* pUserContext ) { g_DialogResourceManager.OnD3D9DestroyDevice(); g_SettingsDlg.OnD3D9DestroyDevice(); CDXUTDirectionWidget::StaticOnD3D9DestroyDevice(); SAFE_RELEASE( g_pEffect ); SAFE_RELEASE( g_pFont ); SAFE_RELEASE( g_pMesh ); SAFE_RELEASE( g_pMeshTexture ); } 21
  • 22. Practice: Build and Run BasicHLSL Step1 22
  • 23. Step2 : Diffuse Light in Local Space  Use Object space uniform variables in Shader to speed up. 23
  • 25. 25
  • 27. Practice: Build and Run BasicHLSL Step2 27
  • 28. Step3 : Specular Light 28
  • 29. Reflection vector  r = a - 2(a·n)n 29
  • 30. Specular Reflection  Two vectors are used to calculate the specular component— the Light vector L and the reflection vector R.  The more L is aligned with R, the brighter the specular light should be. 30
  • 31. Half Vector  If one calculates a halfway vector between the viewer and light-source vectors we can replace L·R with H·N. 31
  • 34. 34
  • 35. Client: OnFrameRender() Differences  Prepare WorldView and WorldViewInv matrices. 35
  • 36.  Get Object space eye position. 36
  • 37.  Set Object space eye position. 37
  • 38. Practice: Build and Run BasicHLSL Step3 38
  • 39. Step4 : Specular Light in Pixel Shader  Specular light calculation in pixel shader to get more precise result. 39
  • 40. Effect Differences  Add Normal and Eye vector to VS_OUTPUT. 40
  • 41. Vertex Shader Differences  Pass Normal and Eye vector to Pixel shader. 41
  • 43. Practice: Build and Run BasicHLSL Step4 43
  • 44. Step5 : Normal Mapping 44
  • 45. Normal Map  In 3D computer graphics, normal mapping is a technique used for faking the lighting of bumps and dents – an implementation of bump mapping.  It is used to add details without using more polygons. • Example of a normal map (center) with the scene it was calculated from (left) and the result when applied to a flat surface (right). 45
  • 47. Normal Map  RGB color of pixel in image file is a direction (x,y,z) in tangent space. 47
  • 48. Effect Differences: Added normal map texture 48
  • 49. Added Light vector in tangent space 49
  • 51.  Eye and Light vectors must be transformed to tangent space. 51
  • 52. Pixel Shader PS_OUTPUT RenderScenePS( VS_OUTPUT In, uniform bool bTexture ) { PS_OUTPUT Output; float3 N = 2.0f * tex2D( MeshBumpTextureSampler, In.TextureUV ).xyz - 1.0f; float3 L = normalize( In.L ); float3 R = reflect( -normalize( In.Eye ), N ); // reflection vector // Lookup mesh texture and modulate it with diffuse if( bTexture ) { Output.RGBColor = tex2D( MeshTextureSampler, In.TextureUV ) *In.Diffuse * max( 0, dot( N, L ) ); } else { Output.RGBColor = In.Diffuse * max( 0, dot( N, L ) ); }//if.. else.. Output.RGBColor += pow( max( 0, dot( R, L ) ), 10 ); return Output; } 52
  • 53. Client: Added normal map texture 53
  • 55. OnResetDevice() Differences() D3DVERTEXELEMENT9 decl[] = { { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, { 0, 24, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0 }, { 0, 36, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, D3DDECL_END() };//decl[] if( g_pMesh ) { LPD3DXMESH pMesh; g_pMesh->CloneMesh( g_pMesh->GetOptions(), decl, pd3dDevice, &pMesh ); D3DXComputeNormals( pMesh, NULL ); D3DXComputeTangent( pMesh, 0, 0, 0, TRUE, NULL ); SAFE_RELEASE( g_pMesh ); g_pMesh = pMesh; }//if 55