Example #1
0
        public void Rotate(double deltaX, double deltaY)
        {
            //double p = ((((((pitch) > (minRy)) ? (pitch) : (minRy))) < (maxRy)) ? ((((pitch) > (minRy)) ? (pitch) : (minRy))) : (maxRy));
            //base.Rotate(yaw, p, roll);

            double mouseSpeed = 0.1f;

            double horizontalAngle = mouseSpeed * deltaX;
            double verticalAngle   = mouseSpeed * deltaY;

            //// Direction : Spherical coordinates to Cartesian coordinates conversion
            Vector3d directionNew = new Vector3d(Convert.ToSingle(Math.Cos(verticalAngle) * Math.Sin(horizontalAngle)),
                                                 Convert.ToSingle(Math.Sin(verticalAngle)),
                                                 Convert.ToSingle(Math.Cos(verticalAngle) * Math.Cos(horizontalAngle)));

            //// Right vector
            Vector3d rightV = new Vector3d(Convert.ToSingle(Math.Sin(horizontalAngle - 3.14f / 2.0f)),
                                           0,
                                           Convert.ToSingle(Math.Cos(horizontalAngle - 3.14f / 2.0f)));

            //// Up vector
            Vector3d up = Vector3d.Cross(right, directionNew);

            V = Matrix4d.LookAt(Position,                // Camera is here
                                Position + directionNew, // and looks here : at the same position, plus "direction"
                                up);                     // Head is up (set to 0,-1,0 to look upside-down)
        }
Example #2
0
        public void SetupGLView()
        {
            GL.MatrixMode(MatrixMode.Modelview);
            Matrix4d lookAt = Matrix4d.LookAt(mEye, mCenter, mUp);

            GL.LoadMatrix(ref lookAt);
        }
Example #3
0
        private void glControl1_Paint(object sender, PaintEventArgs e)
        {
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); //limpa os buffers
            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadIdentity();                                                         //zera a matriz de proje��o com a matriz identidade

            Matrix4d lookat = Matrix4d.LookAt(pos.X, pos.Y, pos.Z, dir.X, dir.Y, dir.Z, 0, 0, 1);

            //aplica a transformacao na matriz de rotacao
            GL.LoadMatrix(ref lookat);
            //GL.Rotate(camera_rotation, 0, 0, 1);

            GL.Enable(EnableCap.DepthTest);


            //EIXOS X, Y, Z
            GL.Begin(PrimitiveType.Lines);
            GL.Color3(Color.Red);
            GL.Vertex3(0, 0, 0); GL.Vertex3(500, 0, 0);
            GL.Color3(Color.Blue);
            GL.Vertex3(0, 0, 0); GL.Vertex3(0, 500, 0);
            GL.Color3(Color.Green);
            GL.Vertex3(0, 0, 0); GL.Vertex3(0, 0, 500);
            GL.End();

            casaDraw();
            //Utilizamos o Enable para ativar o desenho com as texturas

            glControl1.SwapBuffers(); //troca os buffers de frente e de fundo
        }
Example #4
0
        public bool UpdateMatrices()
        {
            if (hasChanged == false)
            {
                return(false);
            }
            hasChanged = false;

            ViewMatrix = Matrix4d.LookAt(Position, LookAt, Vector3d.UnitY);

            switch (ProjectionType)
            {
            case ProjectionType.Perspective:
                ProjectionMatrix = Matrix4d.CreatePerspectiveFieldOfView(FovRads, Width / (float)Height, NearZ, FarZ);
                break;

            case ProjectionType.Ortographic:
                var halfWidth  = Width / 2f;
                var halfHeight = Height / 2f;
                ProjectionMatrix = Matrix4d.CreateOrthographicOffCenter(-halfWidth, halfWidth, -halfHeight, halfHeight, NearZ, FarZ);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
            return(true);
        }
Example #5
0
        private void Render()
        {
            glControl1.MakeCurrent(); //后续OpenGL显示操作在当前控件窗口内进行
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            SetupLineList();
            if (isBackGround)
            {
                GradientBackgroudColor();
            }
            if (octree != null)
            {
                octree.render();
            }
            GL.CallList(isShowListNum);

            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadIdentity();
            Matrix4d lookat = Matrix4d.LookAt(c.X, c.Y, c.Z, l.X, l.Y, l.Z, h.X, h.Y, h.Z);

            GL.LoadMatrix(ref lookat);
            GL.Rotate(MouseY, 1, 0, 0);
            GL.Rotate(MouseX, 0, 1, 0);
            GL.Rotate(MouseZ, 0, 0, 1);
            GL.Scale(scale, scale, scale);

            glControl1.SwapBuffers();
            //交换缓冲区。双缓冲绘制时,所有的绘制都是绘制到后台缓冲区里,如果不交换缓冲区,就看不到绘制内容。OpenTK 默认双缓冲
        }
Example #6
0
        /// <summary>
        /// Call this once to initialise the renderer
        /// </summary>
        internal static void Initialize()
        {
            GL.ShadeModel(ShadingModel.Smooth);
            GL.ClearColor(Color4.Black);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            GL.Enable(EnableCap.DepthTest);
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
            GL.DepthFunc(DepthFunction.Lequal);
            GL.Hint(HintTarget.FogHint, HintMode.Fastest);
            GL.Hint(HintTarget.LineSmoothHint, HintMode.Fastest);
            GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Fastest);
            GL.Hint(HintTarget.PointSmoothHint, HintMode.Fastest);
            GL.Hint(HintTarget.PolygonSmoothHint, HintMode.Fastest);
            GL.Hint(HintTarget.GenerateMipmapHint, HintMode.Nicest);
            GL.Disable(EnableCap.Dither);
            GL.CullFace(CullFaceMode.Front);
            GL.Enable(EnableCap.CullFace); CullEnabled        = true;
            GL.Disable(EnableCap.Lighting); LightingEnabled   = false;
            GL.Disable(EnableCap.Texture2D); TexturingEnabled = false;
            Interface.LoadHUD();
            InitLoading();
            Matrix4d lookat = Matrix4d.LookAt(0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0);

            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadMatrix(ref lookat);
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
            GL.Enable(EnableCap.Blend); BlendEnabled        = true;
            GL.Disable(EnableCap.Lighting); LightingEnabled = false;
            GL.Disable(EnableCap.Fog);
        }
