472,354 Members | 1,416 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,354 software developers and data experts.

Why isn't the lighting working?

There's a sample project in the DirectX SDK that draws a revolving
triangle. From it, I've written a simple program that draws a
revolving box. The problem is, even though I have set the material and
the light, the box is completly black. I don't know what's wrong.

The C# tutorial on an internet site, which I have read to write this,
calls SetupLights() each time in the Render(), but the example
(written in Visual C++) on my textbook initialzes lights and materials
only once at the setup() function. I thought the later way is better
so I initialized them at the InitializeGraphics() method.

Could you please tell me what is wrong? You can download this project
file at
http://www.gloomywind.com/box.rar
Or see the complete code below.
Thanks.

//-----------------------------------------------------------------------------
// File: Matrices.cs
//
// Desc: Now that we know how to create a device and render some 2D
vertices,
// this tutorial goes the next step and renders 3D geometry. To
deal with
// 3D geometry we need to introduce the use of 4x4 matrices to
transform
// the geometry with translations, rotations, scaling, and
setting up our
// camera.
//
// Geometry is defined in model space. We can move it
(translation),
// rotate it (rotation), or stretch it (scaling) using a world
transform.
// The geometry is then said to be in world space. Next, we need
to
// position the camera, or eye point, somewhere to look at the
geometry.
// Another transform, via the view matrix, is used, to position
and
// rotate our view. With the geometry then in view space, our
last
// transform is the projection transform, which "projects" the
3D scene
// into our 2D viewport.
//
// Note that in this tutorial, we are introducing the use of
D3DX, which
// is a set of helper utilities for D3D. In this case, we are
using some
// of D3DX's useful matrix initialization functions. To use
D3DX, simply
// include the D3DX reference in your project
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using Direct3D=Microsoft.DirectX.Direct3D;
using System.Diagnostics;

