Sign in to follow this  
s3mt3x

OpenGL Can someone try this for me (cool camera code)

Recommended Posts

Hi Guys, I'm porting an old applicatin over from OpenGl to managed directx, and i'm getting poor performance on my machine. I was wondering if some of you could try the following code on your machines to see if you get the same? I need to know whether this is just my crappy old PC or an issue with mdx. I'm repainting responding to mouse events (it's a modelling app, not a game before i get flamed!!). The code features a cool maya style camera for anyone who's interested. Any feedback would be great.
public partial class Form1 : Form
    {
        //our device
        Device device;

        //constant to convert degrees to radians
        const float RAD = 0.0174532925f;

        #region Camera Variables
        //integers to track our mouse position
        int mouseX;
        int mouseY;

        //our mouse button states
        private bool leftMouseDown = false;
        private bool middleMouseDown = false;
        private bool rightMouseDown = false;

        private Vector3 translation = new Vector3();
        //Up Vector
        Vector3 up = new Vector3(0, 1, 0);
        //Left Vector 
        Vector3 left = new Vector3(1, 0, 0);
        //forward Vector
        Vector3 forward = new Vector3(0, 0, 1);
        //vector to store our rotation
        Vector3 rotation = new Vector3();
        //our zoom value
        private float zoom = 100f;
        //the plane we drag our mouse on
        private Plane middleMouseDragPlane;
        //our view matricies
        Matrix projectionMatrix;
        Matrix viewMatrix;
        //our viewport
        Viewport viewPort;
        #endregion

        #region Grid Variables
        //the grid vertices
        CustomVertex.PositionColored[] gridGeometry;
        //the grid size
        int gridSize = 500;
        //the grid step
        int gridStep = 10;
        #endregion

        /// <summary>
        /// Returns the camera's position in world space
        /// </summary>
        public Vector3 CameraPosition
        {
            get
            {
                Matrix inverseView = Matrix.Multiply(this.viewMatrix, Matrix.Identity);
                inverseView.Invert();
                Vector4 temp = Vector3.Transform(new Vector3(), inverseView);
                return new Vector3(temp.X, temp.Y, temp.Z);
            }
        }

        public Form1()
        {
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.Opaque, true);
            this.SetStyle(ControlStyles.UserPaint, true);
            InitializeComponent();
            InitializeGraphics();

            //manually call our resize method to initialize our viewport
            this.OnResize(new System.EventArgs());
        }

        private void InitializeGraphics()
        {
            PresentParameters present = new PresentParameters();
            present = new PresentParameters();
            present.SwapEffect = SwapEffect.Discard;
            present.Windowed = true;
            present.EnableAutoDepthStencil = true;
            present.AutoDepthStencilFormat = DepthFormat.D16;

            this.device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, present);

            this.InitializeGrid();
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            this.viewPort = new Viewport();
            this.viewPort.X = 0;
            this.viewPort.Y = 0;
            this.viewPort.Width = this.ClientSize.Width;
            this.viewPort.Height = this.ClientSize.Height;

            this.viewPort.MinZ = 0.0f;
            this.viewPort.MaxZ = 1.0f;
        }

        public void SetupView(Device device)
        {
            device.Viewport = this.viewPort;

            this.projectionMatrix = Matrix.PerspectiveFovLH((float)Math.PI / 4, ((float)this.ClientSize.Width) / ((float)this.ClientSize.Height), 1f, 20000.0f);
            device.Transform.Projection = this.projectionMatrix;

            Matrix zoomMat = Matrix.LookAtLH(new Vector3(0, 0, this.zoom), new Vector3(), new Vector3(0, 1, 0));
            Matrix rotationXMat = Matrix.RotationX(this.rotation.X * RAD);
            Matrix rotationYMat = Matrix.RotationY(this.rotation.Y * RAD);
            Matrix translationMat = Matrix.Translation(this.translation.X, this.translation.Y, this.translation.Z);

            this.viewMatrix = translationMat * rotationYMat * rotationXMat * zoomMat;
            device.Transform.View = this.viewMatrix;

            Matrix negativeRotationX = Matrix.RotationX(-this.rotation.X * RAD);
            Matrix negativeRotationY = Matrix.RotationY(-this.rotation.Y * RAD);

            Matrix axisRotation = negativeRotationX * negativeRotationY;

            //transform static view vectors
            Vector4 tempUp = Vector3.Transform(new Vector3(0, 1, 0), axisRotation);
            Vector4 tempLeft = Vector3.Transform(new Vector3(1, 0, 0), axisRotation);
            Vector4 tempForward = Vector3.Transform(new Vector3(0, 0, 1), axisRotation);

            //set our view vectors to the result
            this.up = new Vector3(tempUp.X, tempUp.Y, tempUp.Z);
            this.left = new Vector3(tempLeft.X, tempLeft.Y, tempLeft.Z);
            this.forward = new Vector3(tempForward.X, tempForward.Y, tempForward.Z);
            //make sure we've normailised our view vectors
            this.up.Normalize();
            this.left.Normalize();
            this.up.Normalize();
        }

        public Microsoft.DirectX.Vector3 GenerateNormalizedPickRay(int x, int y)
        {
            Vector3 near = new Vector3(x, y, 0);
            Vector3 far = new Vector3(x, y, 1);
            Viewport viewPort = new Viewport();
            viewPort.Width = this.viewPort.Width;
            viewPort.Height = this.viewPort.Height;
            viewPort.MinZ = 0;
            viewPort.MaxZ = 1;
            near.Unproject(viewPort, this.projectionMatrix, this.viewMatrix, Matrix.Identity);
            far.Unproject(viewPort, this.projectionMatrix, this.viewMatrix, Matrix.Identity);

            Vector3 direction = Vector3.Subtract(far, near);

            return Vector3.Normalize(direction);
        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            int x = e.X;
            int y = e.Y;
            System.Windows.Forms.MouseButtons buttons = e.Button;
            switch (buttons)
            {
                case System.Windows.Forms.MouseButtons.Left:
                    this.leftMouseDown = true;
                    break;
                case System.Windows.Forms.MouseButtons.Middle:
                    Vector3 cameraPosition = this.CameraPosition;
                    Vector3 focalDirection = new Vector3(this.forward.X, this.forward.Y, this.forward.Z);
                    Vector3 focalPoint = new Vector3(cameraPosition.X - 
(focalDirection.X * this.zoom), cameraPosition.Y - (focalDirection.Y * this.zoom), cameraPosition.Z - (focalDirection.Z * this.zoom));
                    this.middleMouseDragPlane = Plane.FromPointNormal(focalPoint, this.forward);
                    this.middleMouseDown = true;
                    break;
                case System.Windows.Forms.MouseButtons.Right:
                    this.rightMouseDown = true;
                    break;
            }
            this.mouseX = x;
            this.mouseY = y;
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            int x = e.X;
            int y = e.Y;
            System.Windows.Forms.MouseButtons buttons = e.Button;
            if (this.leftMouseDown)
            {
                this.rotation.Y += this.mouseX - x;
                this.rotation.X -= this.mouseY - y;

                if (this.rotation.X > 90)
                {
                    this.rotation.X = 90;
                }

                if (this.rotation.X < -90)
                {
                    this.rotation.X = -90;
                }

                if (this.rotation.Y > 360)
                {
                    this.rotation.Y = this.rotation.Y % 360.0f;
                }

                if (this.rotation.Y < 0)
                {
                    this.rotation.Y = 360.0f - this.rotation.Y;
                }
            }
            else if (this.middleMouseDown)
            {
                Vector3 cameraPosition = this.CameraPosition;

                Vector3 newPosition = Plane.IntersectLine(this.middleMouseDragPlane, cameraPosition, this.CameraPosition + (this.GenerateNormalizedPickRay(x, y) * this.zoom));
                Vector3 currentPosition = Plane.IntersectLine
(this.middleMouseDragPlane, cameraPosition, this.CameraPosition + 
(this.GenerateNormalizedPickRay(this.mouseX, this.mouseY) * this.zoom));
                Vector3 difference = newPosition - currentPosition;
                this.translation.X += difference.X;
                this.translation.Y += difference.Y;
                this.translation.Z += difference.Z;
            }
            else if (this.rightMouseDown)
            {
                int deltaY = y - this.mouseY;
                this.zoom -= ((float)deltaY) * (this.zoom / 1000.0f);
            }

            this.mouseX = x;
            this.mouseY = y;

            if (this.leftMouseDown | this.middleMouseDown | this.rightMouseDown)
            {
                this.Invalidate();
            }
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            int x = e.X;
            int y = e.Y;
            System.Windows.Forms.MouseButtons buttons = e.Button;
            switch (buttons)
            {
                case System.Windows.Forms.MouseButtons.Left:
                    this.leftMouseDown = false;
                    break;
                case System.Windows.Forms.MouseButtons.Middle:
                    this.middleMouseDown = false;
                    break;
                case System.Windows.Forms.MouseButtons.Right:
                    this.rightMouseDown = false;
                    break;
            }
            this.mouseX = x;
            this.mouseY = y;

            this.Invalidate();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            device.RenderState.Lighting = false;

            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.FromArgb(161, 161, 161), 1.0f, 0);

            this.SetupView(device);

            device.BeginScene();

            //draw our grid
            device.VertexFormat = CustomVertex.PositionColored.Format;
            device.DrawUserPrimitives(PrimitiveType.LineList, this.gridGeometry.Length / 2, this.gridGeometry);

            device.EndScene();

            device.Present();
            
            base.OnPaint(e);
        }


        private void InitializeGrid()
        {
            int numLines = this.gridSize / this.gridStep;

            this.gridGeometry = new CustomVertex.PositionColored[((numLines * 2) * 2) + 4];
            int gridIndex = 0;
            for (int x = 0 - this.gridSize / 2; x <= this.gridSize / 2; x += this.gridStep)
            {
                this.gridGeometry[gridIndex].X = x;
                this.gridGeometry[gridIndex].Y = 0;
                this.gridGeometry[gridIndex].Z = 0 - this.gridSize / 2;
                if (x != 0)
                {
                    this.gridGeometry[gridIndex].Color = System.Drawing.Color.FromArgb(128, 128, 128).ToArgb();
                }
                else
                {
                    this.gridGeometry[gridIndex].Color = System.Drawing.Color.Black.ToArgb();
                }



                this.gridGeometry[gridIndex + 1].X = x;
                this.gridGeometry[gridIndex + 1].Y = 0;
                this.gridGeometry[gridIndex + 1].Z = this.gridSize / 2;
                if (x != 0)
                {
                    this.gridGeometry[gridIndex + 1].Color = System.Drawing.Color.FromArgb(128, 128, 128).ToArgb();
                }
                else
                {
                    this.gridGeometry[gridIndex + 1].Color = System.Drawing.Color.Black.ToArgb();
                }

                gridIndex += 2;
            }

            for (int z = 0 - this.gridSize / 2; z <= this.gridSize / 2; z += this.gridStep)
            {
                this.gridGeometry[gridIndex].X = 0 - this.gridSize / 2;
                this.gridGeometry[gridIndex].Y = 0;
                this.gridGeometry[gridIndex].Z = z;
                if (z != 0)
                {
                    this.gridGeometry[gridIndex].Color = System.Drawing.Color.FromArgb(128, 128, 128).ToArgb();
                }
                else
                {
                    this.gridGeometry[gridIndex].Color = System.Drawing.Color.Black.ToArgb();
                }


                this.gridGeometry[gridIndex + 1].X = this.gridSize / 2;
                this.gridGeometry[gridIndex + 1].Y = 0;
                this.gridGeometry[gridIndex + 1].Z = z;
                if (z != 0)
                {
                    this.gridGeometry[gridIndex + 1].Color = System.Drawing.Color.FromArgb(128, 128, 128).ToArgb();
                }
                else
                {
                    this.gridGeometry[gridIndex + 1].Color = System.Drawing.Color.Black.ToArgb();
                }

                gridIndex += 2;
            }
        }
    }