Example #7
0
        private void DrawStereoImages()
        {
            Vector3d vectorLeftEye = this.eye - this.distEye * (double)this.StereoDistance * this.esq;

            GL.DrawBuffer(DrawBufferMode.BackRight);
            GL.ClearColor(this.ClearColor[0], this.ClearColor[1], this.ClearColor[2], 0.0f);
            GL.Clear(ClearBufferMask.DepthBufferBit | ClearBufferMask.ColorBufferBit);
            GL.LoadIdentity();
            Matrix4d perspectiveFieldOfView1 = Matrix4d.CreatePerspectiveFieldOfView(Math.PI / 4.0, (double)this.glControl1.Width / (double)this.glControl1.Height, (double)this.zFar * 0.001, (double)this.zFar + 1000.0);

            GL.LoadMatrix(ref perspectiveFieldOfView1);
            Matrix4d mat1 = Matrix4d.LookAt(vectorLeftEye.X, vectorLeftEye.Y, vectorLeftEye.Z, this.center.X, this.center.Y, this.center.Z, this.up.X, this.up.Y, this.up.Z);

            GL.MultMatrix(ref mat1);

            this.DrawAll3DObjects();

            Vector3d vectorRightEye = this.eye + this.distEye * (double)this.StereoDistance * this.esq;

            GL.DrawBuffer(DrawBufferMode.BackLeft);
            GL.ClearColor(this.ClearColor[0], this.ClearColor[1], this.ClearColor[2], 0.0f);
            GL.Clear(ClearBufferMask.DepthBufferBit | ClearBufferMask.ColorBufferBit);
            GL.LoadIdentity();
            Matrix4d perspectiveFieldOfView2 = Matrix4d.CreatePerspectiveFieldOfView(Math.PI / 4.0, (double)this.glControl1.Width / (double)this.glControl1.Height, (double)this.zFar * 0.001, (double)this.zFar + 1000.0);

            GL.LoadMatrix(ref perspectiveFieldOfView2);
            Matrix4d mat2 = Matrix4d.LookAt(vectorRightEye.X, vectorRightEye.Y, vectorRightEye.Z, this.center.X, this.center.Y, this.center.Z, this.up.X, this.up.Y, this.up.Z);

            GL.MultMatrix(ref mat2);

            this.DrawAll3DObjects();

            this.glControl1.SwapBuffers();
        }
Example #8
0
 public MGUI(string sName = "GUI") : base(sName)
 {
     _instance         = this;
     CreateGeometry    = false;
     _projectionMatrix = Matrix4d.CreateOrthographicOffCenter(0, 100, 0, 100, 0.01, 50);
     _viewMatrix       = Matrix4d.LookAt(new Vector3d(0, 0, 10), new Vector3d(0, 0, 0), new Vector3d(0, 1, 0));
 }
Example #9
0
        private void SetupCamera()
        {
            GL.MatrixMode(MatrixMode.Modelview);
            var      eye    = new Vector3d(xpos, ypos, zpos);
            Matrix4d matrix = Matrix4d.LookAt(eye, new Vector3d(64, 0, 64), Vector3d.UnitY);

            GL.LoadMatrix(ref matrix);
        }
Example #10
0
        public Matrix4d UpdateLookAt()
        {
            lookAt = Matrix4d.LookAt(CameraX, CameraY, CameraZ,
                                     CameraX + lookX, (CameraY + lookY) - 0.1 + lookdown * 0.1 + lookY, CameraZ + lookZ,
                                     0, 1, 0);

            return(lookAt);
        }
Example #11
0
        public virtual Matrix4d GetCameraMatrix()
        {
            Position.Normalize();
            Target.Normalize();
            Up.Normalize();

            return(Matrix4d.LookAt(Position, Target, Up));
        }
Example #12
0
        private void Form1_Load(object sender, EventArgs e)
        {
            InitialGL();
            Matrix4d lookat = Matrix4d.LookAt(0, 0, 1, 0, 0, 0, 0, 1, 0);

            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadMatrix(ref lookat);
            PaintBall();
        }