namespace MatricesTutorial
{
public class Matrices : Form
{
// Our global variables for this project
Device device = null; // Our rendering device
VertexBuffer vertexBuffer = null;
IndexBuffer MyIndexBuffer = null;
PresentParameters presentParams = new PresentParameters();
bool pause = false;

public Matrices()
{
// Set the initial size of our form
this.ClientSize = new System.Drawing.Size(400,300);
// And it's caption
this.Text = "Direct3D Tutorial 3 - Matrices";
}

public bool InitializeGraphics()
{
try
{
// Now let's setup our D3D stuff
presentParams.Windowed=true;
presentParams.AutoDepthStencilFormat = DepthFormat.D16;
presentParams.EnableAutoDepthStencil= true;
presentParams.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Hardware, this,
CreateFlags.SoftwareVertexProcessing, presentParams);
device.DeviceReset += new System.EventHandler(this.OnResetDevice);
this.OnCreateDevice(device, null);
this.OnResetDevice(device, null);
device.RenderState.Lighting = true;
device.RenderState.NormalizeNormals = true;
device.RenderState.SpecularEnable = true;
SetupMaterials();
SetupLights();
pause = false;
return true;
}
catch (DirectXException)
{
return false;
}
}
public void OnCreateDevice(object sender, EventArgs e)
{
Debug.WriteLine("OnCreateDevice");
Device dev = (Device)sender;
// Now Create the VB
vertexBuffer = new
VertexBuffer(typeof(CustomVertex.PositionNormal), 24, dev, 0,
CustomVertex.PositionNormal.Format, Pool.Default);
vertexBuffer.Created += new
System.EventHandler(this.OnCreateVertexBuffer);
MyIndexBuffer = new IndexBuffer(typeof(short), 36, dev, 0,
Pool.Default);
MyIndexBuffer.Created += new EventHandler(OnCreateMyIndexBuffer);
this.OnCreateVertexBuffer(vertexBuffer, null);
}
void OnCreateMyIndexBuffer(object sender, EventArgs e)
{
IndexBuffer id = (IndexBuffer)sender;
short[] indices = (short[])id.Lock(0, 0);
int index = 0;
indices[index++] = 0;
indices[index++] = 2;
indices[index++] = 1;
indices[index++] = 1;
indices[index++] = 2;
indices[index++] = 3;

indices[index++] = 4;
indices[index++] = 6;
indices[index++] = 5;
indices[index++] = 5;
indices[index++] = 6;
indices[index++] = 7;

indices[index++] = 8;
indices[index++] = 10;
indices[index++] = 9;
indices[index++] = 9;
indices[index++] = 10;
indices[index++] = 11;

indices[index++] = 12;
indices[index++] = 14;
indices[index++] = 13;
indices[index++] = 13;
indices[index++] = 14;
indices[index++] = 15;

indices[index++] = 16;
indices[index++] = 18;
indices[index++] = 17;
indices[index++] = 17;
indices[index++] = 18;
indices[index++] = 19;

indices[index++] = 20;
indices[index++] = 22;
indices[index++] = 21;
indices[index++] = 21;
indices[index++] = 22;
indices[index++] = 23;

id.Unlock();
}
public void OnResetDevice(object sender, EventArgs e)
{
Device dev = (Device)sender;
// Turn off culling, so we see the front and back of the triangle
//dev.RenderState.CullMode = Cull.None;
// Turn off D3D lighting, since we are providing our own vertex
colors
//dev.RenderState.Lighting =false;
Debug.WriteLine("Reset");
}
public void OnCreateVertexBuffer(object sender, EventArgs e)
{
VertexBuffer vb = (VertexBuffer)sender;
CustomVertex.PositionNormal[] verts =
(CustomVertex.PositionNormal[])vb.Lock(0,0);
int index = 0;
//Front
verts[index++] = new CustomVertex.PositionNormal(0, -1, 1, 0, -1,
0);
verts[index++] = new CustomVertex.PositionNormal(1, -1, 1, 0, -1,
0);
verts[index++] = new CustomVertex.PositionNormal(0, -1, 0, 0, -1,
0);
verts[index++] = new CustomVertex.PositionNormal(1, -1, 0, 0, -1,
0);
//Right
verts[index++] = new CustomVertex.PositionNormal(1, -1, 1, 1,0, 0);
verts[index++] = new CustomVertex.PositionNormal(1, 0, 1, 1, 0, 0);
verts[index++] = new CustomVertex.PositionNormal(1, -1, 0, 1, 0,
0);
verts[index++] = new CustomVertex.PositionNormal(1, 0, 0, 1, 0, 0);
//Back
verts[index++] = new CustomVertex.PositionNormal(1, 0, 1, 0, 1, 0);
verts[index++] = new CustomVertex.PositionNormal(0, 0, 1, 0, 1, 0);
verts[index++] = new CustomVertex.PositionNormal(1, 0, 0, 0, 1, 0);
verts[index++] = new CustomVertex.PositionNormal(0, 0, 0, 0, 1, 0);
//Left
verts[index++] = new CustomVertex.PositionNormal(0, 0, 1, -1, 0,
0);
verts[index++] = new CustomVertex.PositionNormal(0, -1, 1, -1, 0,
0);
verts[index++] = new CustomVertex.PositionNormal(0, 0, 0, -1, 0,
0);
verts[index++] = new CustomVertex.PositionNormal(0, -1, 0, -1, 0,
0);
//Top
verts[index++] = new CustomVertex.PositionNormal(0, 0, 1, 0, 0, 1);
verts[index++] = new CustomVertex.PositionNormal(1, 0, 1, 0, 0, 1);
verts[index++] = new CustomVertex.PositionNormal(0, -1, 1, 0, 0,
1);
verts[index++] = new CustomVertex.PositionNormal(1, -1, 1, 0, 0,
1);
//Bottom
verts[index++] = new CustomVertex.PositionNormal(1, 0, 0, 0, 0,
-1);
verts[index++] = new CustomVertex.PositionNormal(0, 0, 0, 0, 0,
-1);
verts[index++] = new CustomVertex.PositionNormal(1, -1, 0, 0, 0,
-1);
verts[index++] = new CustomVertex.PositionNormal(0, -1, 0, 0, 0,
-1);

vb.Unlock();
}

private void Render()
{
if (device == null)
return;

if (pause)
return;
//Clear the backbuffer to a blue color
device.Clear(ClearFlags.Target|ClearFlags.ZBuffer ,
System.Drawing.Color.White, 1.0f, 0);
//Begin the scene
device.BeginScene();
// Setup the world, view, and projection matrices
SetupMatrices();
device.SetStreamSource(0, vertexBuffer, 0);
device.VertexFormat = CustomVertex.PositionNormal.Format;
device.Indices = MyIndexBuffer;
device.DrawIndexedPrimitives(PrimitiveType.Triangl eList, 0, 0, 24,
0, 12);

//End the scene
device.EndScene();
device.Present();
}
protected void SetupMaterials()
{
Material mat = new Material();
// Set the properties of the material
// The object itself will be blue
mat.Diffuse = Color.Red;
//mat.Emissive = Color.Orange;
//mat.Ambient = Color.Purple;

// We want it to look slightly dull, so maybe a grey
// wide highlight
mat.Specular = Color.LightGray;
mat.SpecularSharpness = 15.0F;

device.Material = mat;
// Very important - without this there is no specularity
device.RenderState.SpecularEnable = true;
}
private void SetupMatrices()
{
// For our world matrix, we will just rotate the object about the y-
axis.

// Set up the rotation matrix to generate 1 full rotation (2*PI
radians)
// every 1000 ms. To avoid the loss of precision inherent in very
high
// floating point numbers, the system time is modulated by the
rotation
// period before conversion to a radian angle.
int iTime = Environment.TickCount % 7000;
float fAngle = iTime * (2.0f * (float)Math.PI) / 7000.0f;
device.Transform.World = Matrix.RotationYawPitchRoll(fAngle,
fAngle,fAngle );

// Set up our view matrix. A view matrix can be defined given an
eye point,
// a point to lookat, and a direction for which way is up. Here, we
set the
// eye five units back along the z-axis and up three units, look at
the
// origin, and define "up" to be in the y-direction.
device.Transform.View = Matrix.LookAtLH( new Vector3( 0.0f,
3.0f,-5.0f ), new Vector3( 0.0f, 0.0f, 0.0f ), new Vector3( 0.0f,
1.0f, 0.0f ) );

// For the projection matrix, we set up a perspective transform
(which
// transforms geometry from 3D view space to 2D viewport space,
with
// a perspective divide making objects smaller in the distance). To
build
// a perpsective transform, we need the field of view (1/4 pi is
common),
// the aspect ratio, and the near and far clipping planes (which
define at
// what distances geometry should be no longer be rendered).
device.Transform.Projection =
Matrix.PerspectiveFovLH( (float)Math.PI / 4, 1.0f, 1.0f, 100.0f );
}
protected void SetupLights()
{
device.Lights[0].Diffuse = Color.Yellow;
device.Lights[0].Specular = Color.Yellow;
device.Lights[0].Ambient = Color.Yellow;
device.Lights[0].Type = LightType.Directional;
device.Lights[0].Direction = new Vector3(1, -1, 0);

device.Lights[0].Update();

device.Lights[0].Enabled = true;
device.RenderState.Ambient = Color.FromArgb(0x40, 0x40, 0x40);
}
protected override void OnPaint(System.Windows.Forms.PaintEventArgs
e)
{
this.Render(); // Render on painting
}
protected override void
OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
{
if ((int)(byte)e.KeyChar == (int)System.Windows.Forms.Keys.Escape)
this.Close(); // Esc was pressed
}
protected override void OnResize(System.EventArgs e)
{
pause = ((this.WindowState == FormWindowState.Minimized)
|| !this.Visible);
}

