Jump to content
  • Advertisement
Sign in to follow this  

Ambient light not working?

This topic is 4021 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

Hi I'm trying to creat my own engine. Eveerything went well untill scene lighting. It seems that RenderScene.Ambient does not affect the scene. Here's GFX class code
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.IO;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;

namespace SharpXEngine
    class CSharpXGFXEngine
        private Device device;       //Device
        private COnScreenFont Arial20;  //Font to display messages, Arial, 12pt
        private int frames, lastTickCount; //FPS counter vairaibles
        private string fpsText;
        private VertexBuffer vertices;

        public CSharpXGFXEngine(SharpXEngine mainEngine)
            if (!CreateAppWindow(mainEngine)) return;

        public void Render()
            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.DarkCyan, 1.0f, 0);

            device.RenderState.Ambient = Color.LightGray;


            device.SetStreamSource(0, vertices, 0);
            device.DrawPrimitives(PrimitiveType.TriangleList, 0, 12);

            Arial20.DrawText("FPS:"+fpsText, 20, 20, device.RenderState.Ambient);


        protected void SetupLights()

            // Use a white, directional light coming from over our right shoulder
            device.Lights[0].Diffuse = Color.White;
            device.Lights[0].Type = LightType.Directional;
            device.Lights[0].Direction = new Vector3(-3, -1, 3);
            device.Lights[0].Enabled = true;

        protected void SetupMatrices()
            float angle = Environment.TickCount / 5000.0F;
            device.Transform.World = Matrix.RotationX(angle) *Matrix.RotationY(angle / 2) * Matrix.RotationY(angle / 3);
            device.Transform.View = Matrix.LookAtLH(new Vector3(0, 0.5F, -7),
              new Vector3(0, 0.5F, 0), new Vector3(0, 1, 0));
            device.Transform.Projection =
              Matrix.PerspectiveFovLH((float)Math.PI / 4.0F, 1.0F, 1.0F, 13.25F);

        protected void CalculateFrameRate()

            int ticks = Environment.TickCount;
            int elapsed = ticks - lastTickCount;
            if (elapsed > 1000)
                fpsText = frames.ToString();
                frames = 0;
                lastTickCount = ticks;

        public void Init()
            //this.TopMost = true;
            Arial20 = new COnScreenFont("Arial", 20, device);

            // Add a little ambient light to the scene
            device.RenderState.Lighting = true; 
            device.RenderState.CullMode = Cull.None;
            //device.RenderState.FillMode = FillMode.WireFrame;

            vertices = CreateVertexBuffer(device);

        /// <summary>
        /// Creates VertexBuffer for Direct3D device
        /// </summary>
        /// <param name="device">Direct3D device for which the buffer is created</param>
        /// <returns>Newly created buffer</returns>
        protected VertexBuffer CreateVertexBuffer(Device device)
            //set vertices format (FVF)
            device.VertexFormat = CustomVertex.PositionNormalColored.Format;

            //create VertexBuffer itself
            VertexBuffer buffer = new VertexBuffer(

            //create vertices array
            CustomVertex.PositionNormalColored[] vertices = (CustomVertex.PositionNormalColored[])buffer.Lock(0, 0);

            //fill the buffer with vertices

/* Blah blah, verices data here


            //return created and populated buffer
            return buffer;

        public void Release()

        private bool CreateAppWindow(SharpXEngine mainEngine)
            int Height = 480, Width = 640, RefreshRate = 60;
            bool Windowed = true;
            Format PixelFormat = Format.X8B8G8R8;
            if (!LoadGFXConfig(ref Height, ref Width, ref RefreshRate, ref Windowed, ref PixelFormat)) return false;

            //Prepare device creation parameters
            AdapterInformation adapter = Manager.Adapters[0];

            DisplayMode Mode = new DisplayMode();
            Mode.Width = Width;
            Mode.Height = Height;
            Mode.RefreshRate = RefreshRate;
            Mode.Format = PixelFormat;

            PresentParameters presParams = new PresentParameters();
            presParams.BackBufferFormat = PixelFormat;
            presParams.BackBufferHeight = Height;
            presParams.BackBufferWidth = Width;
            presParams.SwapEffect = SwapEffect.Flip;
            presParams.Windowed = Windowed;
            presParams.PresentationInterval = PresentInterval.Immediate;    //Vsync off
            //activate and mange z-buffer
            presParams.EnableAutoDepthStencil = true;
            presParams.AutoDepthStencilFormat = DepthFormat.D16;

            mainEngine.Height = Height;
            mainEngine.Width = Width;
            mainEngine.Text = "SharpXEngine";
            //if (Windowed) mainEngine.TopMost = true;

            //Create device
                device = new Device(
            catch (DirectXException e)
                return false;

            return true;
        private bool LoadGFXConfig(ref int Height, ref int Width, ref int RefreshRate, ref bool Windowed, ref Format PixelFormat)
                //Try to open config file
                StreamReader sr = new StreamReader("MDX9.cfg");
                String line;

                //Load config file data
                while ((line = sr.ReadLine()) != null)
                    switch (line[0])
                        case '[':
                            switch (line)
                                case "[Rozdzielczosc]":
                                    //next 4 lines in config file describe selected resolution
                                    //in order: Width, Height, RefreshRate, Format
                                    Width = Convert.ToInt16((sr.ReadLine()).Substring(6));
                                    Height = Convert.ToInt16((sr.ReadLine()).Substring(7));
                                    RefreshRate = Convert.ToInt16((sr.ReadLine()).Substring(12));
                                    PixelFormat = (Format)Enum.Parse(typeof(Format), (sr.ReadLine()).Substring(7));
                                case "[W okienku]":
                                    //next line of config file indicate window mode flag
                                    Windowed = Convert.ToBoolean((sr.ReadLine()).Substring(9));
                return true;
            catch (FileNotFoundException)
                //Config file not found - run config manager
                MessageBox.Show("Nieudane wczytanie konfiguracji", "Wczytanie", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //Run config application
                return false;
I tried to put RenderState.Ambient in various parts of the code, but the effect was always the same - faces away from the light are black. Please note, that here
Arial20.DrawText("FPS:"+fpsText, 20, 20, device.RenderState.Ambient);
I use ambient light color to draw FPS counter, and here it works OK. I tried also to run the app on diffrent PC, but the effect was the same. Also sample code from some tutorials I found gives same result. Anyone has the idea where the problem lies?

Share this post

Link to post
Share on other sites
Hello again

I finally managed to make it work.
In my case it seems that ambient light works only if there is a material created and its ambient color set.
Then total pixel color is an "average" of material color and light color.
I wonder why it's not working for simple colored vertices...

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!