Example #13
0
        protected override void OnRenderFrame(FrameEventArgs e)
        {
            double fpsstability = 10.0;

            this._AverageFPS = (this.RenderFrequency + this._AverageFPS * fpsstability) / (fpsstability + 1);
            this.Title       = DefaultTitle + " - Press H for help!"; // fps messurement is off

            GL.ClearColor(0.3f, 0.5f, 1.0f, 1.0f);
            GL.Clear(ClearBufferMask.DepthBufferBit | ClearBufferMask.ColorBufferBit);

            GL.MatrixMode(MatrixMode.Projection);
            Matrix4d proj = Matrix4d.CreatePerspectiveFieldOfView(0.9, (double)this.Width / (double)this.Height, 0.2, 600.0);

            GL.LoadMatrix(ref proj);
            Matrix4d view = Matrix4d.LookAt(
                Vector.FromDoubleVector(this._CamPos),
                Vector.FromDoubleVector(Vector.Add(this._CamPos, this.CamDirection)),
                new Vector3d(0.0, 0.0, 1.0));

            GL.MultMatrix(ref view);

            // Test picking
            int             mx         = this.Mouse.X;
            int             my         = this.Mouse.Y;
            int             sx         = this.ClientSize.Width;
            int             sy         = this.ClientSize.Height;
            Vector3d        p          = Unproject(new Vector3d(-1.0 + 2.0 * ((double)mx / (double)sx), 1.0 - 2.0 * ((double)my / (double)sy), 0.995), view, proj);
            Vector <double> tracestart = this._CamPos;
            Vector <double> traceend   = new Vector <double>(p.X, p.Y, p.Z);
            Vector <double> dif        = Vector.Normalize(Vector.Subtract(traceend, tracestart));

            traceend = Vector.Add(Vector.Multiply(dif, 400), tracestart);
            foreach (TraceHit <MinecraftRenderer.HitBorder> hb in Trace.TraceRay(this._Renderer.GetHitSurface(this.Slice), tracestart, traceend, MinecraftRenderer.HitBorder.Default))
            {
                if ((hb.Border.Value.Polarity == Polarity.Positive && tracestart[hb.Border.Direction] > hb.Border.Position[hb.Border.Direction]) ||
                    (hb.Border.Value.Polarity == Polarity.Negative && tracestart[hb.Border.Direction] < hb.Border.Position[hb.Border.Direction]))
                {
                    this._LastHit = hb.Border;
                    break;
                }
            }

            Point <int>?highlight = this._LastHit.HasValue ? this._LastHit.Value.Value.Chunk : null;

            if (this._SliceAxis.HasValue)
            {
                if (this._SliceAxis.Value == Axis.Z)
                {
                    this._SliceLevel = this._SliceLevel < 1 ? 1 : this._SliceLevel;
                    this._SliceLevel = this._SliceLevel > MinecraftRenderer.ChunkSize - 1 ? MinecraftRenderer.ChunkSize - 1 : this._SliceLevel;
                }
            }
            this._Renderer.Render(this._CamPos, this.Slice, highlight);
            this._RendererTrans.Render(this._CamPos, this.Slice, highlight);
            this.SwapBuffers();
        }
        public void changeTarget(Vector3d whatTarget)
        {
            Vector3d normalizedConnection = Vector3d.NormalizeFast(position - target);
            double   cosine = Vector3d.Dot(normalizedConnection, Vector3d.UnitY);

            if (!(cosine < 1.02 && cosine > 0.98) && !(cosine > -1.02 && cosine < -0.98))
            {
                target       = whatTarget;
                cameraMatrix = Matrix4d.LookAt(position, target, Vector3d.UnitY);
            }
        }
Example #15
0
        /// <summary>
        /// Convert a world space coordinate into a screen space coordinate.
        /// </summary>
        /// <param name="world">The world coordinate</param>
        /// <returns>The screen coordinate</returns>
        public Coordinate WorldToScreen(Coordinate world)
        {
            var viewport = new[] { 0, 0, Width, Height };
            var pm       = Matrix4d.CreatePerspectiveFieldOfView(MathHelper.DegreesToRadians(Camera.FOV), Width / (float)Height, 0.1f, 50000);
            var vm       = Matrix4d.LookAt(
                new Vector3d(Camera.Location.X, Camera.Location.Y, Camera.Location.Z),
                new Vector3d(Camera.LookAt.X, Camera.LookAt.Y, Camera.LookAt.Z),
                Vector3d.UnitZ);

            return(MathFunctions.Project(world, viewport, pm, vm));
        }
Example #16
0
        private void CalcVMatrix()
        {
            //look = (target - position).Normalize();
            CenterOfInterest = (Target - Position);
            CenterOfInterest.Normalize();
            right = Vector3d.Cross(CenterOfInterest, Up);


            V = Matrix4d.LookAt(Position, // Camera is here
                                Target,   // and looks here : at the same position, plus "direction"
                                Up);      // Head is up (set to 0,-1,0 to look upside-down)
        }