Thanks, Chris [Edited by - s3mt3x on May 6, 2007 6:08:24 AM]

Share this post


Link to post
Share on other sites
Chris,

Yea that works super. I have an exact one of those that I use for level editing. Setup on the form a bit different but still operates the same. I like that style, it gives you good control over the environment.

-Devin

[edit] Oops, should have addressed the pefromance issue. You should be using a render loop instead of the OnPaint event of the Form if you want better performance. Look at the following thread:

Render Loop Thread

Share this post


Link to post
Share on other sites
Hi Devin,

Thanks for trying it out - with regard to the rendering loop, like i said, i'm repainting based on mouse movements - there's no need to repaint using a render loop - the only time the display needs to be updated is in response to input in some shape or form.

Did the camera motion go "scratchy"? On my pc once i start the application it drops in performance when the mouse is moved - however, sometimes it's smooth as expected.


Thanks again,


Chris

Share this post


Link to post
Share on other sites
Oh, OK, I see. If that is the case then I'm unsure what performance you are talking about. Is it rotating slow for you? It seems fine on my machine. I'll look at the code again just to verify everything's tops.

-Devin

Share this post


Link to post
Share on other sites
Just going thru your code to point a couple of things out. The following code is reduntant because any matrix multiplied by the identity is the matrix. Multiplying a matrix by the identity does nothing. If you're trying to get a new matrix then simply assigning it would be suffice (ie: Matrix inverseView = this.viewMatrix;). The reason for this is that Matrix is a struct and duplicates itself on assignment rather than assigning a reference of itself like an object would do.

