SlideShare a Scribd company logo
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

More Related Content

PPTX
Trident International Graphics Workshop 2014 4/5
PPTX
Beginning direct3d gameprogramming07_lightsandmaterials_20161117_jintaeks
PPTX
Beginning direct3d gameprogramming09_shaderprogramming_20160505_jintaeks
PPTX
Trident International Graphics Workshop 2014 5/5
PPT
Geometry Shader-based Bump Mapping Setup
PDF
Better Visualization of Trips through Agglomerative Clustering
PDF
Task based Programming with OmpSs and its Application
PPT
CS 354 Pixel Updating
Trident International Graphics Workshop 2014 4/5
Beginning direct3d gameprogramming07_lightsandmaterials_20161117_jintaeks
Beginning direct3d gameprogramming09_shaderprogramming_20160505_jintaeks
Trident International Graphics Workshop 2014 5/5
Geometry Shader-based Bump Mapping Setup
Better Visualization of Trips through Agglomerative Clustering
Task based Programming with OmpSs and its Application
CS 354 Pixel Updating

What's hot (20)

PPTX
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
PPT
Shadow Volumes on Programmable Graphics Hardware
PPT
PDF
Deep learning with C++ - an introduction to tiny-dnn
PPT
CS 354 Transformation, Clipping, and Culling
PPTX
Maximizing performance of 3 d user generated assets in unity
PPTX
Show, Attend and Tell: Neural Image Caption Generation with Visual Attention
PDF
Introducton to Convolutional Nerural Network with TensorFlow
PPT
CS 354 Graphics Math
PPT
CS 354 Understanding Color
PDF
Lecture 11 (Digital Image Processing)
PDF
Epsrcws08 campbell isvm_01
PPTX
2.5D Clip-Surfaces for Technical Visualization
PDF
Automatic Gain Tuning based on Gaussian Process Global Optimization (= Bayesi...
PDF
(Paper Review)3D shape reconstruction from sketches via multi view convolutio...
PPTX
Geometry Batching Using Texture-Arrays
PDF
PDF
[MIRU2018] Global Average Poolingの特性を用いたAttention Branch Network
PPTX
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
Shadow Volumes on Programmable Graphics Hardware
Deep learning with C++ - an introduction to tiny-dnn
CS 354 Transformation, Clipping, and Culling
Maximizing performance of 3 d user generated assets in unity
Show, Attend and Tell: Neural Image Caption Generation with Visual Attention
Introducton to Convolutional Nerural Network with TensorFlow
CS 354 Graphics Math
CS 354 Understanding Color
Lecture 11 (Digital Image Processing)
Epsrcws08 campbell isvm_01
2.5D Clip-Surfaces for Technical Visualization
Automatic Gain Tuning based on Gaussian Process Global Optimization (= Bayesi...
(Paper Review)3D shape reconstruction from sketches via multi view convolutio...
Geometry Batching Using Texture-Arrays
[MIRU2018] Global Average Poolingの特性を用いたAttention Branch Network
Ad

Viewers also liked (20)

PPTX
Beginning direct3d gameprogrammingmath06_transformations_20161019_jintaeks
PPTX
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
PPTX
Beginning direct3d gameprogrammingmath04_calculus_20160324_jintaeks
PPTX
Beginning direct3d gameprogramming01_20161102_jintaeks
PPTX
Beginning direct3d gameprogramming02_overviewofhalandcom_20160408_jintaeks
PPTX
Beginning direct3d gameprogrammingmath03_vectors_20160328_jintaeks
PPTX
Beginning direct3d gameprogramming01_thehistoryofdirect3dgraphics_20160407_ji...
PPTX
Beginning direct3d gameprogramming03_programmingconventions_20160414_jintaeks
PPTX
Beginning direct3d gameprogramming04_3dfundamentals_20160414_jintaeks
PPTX
Beginning direct3d gameprogramming05_thebasics_20160421_jintaeks
PPTX
Beginning direct3d gameprogramming08_usingtextures_20160428_jintaeks
PPTX
Beginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeks
PPTX
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
PPTX
Spark Data Streaming Pipeline
PPTX
Pixel shaders
PDF
Big Data Logging Pipeline with Apache Spark and Kafka
PDF
Email Classifier using Spark 1.3 Mlib / ML Pipeline
ODP
PDF
Shaders - Claudia Doppioslash - Unity With the Best
PDF
Unity Surface Shader for Artist 02
Beginning direct3d gameprogrammingmath06_transformations_20161019_jintaeks
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
Beginning direct3d gameprogrammingmath04_calculus_20160324_jintaeks
Beginning direct3d gameprogramming01_20161102_jintaeks
Beginning direct3d gameprogramming02_overviewofhalandcom_20160408_jintaeks
Beginning direct3d gameprogrammingmath03_vectors_20160328_jintaeks
Beginning direct3d gameprogramming01_thehistoryofdirect3dgraphics_20160407_ji...
Beginning direct3d gameprogramming03_programmingconventions_20160414_jintaeks
Beginning direct3d gameprogramming04_3dfundamentals_20160414_jintaeks
Beginning direct3d gameprogramming05_thebasics_20160421_jintaeks
Beginning direct3d gameprogramming08_usingtextures_20160428_jintaeks
Beginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeks
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
Spark Data Streaming Pipeline
Pixel shaders
Big Data Logging Pipeline with Apache Spark and Kafka
Email Classifier using Spark 1.3 Mlib / ML Pipeline
Shaders - Claudia Doppioslash - Unity With the Best
Unity Surface Shader for Artist 02
Ad

Similar to Beginning direct3d gameprogramming10_shaderdetail_20160506_jintaeks (20)

PPTX
Trident International Graphics Workshop 2014 1/5
PDF
CD504 CGM_Lab Manual_004e08d3838702ed11fc6d03cc82f7be.pdf
PPT
Advanced Lighting Techniques Dan Baker (Meltdown 2005)
PDF
Lec 9 05_sept [compatibility mode]
PDF
Graph Neural Network in practice
PDF
Subquad multi ff
PDF
Tao Fayan_Iso and Full_volume rendering
PDF
Games 3 dl4-example
PDF
Lecture03 p1
PPTX
Trident International Graphics Workshop2014 3/5
PDF
SA09 Realtime education
PDF
Rendering Techniques in Rise of the Tomb Raider
PPT
Programming Fundamentals, C++, Object Oriented Programming
PDF
Parallel Evaluation of Multi-Semi-Joins
DOCX
B61301007 matlab documentation
PDF
Algorithm
PPTX
20101017 program analysis_for_security_livshits_lecture02_compilers
PPTX
Deep Learning, Keras, and TensorFlow
PPTX
Explanation on Tensorflow example -Deep mnist for expert
PDF
From RNN to neural networks for cyclic undirected graphs
Trident International Graphics Workshop 2014 1/5
CD504 CGM_Lab Manual_004e08d3838702ed11fc6d03cc82f7be.pdf
Advanced Lighting Techniques Dan Baker (Meltdown 2005)
Lec 9 05_sept [compatibility mode]
Graph Neural Network in practice
Subquad multi ff
Tao Fayan_Iso and Full_volume rendering
Games 3 dl4-example
Lecture03 p1
Trident International Graphics Workshop2014 3/5
SA09 Realtime education
Rendering Techniques in Rise of the Tomb Raider
Programming Fundamentals, C++, Object Oriented Programming
Parallel Evaluation of Multi-Semi-Joins
B61301007 matlab documentation
Algorithm
20101017 program analysis_for_security_livshits_lecture02_compilers
Deep Learning, Keras, and TensorFlow
Explanation on Tensorflow example -Deep mnist for expert
From RNN to neural networks for cyclic undirected graphs

More from JinTaek Seo (14)

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

Recently uploaded (20)

PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
web development for engineering and engineering
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
additive manufacturing of ss316l using mig welding
PPTX
CH1 Production IntroductoryConcepts.pptx
PDF
Digital Logic Computer Design lecture notes
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPT
Mechanical Engineering MATERIALS Selection
PPTX
Foundation to blockchain - A guide to Blockchain Tech
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPTX
Geodesy 1.pptx...............................................
PPTX
Sustainable Sites - Green Building Construction
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PDF
Well-logging-methods_new................
Internet of Things (IOT) - A guide to understanding
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Automation-in-Manufacturing-Chapter-Introduction.pdf
web development for engineering and engineering
R24 SURVEYING LAB MANUAL for civil enggi
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
additive manufacturing of ss316l using mig welding
CH1 Production IntroductoryConcepts.pptx
Digital Logic Computer Design lecture notes
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
Mechanical Engineering MATERIALS Selection
Foundation to blockchain - A guide to Blockchain Tech
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Geodesy 1.pptx...............................................
Sustainable Sites - Green Building Construction
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
Well-logging-methods_new................

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