Example #17
0
        /// <summary>
        /// Build a world space to camera space matrix
        /// </summary>
        /// <param name="eye">Eye (camera) position in world space</param>
        /// <param name="target">Target position in world space</param>
        /// <param name="up">Up vector in world space (should not be parallel to the camera direction, that is target - eye)</param>
        /// <returns>A Matrix that transforms world space to camera space</returns>
        public static Matrix <double> LookAt(Matrix <double> eye, Matrix <double> target, Matrix <double> up)
        {
            var test = Matrix4d.LookAt(
                eye[0, 0], eye[1, 0], eye[2, 0],
                target[0, 0], target[1, 0], target[2, 0],
                up[0, 0], up[1, 0], up[2, 0]);
            var ret = new Matrix <double>(test.toArray()).Transpose();

            //var wrld = ret.Inverted(DecompMethod.LU);
            //var wrldd = test.Inverted();
            return(ret);
        }
Example #18
0
        public void Draw(TriMesh front, TriMesh back, Vector3D light)
        {
            Vector4d light4d  = new Vector4d(light.x, light.y, light.z, 0);
            Vector3D frontPos = new Vector3D(0.5, 0.5, 0.8);
            Vector3D backPos  = new Vector3D(0, 0, 0);

            GL.Enable(EnableCap.Lighting);
            GL.Enable(EnableCap.Light0);
            GL.Light(LightName.Light0, LightParameter.Diffuse, Color.White);
            GL.Light(LightName.Light0, LightParameter.Position, (Vector4)light4d);

            GL.Enable(EnableCap.CullFace);
            GL.CullFace(CullFaceMode.Back);

            GL.Enable(EnableCap.DepthTest);
            GL.DepthFunc(DepthFunction.Lequal);
            GL.Clear(ClearBufferMask.DepthBufferBit);

            GL.Enable(EnableCap.StencilTest);
            GL.StencilOp(StencilOp.Keep, StencilOp.Keep, StencilOp.Replace);
            GL.StencilFunc(StencilFunction.Always, 1, 1);
            GL.Clear(ClearBufferMask.StencilBufferBit);

            GL.MatrixMode(MatrixMode.Modelview);
            GL.PushMatrix();
            Matrix4d m = Matrix4d.LookAt(light4d.Xyz, Vector3d.Zero, Vector3d.UnitY);

            GL.MultMatrix(ref m);

            GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Diffuse, Color.Red);
            GL.ColorMask(false, false, false, false);
            DrawMesh(front, frontPos);
            GL.ColorMask(true, true, true, true);
            GL.PopMatrix();

            GL.StencilFunc(StencilFunction.Equal, 1, 1);
            GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Diffuse, Color.Black);
            DrawMesh(back, backPos);

            GL.StencilFunc(StencilFunction.Equal, 0, 1);
            GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Diffuse, Color.CornflowerBlue);
            DrawMesh(back, backPos);
            GL.Disable(EnableCap.StencilTest);

            GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Diffuse, Color.CornflowerBlue);
            DrawMesh(front, frontPos);

            GL.Material(MaterialFace.FrontAndBack,
                        MaterialParameter.Diffuse, Color.Red);
            DrawMesh(this.sphere, light);

            GL.Disable(EnableCap.DepthTest);
        }
Example #19
0
        /// <summary>
        /// Project the 2D coordinates from the screen coordinates outwards
        /// from the camera along the lookat vector, taking the frustrum
        /// into account. The resulting line will be run from the camera
        /// position along the view axis and end at the back clipping pane.
        /// </summary>
        /// <param name="x">The X coordinate on screen</param>
        /// <param name="y">The Y coordinate on screen</param>
        /// <returns>A line beginning at the camera location and tracing
        /// along the 3D projection for at least 1,000,000 units.</returns>
        public Line CastRayFromScreen(int x, int y)
        {
            var near = new Coordinate(x, Height - y, 0);
            var far  = new Coordinate(x, Height - y, 1);
            var pm   = Matrix4d.CreatePerspectiveFieldOfView(MathHelper.DegreesToRadians(Camera.FOV), Width / (float)Height, 0.1f, 50000);
            var vm   = Matrix4d.LookAt(
                new Vector3d(Camera.Location.X, Camera.Location.Y, Camera.Location.Z),
                new Vector3d(Camera.LookAt.X, Camera.LookAt.Y, Camera.LookAt.Z),
                Vector3d.UnitZ);
            var viewport = new[] { 0, 0, Width, Height };
            var un       = MathFunctions.Unproject(near, viewport, pm, vm);
            var uf       = MathFunctions.Unproject(far, viewport, pm, vm);

            return((un == null || uf == null) ? null : new Line(un, uf));
        }
        /// <summary>Calculate the Projection matrix - projects the 3d model space to the 2D screen</summary>
        public void CalculateModelMatrix(Vector3d lookatd, Vector3d eyepositiond, double camerarotation)
        {
            LookAt      = new Vector3((float)lookatd.X, (float)lookatd.Y, (float)lookatd.Z); // record for shader use
            EyePosition = new Vector3((float)eyepositiond.X, (float)eyepositiond.Y, (float)eyepositiond.Z);
            EyeDistance = (float)((lookatd - eyepositiond).Length);

            //  System.Diagnostics.Debug.WriteLine($"CMM {lookat} {eyeposition} dist {EyeDistance} {cameradirection} {camerarotation}");

            Matrix4d mat;

            if (InPerspectiveMode)
            {
                Vector3d camnormal = new Vector3d(0, ModelAxisPositiveZAwayFromViewer ? -1 : 1, 0);

                if (camerarotation != 0)     // if we have camera rotation, then rotate the up vector
                {
                    Matrix4d rot = Matrix4d.CreateRotationZ((float)camerarotation.Radians());
                    camnormal = Vector3d.Transform(camnormal, rot);
                }

                mat = Matrix4d.LookAt(eyepositiond, lookatd, camnormal);   // from eye, look at target, with normal giving the rotation of the look
            }
            else
            {
                Size   scr         = ViewPort.Size;
                double orthoheight = (OrthographicDistance / 5.0f) * scr.Height / scr.Width;  // this comes from the projection calculation, and allows us to work out the scale factor the eye vs lookat has
                double scaler      = orthoheight / EyeDistance;

                // no create scale, do it manually.
                Matrix4d scale = new Matrix4d(new Vector4d(scaler, 0, 0, 0), new Vector4d(0, scaler, 0, 0), new Vector4d(0, 0, scaler, 0), new Vector4d(0, 0, 0, 1));

                mat = Matrix4d.CreateTranslation(-lookatd.X, 0, -lookatd.Z);         // we offset by the negative of the position to give the central look
                mat = Matrix4d.Mult(mat, scale);                                     // translation world->View = scale + offset

                Matrix4d rotcam = Matrix4d.CreateRotationX(90.0 * Math.PI / 180.0f); // flip 90 along the x axis to give the top down view
                mat = Matrix4d.Mult(mat, rotcam);
            }

            // and turn it to float model matrix
            ModelMatrix = new Matrix4((float)mat.M11, (float)mat.M12, (float)mat.M13, (float)mat.M14, (float)mat.M21, (float)mat.M22, (float)mat.M23, (float)mat.M24, (float)mat.M31, (float)mat.M32, (float)mat.M33, (float)mat.M34, (float)mat.M41, (float)mat.M42, (float)mat.M43, (float)mat.M44);

            //System.Diagnostics.Debug.WriteLine("MM\r\n{0}", ModelMatrix);

            ProjectionModelMatrix = Matrix4.Mult(ModelMatrix, ProjectionMatrix);        // order order order ! so important.
            CountMatrixCalcs++;
        }
Example #21
0
        /// <summary>
        /// Push the modelview matrix, load the identity and load a new matrix at the origin and looking the same way as the player.
        /// After rendering the skybox, enable blending and render the sun and moon.
        /// </summary>
        /// <remarks>
        /// A future optimization would be to draw all opaque world objects first and then render the skybox followed by transparent world objects.
        /// This prevents the pixel shader from drawing many of the same pixels twice. However is more complicated for a small benefit.
        /// </remarks>
        public void Render(FrameEventArgs e)
        {
            GL.PushMatrix();
            GL.LoadIdentity();
            var sky = Matrix4d.LookAt(0, 0, 0, (float)Math.Cos(Game.Player.Coords.Direction) * (float)Math.Cos(Game.Player.Coords.Pitch), (float)Math.Sin(Game.Player.Coords.Pitch), (float)Math.Sin(Game.Player.Coords.Direction) * (float)Math.Cos(Game.Player.Coords.Pitch), 0, 1, 0);

            GL.LoadMatrix(ref sky);

            GL.PushAttrib(AttribMask.EnableBit);
            GL.Disable(EnableCap.DepthTest);
            GL.Disable(EnableCap.Texture2D);

            const float TOP      = 0.3f;
            const float BOTTOM   = 0.04f;           //make bottom color at the horizon so we can always set the fog color to the same and have nice blending
            const float SIDE     = 0.5f;
            const float SIDE_OUT = SIDE + SIDE / 2; //where the sides stick out to create 8 faces

            //draw skybox as a triangle fan with a center top point and 8 bottom points, cuts down on the noticeable gradient corners
            //drawn clockwise because we are "inside" the skybox, not in a display list because the colors change on every render (could make a dynamic vbo)
            GL.Begin(BeginMode.TriangleFan);
            GL.Color3(SkyTopCurrentColor.ToFloatArray());
            GL.Vertex3(0, TOP, 0);             //center top point
            GL.Color3(SkyBottomCurrentColor.ToFloatArray());
            GL.Vertex3(SIDE, BOTTOM, SIDE);
            GL.Vertex3(0, BOTTOM, SIDE_OUT);
            GL.Vertex3(-SIDE, BOTTOM, SIDE);
            GL.Vertex3(-SIDE_OUT, BOTTOM, 0);
            GL.Vertex3(-SIDE, BOTTOM, -SIDE);
            GL.Vertex3(0, BOTTOM, -SIDE_OUT);
            GL.Vertex3(SIDE, BOTTOM, -SIDE);
            GL.Vertex3(SIDE_OUT, BOTTOM, 0);
            GL.Vertex3(SIDE, BOTTOM, SIDE);
            GL.End();
            GlHelper.ResetColor();

            //render sun/moon
            GL.Enable(EnableCap.Texture2D);
            GL.Enable(EnableCap.Blend);
            DisplayList.RenderDisplayList(DisplayList.SunId, SunPosition.X, SunPosition.Y, 0, Textures.EnvironmentTextureType.Sun);
            DisplayList.RenderDisplayList(DisplayList.MoonId, -SunPosition.X, -SunPosition.Y, 0, Textures.EnvironmentTextureType.Moon);

            GL.PopAttrib();
            GL.PopMatrix();
        }
