print("hello world")
comment
-- one line
--[[
multiple lines
--]]
global variable, value is treated as global by default, only you use “local” to define it. if you awnt to delete it, just set it as nil.
Lua data type:nil、boolean、number、string、userdata、function、thread、table. Logic operations: and, or, not
print(type("hello world"))
-- string
print(type(true))
-- boolean
string
string1 = "hello world"
string2 = 'hello world'
string3 = [[
hello world
]]
-- string append
print("a"..'b')
-- string length #
print(#string2)
string.len("abc")
-- string to upper
string.upper(argument)
-- string to lower
string.lower(argument)
-- string replace
string.gsub(mainString,findString,replaceString,num)
string.gsub("aaaa","a","z",3)
-- return zzza, 3
-- find the index, 1 as the begin point
string.find("Hello Lua user", "Lua", 1)
-- reverse the string
string.reverse("lua")
-- string copy
string.rep("abc", 2)
table
local tbl2 = {"apple", "pear", "orange", "grape"}
-- table contact
fruits = {"banana","orange","apple"}
print(table.concat(fruits))
-- return bananaorangeapple
print(table.concat(fruits,", "))
-- return banana, orange, apple
print(table.concat(fruits,", ", 2,3))
-- return orange, apple
-- remove
table.remove(fruits, pos)
-- insert
table.insert(fruits, 2, "mongo")
--sort
table.sort(fruits)
function
function factorial1(n)
if n == 0 then
return 1
else
return n * factorial1(n - 1)
end
end
print(factorial1(5))
factorial2 = factorial1
print(factorial2(5))
-- it can also return multiple values
s, e = string.find("www.runoob.com", "runoob")
-- return 5 10
user data: user can define the data type and value at any style
assignment
t.n = t.n + 1
a, b = 10, 2*x <--> a=10; b=2*x
a[i], a[j] = a[j], a[i] -- swap 'a[i]' for 'a[j]'
a, b, c = 0, 1
print(a,b,c) --> 0 1 nil
a, b = a+1, b+1, b+2 -- value of b+2 is ignored
print(a,b) --> 1 2
index
t[i]
t.i
loop
-- false and nil are false, true and non-nil are true, so 0 is false
if(0)
then
print("0 is true")
end
if (condition1)
then
do sth1
elseif (condition2)
then
do sth2
else
do sth3
end
while( true )
do
print("loop forever")
end
for i=1,f(x) do
print(i)
end
for i=10,1,-1 do
print(i)
end
days = {"Suanday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}
for i, v in ipairs(days) do
print(v)
end
repeat
statements
until( condition )
-- can use break
module
module={}
module.constant = "value"
function module.func()
io.write("a public function")
end
-- load a module
require "module"
IO
-- only read
file = io.open("test.lua", "r")
io.input(file)
io.close(file)
io.write("-- test.lua 文件末尾注释")
coroutine
-- use producer and consumer as the example
local newProductor
function productor()
local i = 0
while true do
i = i + 1
send(i) -- send the products to consumers
end
end
function consumer()
while true do
local i = receive() -- get the products from the productor
print(i)
end
end
function receive()
local status, value = coroutine.resume(newProductor)
return value
end
function send(x)
coroutine.yield(x) -- x is the value, coroutine
end
-- start
newProductor = coroutine.create(productor)
consumer()
This tutorials are based on the DirectX Tutorial, talking about point lights and spot lights.
A point light, as discussed in the previous lesson, is a light which has an exact location, and emanates light in all directions from that location.
Unlike a directional light, a point light does not go on indefinitely. As the light travels away from the source, it gets dispersed, spreading out in every direction equally. Therefore, the farther an object is from a directional light, the less illuminated that object will be.
light.Range = 100.0f;
I am going to give you the algebraic function (not C++ function) for attenuation,
Atten = 1 / (att0 + att1 * d + att2 * d2)
Atten: It is a number between 1.0 and 0.0 which indicates the intensity of light. 1.0 is full intensity, while 0.0 is no intensity (no light).
d: the distance between the vertex and the light
att0: a constant modifier. if you put 0.5 in this value, you will get a half-lit light that will extend all the way to the maximum range of the light.
att1: If used by itself, it is an inverse function, meaning that the light will dissipate more slowly as the distance increases.
att2: If used by itself, it is an inverse square function, meaning that the light will not only dissipate more slowly as the distance increases, but the dissipation will be very rapid at first, then sharply slow down.
Coding a Point Light
void init_light(void)
{
D3DLIGHT9 light;
D3DMATERIAL9 material;
ZeroMemory(&light, sizeof(light));
light.Type = D3DLIGHT_POINT; // make the light type 'point light'
light.Diffuse = D3DXCOLOR(0.5f, 0.5f, 0.5f, 1.0f);
light.Position = D3DXVECTOR3(0.0f, 5.0f, 0.0f);
light.Range = 100.0f; // a range of 100
light.Attenuation0 = 0.0f; // no constant inverse attenuation
light.Attenuation1 = 0.125f; // only .125 inverse attenuation
light.Attenuation2 = 0.0f; // no square inverse attenuation
d3ddev->SetLight(0, &light);
d3ddev->LightEnable(0, TRUE);
ZeroMemory(&material, sizeof(D3DMATERIAL9));
material.Diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
material.Ambient = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
d3ddev->SetMaterial(&material);
}
The spotlight is the least-used, least-efficient, and least-simple type of light there is. It actually requires the entire D3DLIGHT9 struct to be filled.
In Direct3D, this is recreated using two values to show how wide these two circles are. As you can see, Theta represents the inner circle and Phi represents the outer circle. Phi and Theta are both float values which hold the angle used to determine the size of each circle.
Falloff: You will see that the bright circle actually fades away into the dark circle.
Coding a Spot Light
void init_light(void)
{
D3DLIGHT9 light;
D3DMATERIAL9 material;
ZeroMemory(&light, sizeof(light));
light.Type = D3DLIGHT_SPOT; // make the light type 'spot light'
light.Diffuse = D3DXCOLOR(0.5f, 0.5f, 0.5f, 1.0f);
light.Position = D3DXVECTOR3(-12.0f, 0.0f, 30.0f);
light.Direction = D3DXVECTOR3(0.0f, 0.0f, -1.0f);
light.Range = 100.0f; // a range of 100
light.Attenuation0 = 0.0f; // no constant inverse attenuation
light.Attenuation1 = 0.125f; // only .125 inverse attenuation
light.Attenuation2 = 0.0f; // no square inverse attenuation
light.Phi = D3DXToRadian(40.0f); // set the outer cone to 30 degrees
light.Theta = D3DXToRadian(20.0f); // set the inner cone to 10 degrees
light.Falloff = 1.0f; // use the typical falloff
d3ddev->SetLight(0, &light);
d3ddev->LightEnable(0, TRUE);
ZeroMemory(&material, sizeof(D3DMATERIAL9));
material.Diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
material.Ambient = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
d3ddev->SetMaterial(&material);
}
You can get the complete codes from Github
If you run this program you should get something like this:
This tutorials are based on the DirectX Tutorial, show how to use lights to illuminate your 3D scene.
Direct3D uses lights to approximate real-world lighting. It does this using a system of calculation that is much less time-consuming, and that can therefore be run in real-time. This system is built up of a set of types of lighting and types of light sources.
There are three types of lighting that can be used to approximate real-world light. They are called diffuse lighting, ambient lighting and specular lighting.
Diffuse lighting is light that more or less falls directly onto a surface. Diffuse lighting is light that more or less falls directly onto a surface. If you hold up your hand in a room with one light source, you will see that one side of your hand is lit, it is.
Ambient lighting consists of light that is everywhere. Generally speaking, it is quite dark (though not totally dark). When you hold your hand up in that room with one light source, the dark side of your hand is ambiently lit, and the light that is reflected there is refered to as ambient light.
Specular lighting is often refered to as specular highlight or reflection. When light reflects off an object, ususally most of the light will go in one specific direction. The result is that each object has a little shine on it that comes from the light source.
In order to produce the three types of light, there are several types of lights (or light sources) that emanate light.
Ambient Lights
Directional Lights
Point Lights
Spot Lights
A material is a description of how surfaces reflect light, and which colors are involved. In other words, you won’t necessarily see this color. You will only see it when you shine a light on it.
Let’s go practice.
Step 1. Setting Up a New Flexible Vertex Format
struct CUSTOMVERTEX {FLOAT X, Y, Z; D3DVECTOR NORMAL;};
#define CUSTOMFVF (D3DFVF_XYZ | D3DFVF_NORMAL)
typedef struct D3DVECTOR {
float x, y, z;
} D3DVECTOR, *LPD3DVECTOR;
Step 2. Turning the Lighting On
d3ddev->SetRenderState(D3DRS_LIGHTING, TRUE);
Step 3. Setting the Ambient Light
d3ddev->SetRenderState(D3DRS_AMBIENT, D3DCOLOR_XRGB(50, 50, 50)); // ambient light
Step 4. Creating and Setting the Diffuse Light
// this is the function that sets up the lights and materials
void init_light(void)
{
D3DLIGHT9 light; // create the light struct
ZeroMemory(&light, sizeof(light)); // clear out the light struct for use
light.Type = D3DLIGHT_DIRECTIONAL; // make the light type 'directional light'
light.Diffuse = D3DXCOLOR(0.5f, 0.5f, 0.5f, 1.0f); // set the light's color
light.Direction = D3DXVECTOR3(-1.0f, -0.3f, -1.0f);
d3ddev->SetLight(0, &light); // send the light struct properties to light #0
d3ddev->LightEnable(0, TRUE); // turn on light #0
ZeroMemory(&material, sizeof(D3DMATERIAL9)); // clear out the struct for use
}
Step 5. Creating and Setting the Material
material.Diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); // set diffuse color to white
material.Ambient = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); // set ambient color to white
d3ddev->SetMaterial(&material); // set the globably-used material to &material
// Use D3DX to create a texture from a file based image
if (FAILED(D3DXCreateTextureFromFile(g_pd3dDevice, L"banana.bmp", &g_pTexture)))
{
// If texture is not in current folder, try parent folder
if (FAILED(D3DXCreateTextureFromFile(g_pd3dDevice, L"banana.bmp", &g_pTexture)))
{
MessageBox(NULL, L"Could not find banana.bmp", L"Textures.exe", MB_OK);
return E_FAIL;
}
}
You can get the complete codes from Github
If you run this program you should get something like this:
This report discusses the small task when I started to learn DirectX. The following is the task details:
#include <windows.h>
#include "d3dUtility.h"
#include <d3dx9.h>
// Globals
IDirect3DDevice9* Device = 0;
const int Width = 500;
const int Height = 500;
IDirect3DVertexBuffer9* Quad = 0;
IDirect3DTexture9* Tex = 0;
ID3DXMesh* Objects;//cylinder
ID3DXMesh* Objects2;//sphere
D3DXMATRIX ObjWorldMatrices;
D3DXMATRIX ObjWorldMatrices2;
// spot light
D3DLIGHT9 Spot;
static D3DMATERIAL9 Mtrls = d3d::WHITE_MTRL;
static D3DMATERIAL9 MtrlsCylinder = d3d::WHITE_MTRL;
static IDirect3DBaseTexture9* tempTexture = NULL;
D3DXMATRIX Worlds;
static float x = 1.0f;
static float y = 2.0f;
static float z = -10.0f;
static float angle = (3.0f * D3DX_PI) / 2.0f;
static int count = 0;
static float time = 0.0f;
struct Vertex
{
Vertex(){}
Vertex(
float x, float y, float z,
float nx, float ny, float nz,
float u, float v)
{
_x = x; _y = y; _z = z;
_nx = nx; _ny = ny; _nz = nz;
_u = u; _v = v;
}
float _x, _y, _z;
float _nx, _ny, _nz;
float _u, _v; // texture coordinates
static const DWORD FVF; //not sure what's this?
};
const DWORD Vertex::FVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1;
// Framework Functions
bool Setup()
{
// Create the quad vertex buffer and fill it with the
// quad geoemtry.
Device->CreateVertexBuffer(
6 * sizeof(Vertex),
D3DUSAGE_WRITEONLY,
Vertex::FVF,
D3DPOOL_MANAGED,
&Quad,
0);
Vertex* v;
Quad->Lock(0, 0, (void**)&v, 0);
// quad built from two triangles, note texture coordinates:
v[0] = Vertex(-25.0f, -25.0f, 1.25f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f);
v[1] = Vertex(-25.0f, 25.0f, 1.25f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f);
v[2] = Vertex(25.0f, 25.0f, 1.25f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f);
v[3] = Vertex(-25.0f, -25.0f, 1.25f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f);
v[4] = Vertex(25.0f, 25.0f, 1.25f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f);
v[5] = Vertex(25.0f, -25.0f, 1.25f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f);
Quad->Unlock();
// Create the texture and set filters.
D3DXCreateTextureFromFile(
Device,
"grass.png",
&Tex);
D3DXMatrixTranslation(&Worlds, 0.0f, 0.0f, 5.0f);
Device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
Device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
Device->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_POINT);
//cylinder
D3DXCreateCylinder(
Device,
1.0f, // radius at negative z end
1.0f, // radius at positive z end
5.0f, // length of cylinder
20, // slices
20, // stacks
&Objects,
0);
// build the ObjWorldMatrices which translates by (0.0f, 0.0f, 1.25f)
D3DXMatrixTranslation(&ObjWorldMatrices, 0.0f, 0.0f, 1.25f);
//sphere
D3DXCreateSphere(
Device,
0.4f, // radius
10, // slices
10, // stacks
&Objects2,
0);
//ÉèÖÃͶӰ¾ØÕó
D3DXMATRIX proj;
D3DXMatrixPerspectiveFovLH(
&proj, //output
D3DX_PI * 0.5f, // 90 - degree
(float)Width / (float)Height,//aspect
1.0f,//½ü²Ã¼ôÃæλÖÃZ
1000.0f);//Ô¶²Ã¼ôÃæλÖÃZ
Device->SetTransform(D3DTS_PROJECTION, &proj);//projection transformation
// use lighting
Device->SetRenderState(D3DRS_LIGHTING, true);
Device->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD);//Gouraud
return true;
}
void Cleanup()
{
d3d::Release<IDirect3DVertexBuffer9*>(Quad);
d3d::Release<IDirect3DTexture9*>(Tex);
d3d::Release<ID3DXMesh*>(Objects);
d3d::Release<ID3DXMesh*>(Objects2);
}
bool Display(float timeDelta)
{
if (Device)
{
D3DXVECTOR3 position(x, y, z);
// the camera is targetted at the origin of the world
D3DXVECTOR3 target(0.0f, 0.0f, 1.25f);
// the worlds up vector
D3DXVECTOR3 up(0.0f, 1.0f, 0.0f);
D3DXMATRIX V;
// up - position ¾ÍÊÇÏà»úµÄ³¯Ïò
D3DXMatrixLookAtLH(&V, &position, &target, &up);
Device->SetTransform(D3DTS_VIEW, &V);
//rotate with itself
D3DXMATRIX Rx, Ry, Rz;
static float xx, yy, zz;
D3DXMatrixRotationX(&Rx, xx);
D3DXMatrixRotationY(&Ry, yy);
D3DXMatrixRotationZ(&Rz, zz);
// rotate around the cylinder
D3DXMATRIX p2;
p2 = Rx * Rz;
D3DXMatrixTranslation(&ObjWorldMatrices2, cosf(angle) *5.0f, sinf(angle)*5.0f, 5.0f);
ObjWorldMatrices2 = p2*ObjWorldMatrices2;
//set up spot light
/*D3DXVECTOR3 pos(0.0f, 0.0f, -100.0f);*/
D3DXVECTOR3 pos(cosf(angle) *10.0f, sinf(angle)*10.0f, -100.0f);
time += timeDelta;
/*if (time > 10)
return true;*/
angle += timeDelta;
if (angle >= 6.28f)
angle = 0.0f;
xx += timeDelta;
yy += timeDelta;
zz += timeDelta;
D3DXVECTOR3 dir(0.0f, 0.0f, 1.0f);
D3DXCOLOR c = d3d::WHITE;
Spot = d3d::InitSpotLight(&pos, &dir, &c);
//enable a spot light
Device->SetLight(0, &Spot);
Device->LightEnable(0, true);
// Set light related render states.
Device->SetRenderState(D3DRS_NORMALIZENORMALS, true);
Device->SetRenderState(D3DRS_SPECULARENABLE, true);
Device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0);
Device->BeginScene();
// texture
Device->SetTexture(0,Tex);
Device->SetStreamSource(0, Quad, 0, sizeof(Vertex));
Device->SetFVF(Vertex::FVF);
Device->SetTransform(D3DTS_WORLD, &Worlds);
Device->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 2);
// cylinder
Device->SetTexture(0, tempTexture);
Device->SetMaterial(&MtrlsCylinder);
Device->SetTransform(D3DTS_WORLD, &ObjWorldMatrices);
Objects->DrawSubset(0);
//sphere
Device->SetTexture(0, NULL);
Device->SetMaterial(&Mtrls);
Device->SetTransform(D3DTS_WORLD, &ObjWorldMatrices2);
Objects2->DrawSubset(0);
Device->EndScene();
Device->Present(0, 0, 0, 0);
}
return true;
}
//
// WndProc
//
LRESULT CALLBACK d3d::WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_DESTROY:
::PostQuitMessage(0);
break;
case WM_CHAR:
switch (wParam) {
case('R'):
MtrlsCylinder = d3d::RED_MTRL;
break;
case('r') :
MtrlsCylinder = d3d::RED_MTRL;
break;
case('G') :
MtrlsCylinder = d3d::GREEN_MTRL;
break;
case('g') :
MtrlsCylinder = d3d::GREEN_MTRL;
break;
case('B'):
MtrlsCylinder = d3d::BLUE_MTRL;
break;
case('b') :
MtrlsCylinder = d3d::BLUE_MTRL;
break;
case('W') :
MtrlsCylinder = d3d::WHITE_MTRL;
break;
case('w') :
MtrlsCylinder = d3d::WHITE_MTRL;
break;
case ('X'):
z += 1.0f;
break;
case ('Z'):
z -= 1.0f;
break;
case ('C') :
x += 1.0f;
break;
case ('V') :
x -= 1.0f;
break;
case ('T') :
tempTexture = Tex;
break;
case ('t') :
tempTexture = Tex;
break;
case ('S') : {
count++;
int temp = count % 3;
if (temp == 0) {
x = 1.0f; y = 2.0f; z = -10.0f;
}
else if (temp == 1) {
x = cosf(angle) *5.0f;
y = sinf(angle)*5.0f;
z = 5.0f;
}
else {
x = cosf(angle) *10.0f;
y = sinf(angle)*10.0f;
z = -100.0f;
}
break;
}
}
}
return ::DefWindowProc(hwnd, msg, wParam, lParam);
}
//
// WinMain
//
int WINAPI WinMain(HINSTANCE hinstance,
HINSTANCE prevInstance,
PSTR cmdLine,
int showCmd)
{
if (!d3d::InitD3D(hinstance,
Width, Height, true, D3DDEVTYPE_HAL, &Device))
{
::MessageBox(0, "InitD3D() - FAILED", 0, 0);
return 0;
}
if (!Setup())
{
::MessageBox(0, "Setup() - FAILED", 0, 0);
return 0;
}
d3d::EnterMsgLoop(Display);
Cleanup();
Device->Release();
return 0;
}
For the complete codes, you can get it from Github
在参与过了美食节之后,小Hi和小Ho在别的地方又玩耍了一阵子,在这个过程中,小Ho得到了一个非常有意思的玩具——一棵由小球和木棍连接起来的二叉树!
小Ho对这棵二叉树爱不释手,于是给它的每一个节点都标记了一个标号——一个属于A..Z的大写字母,并且没有任意两个节点的标号是一样的。小Hi也瞅准了这个机会,重新巩固了一下小Ho关于二叉树遍历的基础知识~就这样,日子安稳的过了两天。
这天,小Ho正好在求解这棵二叉树的前序、中序和后序遍历的结果,但是却在求出前序遍历和中序遍历之后不小心把二叉树摔到了地上,小球和木棍等零件散落了一地!
小Ho损失了心爱的玩具,正要嚎啕大哭起来,所幸被小Hi发现了,劝说道:“别着急,这不是零件都还在么?拼起来不就是了?”
“可是我忘记了二叉树长什么样子了!”小Ho沮丧道。
“这个简单,你不是刚刚求出了这棵二叉树的前序和中序遍历的结果么,利用这两个信息就可以还原出整棵二叉树来哦!”
“这样么?!!”小Ho止住了泪水,问道:“那要怎么做呢?”
没错!小Ho在这一周遇到的问题便是:给出一棵二叉树的前序和中序遍历的结果,还原这棵二叉树并输出其后序遍历的结果。
提示:分而治之——化大为小,化小为无
输入
每个测试点(输入文件)有且仅有一组测试数据。
每组测试数据的第一行为一个由大写英文字母组成的字符串,表示该二叉树的前序遍历的结果。
每组测试数据的第二行为一个由大写英文字母组成的字符串,表示该二叉树的中序遍历的结果。
对于100%的数据,满足二叉树的节点数小于等于26。
输出
对于每组测试数据,输出一个由大写英文字母组成的字符串,表示还原出的二叉树的后序遍历的结果。
样例输入
AB
BA
样例输出
BA
#include <iostream>
#include <string>
using namespace std;
string pre, mid;
int point; // for preorder traversal
//curr is the root, recusive between a and b
void DFS(int a, int curr, int b) {
if (a==b) {
cout << mid[curr];
return;
}
if (curr-a!=0)
DFS(a, mid.find(pre[++point]), curr-1);
if (curr-b!=0)
DFS(curr+1, mid.find(pre[++point]), b);
cout << mid[curr];
}
int main() {
cin >> pre >> mid;
DFS(0, mid.find(pre[0]), pre.size()-1);
return 0;
}
This tutorials are based on the DirectX Tutorial, show how to deal with the render depth problems using DirectX 9.
Let’s say we wanted to draw two triangles, one behind the other, and then view them from an angle where the farther triangle was partially behind the other. If we did this with what code we’ve covered so far, this is how that might look:
This, unfortunately, defies the laws of physics. Things that are farther do not usually appear in front of closer things, especially when the closer thing is blocking it. The way it should appear is like this:
How This Works (or rather, why it doesn’t)
When a model is rendered, several things happen. First, Direct3D calls up the pipeline you built. It is all neatly packed away in memory. Direct3D takes this and processes each model, one at a time, into a 2D image. Immediately after creating that image, it is drawn to the back buffer.
After the first image has been drawn to the screen, the next model is taken up, processed, and drawn to the back buffer. However, no matter where the model was placed in 3D space, the second image is shown over the first one, and you get the result shown in the first image.
Fortunately, Direct3D provides an easy solution to this. The solution is known as a Z-Buffer.
is simply a large buffer that keeps track of the distance from the camera of every pixel on the screen.
Whenever a pixel is drawn, it takes the closest pixel to the camera and draws that on the back buffer. At the same time, it stores the depth value into the same spot in the z-buffer, so that the next time something is drawn
There are some steps to get Z-Buffering.
Step 1. Setting the Appropriate Presentation Parameters
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory(&d3dpp, sizeof(d3dpp));
d3dpp.Windowed = FALSE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.hDeviceWindow = hWnd;
d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
d3dpp.BackBufferWidth = SCREEN_WIDTH;
d3dpp.BackBufferHeight = SCREEN_HEIGHT;
d3dpp.EnableAutoDepthStencil = TRUE; // tell D3D to create it automatically
d3dpp.AutoDepthStencilFormat = D3DFMT_D16; // This means that each pixel is 16-bit.
Step 2. Turning On Z-Buffering
d3ddev->SetRenderState(D3DRS_LIGHTING, FALSE); // turn off the 3D lighting
d3ddev->SetRenderState(D3DRS_ZENABLE, TRUE); // turn on the z-buffer
Step 3. Clearing the Z-Buffer
d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
d3ddev->Clear(0, NULL, D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
You can get the complete codes from Github
If you run this program you should get something like this: