Sign in to follow this  
corntown

problem with lightning

Recommended Posts

corntown    122
I've created a cube and activated lightning for my device but for some reason the cube seems to be colored in black and the lightning doesn't effect it, I tried ambient light and pointlight but it doesn't seem to take effect, here's the code:
// Include the Windows header file that’s needed for all Windows applications
#include <windows.h>
#include <d3d9.h>
#include <d3dx9.h>
#include <iostream>
using namespace std;


#define Move_Speed 10





// a structure for your custom vertex type
typedef struct CUSTOMVERTEX
{
FLOAT x, y, z; // the transformed, 3D position for the vertex
DWORD color; // the vertex color
}customV;

customV  g_Vertices[] =
{
// 1
{ -64.0f, 64.0f, -64.0f, D3DCOLOR_ARGB(0,0,0,255)},
{ 64.0f, 64.0f, -64.0f, D3DCOLOR_ARGB(0,0,0,255)},
{ -64.0f, -64.0f, -64.0f, D3DCOLOR_ARGB(0,0,0,255)},
{ 64.0f, -64.0f, -64.0f, D3DCOLOR_ARGB(0,0,0,255)},
// 2

{ -64.0f, 64.0f, 64.0f, D3DCOLOR_ARGB(0,255,0,0)},
{ -64.0f, -64.0f, 64.0f, D3DCOLOR_ARGB(0,255,0,0)},
{ 64.0f, 64.0f, 64.0f, D3DCOLOR_ARGB(0,255,0,0)},
{ 64.0f, -64.0f, 64.0f, D3DCOLOR_ARGB(0,255,0,0)},
// 3
{ -64.0f, 64.0f, 64.0f, D3DCOLOR_ARGB(0,0,255,0)},
{ 64.0f, 64.0f, 64.0f, D3DCOLOR_ARGB(0,0,255,0)},
{ -64.0f, 64.0f, -64.0f, D3DCOLOR_ARGB(0,0,255,0)},
{ 64.0f, 64.0f, -64.0f, D3DCOLOR_ARGB(0,0,255,0)},
// 4
{ -64.0f, -64.0f, 64.0f, D3DCOLOR_ARGB(0,255,0,0)},
{ -64.0f, -64.0f, -64.0f, D3DCOLOR_ARGB(0,255,0,0)},
{ 64.0f, -64.0f, 64.0f, D3DCOLOR_ARGB(0,255,0,0)},
{ 64.0f, -64.0f, -64.0f, D3DCOLOR_ARGB(0,255,0,0)},
// 5
{ 64.0f, 64.0f, -64.0f, D3DCOLOR_ARGB(0,255,255,255)},
{ 64.0f, 64.0f, 64.0f, D3DCOLOR_ARGB(0,255,255,255)},
{ 64.0f, -64.0f, -64.0f, D3DCOLOR_ARGB(0,255,255,255)},
{ 64.0f, -64.0f, 64.0f, D3DCOLOR_ARGB(0,255,255,255)},
// 6
{-64.0f, 64.0f, -64.0f, D3DCOLOR_ARGB(0,80,80,80)},
{-64.0f, -64.0f, -64.0f, D3DCOLOR_ARGB(0,80,80,80)},
{-64.0f, 64.0f, 64.0f, D3DCOLOR_ARGB(0,80,80,80)},
{-64.0f, -64.0f, 64.0f, D3DCOLOR_ARGB(0,80,80,80)},
};




//------------------------------------------------------------------------




HINSTANCE hInst; // global handle to hold the application instance
HWND wndHandle; // global variable to hold the window handle
// forward declarations

LPDIRECT3D9 pD3D; // the Direct3D object
LPDIRECT3DDEVICE9 pd3dDevice; // the Direct3D device

IDirect3DSurface9* surface; //personal surface pointer
IDirect3DSurface9* surface2;

LARGE_INTEGER timeStart; // holds the starting count
LARGE_INTEGER timeEnd; // holds the ending count
LARGE_INTEGER timerFreq; // holds the frequency of the counter

float anim_rate;


LPDIRECT3DVERTEXBUFFER9 buffer = NULL;
VOID* pVertices;

D3DXMATRIX matProj;
D3DXMATRIX matView;

//float CubeUp=400.0f;
//float CubeLeft=-80.0f;

float CubeUp=0.0f;
float CubeLeft=0.0f;
float CubeDepth=-1000.0f;
//-------------------------------------------------
bool initWindow( HINSTANCE hInstance );
LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM );

bool initDirect3D(void);
void render(void);
void cleanUp (void);