Example #22
0
        /// <summary>Render scene for selection</summary>
        private static void RenderSceneSelection(bool IsDebugTouchMode = false)
        {
            // initialize
            GL.InitNames();
            GL.PushName(0);
            int PartId = 0;

            // set up camera
            double   dx     = World.AbsoluteCameraDirection.X;
            double   dy     = World.AbsoluteCameraDirection.Y;
            double   dz     = World.AbsoluteCameraDirection.Z;
            double   ux     = World.AbsoluteCameraUp.X;
            double   uy     = World.AbsoluteCameraUp.Y;
            double   uz     = World.AbsoluteCameraUp.Z;
            Matrix4d LookAt = Matrix4d.LookAt(0.0, 0.0, 0.0, dx, dy, dz, ux, uy, uz);

            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadMatrix(ref LookAt);

            if (LightingEnabled)
            {
                GL.Disable(EnableCap.Lighting);
                LightingEnabled = false;                 // TODO: was 'true' before
            }
            OptionLighting = false;
            if (!BlendEnabled)
            {
                GL.Enable(EnableCap.Blend);
                BlendEnabled = true;
            }
            GL.DepthMask(false);
            GL.Disable(EnableCap.DepthTest);
            UnsetAlphaFunc();
            Touch.SortPolygons();
            for (int i = 0; i < Touch.FaceCount; i++)
            {
                GL.LoadName(PartId);
                RenderFace(ref Touch.Faces[i], World.AbsoluteCameraPosition, IsDebugTouchMode);
                PartId++;
            }

            GL.PopName();
            OptionLighting = true;
        }
Example #23
0
        public override void Update()
        {
            if (Widget.Enabled)
            {
                //ScreenPos = new Vector3d(Settings.Tweak1 * 0.01, Settings.Tweak2*0.01, Settings.Tweak3*0.01);

                Widget.transform.Position = ScreenPos;
                Vector3d AP = Globals.Avatar.GetPosition();

                if (Target == AP)
                {
                    Target = AP + new Vector3d(0, 0, 1);
                }
                Matrix4d Rot = Matrix4d.CreateFromQuaternion(Globals.Avatar.GetRotation())
                               * Matrix4d.LookAt(Target, AP - Globals.Avatar.Up() * 2,
                                                 Globals.Avatar.Up());
                Widget.transform.Rotation = Rot.Inverted().ExtractRotation();
            }
        }
        /// <summary>
        /// Generates a 4x4 double Matrix representing the camera's View (with Perspective added)
        /// </summary>
        /// <param name="Pos">The camera's Position</param>
        /// <param name="Up">The camera's Up vector</param>
        /// <param name="Target">The camera's Target vector</param>
        /// <param name="cameraType">The camera's Type</param>
        /// <param name="zFar">The camera's ZFar</param>
        /// <param name="zNear">The camera's zNear</param>
        /// <param name="cameraWidth">The camera's width</param>
        /// <param name="cameraHeight">The camera's height</param>
        /// <param name="cameraAspect">The camera's aspect ratio</param>
        /// <param name="cameraFOV">The camera's field of view</param>
        /// <returns>a 4x4 double Matrix</returns>
        private Matrix4d generateMatrix(Vector3d Pos, Vector3d Up, Vector3d Target, ComponentConstants.CAM_TYPES cameraType, double zNear, double zFar, double cameraWidth = 0, double cameraHeight = 0, double cameraAspect = 0, double cameraFOV = 0)
        {
            Matrix4d ProjectionMatrix;

            if (cameraType == ComponentConstants.CAM_TYPES.ORTHOGRAPHIC)
            {
                ProjectionMatrix = Matrix4d.CreateOrthographic(cameraWidth, cameraHeight, zNear, zFar);
            }
            else
            {
                ProjectionMatrix = Matrix4d.CreatePerspectiveFieldOfView(cameraFOV, cameraAspect, zNear, zFar);
            }

            Matrix4d ViewMatrix = Matrix4d.LookAt(Pos, Target, Up);

            Matrix4d ResultMatrix = ProjectionMatrix * ViewMatrix;

            return(ResultMatrix);
        }
Example #25
0
        private void Draw3D()
        {
            GL.DrawBuffer(DrawBufferMode.Back);
            GL.ClearColor(this.ClearColor[0], this.ClearColor[1], this.ClearColor[2], 0.0f);
            GL.Clear(ClearBufferMask.DepthBufferBit | ClearBufferMask.ColorBufferBit);
            GL.LoadIdentity();
            Matrix4d perspectiveFieldOfView = Matrix4d.CreatePerspectiveFieldOfView(Math.PI / 4.0, (double)this.glControl1.Width / (double)this.glControl1.Height, (double)this.zFar * 0.001, (double)this.zFar + 1000.0);

            GL.LoadMatrix(ref perspectiveFieldOfView);
            Matrix4d mat = Matrix4d.LookAt(this.eye.X, this.eye.Y, this.eye.Z, this.center.X, this.center.Y, this.center.Z, this.up.X, this.up.Y, this.up.Z);

            GL.MultMatrix(ref mat);

            this.DrawAll3DObjects();

            GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Shininess, new float[4] {
                0.9f, 0.9f, 0.9f, 1f
            });
            this.glControl1.SwapBuffers();
        }
