Jump to content
  • Advertisement
Sign in to follow this  
ScopeDynamo

When lighting goes bad IV (c)FOX

This topic is 4844 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Can anyone see what's up with this lighting code? It's basically a simple omni point light class, but it's just resulting in shadeless black meshes.

namespace Vivid.Lighting
{
    public class Light : Pivot
    {
        static public bool[] LightUsed = new bool[256];
        static public int lightsUsed = 0;
        static public int lightLimit = 8;
        static public ArrayList lights = new ArrayList();
        private int handle;
        /// <summary>
        /// For internal use.
        /// </summary>
        /// <returns></returns>
        static public int ObtainFreeLight()
        {
            if (lightsUsed == lightLimit)
            {
                return -1;
            }
            LightUsed[lightsUsed] = true;
            lightsUsed++;
            return (lightsUsed - 1);
        }

        /// <summary>
        /// default Point Light constructor. 
        /// </summary>
        public Light()
        {
            handle = ObtainFreeLight();
            if (handle == -1)
            {
                System.Windows.Forms.MessageBox.Show("Ran out of free hardware lights", "DX ERROR");
            }
            Engine.hwDevice.Lights[handle].Diffuse = System.Drawing.Color.LightBlue;
            Engine.hwDevice.Lights[handle].Type = LightType.Point;
            Engine.hwDevice.Lights[handle].Update();
            Engine.hwDevice.Lights[handle].Range = 500;
            Engine.hwDevice.Lights[handle].Enabled = true;
            Light.lights.Add(this);
            Sync();
            Light.AmbientLight(120, 120, 120);

        }

        public void Sync()
        {
            Engine.hwDevice.Lights[handle].Update();
            Engine.hwDevice.Lights[handle].Position = new Vector3(this.X,this.Y,this.Z);
        }

        static public void SyncLights()
        {
            foreach (Light light in lights)
            {
                light.Sync();
            }
            Engine.hwDevice.RenderState.Lighting = true;
         
        }
        
        static public void AmbientLight(int red, int blue, int green)
        {
            Engine.hwDevice.RenderState.Ambient = Light.genColor(red, blue, green,255);
        }

        static public System.Drawing.Color genColor(int  r, int  g, int  b,int  a)
        {
            return System.Drawing.Color.FromArgb(a, r, g, b);
        }

    }
}





Here's the geo class, there's a function in there that generates normals I'm not sure that's working. It worked in it's original form, but I had to convert it over to C#.


namespace Vivid
{
    namespace CustomVertex
    {
        public struct Vertex
        {
         
            public float X;
            public float Y;
            public float Z;
            public float nx;
            public float ny;
            public float nz;
            public float u0,v0;
            public float u1,v1;
            public float u2,v2;
            public float u3,v3;
            public UInt32 Color;
            public static readonly D3D.VertexFormats Format = D3D.VertexFormats.Position | D3D.VertexFormats.Normal | D3D.VertexFormats.Texture0 | D3D.VertexFormats.Texture1 | D3D.VertexFormats.Texture2 | D3D.VertexFormats.Texture3 | D3D.VertexFormats.Diffuse;
            public static readonly int StrideSize=DX.DXHelp.GetTypeSize(typeof(Vertex));
            public Vertex(float p_x, float p_y, float p_z)
            {
                X = p_x;
                Y = p_y;
                Z = p_z;
                nx = ny = nz = 0;
                u0=u1=u2=u3=v0=v1=v2=v3=0;
                Color = 0;
            }
            public Vertex(float p_x,float p_y,float p_z,uint p_color)
            {
                X=p_x;
                Y=p_y;
                Z=p_z;
                nx = ny = nz = 0;
                u0=u1=u2=u3=v0=v1=v2=v3=0;
                Color = p_color;
            }
        }
  
        public struct TransformedVivid2
        {
        }
        public struct TransformedShape
        {
        }
    }

    public class Triangle
    {
        D3D.CustomVertex.PositionNormalTextured[] vertices;
        public Triangle()
        {
            vertices = new D3D.CustomVertex.PositionNormalTextured[3];
        }

        public Triangle(D3D.CustomVertex.PositionNormalTextured  vertex1,D3D.CustomVertex.PositionNormalTextured vertex2, D3D.CustomVertex.PositionNormalTextured vertex3)
        {
            vertices = new D3D.CustomVertex.PositionNormalTextured[3];
            vertices[0] = vertex1;
            vertices[1] = vertex2;
            vertices[2] = vertex3;
        }

    }
    public class Geo
    {
     
        private VertexBuffer vertexBuf;
        private IndexBuffer indexBuf;
        private D3D.CustomVertex.PositionNormalTextured[] vertices;
        private bool isLocked;
        private int numVerts, numTris;
        private ArrayList triangles = new ArrayList();
        private int[] indices;
        
        private bool SizeTo(int verts, int tris)
        {
                 
            if (verts != -1)
            {
               if (vertices == null)
                {
                    vertices = new D3D.CustomVertex.PositionNormalTextured[verts];
                }
                else
                {
                    D3D.CustomVertex.PositionNormalTextured[] newVerts = new D3D.CustomVertex.PositionNormalTextured[verts];
                    vertices.CopyTo(newVerts,0);
                    vertices = newVerts;
                }
                if (vertices == null)return (false);
            }
            if (tris != -1)
            {
                if (indices == null)
                {
                    indices = new int[tris * 3];
                }
                else
                {
                    int[] newInds = new int[tris * 3];
                    indices.CopyTo(newInds, 0);
                    indices = newInds;
                }
                if (indices == null) return (false);
            }
            return (true);
        }
        /// <summary>
        /// Creates a vertex.
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="z"></param>
        /// <returns>Integer handle unique to this instance</returns>
        public int CreateVertex(float x, float y, float z)
        {
            D3D.CustomVertex.PositionNormalTextured vert = new D3D.CustomVertex.PositionNormalTextured(x, y, z, 0, 0, 0, 0, 0);
            vertices[numVerts] = vert;
          //  vert.GeoId = numVerts;
            numVerts++;
            if (numVerts == vertices.GetLength(0))
            {
                SizeTo(vertices.GetLength(0) * 2, -1);
            }
            return(numVerts-1);
        }

        /// <summary>
        /// Create a triangle object comprised of three vertices.
        /// </summary>
        /// <param name="vertex1">Vertex 1</param>
        /// <param name="vertex2">Vertex 2</param>
        /// <param name="vertex3">Vertex 3</param>
        /// <returns>Integer handle unique to this geo instance</returns>
        public int CreateTriangle(int vertex1, int vertex2, int vertex3)
        {
            Triangle newTri = new Triangle(vertices[vertex1], vertices[vertex2], vertices[vertex3]);
            indices[numTris * 3] = vertex1;
            indices[numTris * 3+1] = vertex2;
            indices[numTris * 3+2] = vertex3;
            numTris++;
            if (numTris == indices.GetLength(0))
            {
                SizeTo(-1, indices.GetLength(0) * 2);
            }
            return(numTris-1);
        }

        public int TriangleVertex(int triangle,int vertex)
        {
            return indices[triangle * 3 + vertex];
        }

