473,903 Members | 3,525 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 InitializeGraph ics() 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.Direc tX;
using Microsoft.Direc tX.Direct3D;
using Direct3D=Micros oft.DirectX.Dir ect3D;
using System.Diagnost ics;

namespace MatricesTutoria l
{
public class Matrices : Form
{
// Our global variables for this project
Device device = null; // Our rendering device
VertexBuffer vertexBuffer = null;
IndexBuffer MyIndexBuffer = null;
PresentParamete rs presentParams = new PresentParamete rs();
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 InitializeGraph ics()
{
try
{
// Now let's setup our D3D stuff
presentParams.W indowed=true;
presentParams.A utoDepthStencil Format = DepthFormat.D16 ;
presentParams.E nableAutoDepthS tencil= true;
presentParams.S wapEffect = SwapEffect.Disc ard;
device = new Device(0, DeviceType.Hard ware, this,
CreateFlags.Sof twareVertexProc essing, presentParams);
device.DeviceRe set += new System.EventHan dler(this.OnRes etDevice);
this.OnCreateDe vice(device, null);
this.OnResetDev ice(device, null);
device.RenderSt ate.Lighting = true;
device.RenderSt ate.NormalizeNo rmals = true;
device.RenderSt ate.SpecularEna ble = true;
SetupMaterials( );
SetupLights();
pause = false;
return true;
}
catch (DirectXExcepti on)
{
return false;
}
}
public void OnCreateDevice( object sender, EventArgs e)
{
Debug.WriteLine ("OnCreateDevic e");
Device dev = (Device)sender;
// Now Create the VB
vertexBuffer = new
VertexBuffer(ty peof(CustomVert ex.PositionNorm al), 24, dev, 0,
CustomVertex.Po sitionNormal.Fo rmat, Pool.Default);
vertexBuffer.Cr eated += new
System.EventHan dler(this.OnCre ateVertexBuffer );
MyIndexBuffer = new IndexBuffer(typ eof(short), 36, dev, 0,
Pool.Default);
MyIndexBuffer.C reated += new EventHandler(On CreateMyIndexBu ffer);
this.OnCreateVe rtexBuffer(vert exBuffer, null);
}
void OnCreateMyIndex Buffer(object sender, EventArgs e)
{
IndexBuffer id = (IndexBuffer)se nder;
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(o bject 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 OnCreateVertexB uffer(object sender, EventArgs e)
{
VertexBuffer vb = (VertexBuffer)s ender;
CustomVertex.Po sitionNormal[] verts =
(CustomVertex.P ositionNormal[])vb.Lock(0,0);
int index = 0;
//Front
verts[index++] = new CustomVertex.Po sitionNormal(0, -1, 1, 0, -1,
0);
verts[index++] = new CustomVertex.Po sitionNormal(1, -1, 1, 0, -1,
0);
verts[index++] = new CustomVertex.Po sitionNormal(0, -1, 0, 0, -1,
0);
verts[index++] = new CustomVertex.Po sitionNormal(1, -1, 0, 0, -1,
0);
//Right
verts[index++] = new CustomVertex.Po sitionNormal(1, -1, 1, 1,0, 0);
verts[index++] = new CustomVertex.Po sitionNormal(1, 0, 1, 1, 0, 0);
verts[index++] = new CustomVertex.Po sitionNormal(1, -1, 0, 1, 0,
0);
verts[index++] = new CustomVertex.Po sitionNormal(1, 0, 0, 1, 0, 0);
//Back
verts[index++] = new CustomVertex.Po sitionNormal(1, 0, 1, 0, 1, 0);
verts[index++] = new CustomVertex.Po sitionNormal(0, 0, 1, 0, 1, 0);
verts[index++] = new CustomVertex.Po sitionNormal(1, 0, 0, 0, 1, 0);
verts[index++] = new CustomVertex.Po sitionNormal(0, 0, 0, 0, 1, 0);
//Left
verts[index++] = new CustomVertex.Po sitionNormal(0, 0, 1, -1, 0,
0);
verts[index++] = new CustomVertex.Po sitionNormal(0, -1, 1, -1, 0,
0);
verts[index++] = new CustomVertex.Po sitionNormal(0, 0, 0, -1, 0,
0);
verts[index++] = new CustomVertex.Po sitionNormal(0, -1, 0, -1, 0,
0);
//Top
verts[index++] = new CustomVertex.Po sitionNormal(0, 0, 1, 0, 0, 1);
verts[index++] = new CustomVertex.Po sitionNormal(1, 0, 1, 0, 0, 1);
verts[index++] = new CustomVertex.Po sitionNormal(0, -1, 1, 0, 0,
1);
verts[index++] = new CustomVertex.Po sitionNormal(1, -1, 1, 0, 0,
1);
//Bottom
verts[index++] = new CustomVertex.Po sitionNormal(1, 0, 0, 0, 0,
-1);
verts[index++] = new CustomVertex.Po sitionNormal(0, 0, 0, 0, 0,
-1);
verts[index++] = new CustomVertex.Po sitionNormal(1, -1, 0, 0, 0,
-1);
verts[index++] = new CustomVertex.Po sitionNormal(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(Cl earFlags.Target |ClearFlags.ZBu ffer ,
System.Drawing. Color.White, 1.0f, 0);
//Begin the scene
device.BeginSce ne();
// Setup the world, view, and projection matrices
SetupMatrices() ;
device.SetStrea mSource(0, vertexBuffer, 0);
device.VertexFo rmat = CustomVertex.Po sitionNormal.Fo rmat;
device.Indices = MyIndexBuffer;
device.DrawInde xedPrimitives(P rimitiveType.Tr iangleList, 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.SpecularSha rpness = 15.0F;

device.Material = mat;
// Very important - without this there is no specularity
device.RenderSt ate.SpecularEna ble = 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.Tic kCount % 7000;
float fAngle = iTime * (2.0f * (float)Math.PI) / 7000.0f;
device.Transfor m.World = Matrix.Rotation YawPitchRoll(fA ngle,
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.Transfor m.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.Transfor m.Projection =
Matrix.Perspect iveFovLH( (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.Direc tional;
device.Lights[0].Direction = new Vector3(1, -1, 0);

device.Lights[0].Update();

device.Lights[0].Enabled = true;
device.RenderSt ate.Ambient = Color.FromArgb( 0x40, 0x40, 0x40);
}
protected override void OnPaint(System. Windows.Forms.P aintEventArgs
e)
{
this.Render(); // Render on painting
}
protected override void
OnKeyPress(Syst em.Windows.Form s.KeyPressEvent Args e)
{
if ((int)(byte)e.K eyChar == (int)System.Win dows.Forms.Keys .Escape)
this.Close(); // Esc was pressed
}
protected override void OnResize(System .EventArgs e)
{
pause = ((this.WindowSt ate == FormWindowState .Minimized)
|| !this.Visible);
}

/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
using (Matrices frm = new Matrices())
{
if (!frm.Initializ eGraphics()) // 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.Creat ed)
{
frm.Render();
Application.DoE vents();
}
}
}
}
}

Sep 22 '07 #1
0 1512

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

Similar topics

1
2214
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 ).'">'; Gives the output: a:3:{i:0;s:7:
63
2456
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 Giving Back(Thank You) scorpion53061 Straighten This Out....
10
1743
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 hangs. After computers hangs you can move mouse but can not press any key. Alt - Ctrl- Del isn’t working so you have to reset the computer by pressing button. I checked several Win 98 and Me - clean install to - always the same! At the beginning...
2
1288
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 character maker. The "catalist" is a listbox with different values such as "Body1" - "Head" - "Shoes" - "Hair" etc "dyevalue00" is a textbox I have many textboxes that are named the same as the "catalist" values
9
9733
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 master-child link to the first subform. subform2 - Master Field: subTrainingModule.Form!TrainingModuleTopicSK Child Field: TrainingModuleTopicSK
11
3142
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 years. This year I have been trying really hard to get a prototype model working. I need to work out how to use visual basic to 'fade' to a desired figure in a number of seconds. From there I can convert the figure into an analogue voltage (0 - 10v)...
0
1087
by: Now You Know | last post by:
Christmas Decor Residential Commercial decoration Lighting install Los Angeles http://christmaslightinginstall.blogspot.com/
7
2051
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 switch to a new webpage after that date. The original coder had included this quote with the code: It uses PHP to acquire the date from the server and javascript to keep refreshing the live countdown timer. Ok the javascript counter...
12
4960
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 # error_reporting(E_ALL); # ini_set('display_errors', true); echo "test"; $link = mysql_connect('localhost', 'root', '');
0
10006
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9853
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11294
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10990
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10504
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9692
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8057
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7215
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4734
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.