Example #26
0
        public override void Update()
        {
            Matrix4d R = yawPitchRoll(yaw, pitch, roll);

            Position += translation;

            //set this when no movement decay is needed
            //translation=Vector3d(0);

            CenterOfInterest = R.MultiplyVector3d(new Vector4d(0, 0, 1, 0));
            Up    = R.MultiplyVector3d(new Vector4d(0, 1, 0, 0));
            right = Vector3d.Cross(CenterOfInterest, Up);

            Vector3d direction = Position + CenterOfInterest;

            // V = lookAt(Position, tgt, up);
            V = Matrix4d.LookAt(Position,  // Camera is here
                                direction, // and looks here : at the same position, plus "direction"
                                Up);       // Head is up (set to 0,-1,0 to look upside-down)
            //
        }
Example #27
0
        protected override void OnRenderFrame(FrameEventArgs e)
        {
            base.OnRenderFrame(e);

            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadIdentity();

            // SET CAMERA, THEN DRAW STUFF DAMMIT
            Matrix4d camera = Matrix4d.LookAt(OpenTK.Vector3d.Multiply(viewDirection, viewDist),
                                              OpenTK.Vector3d.Zero, up);

            GL.LoadMatrix(ref camera);

            angle += rotation_speed * (float)e.Time;
            GL.Rotate(angle, 0.0f, 1.0f, 0.0f);
            DrawBuffer();

            SwapBuffers();
            Thread.Sleep(1);
        }
Example #28
0
        /// <summary>Update the ModelView and Frustum. Done on every update cycle and before the world is initially loaded so we can preload chunks in the initial frustum.</summary>
        private static void UpdateFrustum()
        {
            ModelView = Matrix4d.LookAt(Player.Coords.Xf, Player.Coords.Yf + Constants.PLAYER_EYE_LEVEL, Player.Coords.Zf, Player.Coords.Xf + (float)Math.Cos(Player.Coords.Direction) * (float)Math.Cos(Player.Coords.Pitch), Player.Coords.Yf + Constants.PLAYER_EYE_LEVEL + (float)Math.Sin(Player.Coords.Pitch), Player.Coords.Zf + (float)Math.Sin(Player.Coords.Direction) * (float)Math.Cos(Player.Coords.Pitch), 0, 1, 0);

            Matrix4d clip;

            Matrix4d.Mult(ref ModelView, ref Projection, out clip);
            LeftFrustum = new Vector4d(clip.M14 + clip.M11, clip.M24 + clip.M21, clip.M34 + clip.M31, clip.M44 + clip.M41);
            LeftFrustum.NormalizeFast();
            RightFrustum = new Vector4d(clip.M14 - clip.M11, clip.M24 - clip.M21, clip.M34 - clip.M31, clip.M44 - clip.M41);
            RightFrustum.NormalizeFast();

            BottomFrustum = new Vector4d(clip.M14 + clip.M12, clip.M24 + clip.M22, clip.M34 + clip.M32, clip.M44 + clip.M42);
            BottomFrustum.NormalizeFast();
            TopFrustum = new Vector4d(clip.M14 - clip.M12, clip.M24 - clip.M22, clip.M34 - clip.M32, clip.M44 - clip.M42);
            TopFrustum.NormalizeFast();

            NearFrustum = new Vector4d(clip.M14 + clip.M13, clip.M24 + clip.M23, clip.M34 + clip.M33, clip.M44 + clip.M43);
            NearFrustum.NormalizeFast();
            FarFrustum = new Vector4d(clip.M14 - clip.M13, clip.M24 - clip.M23, clip.M34 - clip.M33, clip.M44 - clip.M43);
            FarFrustum.NormalizeFast();
        }
Example #29
0
        // Does not draw a background
        public static void StartDraw(Vector2d target)
        {
            // Coordinate transform between gameworld and screenworld coordinates.
            CameraTarget.X = target.Y;
            CameraTarget.Y = 0.0;
            CameraTarget.Z = target.X;

            // This fixes the light position to (10 units above) the gameworld origin.
            L1.Position.X = (float)-target.X;
            L1.Position.Y = (float)-target.Y;
            L1.Position.Z = (float)-0;
            L1.BindToCurrentShader();

            Vector3d CameraLoc = Vector3d.Multiply(OutOfScreen, CameraDistance);

            CameraLoc = Vector3d.Add(CameraTarget, CameraLoc);
            Modelview = Matrix4d.LookAt(CameraLoc, CameraTarget, Up);

            // We also need to transform
            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadMatrix(ref Modelview);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
        }