IDirect3DSurface9* getSurfaceFromBitmap(std::string filename);

HRESULT SetupVB(void);

void createCamera(float nearClip, float farClip);
void pointCamera(D3DXVECTOR3 cameraPosition, D3DXVECTOR3 cameraLook);

void createDirectionalLight ( void );
void createPointLight (void);


//-------------------------------------------------




// This is winmain, the main entry point for Windows applications
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow )
{


	






// Initialize the window
if ( !initWindow( hInstance ) ) //creates window (given instance)
return false;

if ( !initDirect3D( ) ) //init window for 3d usage
return false;




if (FAILED(SetupVB()))
	return false;


    QueryPerformanceFrequency(&timerFreq);



// main message loop:
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );

while( msg.message!=WM_QUIT )
{
	if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
	{
		TranslateMessage ( &msg );
		DispatchMessage ( &msg );
	}
	else
	{
		
		
		QueryPerformanceCounter(&timeStart);
		
		render( );

		QueryPerformanceCounter(&timeEnd);
		anim_rate =((float)timeEnd.QuadPart - (float)timeStart.QuadPart ) /timerFreq.QuadPart;

		
	}
}
 cleanUp ();
return (int) msg.wParam;
	
}



/******************************************************************************
* bool initWindow( HINSTANCE hInstance )
* initWindow registers the window class for the application, creates the window
******************************************************************************/
bool initWindow( HINSTANCE hInstance )
{
	WNDCLASSEX wcex;
	// Fill in the WNDCLASSEX structure. This describes how the window
	// will look to the system
	wcex.cbSize = sizeof(WNDCLASSEX); // the size of the structure
	wcex.style = CS_HREDRAW | CS_VREDRAW; // the class style
	wcex.lpfnWndProc = (WNDPROC)WndProc; // the window procedure callback
	wcex.cbClsExtra = 0; // extra bytes to allocate for this class
	wcex.cbWndExtra = 0; // extra bytes to allocate for this instance
	wcex.hInstance = hInstance; // handle to the application instance
	wcex.hIcon = 0; // icon to associate with the application
	wcex.hCursor = LoadCursor(NULL, IDC_ARROW);// the default cursor
	wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); // the background color
	wcex.lpszMenuName  = NULL; // the resource name for the menu
	wcex.lpszClassName = "DirectXExample"; // the class name being created
	wcex.hIconSm = 0; // the handle to the small icon
	RegisterClassEx(&wcex);


	// Create the window
	wndHandle = CreateWindow(
	"DirectXExample",
	"DirectXExample",
	WS_EX_TOPMOST | WS_POPUP | WS_VISIBLE,
	// the window class to use
	// the title bar text
	// the window style
	CW_USEDEFAULT, // the starting x coordinate
    CW_USEDEFAULT, // the starting y coordinate
	640, // the pixel width of the window
	480, // the pixel height of the window
	NULL, // the parent window; NULL for desktop
	NULL, // the menu for the application; NULL for
	// none
	hInstance, // the handle to the application instance
	NULL); // no values passed to the window
	// Make sure that the window handle that is created is valid
	
	if (!wndHandle)
	return false;

	// Display the window on the screen
	ShowWindow(wndHandle, SW_SHOW);
	UpdateWindow(wndHandle);
	return true;
}


/******************************************************************************
* LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam,
* LPARAM lParam)
* The window procedure
******************************************************************************/
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	// Check any available messages from the queue
	switch (message)
	{
		case WM_DESTROY:
		{
	    MessageBox(NULL,"Window has ended","End",MB_OK);
		PostQuitMessage(0);
		}
		break;
	
	case WM_KEYDOWN:
		{
			switch( wParam )
            {
                case VK_ESCAPE:
                PostQuitMessage(0);
                break;
           
                case VK_LEFT:
				CubeLeft-=Move_Speed;	
				break;
				
				case VK_RIGHT:
				CubeLeft+=Move_Speed;	
				break;

				case VK_UP:
				CubeUp+=Move_Speed;	
				break;

				case VK_DOWN:
				CubeUp-=Move_Speed;	
				break;

				case 189:
				CubeDepth-=Move_Speed;
				break;

				case 187:
				CubeDepth+=Move_Speed;
				break;



				//case VK_ASTERISK:{}
								

            }

	     	
		}
		break;
	
	}
	
	return DefWindowProc(hWnd, message, wParam, lParam);
}