        /// <summary>
        /// Updates the geo's current lighting normals.
        /// Smoth method.
        /// </summary>
        public void UpdateNormals()
        {
            int[] Vertex_ConnectedTris = new int[numVerts];
            int[,] Vertex_TriList = new int[numVerts, 400];
            float[] Face_NX = new float[numTris];
            float[] Face_NY = new float[numTris];
            float[] Face_NZ = new float[numTris];

            for (int j = 0; j < numVerts; j++)
            {
                Vertex_ConnectedTris[j] = 0;
            }
            for (int j = 0; j < numTris; j++)
            {
                int Vertex_0, Vertex_1, Vertex_2;
                Vertex_0 = TriangleVertex(j, 0);
                Vertex_1 = TriangleVertex(j, 1);
                Vertex_2 = TriangleVertex(j, 2);
                int ConnectedTris = Vertex_ConnectedTris[Vertex_0];
                Vertex_TriList[Vertex_0,ConnectedTris] = j;
                Vertex_ConnectedTris[Vertex_0] = ConnectedTris + 1;
				ConnectedTris = Vertex_ConnectedTris[Vertex_1];
				Vertex_TriList[Vertex_1, ConnectedTris] = j;
				Vertex_ConnectedTris[Vertex_1] = ConnectedTris + 1;
                ConnectedTris = Vertex_ConnectedTris[Vertex_2];
				Vertex_TriList[Vertex_2, ConnectedTris] = j;
				Vertex_ConnectedTris[Vertex_2] = ConnectedTris + 1;
				float Ax =vertices[Vertex_0].X;
                float Ay = vertices[Vertex_0].Y;
				float Az = vertices[Vertex_0].Z;
				float Bx = vertices[Vertex_1].X;
				float By = vertices[ Vertex_1].Y;
				float Bz = vertices[ Vertex_1].Z;
				float Cx = vertices[ Vertex_2].X;
				float Cy = vertices[ Vertex_2].Y;
				float Cz = vertices[ Vertex_2].Z;
				float Px = Ax-Bx;
				float Py = Ay-By;
				float Pz = Az-Bz;
				float Qx = Bx-Cx;
				float Qy = By-Cy;
				float Qz = Bz-Cz;
				float Nx = Py*Qz - Pz*Qy;
				float Ny = Pz*Qx - Px*Qz;
				float Nz = Px*Qy - Py*Qx;
				Face_NX[j] = Nx;
				Face_NY[j] = Ny;
				Face_NZ[j] = Nz;
                
            }
            for(int LOOP_Vertices = 0;LOOP_Vertices<vertices.Length;LOOP_Vertices++)
            {
                float Nx, Ny, Nz;
                Nx = Ny = Nz = 0;
             	int Polys = Vertex_ConnectedTris[LOOP_Vertices];
	    		for(int LOOP_Polys = 0;LOOP_Polys<Polys;LOOP_Polys++)
                {
		    		int ThisPoly = Vertex_TriList[LOOP_Vertices, LOOP_Polys];
		    		Nx = Nx + Face_NX[ThisPoly];
		    		Ny = Ny + Face_NY[ThisPoly];
		    		Nz = Nz + Face_NZ[ThisPoly];		
		    	}
                float Nl = (float)Math.Sqrt(Nx * Nx + Ny * Ny + Nz * Nz);
				Nx = Nx / Nl;
				Ny = Ny  / Nl;
				Nz = Nz / Nl;
				vertices[LOOP_Vertices].Nx = Nx;
                vertices[LOOP_Vertices].Ny = Ny;
                vertices[LOOP_Vertices].Nz = Nz;
             
	        }
        }

        /// <summary>
        /// Lock a surface for alteration.
        /// </summary>
        /// <remarks>Must be called before you edit any Geo.</remarks>
        /// <returns>True if sucessful. False otherwise.</returns>
        public bool Lock()
        {
            if (isLocked == true) return false;
             isLocked = true;
             return true;
        }

        /// <summary>
        /// Unlocks a mesh that was previously locked.
        /// </summary>
        /// <returns>True if successful, false otherwise.</returns>
        public bool Unlock()
        {
            if (isLocked == false) return false;
            isLocked = false;
            FinalizeChanges();
            return SyncBuffers();
        }