Example #30
0
        private void Render(object sender, PaintEventArgs e)
        {
            if (!loaded)
            {
                return;
            }
            MakeCurrent();
            SetupViewport();
            //double size = Scene.Size();

            double size = Scene.Max.Y - Scene.Min.Y;

            double SceneYOffset = -size / 2f;

            double defaultzoom = (double)Math.Sqrt(Math.Pow(TableRadius, 2) + Math.Pow(TableHeight, 2));

            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            GL.LoadIdentity();
            var aspect_ratio = Width / (double)Height;
            var projection   = Matrix4d.CreatePerspectiveFieldOfView(
                MathHelper.PiOver4, double.Parse(aspect_ratio.ToString()), 1f, 1024);



            //            var modelview = Matrix4d.LookAt(0, size / 2 , - DragZoom * defaultzoom * 2f,
            //                                            0,TableHeight/2, 0,  0, size, 0);
            var viewHeight = (TableHeight / 2.50) + SceneYOffset;
            var modelview  = Matrix4d.LookAt(0, viewHeight, Math.Max(0.00000001f, -(-Drag.Zoom * defaultzoom * 1.5f)),
                                             0, viewHeight, 0, 0, size, 0);

            GL.MatrixMode(MatrixMode.Projection);
            if (Projection)
            {
                GL.LoadMatrix(ref projection);
            }
            else
            {
                GL.LoadIdentity();
                double x = Math.Max(TableRadius * 2, TableHeight) * Drag.Zoom / 2.0;
                double y = x * ((double)Height / (double)Width);
                GL.Ortho(-x, x, -y, y, 0.0, 10000.0);
            }
            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadMatrix(ref modelview);

            #region LIGHT
            //if (Lightning)
            {
                float[] lightPos = new float[] { (float)(-TableRadius * 2f), (float)TableRadius * 2f, (float)TableHeight * 2f, 1.0f };
                GL.PointSize(5);
                GL.Disable(EnableCap.Lighting);
                GL.Begin(PrimitiveType.Points);
                GL.Color3(Color.Yellow);
                GL.Vertex3(lightPos);
                GL.End();
                GL.PointSize(1);

                float[] light_ambient  = { 0.2f, 0.2f, 0.2f, 1.0f };
                float[] light_diffuse  = { 1.0f, 1.0f, 1.0f, 1.0f };
                float[] light_specular = { 1.0f, 1.0f, 1.0f, 1.0f };
                float[] spotdirection  = { 0.5f, -1.0f, -1.0f };

                GL.Light(LightName.Light0, LightParameter.Ambient, light_ambient);
                GL.Light(LightName.Light0, LightParameter.Diffuse, light_diffuse);
                GL.Light(LightName.Light0, LightParameter.Specular, light_specular);

                GL.Enable(EnableCap.Lighting);
                GL.Light(LightName.Light0, LightParameter.Position, lightPos);
                GL.Enable(EnableCap.Light0);
                //GL.Light(LightName.Light0, LightParameter.SpotDirection, spotdirection);
                //GL.Light(LightName.Light0, LightParameter.SpotCutoff, 20);
            }
            #endregion

            GL.Translate(Drag.Pane.X, -Drag.Pane.Y, 0);
            Matrix4d m = MatrixFromYawPitchRoll(-Math.PI * Drag.Angle.X / 360.0f, -Math.PI * Drag.Angle.Y / 360.0f, 0);
            GL.MultMatrix(ref m);
            // Model space
            #region Box/Axis
            GL.Disable(EnableCap.Lighting);
            Vector3d scannerCenter = new Vector3d(0, -size / 2f, 0);
            Axis(new Vector3d(scannerCenter.X - TableRadius, scannerCenter.Y, scannerCenter.Z + TableRadius), 10);
            #endregion ;

            GL.Translate(0, SceneYOffset, 0);

            if (BoundingBox)
            {
                DrawBoundingBox(Color.Red, Scene.Min, Scene.Max);
            }
            if (Lightning)
            {
                GL.Enable(EnableCap.Lighting);
                GL.ColorMaterial(MaterialFace.FrontAndBack, ColorMaterialParameter.AmbientAndDiffuse);
                GL.Enable(EnableCap.ColorMaterial);
            }


            GL.PointSize(2);
            GL.LineWidth(2);

            RenderingContext context = RenderingContext.From(ViewerConfig);
            context.ApplyFaceDefault();
            GL.ShadeModel(Smooth ? ShadingModel.Smooth : ShadingModel.Flat);
            GL.Enable(EnableCap.CullFace);
            GL.CullFace(CullFaceMode.Back);
            Scene.Render(ref context);
            GL.Translate(0, -SceneYOffset, 0);
            DrawScannerTable(scannerCenter);
            SwapBuffers();
            using (Graphics g = Graphics.FromHwnd(this.Handle))
            {
                using (SolidBrush bg = new SolidBrush(this.BackColor))
                {
                    using (SolidBrush bf = new SolidBrush(this.ForeColor))
                    {
                        string     text = String.Format("{0} points", Scene.GetNumVertices().ToString("N0"));
                        SizeF      s    = g.MeasureString(text, this.Font);
                        RectangleF rect = new RectangleF(0, 0, s.Width, s.Height);
                        rect.Y = this.Height - s.Height;
                        g.FillRectangle(bg, rect);
                        g.DrawString(text, this.Font, bf, rect.Location);
                    }
                }
            }
//            this.Label.Text = String.Format("{0} points", Scene.GetNumVertices());
        }