/*********************************************************************
* initDirect3D
*********************************************************************/
bool initDirect3D(void)
{
	pD3D = NULL;
	pd3dDevice = NULL;


	if( NULL == ( pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
	{
	return false;
	}




	D3DPRESENT_PARAMETERS d3dpp;
	ZeroMemory( &d3dpp, sizeof( d3dpp ) );
	d3dpp.Windowed = FALSE;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
	d3dpp.BackBufferCount = 1;
	d3dpp.BackBufferHeight = 480;
	d3dpp.BackBufferWidth = 640;
	d3dpp.hDeviceWindow = wndHandle;
	




	if( FAILED( pD3D->CreateDevice( D3DADAPTER_DEFAULT,D3DDEVTYPE_REF,wndHandle,
		                            D3DCREATE_SOFTWARE_VERTEXPROCESSING,&d3dpp,&pd3dDevice ) ) )
	{
	return false;
	}
	return true;
}

void render(void)
{
	
	HRESULT hr;
	D3DXMATRIX objMat, matRotate, finalMat,matTranslate,matScale;
	
D3DXMATRIX matFinal;

    IDirect3DSurface9* backbuffer = NULL;
	if( NULL == pd3dDevice )
	return;

  


    pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET,
	D3DCOLOR_XRGB( 0,80,60 ), 1.0f, 0 );

  

if ( SUCCEEDED( pd3dDevice->BeginScene( ) ) )
{
	pd3dDevice->SetStreamSource ( 0, buffer, 0, sizeof(customV) );

	pd3dDevice->SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE);

	createCamera(0.0f, 0.0f);
	pointCamera(D3DXVECTOR3 (-64.0f, 256.0f, CubeDepth), D3DXVECTOR3    (CubeLeft, CubeUp,0.0f));

	
   
   
	
	
         pd3dDevice->SetRenderState (D3DRS_SPECULARENABLE, TRUE);
	pd3dDevice->SetRenderState( D3DRS_LIGHTING, TRUE);
	createPointLight ();
	pd3dDevice->SetRenderState (D3DRS_AMBIENT, D3DCOLOR_XRGB (255, 0, 255));


	
	 

		
	D3DXMatrixIdentity(&objMat);
	
	D3DXMatrixRotationZ(&matRotate,50.0f);

	D3DXMatrixMultiply(&finalMat, &objMat, &matRotate);
    
	D3DXMatrixTranslation(&matRotate, -100.0f,0.0f,0.0f);
	D3DXMatrixMultiply(&finalMat,&finalMat, &matRotate);


    pd3dDevice->SetTransform(D3DTS_WORLD, &finalMat);
   







	pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2 );
	pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 4, 2 );
	pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 8, 2 );
	pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 12, 2 );
	pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 16, 2 );
	pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 20, 2 );
	

   
	hr=pd3dDevice->EndScene();





	if ( FAILED ( hr ) )
	return ;


}

	
	

    //pd3dDevice->GetBackBuffer( 0,0,D3DBACKBUFFER_TYPE_MONO,&backbuffer );
  
   	
	// Present the back buffer contents to the display
	pd3dDevice->Present( NULL, NULL, NULL, NULL );
	

		
	
}


void cleanUp (void)
{
// Release the device and the Direct3D object
if( pd3dDevice != NULL )
pd3dDevice->Release( );
if( pD3D != NULL )
pD3D->Release( );
}



/**********************************************************
* getSurfaceFromBitmap
**********************************************************/
IDirect3DSurface9* getSurfaceFromBitmap(std::string filename)
{
	HRESULT hResult;
	IDirect3DSurface9* surface = NULL;
	D3DXIMAGE_INFO imageInfo; // holds details concerning this bitmap

	// Get the width and height info from this bitmap
	hResult = D3DXGetImageInfoFromFile(filename.c_str(), &imageInfo);
	// Make sure that the call to D3DXGetImageInfoFromFile succeeded
	if FAILED (hResult)
	return NULL;

	// Create the offscreen surface that will hold the bitmap
	hResult = pd3dDevice->CreateOffscreenPlainSurface( 640,
	480,
	D3DFMT_X8R8G8B8,
	D3DPOOL_DEFAULT,
	&surface,
	NULL );

	// Make sure that this function call did not fail; if it did,
	// exit this function
	if ( FAILED( hResult ) )
	return NULL;

	// Load the bitmap into the surface that was created earlier
	hResult = D3DXLoadSurfaceFromFile( surface,
	NULL,
	NULL,
	filename.c_str( ),
	NULL,
	D3DX_DEFAULT,
	0,
	NULL );
	if ( FAILED( hResult ) )
	return NULL;
	return surface;
}