[source lang = "c#"]
Matrix inverseView = Matrix.Multiply(this.viewMatrix, Matrix.Identity);



You might try Hardware Vertex Processing as well in the Device constructor. Just perhaps it might speed things up?:

[source lang = "c#"]
this.device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, present);



Again, it works super.

If you really need more efficiency in your code there are more efficient approaches to doing that. I think if you tweak at it and study the matrices and vector math more you will eventually get your code more and more efficient as time goes on. For now perhaps it's just super :).

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  

  • Announcements

  • Forum Statistics

    • Total Topics
      628364
    • Total Posts
      2982269
  • Similar Content

    • By test opty
      Hi all,
       
      I'm starting OpenGL using a tut on the Web. But at this point I would like to know the primitives needed for creating a window using OpenGL. So on Windows and using MS VS 2017, what is the simplest code required to render a window with the title of "First Rectangle", please?
       
       
    • By DejayHextrix
      Hi, New here. 
      I need some help. My fiance and I like to play this mobile game online that goes by real time. Her and I are always working but when we have free time we like to play this game. We don't always got time throughout the day to Queue Buildings, troops, Upgrades....etc.... 
      I was told to look into DLL Injection and OpenGL/DirectX Hooking. Is this true? Is this what I need to learn? 
      How do I read the Android files, or modify the files, or get the in-game tags/variables for the game I want? 
      Any assistance on this would be most appreciated. I been everywhere and seems no one knows or is to lazy to help me out. It would be nice to have assistance for once. I don't know what I need to learn. 
      So links of topics I need to learn within the comment section would be SOOOOO.....Helpful. Anything to just get me started. 
      Thanks, 
      Dejay Hextrix 
    • By mellinoe
      Hi all,
      First time poster here, although I've been reading posts here for quite a while. This place has been invaluable for learning graphics programming -- thanks for a great resource!
      Right now, I'm working on a graphics abstraction layer for .NET which supports D3D11, Vulkan, and OpenGL at the moment. I have implemented most of my planned features already, and things are working well. Some remaining features that I am planning are Compute Shaders, and some flavor of read-write shader resources. At the moment, my shaders can just get simple read-only access to a uniform (or constant) buffer, a texture, or a sampler. Unfortunately, I'm having a tough time grasping the distinctions between all of the different kinds of read-write resources that are available. In D3D alone, there seem to be 5 or 6 different kinds of resources with similar but different characteristics. On top of that, I get the impression that some of them are more or less "obsoleted" by the newer kinds, and don't have much of a place in modern code. There seem to be a few pivots:
      The data source/destination (buffer or texture) Read-write or read-only Structured or unstructured (?) Ordered vs unordered (?) These are just my observations based on a lot of MSDN and OpenGL doc reading. For my library, I'm not interested in exposing every possibility to the user -- just trying to find a good "middle-ground" that can be represented cleanly across API's which is good enough for common scenarios.
      Can anyone give a sort of "overview" of the different options, and perhaps compare/contrast the concepts between Direct3D, OpenGL, and Vulkan? I'd also be very interested in hearing how other folks have abstracted these concepts in their libraries.
    • By aejt
      I recently started getting into graphics programming (2nd try, first try was many years ago) and I'm working on a 3d rendering engine which I hope to be able to make a 3D game with sooner or later. I have plenty of C++ experience, but not a lot when it comes to graphics, and while it's definitely going much better this time, I'm having trouble figuring out how assets are usually handled by engines.
      I'm not having trouble with handling the GPU resources, but more so with how the resources should be defined and used in the system (materials, models, etc).
      This is my plan now, I've implemented most of it except for the XML parts and factories and those are the ones I'm not sure of at all:
      I have these classes:
      For GPU resources:
      Geometry: holds and manages everything needed to render a geometry: VAO, VBO, EBO. Texture: holds and manages a texture which is loaded into the GPU. Shader: holds and manages a shader which is loaded into the GPU. For assets relying on GPU resources:
      Material: holds a shader resource, multiple texture resources, as well as uniform settings. Mesh: holds a geometry and a material. Model: holds multiple meshes, possibly in a tree structure to more easily support skinning later on? For handling GPU resources:
      ResourceCache<T>: T can be any resource loaded into the GPU. It owns these resources and only hands out handles to them on request (currently string identifiers are used when requesting handles, but all resources are stored in a vector and each handle only contains resource's index in that vector) Resource<T>: The handles given out from ResourceCache. The handles are reference counted and to get the underlying resource you simply deference like with pointers (*handle).  
      And my plan is to define everything into these XML documents to abstract away files:
      Resources.xml for ref-counted GPU resources (geometry, shaders, textures) Resources are assigned names/ids and resource files, and possibly some attributes (what vertex attributes does this geometry have? what vertex attributes does this shader expect? what uniforms does this shader use? and so on) Are reference counted using ResourceCache<T> Assets.xml for assets using the GPU resources (materials, meshes, models) Assets are not reference counted, but they hold handles to ref-counted resources. References the resources defined in Resources.xml by names/ids. The XMLs are loaded into some structure in memory which is then used for loading the resources/assets using factory classes:
      Factory classes for resources:
      For example, a texture factory could contain the texture definitions from the XML containing data about textures in the game, as well as a cache containing all loaded textures. This means it has mappings from each name/id to a file and when asked to load a texture with a name/id, it can look up its path and use a "BinaryLoader" to either load the file and create the resource directly, or asynchronously load the file's data into a queue which then can be read from later to create the resources synchronously in the GL context. These factories only return handles.
      Factory classes for assets:
      Much like for resources, these classes contain the definitions for the assets they can load. For example, with the definition the MaterialFactory will know which shader, textures and possibly uniform a certain material has, and with the help of TextureFactory and ShaderFactory, it can retrieve handles to the resources it needs (Shader + Textures), setup itself from XML data (uniform values), and return a created instance of requested material. These factories return actual instances, not handles (but the instances contain handles).
       
       
      Is this a good or commonly used approach? Is this going to bite me in the ass later on? Are there other more preferable approaches? Is this outside of the scope of a 3d renderer and should be on the engine side? I'd love to receive and kind of advice or suggestions!
      Thanks!
    • By nedondev
      I 'm learning how to create game by using opengl with c/c++ coding, so here is my fist game. In video description also have game contain in Dropbox. May be I will make it better in future.
      Thanks.
  • Popular Now