        /// <summary>
        /// Must be called before syncing data buffers.
        /// Geo.Unlock() Calls this function automatically.
        /// <remarks>Only required when editing geo 
        /// without use of the Lock/Unlock mechinism</remarks>
        /// </summary>
        /// <returns>True if succesful, false otherwise.</returns>
        public bool FinalizeChanges()
        {
            if (numVerts < vertices.GetLength(0))
            {
                D3D.CustomVertex.PositionNormalTextured[] newVerts = new D3D.CustomVertex.PositionNormalTextured[numVerts];
                Array.Copy(vertices, newVerts, numVerts);
                vertices = newVerts;
            }
            if (numTris * 3 < indices.GetLength(0))
            {
                int[] newInd = new int[numTris * 3];
                Array.Copy(indices, newInd, numTris * 3);
                indices = newInd;
            }
            return true;
        }
        /// <summary>
        /// Sync the vertex and index buffers of a Geo Instance.
        /// </summary>
        /// <remarks>This function will sync the vertex and index buffers of a mesh
        /// until this is done, no changes made to the mesh will be visually represented
        /// as the raw mesh data the video card uses will not have changed.
        /// Geo.Unlock() Calls this function as required. You only require
        /// it when circumventing the lock/unlock mechnisim</remarks>
        /// <returns>Bool True if sucessful. False if not.</returns>
        public bool SyncBuffers()
        {

            try
            {
                vertexBuf = new VertexBuffer(
                 typeof(D3D.CustomVertex.PositionNormalTextured),
                 vertices.Length,
                 Engine.hwDevice, DX.Direct3D.Usage.Dynamic | DX.Direct3D.Usage.WriteOnly,
                 D3D.CustomVertex.PositionNormalTextured.Format,
                 Pool.Default);
                if (vertexBuf == null)
                {
                    System.Windows.Forms.MessageBox.Show("Vertex buffer creation failed", "Geo.SyncBuffers()");
                }
                vertexBuf.SetData(vertices, 0, Microsoft.DirectX.Direct3D.LockFlags.None);

            //    GraphicsStream stream = vertexBuf.Lock(0, 0, 0);

                //  stream.Write((byte[])(object)vertices,0,numVerts*D3D.CustomVertex.PositionNormalTextured.StrideSize);
              //  stream.Write(vertices);
                //vertexBuf.Unlock();

                indexBuf = new IndexBuffer(
                typeof(int),    // What will the indices be?
                indices.Length,               // How many of them will there be? 
                Engine.hwDevice,
                DX.Direct3D.Usage.WriteOnly | DX.Direct3D.Usage.Dynamic,                // Advanced setting
                Pool.Default      // Advanced setting
                );
                indexBuf.SetData(indices, 0, Microsoft.DirectX.Direct3D.LockFlags.None);
                //indexBuf.SizeInBytes();

                // stream = indexBuf.Lock(0, 0, 0);
                //  stream.Write( (byte[])(object)indices,0,(numTris*3)*D3D.CustomVertex.PositionNormalTextured.StrideSize );
               // stream.Write(indices);
               // indexBuf.Unlock();
            }
            catch (Direct3DXException)
            {
                System.Windows.Forms.MessageBox.Show("Direct3D Threw an Exception", "Geo.SyncBuffers()");
            }
            catch (DirectXException)
            {
                System.Windows.Forms.MessageBox.Show("DirectX Threw an Exception", "Geo.SyncBuffers");
            }
            return true;
        }

        // Call once mesh will no longer be edited.
        public bool Optimize()
        {
            //SizeToSlow(numVerts, numTris);
            return true;
        }

        public int AddTriangle( Triangle Tri)
        {
            int tCount = 0;
            lock (triangles)
            {
                triangles.Add(Tri);
            }
            return tCount;
        }
            
        
        public Geo()
        {
            numVerts = 0;
            numTris = 0;
            SizeTo(500, 500);    
            isLocked = false;
        }
        
        ~Geo()
        {
                  
        }

        public Geo(int MaxYris ,int MaxVerts )
        {
           
        }
        /// <summary>
        /// Renders a geo class directly without altering the current
        /// display and camera set up.
        /// </summary>
        /// <exception cref="InvalidCall"
        /// <seealso cref="Entity.Render()"/>
        /// <returns></returns>
        public bool Render()
        {
            //System.Windows.Forms.MessageBox.Show("Testing!");
            Engine.hwDevice.VertexFormat = D3D.CustomVertex.PositionNormalTextured.Format;
            Engine.hwDevice.SetStreamSource(0, vertexBuf,0);
            Engine.hwDevice.Indices = indexBuf;
            Engine.hwDevice.SetRenderState(RenderStates.CullMode, (int)Cull.None);
            try
            {
                Engine.hwDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, numVerts, 0, numTris);
            }
            catch (InvalidCallException)
            {
               System.Windows.Forms.MessageBox.Show("Invalid Dx call in Geo.Render()","Vivid Ultra Error",System.Windows.Forms.MessageBoxButtons.OK);
              // System.Windows.Forms.MessageBox.Show("VBytes:" + (char)vertexBuf.SizeInBytes);

            }
            //System.Windows.Forms.MessageBox.Show("Render Cycle Over");
            return true;
        }
     
    }
}


[Edited by - Coder on August 16, 2005 7:23:29 AM]

Share this post


Link to post
Share on other sites
Advertisement
please please PLEASE use the [ source ] and [ /source ] tags (no spaces between the brackets).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!