HRESULT SetupVB()
{
	HRESULT hr;
    // Define the vertices to be used in the buffer
	

	// Create the vertex buffer
	hr = pd3dDevice->CreateVertexBuffer(
	sizeof(g_Vertices)*sizeof(customV),
	0,
	D3DFVF_XYZ | D3DFVF_DIFFUSE,
	D3DPOOL_DEFAULT,
	&buffer,
	NULL );

	if FAILED ( hr )
	return E_FAIL;

	
	

	hr = buffer->Lock( 0,sizeof(g_Vertices), ( void** ) &pVertices, 0 );

	if FAILED (hr)
	return E_FAIL;

	memcpy( pVertices, g_Vertices, sizeof(g_Vertices) );

	buffer->Unlock();

    return S_OK;
}


void createCamera(float nearClip, float farClip)
{
	// Here, you specify the field of view, aspect ratio,
	// and near and far clipping planes
	D3DXMatrixPerspectiveFovLH(&matProj, D3DX_PI/4, 640/480,nearClip, farClip);
	// Apply the matProj matrix to the projection stage of the pipeline
	pd3dDevice->SetTransform(D3DTS_PROJECTION, &matProj);
}

/*************************************************************************
* pointCamera
* points the camera at a location specified by the passed vector
*************************************************************************/
void pointCamera(D3DXVECTOR3 cameraPosition, D3DXVECTOR3 cameraLook)
{
	D3DXMatrixLookAtLH (&matView,
	&cameraPosition, //camera position
	&cameraLook, //look at position
	&D3DXVECTOR3 (0.0f, 1.0f, 0.0f)); //up direction
	// Apply the matrix to the view stage of the pipeline
	pd3dDevice->SetTransform (D3DTS_VIEW, &matView);
}

void createDirectionalLight ( void )
{
// Create and turn on a directional light
D3DLIGHT9 light;
// Set the type of light
light.Type = D3DLIGHT_DIRECTIONAL;
// Set the direction that this light will generate light from
D3DXVECTOR3 vDir( 1.0f, 0.0f, 0.0f );
// Normalize the light direction
D3DXVec3Normalize ((D3DXVECTOR3*) &light.Direction, &vDir);
// Set the diffuse color for this light
light.Diffuse.r = 0.0f;
light.Diffuse.g = 0.0f;
light.Diffuse.b = 0.5f;
// Set the ambient color for this light
light.Ambient.r = 0.0f;
light.Ambient.g = 0.0f;
light.Ambient.b = 0.3f;
// Set the range of this light
light.Range = sqrtf (FLT_MAX);
// Tell Direct3D to set the newly created light
pd3dDevice->SetLight (0, &light);
// Enable the new light
pd3dDevice->LightEnable (0, TRUE);
}

void createPointLight (void)
{
// Create and turn on a directional light
D3DLIGHT9 light;
// Set the type of light
light.Type = D3DLIGHT_POINT;
// Set the position for this light
light.Position = D3DXVECTOR3( 200.0f, 150.0f, 0.0f );
// Set the red, green, and blue diffuse components for this
// light source
light.Diffuse.r = 1.0f;
light.Diffuse.g = 0.5f;
light.Diffuse.b = 0.5f;
// Set the red, green, and blue ambient components for this
// light source
light.Ambient.r = 0.5f;
light.Ambient.g = 0.0f;
light.Ambient.b = 0.0f;
light.Range = sqrtf(FLT_MAX);
// Tell Direct3D to create the new light
pd3dDevice->SetLight(0, &light );
// Enable the light
pd3dDevice->LightEnable (0, TRUE);
}


What am I missing ? thanks

Share this post


Link to post
Share on other sites
Three things:

1. Your vertices need normals in order to use lighting

// order not important.
fvf = D3DFVF_POSITION | D3DFVF_DIFFUSE | D3DFVF_NORMAL;

// order important
class MyVert
{
public:
float x,y,z;
float nx,ny,nz;
DWORD color;
};

Set the normals of your vertices to a unit vector pointing out from your face. For example, the right faces of a cube would have a normal (1,0,0), while the left faces of a cube would have a normal of (-1,0,0). The top faces would be (0,1,0), etc.

2. Also your point light will require attenuation values, which control how quickly the light intensity falls off, and the shape of the curve. Look up the SDK page on the mathematics of lighting for details of what the numbers do.

3. You need a material

D3DMATERIAL9 mat;

mat.Diffuse.R = 1;
mat.Diffuse.G = 1;
mat.Diffuse.B = 1;
mat.Diffuse.A = 0;
// Set specular, emissive, and ambient too.
pDev->SetMaterial(&mat);

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this