/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
using (Matrices frm = new Matrices())
{
if (!frm.InitializeGraphics()) // Initialize Direct3D
{
MessageBox.Show("Could not initialize Direct3D.
This tutorial will exit.");
return;
}
frm.Show();
frm.ClientSize = new Size(500, 500);
// While the form is still valid, render and process
messages
while(frm.Created)
{
frm.Render();
Application.DoEvents();
}
}
}
}
}

Sep 22 '07 #1
0 1385

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Sebastian Aguilera | last post by:
Hi everyone. I have some troubles using the unserialize() function. I have serialized an array and that works perfect: echo '<input type="hidden" name="vardekedja" value="'.serialize($_POST...
63
by: IAmIronMan | last post by:
This individual is stealing other peoples code and claiming it as his own. The proof is when I asked him to explain his code he would not. For proof view these threads in dotnet.languages.vb ...
10
by: sp | last post by:
The application is written in Visual Basic / .NET and working without problems under Windows XP, Windows 2000, Windows 2003 but it isn't working under Windows ME and Windows 98 - the computer...
2
by: PrinceMhul | last post by:
var objListBox = document.getElementById('catalist'); var val = objListBox.value; var txt = dyevalue00.value; document.getElementById(val).value = txt; To explain real quick, this is for a...
9
by: Ecohouse | last post by:
I have a main form with two subforms. The first subform has the child link to the main form identity key. subform1 - Master Field: SK Child Field: TrainingMasterSK The second subform has a...
11
by: drumsticksplinter | last post by:
Hi, I'm quite new to all this so please forgive my lack of technical description. Project background: Basically I have had the vision of creating a home lighting control system for the last 3...
0
by: Now You Know | last post by:
Christmas Decor Residential Commercial decoration Lighting install Los Angeles http://christmaslightinginstall.blogspot.com/
7
by: nassausky | last post by:
I acquired a very basic redirect script from: http://www.minisitegallery.com/blog/php-javascript-countdown-script-with-timezone-setting.html which is supposed to count down to a specified date and...
12
by: Hendor | last post by:
Hi all. I've recently set up Apache 2.2 with PHP 5.2 and MySQL 5.1. I played around with SQL a bit, and now I'm trying to access it with PHP. I currently have the code: <?php #...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
1
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. header("Location:".$urlback); Is this the right layout the...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it so the python app could use a http request to get...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and credentials and received a successful connection...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.