Exemplo n.º 1
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            UpdateTooltip();

            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            GL.ClearColor(204 / 255.0F, 1.0f, 1.0f, 1.0f);

            Matrix4 model = rotator;

            viewModel = model * Matrix4.LookAt(FarOffset / 10.0f, FarOffset / 10.0f, FarOffset / 10.0f, 0, 0, 0, 0, 1, 0);
            Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView((float)(Math.PI / 2.0), glControl1.Width / (float)glControl1.Height, 0.01f, 1000.0f);

            mult = viewModel * projection;

            basic.Use();

            //model *= Matrix4.CreateTranslation(FarOffset/10.0f, FarOffset/10.0f, FarOffset/10.0f);

            GL.UniformMatrix4(basic.shaderMVLocation_, false, ref viewModel);
            GL.UniformMatrix4(basic.shaderPLocation_, false, ref projection);
            if (wire)
            {
                GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line);
                GL.CullFace(CullFaceMode.FrontAndBack);
            }
            else
            {
                GL.PolygonMode(MaterialFace.Front, PolygonMode.Fill);
                GL.CullFace(CullFaceMode.Back);
            }

            GL.Enable(EnableCap.DepthTest);
            MainMesh_.Bind(basic);
            MainMesh_.Render();

            GL.Disable(EnableCap.DepthTest);
            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadMatrix(ref mult);
            GL.UseProgram(0);
            GL.Begin(PrimitiveType.Lines);
            GL.Color4(Color.Blue);
            GL.Vertex3(0, 0, 0);
            GL.Vertex3(0, 0, FarOffset / 20.0f);
            GL.Color4(Color.GreenYellow);
            GL.Vertex3(0, 0, 0);
            GL.Vertex3(0, FarOffset / 20.0f, 0);
            GL.Color4(Color.Red);
            GL.Vertex3(0, 0, 0);
            GL.Vertex3(FarOffset / 20.0f, 0, 0);
            GL.End();

            GL.Flush();
            glControl1.SwapBuffers();

            if ((int)(OcclusionMap.AorResultTotal * 0.99f) < OcclusionMap.AorResult)
            {
                toolStripProgressBar1.Value = 0;
            }
            else
            {
                toolStripProgressBar1.Maximum = OcclusionMap.AorResultTotal;
                toolStripProgressBar1.Value   = OcclusionMap.AorResult;
            }

            if (Log.updated && textBox1.Visible)
            {
                Log.updated   = false;
                textBox1.Text = Log.Get();
            }
        }
Exemplo n.º 2
0
        // render all committed lines
        public static void Render()
        {
            // half width of line, in pixels
            const float half_width = 2.0f;

            // store stuff
            Vector3 a;                        // shortcut to line start
            Vector3 b;                        // shortcut to line end
            Vector3 diff;                     // vector from a to b
            Vector3 v;                        // perpendicular vector
            Vector3 Va;                       // perpendicular vector scaled by start distance
            Vector3 Vb;                       // perpendicular vector scaled by end distance
            Vector3 p0;                       // bottom left point
            Vector3 p1;                       // bottom right point
            Vector3 p2;                       // top left point
            Vector3 p3;                       // top right point

            // get camera
            var     cam       = PlanetariumCamera.Camera;
            Vector3 cam_pos   = cam.transform.position;
            Vector3 cam_up    = cam.transform.up;
            Vector3 cam_right = cam.transform.right;

            // enable the material
            mat.SetPass(0);

            // start rendering lines
            GL.Begin(GL.TRIANGLES);

            // projection factor
            // note: for some reasons, this result in a screen size 20% smaller than it should be
            float k = half_width * 2.0f * Mathf.Tan(cam.fieldOfView * 0.5f * Mathf.Deg2Rad) / Screen.height;

            // for each line we got
            foreach (Line_data line in lines)
            {
                // shortcuts
                a = line.a;
                b = line.b;

                // set the color
                GL.Color(line.color);

                // find vector perpendicular to look and line, in world space
                diff = b - a;
                v    = (cam_right * -Vector3.Dot(diff, cam_up) + cam_up * Vector3.Dot(diff, cam_right)).normalized * k;

                // scale perpendicular vector to have exact pixel length
                Va = v * (a - cam_pos).magnitude;
                Vb = v * (b - cam_pos).magnitude;

                // calculate quand points
                p0 = a - Va;
                p1 = a + Va;
                p2 = b - Vb;
                p3 = b + Vb;

                // bottom left
                GL.TexCoord2(-1.0f, 0.0f);
                GL.Vertex(p0);

                // bottom right
                GL.TexCoord2(1.0f, 0.0f);
                GL.Vertex(p1);

                // top right
                GL.TexCoord2(1.0f, 0.0f);
                GL.Vertex(p3);

                // top right
                GL.TexCoord2(1.0f, 0.0f);
                GL.Vertex(p3);

                // top left
                GL.TexCoord2(-1.0f, 0.0f);
                GL.Vertex(p2);

                // bottom left
                GL.TexCoord2(-1.0f, 0.0f);
                GL.Vertex(p0);
            }

            // stop rendering triangles
            GL.End();

            // clear all committed lines
            lines.Clear();
        }
Exemplo n.º 3
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());
        }
        /// <summary>
        /// <see cref="ISceneRenderer.Render"/>
        /// </summary>
        public void Render(ICameraController cam, Dictionary <Node, List <Mesh> > visibleMeshesByNode,
                           bool visibleSetChanged,
                           bool texturesChanged,
                           RenderFlags flags,
                           Renderer renderer)
        {
            GL.Disable(EnableCap.Texture2D);
            GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);
            GL.Enable(EnableCap.DepthTest);

            if (flags.HasFlag(RenderFlags.Wireframe))
            {
                GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line);
            }
            var tmp = InitposeMax.X - InitposeMin.X;

            tmp = Math.Max(InitposeMax.Y - InitposeMin.Y, tmp);
            tmp = Math.Max(InitposeMax.Z - InitposeMin.Z, tmp);
            int   logScale = (int)Math.Truncate(Math.Log10(tmp * 10 / 50)); //  Up to 50units max size = 50m: keep scale (for smaller scenes).
            float scale    = 1;

            for (int i = 0; i < logScale; i++)
            {
                scale = scale / 10;
            }
            Owner.Scale = scale;
            if (cam != null)
            {
                //       cam.SetPivot(Owner.Pivot * (float)scale); this does nothing (?) only makes controller dirty
            }
            var view = cam == null?Matrix4.LookAt(0, 10, 5, 0, 0, 0, 0, 1, 0) : cam.GetView();

            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadMatrix(ref view);
            GL.Scale(scale, scale, scale);
            Owner.MaterialMapper.BeginScene(renderer, flags.HasFlag(RenderFlags.UseSceneLights)); //here we switch on lights

            if (flags.HasFlag(RenderFlags.ShowLightDirection))                                    //switch off for video??
            {
                var dir = new Vector3(1, 1, 0);
                var mat = renderer.LightRotation;
                Vector3.TransformNormal(ref dir, ref mat, out dir);
                OverlayLightSource.DrawLightSource(dir);
            }

            // If textures changed, we may need to upload some of them to VRAM.
            // it is important this happens here and not accidentially while
            // compiling a displist.
            if (texturesChanged)
            {
                UploadTextures();
            }
            UploadDynamicTextures();

            GL.PushMatrix();

            // Build and cache Gl displaylists and update only when the scene changes.
            // when the scene is being animated, this changes each frame
            var animated = Owner.SceneAnimator.IsAnimationActive;

            if (visibleSetChanged || texturesChanged || flags != _lastFlags || (animated && (Owner.NewFrame) || wasAnimated))
            {
                int startList = 4; //we update only 4 animation displists
                if (visibleSetChanged || texturesChanged || flags != _lastFlags)
                {
                    startList = 0;
                }
                _lastFlags = flags;

                // handle opaque geometry
                for (int currDispList = startList; currDispList < _displayListCount; currDispList++)
                {
                    if (_displayList[currDispList, 0] == 0)
                    {
                        _displayList[currDispList, 0] = GL.GenLists(1);
                    }
                    GL.NewList(_displayList[currDispList, 0], ListMode.Compile);
                    var needAlpha = RecursiveRender(Owner.Raw.RootNode, visibleMeshesByNode, flags, animated, currDispList);
                    if (flags.HasFlag(RenderFlags.ShowSkeleton))
                    {
                        RecursiveRenderNoScale(Owner.Raw.RootNode, visibleMeshesByNode, flags, 1.0f / scale, animated, currDispList);
                    }
                    if (flags.HasFlag(RenderFlags.ShowNormals))
                    {
                        RecursiveRenderNormals(Owner.Raw.RootNode, visibleMeshesByNode, flags, 1.0f / scale, animated, Matrix4.Identity, currDispList);
                    }
                    GL.EndList();
                    if (needAlpha)
                    {
                        // handle semi-transparent geometry
                        if (_displayList[currDispList, 1] == 0)
                        {
                            _displayList[currDispList, 1] = GL.GenLists(1);
                        }
                        GL.NewList(_displayList[currDispList, 1], ListMode.Compile);
                        RecursiveRenderWithAlpha(Owner.Raw.RootNode, visibleMeshesByNode, flags, animated, currDispList);
                        GL.EndList();
                    }
                    else if (_displayList[currDispList, 1] != 0)
                    {
                        GL.DeleteLists(_displayList[currDispList, 1], 1);
                        _displayList[currDispList, 1] = 0;
                    }
                }
            }

            Owner.NewFrame = false;
            wasAnimated    = animated;

            /* display lists:
             * 0: Background;
             * 1: Else (always visible);
             * 2: Foreground;
             * 3: GreenScreen;
             * 4: BackgroundAnimated;
             * 5: ElseAnimated (always visible);
             * 6: ForegroundAnimated;
             * 7: GreenScreenAnimated;
             * Animated - list is refreshed each frame
             */
            switch (cam.GetScenePartMode())
            {
            case ScenePartMode.Background:
                if (_displayList[0, 0] != 0)
                {
                    GL.CallList(_displayList[0, 0]);
                }
                if (_displayList[4, 0] != 0)
                {
                    GL.CallList(_displayList[4, 0]);
                }
                if (_displayList[0, 1] != 0)
                {
                    GL.CallList(_displayList[0, 1]);
                }
                if (_displayList[4, 1] != 0)
                {
                    GL.CallList(_displayList[4, 1]);
                }
                break;

            case ScenePartMode.Foreground:
                if (_displayList[2, 0] != 0)
                {
                    GL.CallList(_displayList[2, 0]);
                }
                if (_displayList[6, 0] != 0)
                {
                    GL.CallList(_displayList[6, 0]);
                }
                if (_displayList[2, 1] != 0)
                {
                    GL.CallList(_displayList[2, 1]);
                }
                if (_displayList[6, 1] != 0)
                {
                    GL.CallList(_displayList[6, 1]);
                }
                break;

            case ScenePartMode.Others:
                if (_displayList[1, 0] != 0)
                {
                    GL.CallList(_displayList[1, 0]);
                }
                if (_displayList[5, 0] != 0)
                {
                    GL.CallList(_displayList[5, 0]);
                }
                if (_displayList[1, 1] != 0)
                {
                    GL.CallList(_displayList[1, 1]);
                }
                if (_displayList[5, 1] != 0)
                {
                    GL.CallList(_displayList[5, 1]);
                }
                break;

            case ScenePartMode.GreenScreen:
                if (_displayList[3, 0] != 0)
                {
                    GL.CallList(_displayList[3, 0]);
                }
                if (_displayList[7, 0] != 0)
                {
                    GL.CallList(_displayList[7, 0]);
                }
                if (_displayList[3, 1] != 0)
                {
                    GL.CallList(_displayList[3, 1]);
                }
                if (_displayList[7, 1] != 0)
                {
                    GL.CallList(_displayList[7, 1]);
                }
                break;

            case ScenePartMode.All:
                for (int currDispList = 0; currDispList < _displayListCount; currDispList++)
                {
                    if (_displayList[currDispList, 0] != 0)
                    {
                        GL.CallList(_displayList[currDispList, 0]);
                    }
                    if (_displayList[currDispList, 1] != 0)
                    {
                        GL.CallList(_displayList[currDispList, 1]);
                    }
                }
                break;

            default: break;    //at other modes we do not render anything
            }

            GL.PopMatrix();
            // always switch back to FILL
            Owner.MaterialMapper.EndScene(renderer);
            GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill);
            GL.Disable(EnableCap.DepthTest);

#if TEST
            GL.Enable(EnableCap.ColorMaterial);


            // TEST CODE to visualize mid point (pivot) and origin
            GL.LoadMatrix(ref view);
            GL.Begin(BeginMode.Lines);

            GL.Vertex3((InitposeMin + InitposeMax) * 0.5f * (float)scale);
            GL.Color3(0.0f, 1.0f, 0.0f);
            GL.Vertex3(0, 0, 0);
            GL.Color3(0.0f, 1.0f, 0.0f);
            GL.Vertex3((InitposeMin + InitposeMax) * 0.5f * (float)scale);
            GL.Color3(0.0f, 1.0f, 0.0f);

            GL.Vertex3(10, 10, 10);
            GL.Color3(0.0f, 1.0f, 0.0f);
            GL.End();
#endif
            GL.Disable(EnableCap.Texture2D);
        }
Exemplo n.º 5
0
        ////draw the guidance line
        public void DrawCurve()
        {
            int ptCount = refList.Count;

            if (refList.Count == 0)
            {
                return;
            }

            GL.LineWidth(2);
            GL.Color3(0.30f, 0.692f, 0.60f);
            GL.Begin(PrimitiveType.LineStrip);
            for (int h = 0; h < ptCount; h++)
            {
                GL.Vertex3(refList[h].easting, refList[h].northing, 0);
            }
            GL.Color3(0.930f, 0.0692f, 0.260f);
            if (!mf.curve.isCurveSet)
            {
                ptCount--;
                GL.Vertex3(refList[ptCount].easting, refList[ptCount].northing, 0);
#pragma warning disable CS1690 // Accessing a member on a field of a marshal-by-reference class may cause a runtime exception
                GL.Vertex3(mf.pivotAxlePos.easting, mf.pivotAxlePos.northing, 0);
#pragma warning restore CS1690 // Accessing a member on a field of a marshal-by-reference class may cause a runtime exception
            }
            GL.End();

            //just draw ref and smoothed line if smoothing window is open
            if (isSmoothWindowOpen)
            {
                ptCount = smooList.Count;
                if (smooList.Count == 0)
                {
                    return;
                }

                GL.LineWidth(2);
                GL.Color3(0.930f, 0.92f, 0.260f);
                GL.Begin(PrimitiveType.Lines);
                for (int h = 0; h < ptCount; h++)
                {
                    GL.Vertex3(smooList[h].easting, smooList[h].northing, 0);
                }
                GL.End();

                //GL.Color3(0.64f, 0.64f, 0.750f);
                //GL.Begin(PrimitiveType.Lines);
                //GL.Vertex3(boxA.easting, boxA.northing, 0);
                //GL.Vertex3(boxB.easting, boxB.northing, 0);
                //GL.Vertex3(boxC.easting, boxC.northing, 0);
                //GL.Vertex3(boxD.easting, boxD.northing, 0);
                //GL.End();
            }
            //normal. Smoothing window is not open.
            else
            {
                ptCount = curList.Count;
                if (ptCount > 0 || !isCurveSet)
                {
                    GL.PointSize(2);

                    GL.Color3(0.95f, 0.2f, 0.0f);
                    GL.Begin(PrimitiveType.LineStrip);
                    for (int h = 0; h < ptCount; h++)
                    {
                        GL.Vertex3(curList[h].easting, curList[h].northing, 0);
                    }
                    GL.End();

                    if (mf.isPureDisplayOn)
                    {
                        if (ppRadiusCu < 100 && ppRadiusCu > -100)
                        {
                            const int numSegments = 100;
                            double    theta       = glm.twoPI / numSegments;
                            double    c           = Math.Cos(theta); //precalculate the sine and cosine
                            double    s           = Math.Sin(theta);
                            double    x           = ppRadiusCu;      //we start at angle = 0
                            double    y           = 0;

                            GL.LineWidth(1);
                            GL.Color3(0.95f, 0.30f, 0.950f);
                            GL.Begin(PrimitiveType.LineLoop);
                            for (int ii = 0; ii < numSegments; ii++)
                            {
                                //glVertex2f(x + cx, y + cy);//output vertex
                                GL.Vertex3(x + radiusPointCu.easting, y + radiusPointCu.northing, 0); //output vertex
                                double t = x;                                                         //apply the rotation matrix
                                x = (c * x) - (s * y);
                                y = (s * t) + (c * y);
                            }
                            GL.End();
                        }

                        //Draw lookahead Point
                        GL.PointSize(4.0f);
                        GL.Begin(PrimitiveType.Points);
                        GL.Color3(1.0f, 0.5f, 0.95f);
                        GL.Vertex3(goalPointCu.easting, goalPointCu.northing, 0.0);
                        GL.End();
                    }

                    mf.yt.DrawYouTurn();

                    if (mf.yt.isYouTurnTriggered)
                    {
                        GL.Color3(0.95f, 0.95f, 0.25f);
                        GL.LineWidth(4);
                        ptCount = mf.yt.ytList.Count;
                        if (ptCount > 0)
                        {
                            GL.Begin(PrimitiveType.Points);
                            for (int i = 0; i < ptCount; i++)
                            {
                                GL.Vertex3(mf.yt.ytList[i].easting, mf.yt.ytList[i].northing, 0);
                            }
                            GL.End();
                        }

                        GL.Color3(0.95f, 0.05f, 0.05f);
                    }
                }
            }
            GL.PointSize(1.0f);
        }
Exemplo n.º 6
0
        public void DrawBoundingBoxes(DrawMethodArgs args)
        {
            PhysicsScene  scene      = demo.Engine.Factory.PhysicsSceneManager.Get(args.OwnerSceneIndex);
            PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Get(args.OwnerIndex);

            if (!objectBase.Camera.Enabled)
            {
                return;
            }
            if (!objectBase.Camera.Active)
            {
                return;
            }
            if (!enableDrawBoundingBoxes)
            {
                return;
            }

            float time = args.Time;

            PhysicsObject visiblePhysicsObject;
            Vector3       min, max;

            objectBase.Camera.View.GetViewMatrix(ref view);
            objectBase.Camera.Projection.GetProjectionMatrix(ref projection);
            world = matrixIdentity;

            GL.Color3(1.0f, 1.0f, 1.0f);

            render.SetWorld(ref world);
            render.SetView(ref view);
            render.SetProjection(ref projection);

            render.Apply();

            for (int i = 0; i < objectBase.Camera.VisiblePhysicsObjectCount; i++)
            {
                visiblePhysicsObject = objectBase.Camera.GetVisiblePhysicsObject(i);

                visiblePhysicsObject.GetBoundingBox(ref boundingBox);
                min = boundingBox.Min;
                max = boundingBox.Max;

                cameraVertices[0].Position.X = min.X;
                cameraVertices[0].Position.Y = min.Y;
                cameraVertices[0].Position.Z = min.Z;

                cameraVertices[1].Position.X = max.X;
                cameraVertices[1].Position.Y = min.Y;
                cameraVertices[1].Position.Z = min.Z;

                cameraVertices[2].Position.X = min.X;
                cameraVertices[2].Position.Y = min.Y;
                cameraVertices[2].Position.Z = min.Z;

                cameraVertices[3].Position.X = min.X;
                cameraVertices[3].Position.Y = max.Y;
                cameraVertices[3].Position.Z = min.Z;

                cameraVertices[4].Position.X = min.X;
                cameraVertices[4].Position.Y = min.Y;
                cameraVertices[4].Position.Z = min.Z;

                cameraVertices[5].Position.X = min.X;
                cameraVertices[5].Position.Y = min.Y;
                cameraVertices[5].Position.Z = max.Z;

                cameraVertices[6].Position.X = max.X;
                cameraVertices[6].Position.Y = max.Y;
                cameraVertices[6].Position.Z = max.Z;

                cameraVertices[7].Position.X = min.X;
                cameraVertices[7].Position.Y = max.Y;
                cameraVertices[7].Position.Z = max.Z;

                cameraVertices[8].Position.X = max.X;
                cameraVertices[8].Position.Y = max.Y;
                cameraVertices[8].Position.Z = max.Z;

                cameraVertices[9].Position.X = max.X;
                cameraVertices[9].Position.Y = min.Y;
                cameraVertices[9].Position.Z = max.Z;

                cameraVertices[10].Position.X = max.X;
                cameraVertices[10].Position.Y = max.Y;
                cameraVertices[10].Position.Z = max.Z;

                cameraVertices[11].Position.X = max.X;
                cameraVertices[11].Position.Y = max.Y;
                cameraVertices[11].Position.Z = min.Z;

                cameraVertices[12].Position.X = min.X;
                cameraVertices[12].Position.Y = max.Y;
                cameraVertices[12].Position.Z = min.Z;

                cameraVertices[13].Position.X = min.X;
                cameraVertices[13].Position.Y = max.Y;
                cameraVertices[13].Position.Z = max.Z;

                cameraVertices[14].Position.X = min.X;
                cameraVertices[14].Position.Y = max.Y;
                cameraVertices[14].Position.Z = min.Z;

                cameraVertices[15].Position.X = max.X;
                cameraVertices[15].Position.Y = max.Y;
                cameraVertices[15].Position.Z = min.Z;

                cameraVertices[16].Position.X = max.X;
                cameraVertices[16].Position.Y = min.Y;
                cameraVertices[16].Position.Z = max.Z;

                cameraVertices[17].Position.X = max.X;
                cameraVertices[17].Position.Y = min.Y;
                cameraVertices[17].Position.Z = min.Z;

                cameraVertices[18].Position.X = max.X;
                cameraVertices[18].Position.Y = min.Y;
                cameraVertices[18].Position.Z = max.Z;

                cameraVertices[19].Position.X = min.X;
                cameraVertices[19].Position.Y = min.Y;
                cameraVertices[19].Position.Z = max.Z;

                cameraVertices[20].Position.X = min.X;
                cameraVertices[20].Position.Y = max.Y;
                cameraVertices[20].Position.Z = max.Z;

                cameraVertices[21].Position.X = min.X;
                cameraVertices[21].Position.Y = min.Y;
                cameraVertices[21].Position.Z = max.Z;

                cameraVertices[22].Position.X = max.X;
                cameraVertices[22].Position.Y = max.Y;
                cameraVertices[22].Position.Z = min.Z;

                cameraVertices[23].Position.X = max.X;
                cameraVertices[23].Position.Y = min.Y;
                cameraVertices[23].Position.Z = min.Z;

                GL.Begin(PrimitiveType.Lines);

                for (int j = 0; j < 24; j += 2)
                {
                    GL.Vertex3(cameraVertices[j].Position);
                    GL.Vertex3(cameraVertices[j + 1].Position);
                }

                GL.End();
            }
        }
        /// <summary>Renders a string to the screen.</summary>
        /// <param name="font">The font to use.</param>
        /// <param name="text">The string to render.</param>
        /// <param name="location">The location.</param>
        /// <param name="alignment">The alignment.</param>
        /// <param name="color">The color.</param>
        /// <remarks>This function sets the OpenGL blend function to glBlendFunc(Gl.GL_SRC_ALPHA, Gl.GL_ONE_MINUS_SRC_ALPHA).</remarks>
        private static void DrawString(Fonts.OpenGlFont font, string text, Point location, TextAlignment alignment, Color128 color)
        {
            if (text == null || font == null)
            {
                return;
            }

            /*
             * Prepare the top-left coordinates for rendering, incorporating the
             * orientation of the string in relation to the specified location.
             * */
            int left;

            if ((alignment & TextAlignment.Left) == 0)
            {
                int width = 0;
                for (int i = 0; i < text.Length; i++)
                {
                    Textures.Texture     texture;
                    Fonts.OpenGlFontChar data;
                    i     += font.GetCharacterData(text, i, out texture, out data) - 1;
                    width += data.TypographicSize.Width;
                }
                if ((alignment & TextAlignment.Right) != 0)
                {
                    left = location.X - width;
                }
                else
                {
                    left = location.X - width / 2;
                }
            }
            else
            {
                left = location.X;
            }
            int top;

            if ((alignment & TextAlignment.Top) == 0)
            {
                int height = 0;
                for (int i = 0; i < text.Length; i++)
                {
                    Textures.Texture     texture;
                    Fonts.OpenGlFontChar data;
                    i += font.GetCharacterData(text, i, out texture, out data) - 1;
                    if (data.TypographicSize.Height > height)
                    {
                        height = data.TypographicSize.Height;
                    }
                }
                if ((alignment & TextAlignment.Bottom) != 0)
                {
                    top = location.Y - height;
                }
                else
                {
                    top = location.Y - height / 2;
                }
            }
            else
            {
                top = location.Y;
            }

            /*
             * Render the string.
             * */
            GL.Enable(EnableCap.Texture2D);
            for (int i = 0; i < text.Length; i++)
            {
                Textures.Texture     texture;
                Fonts.OpenGlFontChar data;
                i += font.GetCharacterData(text, i, out texture, out data) - 1;
                if (Textures.LoadTexture(texture, Textures.OpenGlTextureWrapMode.ClampClamp))
                {
                    GL.BindTexture(TextureTarget.Texture2D, texture.OpenGlTextures[(int)Textures.OpenGlTextureWrapMode.ClampClamp].Name);

                    int x = left - (data.PhysicalSize.Width - data.TypographicSize.Width) / 2;
                    int y = top - (data.PhysicalSize.Height - data.TypographicSize.Height) / 2;

                    /*
                     * In the first pass, mask off the background with pure black.
                     * */
                    GL.BlendFunc(BlendingFactor.Zero, BlendingFactor.OneMinusSrcColor);
                    GL.Begin(PrimitiveType.Polygon);
                    GL.Color4(color.A, color.A, color.A, 1.0f);
                    GL.TexCoord2(data.TextureCoordinates.Left, data.TextureCoordinates.Top);
                    GL.Vertex2(x, y);
                    GL.Color4(color.A, color.A, color.A, 1.0f);
                    GL.TexCoord2(data.TextureCoordinates.Right, data.TextureCoordinates.Top);
                    GL.Vertex2(x + data.PhysicalSize.Width, y);
                    GL.Color4(color.A, color.A, color.A, 1.0f);
                    GL.TexCoord2(data.TextureCoordinates.Right, data.TextureCoordinates.Bottom);
                    GL.Vertex2(x + data.PhysicalSize.Width, y + data.PhysicalSize.Height);
                    GL.Color4(color.A, color.A, color.A, 1.0f);
                    GL.TexCoord2(data.TextureCoordinates.Left, data.TextureCoordinates.Bottom);
                    GL.Vertex2(x, y + data.PhysicalSize.Height);
                    GL.End();

                    /*
                     * In the second pass, add the character onto the background.
                     * */
                    GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.One);
                    GL.Begin(PrimitiveType.Polygon);
                    GL.Color4(color.R, color.G, color.B, color.A);
                    GL.TexCoord2(data.TextureCoordinates.Left, data.TextureCoordinates.Top);
                    GL.Vertex2(x, y);
                    GL.Color4(color.R, color.G, color.B, color.A);
                    GL.TexCoord2(data.TextureCoordinates.Right, data.TextureCoordinates.Top);
                    GL.Vertex2(x + data.PhysicalSize.Width, y);
                    GL.Color4(color.R, color.G, color.B, color.A);
                    GL.TexCoord2(data.TextureCoordinates.Right, data.TextureCoordinates.Bottom);
                    GL.Vertex2(x + data.PhysicalSize.Width, y + data.PhysicalSize.Height);
                    GL.Color4(color.R, color.G, color.B, color.A);
                    GL.TexCoord2(data.TextureCoordinates.Left, data.TextureCoordinates.Bottom);
                    GL.Vertex2(x, y + data.PhysicalSize.Height);
                    GL.End();
                }
                left += data.TypographicSize.Width;
            }
            GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);             // HACK //
            GL.Disable(EnableCap.Texture2D);
        }
Exemplo n.º 8
0
        void LateUpdate()
        {
            //tex1 = RenderTexture.GetTemporary(300, 300, 16);
            string partModelName = "stretchyTank";

            string sidesName = "sides";

            string endsName      = "ends";
            string collisionName = "collisionMesh";

            List <Mesh>       meshList = new List <Mesh>();
            List <RenderItem> items    = new List <RenderItem>();

            Bounds box = new Bounds(new Vector3(0, 0, 0), new Vector3(0, 0, 0));

            foreach (Part part in FlightGlobals.ActiveVessel.parts)
            {
                if (part == null)
                {
                    continue;
                }
                if (part.GetComponent <Buoyancy>() != null)
                {
                    //Log.post("found buoyancy");
                    Transform partModel = part.FindModelTransform(partModelName);

                    Transform sides      = part.FindModelTransform(sidesName);
                    Transform ends       = part.FindModelTransform(endsName);
                    Transform colliderTr = part.FindModelTransform(collisionName);

                    Material SidesMaterial = sides.renderer.material;
                    Material EndsMaterial  = ends.renderer.material;



                    // Instantiate meshes. The mesh method unshares any shared meshes.
                    Mesh SidesMesh    = sides.GetComponent <MeshFilter>().sharedMesh;
                    Mesh EndsMesh     = ends.GetComponent <MeshFilter>().sharedMesh;
                    Mesh colliderMesh = colliderTr.GetComponent <MeshCollider>().sharedMesh;

                    RenderItem newItem = new RenderItem();

                    newItem.mesh            = colliderMesh;
                    newItem.translation     = sides;
                    newItem.material        = SidesMaterial;
                    newItem.material.shader = Shader.Find("Unlit");
                    items.Add(newItem);

                    box.Encapsulate(SidesMesh.bounds);
                    //box.Encapsulate(EndsMesh.bounds);

                    //foreach (Vector3 v in SidesMesh.vertices)
                    //{
                    //    box.Encapsulate(v);
                    //}



                    //foreach (Vector3 v in EndsMesh.vertices)
                    //{
                    //    box.bounds.Encapsulate(v);
                    //}



                    //Matrix4x4 projMatrix = Matrix4x4.Ortho(-3, 3, -3, 3, -10, 10);

                    //for (int i = 0; i < SidesMaterial.passCount; ++i)
                    //{
                    //    SidesMaterial.SetPass(0);
                    //    Graphics.DrawMeshNow(SidesMesh, projMatrix);
                    //}
                }
            }

            Matrix4x4 projMatrix = Matrix4x4.Ortho(-10, 10, -10, 10, -10, 10);

            //Matrix4x4.Ortho(box.min.x, box.max.x, box.min.y, box.max.y, box.min.z, box.max.z);

            //FlightCamera.fetch.camera
            if (!tex1.IsCreated())
            {
                tex1.Create();
            }

            RenderTexture.active = tex1;
            GL.Clear(true, true, Color.blue);

            GL.LoadProjectionMatrix(projMatrix);
            GL.LoadIdentity();
            GL.PushMatrix();

            GL.Begin(GL.TRIANGLES);
            foreach (RenderItem ri in items)
            {
                ri.material.SetPass(0);

                GL.Color(Color.grey);

                Graphics.DrawMeshNow(ri.mesh, projMatrix);

                foreach (int i in ri.mesh.triangles)
                {
                    GL.Vertex(ri.mesh.vertices[i]);
                    GL.TexCoord(ri.mesh.uv[i]);
                }
            }

            GL.End();

            GL.PopMatrix();


            //Graphics.DrawTexture(new Rect(100, 100, 300, 300), tex1);


            //foreach (Mesh m in meshList)
            //{

            //    Graphics.DrawMeshNow(m, FlightGlobals.ActiveVessel.rootPart.rigidbody.worldCenterOfMass, Quaternion.identity);
            //}
        }
Exemplo n.º 9
0
        void glControl1_Paint(object sender, PaintEventArgs e)
        {
            if (!loaded)
            {
                return;
            }

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

            if (this.system != null)
            {
                // Setup camera.
                GL.MatrixMode(MatrixMode.Projection);
                GL.LoadIdentity();

                OpenTK.Vector3 bounds = this.maxPoint - this.minPoint;

                float controlWidth  = this.glControl1.Width;
                float controlHeight = this.glControl1.Height;

                float controlAspect = controlWidth / controlHeight;

                float maxSize = bounds.Length * 0.5f;
                float orthoWidth = 0, orthoHeight = 0;
                if (controlWidth > controlHeight)
                {
                    orthoHeight = maxSize;
                    orthoWidth  = maxSize * controlAspect;
                }
                else
                {
                    orthoWidth  = maxSize;
                    orthoHeight = maxSize / controlAspect;
                }

                if (isOrtho)
                {
                    GL.Ortho(-orthoWidth, orthoWidth, -orthoHeight, orthoHeight, -100000, 100000);
                }
                else
                {
                    OpenTK.Matrix4 m = OpenTK.Matrix4.CreatePerspectiveFieldOfView((float)(Math.PI * 0.3f), controlAspect, 1, 2 + orthoHeight * 10);
                    GL.MultMatrix(ref m);
                }

                // Render L-System.
                GL.MatrixMode(MatrixMode.Modelview);
                GL.LoadIdentity();

                if (!isOrtho)
                {
                    OpenTK.Matrix4 lookAt = OpenTK.Matrix4.LookAt(0, 0, orthoHeight * 2, 0, 0, 0, 0, 1, 0);
                    GL.MultMatrix(ref lookAt);
                }

                GL.Rotate(cameraAngle.X, 1, 0, 0);
                GL.Rotate(cameraAngle.Y, 0, 1, 0);
                GL.Scale(cameraScale, cameraScale, cameraScale);

                GL.Translate((this.maxPoint + this.minPoint) * (-0.5f));

                // Draw axis.
                float axisLength = Math.Max(orthoWidth, orthoHeight);
                GL.Disable(EnableCap.Lighting);
                GL.Begin(BeginMode.Lines);

                GL.Color3(Color.Red);
                GL.Vertex3(0, 0, 0);
                GL.Vertex3(axisLength, 0, 0);

                GL.Color3(Color.Green);
                GL.Vertex3(0, 0, 0);
                GL.Vertex3(0, axisLength, 0);

                GL.Color3(Color.Blue);
                GL.Vertex3(0, 0, 0);
                GL.Vertex3(0, 0, axisLength);
                GL.End();

                GL.Begin(BeginMode.Lines);
                GL.Color3(Color.Orange);
                for (int i = 0; i < helperLines.Count; i += 2)
                {
                    GL.Vertex3(helperLines[i]);
                    GL.Vertex3(helperLines[i + 1]);
                }
                GL.End();

                GL.Enable(EnableCap.Lighting);

                Render(
                    BeginMode.Quads,
                    this.numQuadVertexes,
                    this.vertexesPtr,
                    this.colorsPtr,
                    this.normalsPtr,
                    null,
                    null);

                Render(
                    BeginMode.Triangles,
                    this.numTriVertexes,
                    this.triVertexesPtr,
                    this.triColorsPtr,
                    this.triNormalsPtr,
                    null,
                    null);
            }

            glControl1.SwapBuffers();
        }
Exemplo n.º 10
0
        public GLDisplayList GetScaleControl()
        {
            //Create the axes.
            GLDisplayList axis = new GLDisplayList();

            axis.Begin();

            //Disable culling so square bases for the arrows aren't necessary to draw
            GL.Disable(EnableCap.CullFace);
            GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill);

            GL.Begin(BeginMode.Lines);

            //X
            if ((_snapY && _snapZ) || (_hiY && _hiZ))
            {
                GL.Color4(Color.Yellow);
            }
            else
            {
                GL.Color4(Color.Red);
            }
            GL.Vertex3(0.0f, _scaleHalf1LDist, 0.0f);
            GL.Vertex3(0.0f, 0.0f, _scaleHalf1LDist);
            GL.Vertex3(0.0f, _scaleHalf2LDist, 0.0f);
            GL.Vertex3(0.0f, 0.0f, _scaleHalf2LDist);

            if (_snapX || _hiX)
            {
                GL.Color4(Color.Yellow);
            }
            else
            {
                GL.Color4(Color.Red);
            }

            GL.Vertex3(0.0f, 0.0f, 0.0f);
            GL.Vertex3(_dst, 0.0f, 0.0f);

            GL.End();

            GL.Begin(BeginMode.Triangles);

            GL.Vertex3(_axisLDist, 0.0f, 0.0f);
            GL.Vertex3(_dst, _apthm, -_apthm);
            GL.Vertex3(_dst, _apthm, _apthm);

            GL.Vertex3(_axisLDist, 0.0f, 0.0f);
            GL.Vertex3(_dst, -_apthm, _apthm);
            GL.Vertex3(_dst, -_apthm, -_apthm);

            GL.Vertex3(_axisLDist, 0.0f, 0.0f);
            GL.Vertex3(_dst, _apthm, _apthm);
            GL.Vertex3(_dst, -_apthm, _apthm);

            GL.Vertex3(_axisLDist, 0.0f, 0.0f);
            GL.Vertex3(_dst, -_apthm, -_apthm);
            GL.Vertex3(_dst, _apthm, -_apthm);

            GL.End();

            GL.Begin(BeginMode.Lines);

            //Y
            if ((_snapZ && _snapX) || (_hiZ && _hiX))
            {
                GL.Color4(Color.Yellow);
            }
            else
            {
                GL.Color4(Color.Green);
            }
            GL.Vertex3(0.0f, 0.0f, _scaleHalf1LDist);
            GL.Vertex3(_scaleHalf1LDist, 0.0f, 0.0f);
            GL.Vertex3(0.0f, 0.0f, _scaleHalf2LDist);
            GL.Vertex3(_scaleHalf2LDist, 0.0f, 0.0f);

            if (_snapY || _hiY)
            {
                GL.Color4(Color.Yellow);
            }
            else
            {
                GL.Color4(Color.Green);
            }
            GL.Vertex3(0.0f, 0.0f, 0.0f);
            GL.Vertex3(0.0f, _dst, 0.0f);

            GL.End();

            GL.Begin(BeginMode.Triangles);

            GL.Vertex3(0.0f, _axisLDist, 0.0f);
            GL.Vertex3(_apthm, _dst, -_apthm);
            GL.Vertex3(_apthm, _dst, _apthm);

            GL.Vertex3(0.0f, _axisLDist, 0.0f);
            GL.Vertex3(-_apthm, _dst, _apthm);
            GL.Vertex3(-_apthm, _dst, -_apthm);

            GL.Vertex3(0.0f, _axisLDist, 0.0f);
            GL.Vertex3(_apthm, _dst, _apthm);
            GL.Vertex3(-_apthm, _dst, _apthm);

            GL.Vertex3(0.0f, _axisLDist, 0.0f);
            GL.Vertex3(-_apthm, _dst, -_apthm);
            GL.Vertex3(_apthm, _dst, -_apthm);

            GL.End();

            GL.Begin(BeginMode.Lines);

            //Z
            if ((_snapX && _snapY) || (_hiX && _hiY))
            {
                GL.Color4(Color.Yellow);
            }
            else
            {
                GL.Color4(Color.Blue);
            }
            GL.Vertex3(0.0f, _scaleHalf1LDist, 0.0f);
            GL.Vertex3(_scaleHalf1LDist, 0.0f, 0.0f);
            GL.Vertex3(0.0f, _scaleHalf2LDist, 0.0f);
            GL.Vertex3(_scaleHalf2LDist, 0.0f, 0.0f);

            if (_snapZ || _hiZ)
            {
                GL.Color4(Color.Yellow);
            }
            else
            {
                GL.Color4(Color.Blue);
            }
            GL.Vertex3(0.0f, 0.0f, 0.0f);
            GL.Vertex3(0.0f, 0.0f, _dst);

            GL.End();

            GL.Begin(BeginMode.Triangles);

            GL.Vertex3(0.0f, 0.0f, _axisLDist);
            GL.Vertex3(_apthm, -_apthm, _dst);
            GL.Vertex3(_apthm, _apthm, _dst);

            GL.Vertex3(0.0f, 0.0f, _axisLDist);
            GL.Vertex3(-_apthm, _apthm, _dst);
            GL.Vertex3(-_apthm, -_apthm, _dst);

            GL.Vertex3(0.0f, 0.0f, _axisLDist);
            GL.Vertex3(_apthm, _apthm, _dst);
            GL.Vertex3(-_apthm, _apthm, _dst);

            GL.Vertex3(0.0f, 0.0f, _axisLDist);
            GL.Vertex3(-_apthm, -_apthm, _dst);
            GL.Vertex3(_apthm, -_apthm, _dst);

            GL.End();

            axis.End();

            return(axis);
        }
Exemplo n.º 11
0
        private unsafe void modelPanel1_PostRender(object sender, TKContext context)
        {
            //GL.LineWidth(2.0f);

            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
            GL.Disable(EnableCap.Lighting);
            GL.Disable(EnableCap.DepthTest);

            //Attributes.PostRender();

            //Render hurtboxes
            if (chkHurtboxes.Checked)
            {
                for (int i = 0; i < listPanel.lstHurtboxes.Items.Count; i++)
                {
                    if (listPanel.lstHurtboxes.GetItemChecked(i))
                    {
                        ((MiscHurtBox)listPanel.lstHurtboxes.Items[i]).Render(SelectedHurtbox != null && SelectedHurtbox.Index == i, Scriptor._hurtBoxType);
                    }
                }
            }

            //Render hitboxes
            if (chkHitboxes.Checked && Manager.Moveset != null)
            {
                GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill);
                GLDisplayList c = context.GetRingList();
                GLDisplayList s = context.GetSphereList();

                foreach (HitBox e in RunTime._hitBoxes)
                {
                    e.Render(context, modelPanel._camera.GetPoint());
                }
            }

            GL.Enable(EnableCap.DepthTest);

            //Show the user where the light source is
            if (_renderLightDisplay)
            {
                GL.PushAttrib(AttribMask.AllAttribBits);

                GL.Color4(Color.Blue);
                GL.Disable(EnableCap.Lighting);
                GL.Disable(EnableCap.DepthTest);

                GL.Scale(modelPanel.LightPosition._x, modelPanel.LightPosition._x, modelPanel.LightPosition._x);

                GL.Rotate(90.0f, 1, 0, 0);

                float azimuth   = modelPanel.LightPosition._y.Clamp180Deg();
                float elevation = modelPanel.LightPosition._z.Clamp180Deg();

                if (Math.Abs(azimuth) == Math.Abs(elevation) && azimuth % 180.0f == 0 && elevation % 180.0f == 0)
                {
                    azimuth   = 0;
                    elevation = 0;
                }

                int   i; float x;
                float e = azimuth;

                bool flip = false;
                if (e < 0)
                {
                    e    = -e;
                    flip = true;
                    GL.Rotate(180.0f, 1, 0, 0);
                }

                float f    = (float)((int)e);
                float diff = (float)Math.Round(e - f, 1);

                GL.Begin(OpenTK.Graphics.OpenGL.BeginMode.Lines);
                for (i = 0; i < f; i++)
                {
                    GL.Vertex2(Math.Cos(i * Maths._deg2radf), Math.Sin(i * Maths._deg2radf));
                    GL.Vertex2(Math.Cos((i + 1) * Maths._deg2radf), Math.Sin((i + 1) * Maths._deg2radf));
                }
                for (x = 0; x < diff; x += 0.1f)
                {
                    GL.Vertex2(Math.Cos((x + (float)i) * Maths._deg2radf), Math.Sin((x + (float)i) * Maths._deg2radf));
                    GL.Vertex2(Math.Cos((x + 0.1f + (float)i) * Maths._deg2radf), Math.Sin((x + 0.1f + (float)i) * Maths._deg2radf));
                }
                GL.End();

                if (flip)
                {
                    GL.Rotate(-180.0f, 1, 0, 0);
                }

                GL.Rotate(90.0f, 0, 1, 0);
                GL.Rotate(90.0f, 0, 0, 1);
                GL.Rotate(180.0f, 1, 0, 0);
                GL.Rotate(90.0f - azimuth, 0, 1, 0);

                e = elevation;

                if (e < 0)
                {
                    e = -e;
                    GL.Rotate(180.0f, 1, 0, 0);
                }

                f    = (float)((int)e);
                diff = (float)Math.Round(e - f, 1);

                GL.Begin(OpenTK.Graphics.OpenGL.BeginMode.Lines);
                for (i = 0; i < f; i++)
                {
                    GL.Vertex2(Math.Cos(i * Maths._deg2radf), Math.Sin(i * Maths._deg2radf));
                    GL.Vertex2(Math.Cos((i + 1) * Maths._deg2radf), Math.Sin((i + 1) * Maths._deg2radf));
                }
                for (x = 0; x < diff; x += 0.1f)
                {
                    GL.Vertex2(Math.Cos((x + (float)i) * Maths._deg2radf), Math.Sin((x + (float)i) * Maths._deg2radf));
                    GL.Vertex2(Math.Cos((x + 0.1f + (float)i) * Maths._deg2radf), Math.Sin((x + 0.1f + (float)i) * Maths._deg2radf));
                }

                GL.Vertex2(Math.Cos((x + (float)i) * Maths._deg2radf), Math.Sin((x + (float)i) * Maths._deg2radf));
                GL.Color4(Color.Orange);
                GL.Vertex3(0, 0, 0);

                GL.End();

                GL.PopAttrib();
            }

            GL.Clear(ClearBufferMask.DepthBufferBit);

            RenderTransformControl(context);

            if (!modelPanel._grabbing && !modelPanel._scrolling && !_playing)
            {
                GL.Color4(Color.Black);
                GL.ColorMask(false, false, false, false);

                if (RenderBones)
                {
                    //Render invisible depth orbs
                    GLDisplayList list = context.GetSphereList();
                    if (_editingAll)
                    {
                        foreach (MDL0Node m in _targetModels)
                        {
                            foreach (MDL0BoneNode bone in m._linker.BoneCache)
                            {
                                if (bone != SelectedBone)
                                {
                                    RenderOrb(bone, list);
                                }
                            }
                        }
                    }
                    else if (TargetModel != null && TargetModel._linker != null && TargetModel._linker.BoneCache != null)
                    {
                        foreach (MDL0BoneNode bone in _targetModel._linker.BoneCache)
                        {
                            if (bone != SelectedBone)
                            {
                                RenderOrb(bone, list);
                            }
                        }
                    }
                }

                //Render invisible depth planes for translation and scale controls
                if (_editType != 0 && SelectedBone != null && RenderBones)
                {
                    #region Axis Selection Display List

                    GLDisplayList selList = new GLDisplayList();

                    selList.Begin();

                    GL.Begin(BeginMode.Quads);

                    //X Axis
                    //XY quad
                    GL.Vertex3(0.0f, -_axisSelectRange, 0.0f);
                    GL.Vertex3(0.0f, _axisSelectRange, 0.0f);
                    GL.Vertex3(_axisLDist, _axisSelectRange, 0.0f);
                    GL.Vertex3(_axisLDist, -_axisSelectRange, 0.0f);
                    //XZ quad
                    GL.Vertex3(0.0f, 0.0f, -_axisSelectRange);
                    GL.Vertex3(0.0f, 0.0f, _axisSelectRange);
                    GL.Vertex3(_axisLDist, 0.0f, _axisSelectRange);
                    GL.Vertex3(_axisLDist, 0.0f, -_axisSelectRange);

                    //Y Axis
                    //YX quad
                    GL.Vertex3(-_axisSelectRange, 0.0f, 0.0f);
                    GL.Vertex3(_axisSelectRange, 0.0f, 0.0f);
                    GL.Vertex3(_axisSelectRange, _axisLDist, 0.0f);
                    GL.Vertex3(-_axisSelectRange, _axisLDist, 0.0f);
                    //YZ quad
                    GL.Vertex3(0.0f, 0.0f, -_axisSelectRange);
                    GL.Vertex3(0.0f, 0.0f, _axisSelectRange);
                    GL.Vertex3(0.0f, _axisLDist, _axisSelectRange);
                    GL.Vertex3(0.0f, _axisLDist, -_axisSelectRange);

                    //Z Axis
                    //ZX quad
                    GL.Vertex3(-_axisSelectRange, 0.0f, 0.0f);
                    GL.Vertex3(_axisSelectRange, 0.0f, 0.0f);
                    GL.Vertex3(_axisSelectRange, 0.0f, _axisLDist);
                    GL.Vertex3(-_axisSelectRange, 0.0f, _axisLDist);
                    //ZY quad
                    GL.Vertex3(0.0f, -_axisSelectRange, 0.0f);
                    GL.Vertex3(0.0f, _axisSelectRange, 0.0f);
                    GL.Vertex3(0.0f, _axisSelectRange, _axisLDist);
                    GL.Vertex3(0.0f, -_axisSelectRange, _axisLDist);

                    GL.End();

                    selList.End();

                    #endregion

                    if (_editType != 0 && SelectedBone != null)
                    {
                        Matrix m = Matrix.TransformMatrix(new Vector3(OrbRadius), new Vector3(), BoneLoc);
                        GL.PushMatrix();
                        GL.MultMatrix((float *)&m);

                        selList.Call();

                        if (_editType == TransformType.Translation)
                        {
                            GL.Begin(BeginMode.Quads);

                            //XY
                            GL.Vertex3(0.0f, _axisSelectRange, 0.0f);
                            GL.Vertex3(_axisHalfLDist, _axisSelectRange, 0.0f);
                            GL.Vertex3(_axisHalfLDist, _axisHalfLDist, 0.0f);
                            GL.Vertex3(0.0f, _axisHalfLDist, 0.0f);

                            //YZ
                            GL.Vertex3(0.0f, 0.0f, _axisSelectRange);
                            GL.Vertex3(0.0f, _axisHalfLDist, _axisSelectRange);
                            GL.Vertex3(0.0f, _axisHalfLDist, _axisHalfLDist);
                            GL.Vertex3(0.0f, 0.0f, _axisHalfLDist);

                            //XZ
                            GL.Vertex3(_axisSelectRange, 0.0f, 0.0f);
                            GL.Vertex3(_axisSelectRange, 0.0f, _axisHalfLDist);
                            GL.Vertex3(_axisHalfLDist, 0.0f, _axisHalfLDist);
                            GL.Vertex3(_axisHalfLDist, 0.0f, 0.0f);

                            GL.End();
                        }
                        else
                        {
                            GL.Begin(BeginMode.Triangles);

                            //XY
                            GL.Vertex3(0.0f, _axisSelectRange, 0.0f);
                            GL.Vertex3(_scaleHalf2LDist, _axisSelectRange, 0.0f);
                            GL.Vertex3(0.0f, _scaleHalf2LDist, 0.0f);

                            //YZ
                            GL.Vertex3(0.0f, 0.0f, _axisSelectRange);
                            GL.Vertex3(0.0f, _scaleHalf2LDist, _axisSelectRange);
                            GL.Vertex3(0.0f, 0.0f, _scaleHalf2LDist);

                            //XZ
                            GL.Vertex3(_axisSelectRange, 0.0f, 0.0f);
                            GL.Vertex3(_axisSelectRange, 0.0f, _scaleHalf2LDist);
                            GL.Vertex3(_scaleHalf2LDist, 0.0f, 0.0f);

                            GL.End();
                        }

                        GL.PopMatrix();
                    }
                }
                GL.ColorMask(true, true, true, true);
            }
        }
Exemplo n.º 12
0
        public override void OnPreviewGUI(Rect r, GUIStyle background)
        {
            if (Event.current.type == EventType.Repaint)
            {
                background.Draw(r, false, false, false, false);
            }

            // show texture
            Texture t = target as Texture;

            if (t == null) // texture might be gone by now, in case this code is used for floating texture preview
            {
                return;
            }

            // Render target must be created before we can display it (case 491797)
            RenderTexture rt = t as RenderTexture;

            if (rt != null)
            {
                if (!SystemInfo.IsFormatSupported(rt.graphicsFormat, FormatUsage.Render))
                {
                    return; // can't do this RT format
                }
                rt.Create();
            }

            if (IsCubemap())
            {
                m_CubemapPreview.OnPreviewGUI(t, r, background);
                return;
            }

            // target can report zero sizes in some cases just after a parameter change;
            // guard against that.
            int texWidth  = Mathf.Max(t.width, 1);
            int texHeight = Mathf.Max(t.height, 1);

            float mipLevel   = GetMipLevelForRendering();
            float zoomLevel  = Mathf.Min(Mathf.Min(r.width / texWidth, r.height / texHeight), 1);
            Rect  wantedRect = new Rect(r.x, r.y, texWidth * zoomLevel, texHeight * zoomLevel);

            PreviewGUI.BeginScrollView(r, m_Pos, wantedRect, "PreHorizontalScrollbar", "PreHorizontalScrollbarThumb");
            FilterMode oldFilter = t.filterMode;

            TextureUtil.SetFilterModeNoDirty(t, FilterMode.Point);
            Texture2D      t2d            = t as Texture2D;
            ColorWriteMask colorWriteMask = ColorWriteMask.All;

            switch (m_PreviewMode)
            {
            case PreviewMode.R:
                colorWriteMask = ColorWriteMask.Red | ColorWriteMask.Alpha;
                break;

            case PreviewMode.G:
                colorWriteMask = ColorWriteMask.Green | ColorWriteMask.Alpha;
                break;

            case PreviewMode.B:
                colorWriteMask = ColorWriteMask.Blue | ColorWriteMask.Alpha;
                break;
            }

            if (m_PreviewMode == PreviewMode.A)
            {
                EditorGUI.DrawTextureAlpha(wantedRect, t, ScaleMode.StretchToFill, 0, mipLevel);
            }
            else
            {
                if (t2d != null && t2d.alphaIsTransparency)
                {
                    EditorGUI.DrawTextureTransparent(wantedRect, t, ScaleMode.StretchToFill, 0, mipLevel, colorWriteMask);
                }
                else
                {
                    EditorGUI.DrawPreviewTexture(wantedRect, t, null, ScaleMode.StretchToFill, 0, mipLevel, colorWriteMask);
                }
            }

            // TODO: Less hacky way to prevent sprite rects to not appear in smaller previews like icons.
            if ((wantedRect.width > 32 && wantedRect.height > 32) && Event.current.type == EventType.Repaint)
            {
                string           path            = AssetDatabase.GetAssetPath(t);
                TextureImporter  textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
                SpriteMetaData[] spritesheet     = textureImporter != null ? textureImporter.spritesheet : null;

                if (spritesheet != null && textureImporter.spriteImportMode == SpriteImportMode.Multiple)
                {
                    Rect screenRect = new Rect();
                    Rect sourceRect = new Rect();
                    GUI.CalculateScaledTextureRects(wantedRect, ScaleMode.StretchToFill, (float)t.width / (float)t.height, ref screenRect, ref sourceRect);

                    int origWidth  = t.width;
                    int origHeight = t.height;
                    textureImporter.GetWidthAndHeight(ref origWidth, ref origHeight);
                    float definitionScale = (float)t.width / (float)origWidth;

                    HandleUtility.ApplyWireMaterial();
                    GL.PushMatrix();
                    GL.MultMatrix(Handles.matrix);
                    GL.Begin(GL.LINES);
                    GL.Color(new Color(1f, 1f, 1f, 0.5f));
                    foreach (SpriteMetaData sprite in spritesheet)
                    {
                        Rect spriteRect       = sprite.rect;
                        Rect spriteScreenRect = new Rect();
                        spriteScreenRect.xMin = screenRect.xMin + screenRect.width * (spriteRect.xMin / t.width * definitionScale);
                        spriteScreenRect.xMax = screenRect.xMin + screenRect.width * (spriteRect.xMax / t.width * definitionScale);
                        spriteScreenRect.yMin = screenRect.yMin + screenRect.height * (1f - spriteRect.yMin / t.height * definitionScale);
                        spriteScreenRect.yMax = screenRect.yMin + screenRect.height * (1f - spriteRect.yMax / t.height * definitionScale);
                        DrawRect(spriteScreenRect);
                    }
                    GL.End();
                    GL.PopMatrix();
                }
            }

            TextureUtil.SetFilterModeNoDirty(t, oldFilter);

            m_Pos = PreviewGUI.EndScrollView();
            if (mipLevel != 0)
            {
                EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 20), "Mip " + mipLevel);
            }
        }
    public static void DrawGraphs(Rect rect, EditorWindow window)
    {
        if (VarTracer.Instance)
        {
            bool isEditorPaused = EditorApplication.isPaused;

            CreateLineMaterial();

            mLineMaterial.SetPass(0);

            int graph_index = 0;

            //use this to get the starting y position for the GL rendering
            Rect find_y = EditorGUILayout.BeginVertical(GUIStyle.none);
            EditorGUILayout.EndVertical();

            int currentFrameIndex = VarTracerNet.Instance.GetCurrentFrameFromTimestamp(VarTracerUtils.GetTimeStamp());
            if (isEditorPaused)
                currentFrameIndex = VarTracerNet.Instance.GetCurrentFrameFromTimestamp(VarTracerUtils.StopTimeStamp);

            float scrolled_y_pos = y_offset - mGraphViewScrollPos.y;
            if (Event.current.type == EventType.Repaint)
            {
                GL.PushMatrix();
                float start_y = find_y.y;
                GL.Viewport(new Rect(0, 0, rect.width, rect.height - start_y));
                GL.LoadPixelMatrix(0, rect.width, rect.height - start_y, 0);

                //Draw grey BG
                GL.Begin(GL.QUADS);
                GL.Color(new Color(0.2f, 0.2f, 0.2f));

                foreach (KeyValuePair<string, VarTracerGraphItData> kv in VarTracer.Instance.Graphs)
                {
                    float height = kv.Value.GetHeight();

                    GL.Vertex3(x_offset, scrolled_y_pos, 0);
                    GL.Vertex3(x_offset + mWidth, scrolled_y_pos, 0);
                    GL.Vertex3(x_offset + mWidth, scrolled_y_pos + height, 0);
                    GL.Vertex3(x_offset, scrolled_y_pos + height, 0);

                    scrolled_y_pos += (height + y_gap);
                }
                GL.End();

                scrolled_y_pos = y_offset - mGraphViewScrollPos.y;
                //Draw Lines
                GL.Begin(GL.LINES);

                foreach (KeyValuePair<string, VarTracerGraphItData> kv in VarTracer.Instance.Graphs)
                {
                    graph_index++;

                    float height = kv.Value.GetHeight();
                    DrawGraphGridLines(scrolled_y_pos, mWidth, height, graph_index == mMouseOverGraphIndex);

                    foreach (KeyValuePair<string, VarTracerDataInternal> entry in kv.Value.mData)
                    {
                        VarTracerDataInternal g = entry.Value;

                        float y_min = kv.Value.GetMin(entry.Key);
                        float y_max = kv.Value.GetMax(entry.Key);
                        float y_range = Mathf.Max(y_max - y_min, 0.00001f);

                        //draw the 0 line
                        if (y_min != 0.0f)
                        {
                            GL.Color(Color.white);
                            float y = scrolled_y_pos + height * (1 - (0.0f - y_min) / y_range);
                            Plot(x_offset, y, x_offset + mWidth, y);
                        }

                        GL.Color(g.mColor);

                        float previous_value = 0, value = 0;
                        int dataInfoIndex = 0, frameIndex = 0;
                        for (int i = 0; i <= currentFrameIndex; i++)
                        {
                            int dataCount = g.mDataInfos.Count;
                            if (dataCount != 0)
                            {
                                int lastFrame = g.mDataInfos[dataCount - 1].FrameIndex;
                                float lastValue = g.mDataInfos[dataCount - 1].Value;
                                frameIndex = g.mDataInfos[dataInfoIndex].FrameIndex;

                                if (dataInfoIndex >= 1)
                                    value = g.mDataInfos[dataInfoIndex - 1].Value;

                                if (dataInfoIndex == 0 && i < frameIndex)
                                    value = 0;

                                if (i >= frameIndex)
                                {
                                    while (g.mDataInfos[dataInfoIndex].FrameIndex == frameIndex && dataInfoIndex < dataCount - 1)
                                    {
                                        dataInfoIndex++;
                                    }
                                }

                                if (i > lastFrame)
                                    value = lastValue;
                            }
                            else
                            {
                                value = 0;
                            }

                            if (i >= 1)
                            {
                                float x0 = x_offset + (i - 1) * kv.Value.XStep - kv.Value.ScrollPos.x;
                                if (x0 <= x_offset - kv.Value.XStep) continue;
                                if (x0 >= mWidth + x_offset) break;
                                float y0 = scrolled_y_pos + height * (1 - (previous_value - y_min) / y_range);

                                if (i == 1)
                                {
                                    x0 = x_offset;
                                    y0 = scrolled_y_pos + height;
                                }

                                float x1 = x_offset + i * kv.Value.XStep - kv.Value.ScrollPos.x;
                                float y1 = scrolled_y_pos + height * (1 - (value - y_min) / y_range);
    
                                if (m_isDrawLine)
                                    Plot(x0, y0, x1, y1);
                                else
                                    Plot(x0, y0, x0+1, y0+1);
                            }
                            previous_value = value;
                        }
                    }

                    scrolled_y_pos += (height + y_gap);
                }
                GL.End();

                scrolled_y_pos = y_offset - mGraphViewScrollPos.y;
                scrolled_y_pos = ShowEventLabel(scrolled_y_pos);
                GL.PopMatrix();

                GL.Viewport(new Rect(0, 0, rect.width, rect.height));
                GL.LoadPixelMatrix(0, rect.width, rect.height, 0);
            }

            mGraphViewScrollPos = EditorGUILayout.BeginScrollView(mGraphViewScrollPos, GUIStyle.none);

            graph_index = 0;
            mWidth = window.position.width - x_offset;
            foreach (KeyValuePair<string, VarTracerGraphItData> kv in VarTracer.Instance.Graphs)
            {
                graph_index++;

                float height = kv.Value.GetHeight();
                float width = currentFrameIndex * kv.Value.XStep;
                if (width < mWidth)
                {
                    width = mWidth - x_offset;
                }
                else
                {
                    if (!EditorApplication.isPaused)
                        kv.Value.ScrollPos = new Vector2(width - mWidth, kv.Value.ScrollPos.y);
                }

                GUIStyle s = new GUIStyle();
                s.fixedHeight = height + y_gap;
                s.stretchWidth = true;
                Rect r = EditorGUILayout.BeginVertical(s);

                //skip subgraph title if only one, and it's the same.
                NameLabel.normal.textColor = Color.white;

                r.height = height + 50;
                r.width = width;
                r.x = x_offset - 35;
                r.y = (height + y_gap) * (graph_index - 1) - 10;

                if (kv.Value.mData.Count > 0)
                {
                    GUILayout.BeginArea(r);
                    GUILayout.BeginVertical();

                    float GraphGap = kv.Value.m_maxValue - kv.Value.m_minValue;
                    float unitHeight = GraphGap / VarTracerConst.Graph_Grid_Row_Num;

                    for (int i = 0; i < VarTracerConst.Graph_Grid_Row_Num + 1; i++)
                    {
                        GUILayout.Space(6);
                        if (unitHeight == 0)
                            EditorGUILayout.LabelField("",NameLabel);
                        else
                            EditorGUILayout.LabelField((kv.Value.m_maxValue - i * unitHeight).ToString(VarTracerConst.NUM_FORMAT_1),NameLabel);
                    }

                    GUILayout.BeginHorizontal();
                    kv.Value.ScrollPos = GUILayout.BeginScrollView(kv.Value.ScrollPos, GUILayout.Width(mWidth), GUILayout.Height(0));
                    GUILayout.Label("", GUILayout.Width(width), GUILayout.Height(0));
                    GUILayout.EndScrollView();
                    GUILayout.EndHorizontal();
                    GUILayout.EndVertical();
                    GUILayout.EndArea();
                }

                DrawGraphAttribute(kv);

                ////Respond to mouse input!
                if (Event.current.type == EventType.MouseDrag && r.Contains(Event.current.mousePosition - Event.current.delta))
                {
                    if (Event.current.button == 0)
                    {
                        kv.Value.ScrollPos = new Vector2(kv.Value.ScrollPos.x + Event.current.delta.x, kv.Value.ScrollPos.y);
                    }
                    window.Repaint();
                }
                EditorGUILayout.EndVertical();
            }
            EditorGUILayout.EndScrollView();
        }
    }
Exemplo n.º 14
0
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        System.Random random = new System.Random(25565);

        EditorGUI.PrefixLabel(position, label);

        position.y += EditorGUIUtility.singleLineHeight;

        cachedWidth = position.x + position.width * (1 - PREVIEW_WIDTH) / 2;

        if (Event.current.type != EventType.Repaint)
        {
            return;
        }

        position.height = position.width / PREVIEW_RATIO;

        Rect rect = new Rect()
        {
            size     = new Vector2(position.width *= PREVIEW_WIDTH, position.width / PREVIEW_RATIO),
            position = new Vector2(position.x += position.width * (1 - PREVIEW_WIDTH) / 2, position.position.y + Y_OFFSET)
        };

        EditorGUI.DrawRect(rect, PREVIEW_BACKGROUND);

        SerializedProperty enemiesArray = property.serializedObject.FindProperty("enemies");

        for (int i = 0; i < enemiesArray.arraySize; i++)
        {
            Vector2 enemyPos = enemiesArray.GetArrayElementAtIndex(i).FindPropertyRelative("startOffset").vector2Value;
            enemyPos.y *= -1;

            Rect enemyRect = new Rect()
            {
                size   = Vector2.one * DOT_SIZE,
                center = rect.center + (rect.size / 2F) * enemyPos
            };
            EditorGUI.DrawRect(enemyRect, PREVIEW_DOT_COLOR);

            SerializedProperty movementsArray = enemiesArray.GetArrayElementAtIndex(i).FindPropertyRelative("movements");

            if (movementsArray.arraySize == 0)
            {
                continue;
            }

            Vector2 last = enemyRect.center;

            GL.Begin(GL.LINE_STRIP);
            GL.Color(new Color(random.Next(50, 255) / 255F, random.Next(50, 255) / 255F, random.Next(50, 255) / 255F));
            GL.Vertex(enemyRect.center);

            for (int j = 0; j < movementsArray.arraySize; j++)
            {
                Vector2 move = movementsArray.GetArrayElementAtIndex(j).FindPropertyRelative("move").vector2Value;
                move   *= rect.width * .025F;
                move.y *= -1;
                Vector2 newPos = last + move;

                GL.Vertex(newPos);

                last = newPos;
            }
            GL.End();
        }
    }
Exemplo n.º 15
0
        public void TimeRuler(Rect position, float frameRate, bool labels, bool useEntireHeight, float alpha,
                              TimeFormat timeFormat)
        {
            Color backupCol = GUI.color;

            GUI.BeginGroup(position);
            InitStyles();

            HandleUtility.ApplyWireMaterial();

            Color tempBackgroundColor = GUI.backgroundColor;

            SetTickMarkerRanges();
            hTicks.SetTickStrengths(kTickRulerDistMin, kTickRulerDistFull, true);

            Color baseColor = timeAreaStyles.timelineTick.normal.textColor;

            baseColor.a = 0.75f * alpha;

            if (Event.current.type == EventType.Repaint)
            {
                if (Application.platform == RuntimePlatform.WindowsEditor)
                {
                    GL.Begin(GL.QUADS);
                }
                else
                {
                    GL.Begin(GL.LINES);
                }

                // Draw tick markers of various sizes

                Rect cachedShowArea = shownArea;
                for (int l = 0; l < hTicks.tickLevels; l++)
                {
                    float   strength = hTicks.GetStrengthOfLevel(l) * .9f;
                    float[] ticks    = hTicks.GetTicksAtLevel(l, true);
                    for (int i = 0; i < ticks.Length; i++)
                    {
                        if (ticks[i] < hRangeMin || ticks[i] > hRangeMax)
                        {
                            continue;
                        }
                        int frame = Mathf.RoundToInt(ticks[i] * frameRate);

                        float height = useEntireHeight
                            ? position.height
                            : position.height * Mathf.Min(1, strength) * kTickRulerHeightMax;
                        float x = FrameToPixel(frame, frameRate, position, cachedShowArea);

                        // Draw line
                        DrawVerticalLineFast(x, position.height - height + 0.5f, position.height - 0.5f,
                                             new Color(1, 1, 1, strength / kTickRulerFatThreshold) * baseColor);
                    }
                }

                GL.End();
            }

            if (labels)
            {
                // Draw tick labels
                int     labelLevel = hTicks.GetLevelWithMinSeparation(kTickRulerDistLabel);
                float[] labelTicks = hTicks.GetTicksAtLevel(labelLevel, false);
                for (int i = 0; i < labelTicks.Length; i++)
                {
                    if (labelTicks[i] < hRangeMin || labelTicks[i] > hRangeMax)
                    {
                        continue;
                    }

                    int frame = Mathf.RoundToInt(labelTicks[i] * frameRate);
                    // Important to take floor of positions of GUI stuff to get pixel correct alignment of
                    // stuff drawn with both GUI and Handles/GL. Otherwise things are off by one pixel half the time.

                    float  labelpos = Mathf.Floor(FrameToPixel(frame, frameRate, position));
                    string label    = FormatTime(labelTicks[i], frameRate, timeFormat);
                    GUI.Label(new Rect(labelpos + 3, -3, 40, 20), label, timeAreaStyles.timelineTick);
                }
            }
            GUI.EndGroup();

            GUI.backgroundColor = tempBackgroundColor;
            GUI.color           = backupCol;
        }
Exemplo n.º 16
0
        public virtual void GL_DrawAliasFrameLerp(qfiles.dmdl_t paliashdr, Single backlerp)
        {
            Single l;

            qfiles.daliasframe_t frame, oldframe;
            Int32[] v, ov;
            Int32[] order;
            var     orderIndex = 0;
            Int32   count;
            Single  frontlerp;
            Single  alpha;

            Single[]   move    = new Single[] { 0, 0, 0 };
            Single[][] vectors = new Single[][] { new Single[] { 0, 0, 0 }, new Single[] { 0, 0, 0 }, new Single[] { 0, 0, 0 } };
            Single[]   frontv  = new Single[] { 0, 0, 0 };
            Single[]   backv   = new Single[] { 0, 0, 0 };
            Int32      i;
            Int32      index_xyz;

            frame    = paliashdr.aliasFrames[currententity.frame];
            v        = frame.verts;
            oldframe = paliashdr.aliasFrames[currententity.oldframe];
            ov       = oldframe.verts;
            order    = paliashdr.glCmds;
            if ((currententity.flags & Defines.RF_TRANSLUCENT) != 0)
            {
                alpha = currententity.alpha;
            }
            else
            {
                alpha = 1F;
            }
            if ((currententity.flags & (Defines.RF_SHELL_RED | Defines.RF_SHELL_GREEN | Defines.RF_SHELL_BLUE | Defines.RF_SHELL_DOUBLE | Defines.RF_SHELL_HALF_DAM)) != 0)
            {
                GL.Disable(EnableCap.Texture2D);
            }
            frontlerp = 1F - backlerp;
            Math3D.VectorSubtract(currententity.oldorigin, currententity.origin, frontv);
            Math3D.AngleVectors(currententity.angles, vectors[0], vectors[1], vectors[2]);
            move[0] = Math3D.DotProduct(frontv, vectors[0]);
            move[1] = -Math3D.DotProduct(frontv, vectors[1]);
            move[2] = Math3D.DotProduct(frontv, vectors[2]);
            Math3D.VectorAdd(move, oldframe.translate, move);
            for (i = 0; i < 3; i++)
            {
                move[i]   = backlerp * move[i] + frontlerp * frame.translate[i];
                frontv[i] = frontlerp * frame.scale[i];
                backv[i]  = backlerp * oldframe.scale[i];
            }

            if (gl_vertex_arrays.value != 0F)
            {
                GL_LerpVerts(paliashdr.num_xyz, ov, v, move, frontv, backv);
                GL.EnableClientState(ArrayCap.VertexArray);
                new Pinnable(vertexArrayBuf.Array, (ptr) =>
                {
                    GL.VertexPointer(3, VertexPointerType.Float, 0, ptr);
                });
                if ((currententity.flags & (Defines.RF_SHELL_RED | Defines.RF_SHELL_GREEN | Defines.RF_SHELL_BLUE | Defines.RF_SHELL_DOUBLE | Defines.RF_SHELL_HALF_DAM)) != 0)
                {
                    GL.DisableClientState(ArrayCap.ColorArray);
                    GL.Color4(shadelight[0], shadelight[1], shadelight[2], alpha);
                }
                else
                {
                    GL.EnableClientState(ArrayCap.ColorArray);
                    new Pinnable(colorArrayBuf.Array, (ptr) =>
                    {
                        GL.ColorPointer(4, ColorPointerType.Float, 0, ptr);
                    });
                    SingleBuffer color = colorArrayBuf;
                    var          j     = 0;
                    for (i = 0; i < paliashdr.num_xyz; i++)
                    {
                        l = shadedots[(v[i] >> 24) & 0xFF];
                        color.Put(j++, l * shadelight[0]);
                        color.Put(j++, l * shadelight[1]);
                        color.Put(j++, l * shadelight[2]);
                        color.Put(j++, alpha);
                    }
                }

                //if (qglLockArraysEXT)
                //    gl.GlLockArraysEXT(0, paliashdr.num_xyz);
                while (true)
                {
                    count = order[orderIndex++];
                    if (count == 0)
                    {
                        break;
                    }
                    if (count < 0)
                    {
                        count = -count;
                        GL.Begin(PrimitiveType.TriangleFan);
                    }
                    else
                    {
                        GL.Begin(PrimitiveType.TriangleStrip);
                    }

                    if ((currententity.flags & (Defines.RF_SHELL_RED | Defines.RF_SHELL_GREEN | Defines.RF_SHELL_BLUE | Defines.RF_SHELL_DOUBLE | Defines.RF_SHELL_HALF_DAM)) != 0)
                    {
                        do
                        {
                            index_xyz   = order[orderIndex + 2];
                            orderIndex += 3;
                            GL.ArrayElement(index_xyz);
                        }while (--count != 0);
                    }
                    else
                    {
                        do
                        {
                            GL.TexCoord2(BitConverter.ToSingle(BitConverter.GetBytes(order[orderIndex + 0])), BitConverter.ToSingle(BitConverter.GetBytes(order[orderIndex + 1])));
                            index_xyz   = order[orderIndex + 2];
                            orderIndex += 3;
                            GL.ArrayElement(index_xyz);
                        }while (--count != 0);
                    }

                    GL.End();
                }

                // if (qglLockArraysEXT)
                //     gl.GlUnlockArraysEXT();
            }
            else
            {
                GL_LerpVerts(paliashdr.num_xyz, ov, v, s_lerped, move, frontv, backv);
                Single[] tmp;
                while (true)
                {
                    count = order[orderIndex++];
                    if (count == 0)
                    {
                        break;
                    }
                    if (count < 0)
                    {
                        count = -count;
                        GL.Begin(PrimitiveType.TriangleFan);
                    }
                    else
                    {
                        GL.Begin(PrimitiveType.TriangleStrip);
                    }

                    if ((currententity.flags & (Defines.RF_SHELL_RED | Defines.RF_SHELL_GREEN | Defines.RF_SHELL_BLUE)) != 0)
                    {
                        do
                        {
                            index_xyz   = order[orderIndex + 2];
                            orderIndex += 3;
                            GL.Color4(shadelight[0], shadelight[1], shadelight[2], alpha);
                            tmp = s_lerped[index_xyz];
                            GL.Vertex3(tmp[0], tmp[1], tmp[2]);
                        }while (--count != 0);
                    }
                    else
                    {
                        do
                        {
                            GL.TexCoord2(BitConverter.ToSingle(BitConverter.GetBytes(order[orderIndex + 0])), BitConverter.ToSingle(BitConverter.GetBytes(order[orderIndex + 1])));
                            index_xyz   = order[orderIndex + 2];
                            orderIndex += 3;
                            l           = shadedots[(v[index_xyz] >> 24) & 0xFF];
                            GL.Color4(l * shadelight[0], l * shadelight[1], l * shadelight[2], alpha);
                            tmp = s_lerped[index_xyz];
                            GL.Vertex3(tmp[0], tmp[1], tmp[2]);
                        }while (--count != 0);
                    }

                    GL.End();
                }
            }

            if ((currententity.flags & (Defines.RF_SHELL_RED | Defines.RF_SHELL_GREEN | Defines.RF_SHELL_BLUE | Defines.RF_SHELL_DOUBLE | Defines.RF_SHELL_HALF_DAM)) != 0)
            {
                GL.Enable(EnableCap.Texture2D);
            }
        }
Exemplo n.º 17
0
    private void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        if (material == null)
        {
            Graphics.Blit(source, destination);
            return;
        }

        //Setup
        material.SetMatrix("_CameraFrustumPlanes", GetCameraFrustumPlanes());
        material.SetMatrix("_CameraToWorldMatrix", myCamera.cameraToWorldMatrix);
        material.SetFloat("_MaxDistance", m_maxDistance);
        material.SetInt("_MaxIterations", m_maxIterations);
        material.SetFloat("_Accuracy", m_accuracy);

        //Color
        material.SetColor("_MainColor", m_mainColor);

        //Light
        material.SetVector("_LightDir", m_lightTransform.forward);
        material.SetColor("_LightCol", m_lightColor);
        material.SetFloat("_LightIntensity", m_lightIntensity);

        //Shadow
        material.SetVector("_ShadowDistance", m_shadowDistance);
        material.SetFloat("_ShadowIntensity", m_shadowIntensity);
        material.SetFloat("_ShadowPenumbra", _shadowPenumbra);

        //Ambient Occlusion
        material.SetFloat("_AOStepSize", m_ambientOcclusionStepSize);
        material.SetInt("_AOIterations", m_ambientOcclusionIterations);
        material.SetFloat("_AOIntensity", m_ambientOcclusionIntensity);

        //Reflection
        material.SetInt("_ReflectionCount", m_reflectionCount);
        material.SetFloat("_ReflectionIntensity", m_reflectionIntensity);
        material.SetFloat("_EnvironmentReflectionIntensity", m_environmentReflectionIntensity);
        material.SetTexture("_ReflectionCube", m_reflectionCube);

        //SDF
        material.SetFloat("_Smooth", m_smooth);
        material.SetVector("_GroundPosition", m_groundPosition);
        material.SetVector("_GroundColor", m_groundColor);

        for (int i = 0; i < m_colors.Length; i++)
        {
            m_colors[i] = m_sphereGradient.Evaluate(i * 1f / (m_colors.Length - 1));
        }
        material.SetColorArray("_SphereColors", m_colors);

        RenderTexture.active = destination;
        material.SetTexture("_MainTex", source);
        GL.PushMatrix();
        GL.LoadOrtho();
        material.SetPass(0);
        GL.Begin(GL.QUADS);

        //BL
        GL.MultiTexCoord2(0, 0, 0);
        GL.Vertex3(0, 0, 3);
        //BR
        GL.MultiTexCoord2(0, 1, 0);
        GL.Vertex3(1, 0, 2);
        //TR
        GL.MultiTexCoord2(0, 1, 1);
        GL.Vertex3(1, 1, 1);
        //TL
        GL.MultiTexCoord2(0, 0, 1);
        GL.Vertex3(0, 1, 0);

        GL.End();
        GL.PopMatrix();
    }
Exemplo n.º 18
0
        protected void DrawBorder(RenderTexture dest, Material material)
        {
            float x1;
            float x2;
            float y1;
            float y2;

            RenderTexture.active = dest;
            bool invertY = true;  // source.texelSize.y < 0.0ff;

            // Set up the simple Matrix
            GL.PushMatrix();
            GL.LoadOrtho();

            for (int i = 0; i < material.passCount; ++i)
            {
                material.SetPass(i);

                float y1_; float y2_;
                if (invertY)
                {
                    y1_ = 1.0f; y2_ = 0.0f;
                }
                else
                {
                    y1_ = 0.0f; y2_ = 1.0f;
                }

                // left
                x1 = 0.0f;
                x2 = 0.0f + 1.0f / (dest.width * 1.0f);
                y1 = 0.0f;
                y2 = 1.0f;
                GL.Begin(GL.QUADS);

                GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
                GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
                GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
                GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);

                // right
                x1 = 1.0f - 1.0f / (dest.width * 1.0f);
                x2 = 1.0f;
                y1 = 0.0f;
                y2 = 1.0f;

                GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
                GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
                GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
                GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);

                // top
                x1 = 0.0f;
                x2 = 1.0f;
                y1 = 0.0f;
                y2 = 0.0f + 1.0f / (dest.height * 1.0f);

                GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
                GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
                GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
                GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);

                // bottom
                x1 = 0.0f;
                x2 = 1.0f;
                y1 = 1.0f - 1.0f / (dest.height * 1.0f);
                y2 = 1.0f;

                GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
                GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
                GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
                GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);

                GL.End();
            }

            GL.PopMatrix();
        }
Exemplo n.º 19
0
        public void DrawImpactFactors(DrawMethodArgs args)
        {
            PhysicsScene  scene      = demo.Engine.Factory.PhysicsSceneManager.Get(args.OwnerSceneIndex);
            PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Get(args.OwnerIndex);

            if (!objectBase.Camera.Enabled)
            {
                return;
            }
            if (!objectBase.Camera.Active)
            {
                return;
            }
            if (!enableDrawImpactFactors)
            {
                return;
            }

            GL.Disable(EnableCap.DepthTest);
            GL.DepthMask(false);

            float time = args.Time;

            PhysicsObject visiblePhysicsObject;
            int           contactPointCount;
            Vector3       start1, end1, start2, end2;
            float         impactFactor, velocityMagnitude;

            objectBase.Camera.View.GetViewMatrix(ref view);
            objectBase.Camera.Projection.GetProjectionMatrix(ref projection);
            world = matrixIdentity;

            render.SetWorld(ref world);
            render.SetView(ref view);
            render.SetProjection(ref projection);

            render.Apply();

            for (int i = 0; i < objectBase.Camera.VisiblePhysicsObjectCount; i++)
            {
                visiblePhysicsObject = objectBase.Camera.GetVisiblePhysicsObject(i);

                for (int j = 0; j < visiblePhysicsObject.CollisionPairCount; j++)
                {
                    contactPointCount = visiblePhysicsObject.GetCollisionPairContactPointCount(j);

                    for (int k = 0; k < contactPointCount; k++)
                    {
                        visiblePhysicsObject.GetCollisionPairContactPointAnchor2(j, k, ref position);
                        visiblePhysicsObject.GetCollisionPairContactPointNormal(j, k, ref direction);

                        impactFactor      = visiblePhysicsObject.GetCollisionPairContactPointImpactFactor(j, k);
                        velocityMagnitude = Math.Min(Math.Max(visiblePhysicsObject.MainWorldTransform.GetLinearVelocityMagnitude() - visiblePhysicsObject.MaxSleepLinearVelocity, 0.0f) + Math.Max(visiblePhysicsObject.MainWorldTransform.GetAngularVelocityMagnitude() - visiblePhysicsObject.MaxSleepAngularVelocity, 0.0f), 1.0f);
                        impactFactor     *= velocityMagnitude;

                        if (impactFactor < 0.001f)
                        {
                            continue;
                        }

                        Vector3.Multiply(ref direction, (float)impactFactor, out direction);
                        Vector3.Multiply(ref direction, 0.5f, out direction);

                        start1 = position;
                        end1   = direction;
                        Vector3.Add(ref start1, ref end1, out end1);

                        start2 = end1;
                        end2   = direction;
                        Vector3.Add(ref start2, ref end2, out end2);

                        GL.Begin(PrimitiveType.Lines);

                        GL.Color3(1.0f, 1.0f, 1.0f);
                        GL.Vertex3(start1);
                        GL.Vertex3(end1);

                        GL.Color3(0.6f, 0.8f, 0.2f);
                        GL.Vertex3(start2);
                        GL.Vertex3(end2);

                        GL.End();
                    }
                }
            }

            GL.DepthMask(true);
            GL.Enable(EnableCap.DepthTest);
        }
Exemplo n.º 20
0
        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            if (this.DesignMode)
            {
                e.Graphics.Clear(Color.Black);
                return;
            }

            GL.Viewport(0, 0, this.Width, this.Height);

            // radians += 5 * deg2rad;

            if (rotatewithdata)
            {
                yaw += 5 * deg2rad;
            }

            MakeCurrent();

            GL.MatrixMode(MatrixMode.Projection);

            double max = Math.Max(Math.Max((maxx - minx) / 2, (maxy - miny) / 2), (maxz - minz) / 2);

            if (max < 300)
            {
                max = 400;
            }

            max *= 1.3;

            if (points.Count > 0)
            {
                Vector3 current = new Vector3(points[points.Count - 1].X, points[points.Count - 1].Y, points[points.Count - 1].Z);

                //yaw = Math.Atan2(points[points.Count - 1].X, points[points.Count - 1].Y);
            }


            OpenTK.Matrix4 projection = OpenTK.Matrix4.CreatePerspectiveFieldOfView((float)(45 * deg2rad), 1f, 0.00001f, 5000.0f);
            GL.LoadMatrix(ref projection);

            float eyedist = (float)max * 3;

            // Z X Y

            eye = Vector3.TransformPosition(eye, Matrix4.CreateRotationZ((float)yaw));

            yaw   = 0;
            pitch = 0;

            if (float.IsNaN(eye.X))
            {
                eye = new Vector3(1, 1, 1);
            }

            eye.Normalize();

            eye *= eyedist;

            //Console.WriteLine("eye "+ eye.ToString());
            //(maxx + minx) / 2, (maxy + miny) / 2, (maxz + minz) / 2
            Matrix4 modelview = Matrix4.LookAt(eye.X, eye.Y, eye.Z, 0, 0, 0, 0, 0, 1); // CenterPoint.X, CenterPoint.Y, CenterPoint.Z

            GL.MatrixMode(MatrixMode.Modelview);

            GL.LoadMatrix(ref modelview);

            GL.ClearColor(Color.Black);

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

            // 3
            GL.PointSize(8);

            GL.Begin(PrimitiveType.Lines);

            // +tivs
            GL.Color3(Color.FromArgb(0, 0, 255));
            GL.Vertex3(0, 0, 0);
            GL.Vertex3(0, 0, max);

            GL.Color3(Color.FromArgb(0, 255, 0));
            GL.Vertex3(0, 0, 0);
            GL.Vertex3(0, max, 0);

            GL.Color3(Color.FromArgb(255, 0, 0));
            GL.Vertex3(0, 0, 0);
            GL.Vertex3(max, 0, 0);

            // -atives
            GL.Color3(Color.FromArgb(255, 255, 0));
            GL.Vertex3(0, 0, 0);
            GL.Vertex3(0, 0, -max);

            GL.Color3(Color.FromArgb(255, 0, 255));
            GL.Vertex3(0, 0, 0);
            GL.Vertex3(0, -max, 0);

            GL.Color3(Color.FromArgb(0, 255, 255));
            GL.Vertex3(0, 0, 0);
            GL.Vertex3(-max, 0, 0);


            GL.End();

            //GL.Rotate(Pitch, 0, 0, 0);
            //GL.Rotate(Roll, 0, 0, 0);
            // GL.Rotate(Yaw, 0, 0, 0);

            GL.Begin(PrimitiveType.Points);


            lock (points)
            {
                foreach (var item in points)
                {
                    float rangex = maxx - minx;
                    float rangey = maxy - miny;
                    float rangez = maxz - minz;

                    int valuex = (int)Math.Abs((((item.X) / rangex) * 254)) & 0xff;
                    int valuey = (int)Math.Abs((((item.Y) / rangey) * 254)) & 0xff;
                    int valuez = (int)Math.Abs((((item.Z) / rangez) * 254)) & 0xff;

                    Color col = Color.FromArgb(valuex, valuey, valuez);

                    GL.Color3(col);

                    Vector3 vec = new Vector3(item.X, item.Y, item.Z) + CenterPoint;

                    GL.Vertex3(vec);
                }

                lock (aimpoints)
                {
                    foreach (var aim in aimpoints)
                    {
                        GL.PointSize(8);
                        GL.Color3(Color.White);
                        GL.Vertex3(new Vector3(aim.X, aim.Y, aim.Z) + CenterPoint);
                    }
                }

                GL.End();

                // 8
                GL.PointSize(12);

                GL.Begin(PrimitiveType.Points);

                GL.Color3(Color.Red);

                if (points.Count > 0)
                {
                    GL.Vertex3(new Vector3(points[points.Count - 1].X, points[points.Count - 1].Y, points[points.Count - 1].Z) + CenterPoint);
                }
            }

            GL.End();

            Console.WriteLine(Math.Atan2(eye.Y, eye.X));

            //float newyaw = 0 * deg2rad;

            //DrawCircle(CenterPoint.X, CenterPoint.Y, CenterPoint.Z, newyaw, (float)(max), 60);

            this.SwapBuffers();
        }
Exemplo n.º 21
0
        public override void Render(ref SSRenderConfig renderConfig)
        {
            UpdateTexture();

            base.Render(ref renderConfig);

            SSShaderProgram.DeactivateAll();              // disable GLSL

            // mode setup
            // GL.PixelStore(PixelStoreParameter.UnpackAlignment, 1);

            // Step 2: setup our material mode and paramaters...
            GL.Disable(EnableCap.CullFace);

            GL.Disable(EnableCap.Lighting);
            if (hasAlpha)
            {
                GL.Enable(EnableCap.AlphaTest);
                GL.Enable(EnableCap.Blend);
                GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
            }
            else
            {
                GL.Disable(EnableCap.AlphaTest);
                GL.Disable(EnableCap.Blend);
            }

            // setup our texture source
            if (textureSurface != null)
            {
                GL.ActiveTexture(TextureUnit.Texture0);
                GL.Enable(EnableCap.Texture2D);
                GL.BindTexture(TextureTarget.Texture2D, textureSurface.TextureID);
            }

            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (float)TextureMagFilter.Nearest);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (float)TextureMinFilter.Nearest);

            // draw text rectangle...
            GL.Begin(PrimitiveType.Triangles);
            GL.Color3(Color.White);  // clear the vertex color to white..

            float w = gdiSize.Width;
            float h = gdiSize.Height;

            if (gdiSize != textureSize)
            {
                // adjust texture coordinates
                throw new Exception("not implemented");
            }

            // upper-left
            GL.TexCoord2(0.0, 0.0); GL.Vertex3(0.0, 0.0, 0.0);
            GL.TexCoord2(1.0, 0.0); GL.Vertex3(w, 0.0, 0.0);
            GL.TexCoord2(0.0, 1.0); GL.Vertex3(0.0, h, 0.0);

            // lower-right
            GL.TexCoord2(0.0, 1.0); GL.Vertex3(0.0, h, 0.0);
            GL.TexCoord2(1.0, 0.0); GL.Vertex3(w, 0.0, 0.0);
            GL.TexCoord2(1.0, 1.0); GL.Vertex3(w, h, 0.0);

            GL.End();
        }
Exemplo n.º 22
0
        public override bool ImageEffect_RenderImage(RenderTexture source, RenderTexture destination, RenderBuffer depthBuffer)
        {
            if (!ImageEffects.ImageEffectManager.AdvanceImangeEffectEnabled)
            {
                return(false);
            }
            if (CheckResources() == false || !IsOnValidLOD())
            {
                return(false);
            }

            //根据人物距离控制强度,如果足够远就关闭
            float fallOff = 0;

            if (hasArea)
            {
                ImageEffectManager result = null;
                ImageEffectManager.ImageEffectManagerTable.TryGetValue(m_Camera, out result);

                if (result != null)
                {
                    if (result.hero != null)
                    {
                        float distance = GetDistanceToOBB(result.hero.transform.position);
                        fallOff = distance / maxDistance;
                        fallOff = Mathf.Clamp01(fallOff);
                        //Debug.Log("sun distance: " + distance);
                    }
                }
                //Debug.Log("sun fallOff: " + fallOff);
            }


            int divider = 4;

            if (resolution == SunShaftsResolution.Normal)
            {
                divider = 2;
            }
            else if (resolution == SunShaftsResolution.High)
            {
                divider = 1;
            }

            Vector3 v = Vector3.one * 0.5f;

            if (sunTransform)
            {
                v = m_Camera.WorldToViewportPoint(sunTransform.position);
            }
            else
            {
                v = new Vector3(0.5f, 0.5f, 0.0f);
            }

            if (v.x < -0.15 || v.x > 1.15 || v.y < -0.15 || v.y > 1.15 || fallOff >= 1)
            {
                return(false);
            }

            int rtW = source.width / divider;
            int rtH = source.height / divider;

            RenderTexture lrColorB;
            RenderTexture lrDepthBuffer = RenderTexture.GetTemporary(rtW, rtH, 0);

            // mask out everything except the skybox
            // we have 2 methods, one of which requires depth buffer support, the other one is just comparing images

            sunShaftsMaterial.SetVector("_BlurRadius4", new Vector4(1.0f, 1.0f, 0.0f, 0.0f) * sunShaftBlurRadius);
            sunShaftsMaterial.SetVector("_SunPosition", new Vector4(v.x, v.y, v.z, maxRadius));
            sunShaftsMaterial.SetVector("_SunThreshold", sunThreshold);

            var skybox = RenderSettings.skybox;

            if (skybox != null && skyMask != null && canUseMask)
            {
                sunShaftsMaterial.SetTexture("_SkyCubemap", skyMask);
                sunShaftsMaterial.SetColor("_SkyTint", skybox.GetColor("_Tint"));
                sunShaftsMaterial.SetFloat("_SkyExposure", skybox.GetFloat("_Exposure"));
                sunShaftsMaterial.SetFloat("_SkyRotation", skybox.GetFloat("_Rotation"));
                sunShaftsMaterial.EnableKeyword("ENABLE_SKY_MASK");
            }
            else
            {
                sunShaftsMaterial.DisableKeyword("ENABLE_SKY_MASK");
            }
            //Graphics.Blit(source, lrDepthBuffer, sunShaftsMaterial, 2);

            var cam     = m_Camera;
            var camtr   = cam.transform;
            var camNear = cam.nearClipPlane;
            var camFar  = cam.farClipPlane;

            var tanHalfFov = Mathf.Tan(cam.fieldOfView * Mathf.Deg2Rad / 2);
            var toRight    = camtr.right * camNear * tanHalfFov * cam.aspect;
            var toTop      = camtr.up * camNear * tanHalfFov;

            var v_tl = camtr.forward * camNear - toRight + toTop;
            var v_tr = camtr.forward * camNear + toRight + toTop;
            var v_br = camtr.forward * camNear + toRight - toTop;
            var v_bl = camtr.forward * camNear - toRight - toTop;

            var v_s = v_tl.magnitude * camFar / camNear;

            // Draw screen quad.
            RenderTexture.active = lrDepthBuffer;


            sunShaftsMaterial.SetTexture("_MainTex", source);
            sunShaftsMaterial.SetPass(2);

            GL.PushMatrix();
            GL.LoadOrtho();
            GL.Begin(GL.QUADS);

            GL.MultiTexCoord2(0, 0, 0);
            GL.MultiTexCoord(1, v_bl.normalized * v_s);
            GL.Vertex3(0, 0, 0.1f);

            GL.MultiTexCoord2(0, 1, 0);
            GL.MultiTexCoord(1, v_br.normalized * v_s);
            GL.Vertex3(1, 0, 0.1f);

            GL.MultiTexCoord2(0, 1, 1);
            GL.MultiTexCoord(1, v_tr.normalized * v_s);
            GL.Vertex3(1, 1, 0.1f);

            GL.MultiTexCoord2(0, 0, 1);
            GL.MultiTexCoord(1, v_tl.normalized * v_s);
            GL.Vertex3(0, 1, 0.1f);

            GL.End();
            GL.PopMatrix();


            // radial blur:

            radialBlurIterations = Mathf.Clamp(radialBlurIterations, 1, 4);

            float ofs = sunShaftBlurRadius * (1.0f / 768.0f);

            sunShaftsMaterial.SetVector("_BlurRadius4", new Vector4(ofs, ofs, 0.0f, 0.0f));
            sunShaftsMaterial.SetVector("_SunPosition", new Vector4(v.x, v.y, v.z, maxRadius));

            for (int it2 = 0; it2 < radialBlurIterations; it2++)
            {
                // each iteration takes 2 * 6 samples
                // we update _BlurRadius each time to cheaply get a very smooth look

                lrColorB = RenderTexture.GetTemporary(rtW, rtH, 0);
                Graphics.Blit(lrDepthBuffer, lrColorB, sunShaftsMaterial, 1);
                RenderTexture.ReleaseTemporary(lrDepthBuffer);
                ofs = sunShaftBlurRadius * (((it2 * 2.0f + 1.0f) * 6.0f)) / 768.0f;
                sunShaftsMaterial.SetVector("_BlurRadius4", new Vector4(ofs, ofs, 0.0f, 0.0f));

                lrDepthBuffer = RenderTexture.GetTemporary(rtW, rtH, 0);
                Graphics.Blit(lrColorB, lrDepthBuffer, sunShaftsMaterial, 1);
                RenderTexture.ReleaseTemporary(lrColorB);
                ofs = sunShaftBlurRadius * (((it2 * 2.0f + 2.0f) * 6.0f)) / 768.0f;
                sunShaftsMaterial.SetVector("_BlurRadius4", new Vector4(ofs, ofs, 0.0f, 0.0f));
            }

            // put together:

            //if (v.z >= 0.0f)
            sunShaftsMaterial.SetVector("_SunColor", new Vector4(sunColor.r, sunColor.g, sunColor.b, sunColor.a) * sunShaftIntensity * (1 - fallOff));
            //else
            //    sunShaftsMaterial.SetVector ("_SunColor", Vector4.zero); // no backprojection !
            sunShaftsMaterial.SetTexture("_ColorBuffer", lrDepthBuffer);
            Graphics.Blit(source, destination, sunShaftsMaterial, 0);

            RenderTexture.ReleaseTemporary(lrDepthBuffer);
            return(true);
        }
        /// <summary>
        /// Draw a mesh using either its given material or a transparent "ghost" material.
        /// </summary>
        /// <param name="node">Current node</param>
        /// <param name="animated">Specifies whether animations should be played</param>
        /// <param name="showGhost">Indicates whether to substitute the mesh' material with a
        /// "ghost" surrogate material that allows looking through the geometry.</param>
        /// <param name="index">Mesh index in the scene</param>
        /// <param name="mesh">Mesh instance</param>
        /// <param name="flags"> </param>
        /// <returns></returns>
        protected override bool InternDrawMesh(Node node, bool animated, bool showGhost, int index, Mesh mesh, RenderFlags flags)
        {
            if (showGhost)
            {
                Owner.MaterialMapper.ApplyGhostMaterial(mesh, Owner.Raw.Materials[mesh.MaterialIndex],
                                                        flags.HasFlag(RenderFlags.Shaded), flags.HasFlag(RenderFlags.ForceTwoSidedLighting));
            }
            else
            {
                Owner.MaterialMapper.ApplyMaterial(mesh, Owner.Raw.Materials[mesh.MaterialIndex],
                                                   flags.HasFlag(RenderFlags.Textured),
                                                   flags.HasFlag(RenderFlags.Shaded), flags.HasFlag(RenderFlags.ForceTwoSidedLighting));
            }

            if (GraphicsSettings.Default.BackFaceCulling)
            {
                GL.FrontFace(FrontFaceDirection.Ccw);
                GL.CullFace(CullFaceMode.Back);
                GL.Enable(EnableCap.CullFace);
            }
            else
            {
                GL.Disable(EnableCap.CullFace);
            }

            var hasColors    = mesh.HasVertexColors(0);
            var hasTexCoords = mesh.HasTextureCoords(0);

            var skinning = mesh.HasBones && animated;

            foreach (var face in mesh.Faces)
            {
                BeginMode faceMode;
                switch (face.IndexCount)
                {
                case 1:
                    faceMode = BeginMode.Points;
                    break;

                case 2:
                    faceMode = BeginMode.Lines;
                    break;

                case 3:
                    faceMode = BeginMode.Triangles;
                    break;

                default:
                    faceMode = BeginMode.Polygon;
                    break;
                }

                GL.Begin(faceMode);
                for (var i = 0; i < face.IndexCount; i++)
                {
                    var indice = face.Indices[i];
                    if (hasColors)
                    {
                        var vertColor = AssimpToOpenTk.FromColor(mesh.VertexColorChannels[0][indice]);
                        GL.Color4(vertColor);
                    }
                    if (mesh.HasNormals)
                    {
                        Vector3 normal;
                        if (skinning)
                        {
                            Skinner.GetTransformedVertexNormal(node, mesh, (uint)indice, out normal);
                        }
                        else
                        {
                            normal = AssimpToOpenTk.FromVector(mesh.Normals[indice]);
                        }

                        GL.Normal3(normal);
                    }
                    if (hasTexCoords)
                    {
                        var uvw = AssimpToOpenTk.FromVector(mesh.TextureCoordinateChannels[0][indice]);
                        GL.TexCoord2(uvw.X, 1 - uvw.Y);
                    }

                    Vector3 pos;
                    if (skinning)
                    {
                        Skinner.GetTransformedVertexPosition(node, mesh, (uint)indice, out pos);
                    }
                    else
                    {
                        pos = AssimpToOpenTk.FromVector(mesh.Vertices[indice]);
                    }
                    GL.Vertex3(pos);
                }
                GL.End();
            }
            GL.Disable(EnableCap.CullFace);
            return(skinning);
        }
Exemplo n.º 24
0
        private void drawTexturedQuads()
        {
            GL.Enable(EnableCap.Texture2D);

            GL.Enable(EnableCap.Blend);
            GL.Enable(EnableCap.DepthTest);


            GL.BindTexture(TextureTarget.Texture2D, textureIdCastle);
            GL.Begin(BeginMode.Quads);

            /*GL.Color3(1.0f, 1.0f, 1.0f);*/ GL.TexCoord2(0, 1); GL.Vertex3(-1.0f, -2.0f, 2.0f);
            /*GL.Color3(1.0f, 1.0f, 1.0f);*/ GL.TexCoord2(1, 1); GL.Vertex3(1.0f, -2.0f, 2.0f);
            /*GL.Color3(1.0f, 1.0f, 1.0f);*/ GL.TexCoord2(1, 0); GL.Vertex3(1.0f, 2.0f, 2.0f);
            /*GL.Color3(1.0f, 1.0f, 1.0f);*/ GL.TexCoord2(0, 0); GL.Vertex3(-1.0f, 2.0f, 2.0f);

            GL.End();

            GL.BindTexture(TextureTarget.Texture2D, textureIdGrid);
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
            //GL.Begin(BeginMode.Quads);

            //for (int i = 10; i > -5; i -= 2)
            //{
            //    GL.TexCoord2(0, 1); GL.Vertex3((-i), -1.0f, 3.9f);
            //    GL.TexCoord2(1, 1); GL.Vertex3((-i) + 2, -1.0f, 3.9f);
            //    GL.TexCoord2(1, 0); GL.Vertex3((-i) + 2, 1.0f, 3.9f);
            //    GL.TexCoord2(0, 0); GL.Vertex3((-i), 1.0f, 3.9f);
            //}

            //for (int i = 10; i > -5; i -= 2)
            //{
            //    GL.TexCoord2(0, 1); GL.Vertex3((-i) + 1, -2.5f, 4.9f);
            //    GL.TexCoord2(1, 1); GL.Vertex3((-i) + 2 + 1, -2.5f, 4.9f);
            //    GL.TexCoord2(1, 0); GL.Vertex3((-i) + 2 + 1, -0.5f, 4.9f);
            //    GL.TexCoord2(0, 0); GL.Vertex3((-i) + 1, -0.5f, 4.9f);
            //}

            //for (int i = 10; i > -5; i -= 2)
            //{
            //    GL.TexCoord2(0, 1); GL.Vertex3((-i), -4.0f, 5.9f);
            //    GL.TexCoord2(1, 1); GL.Vertex3((-i) + 2, -4.0f, 5.9f);
            //    GL.TexCoord2(1, 0); GL.Vertex3((-i) + 2, -2.0f, 5.9f);
            //    GL.TexCoord2(0, 0); GL.Vertex3((-i), -2.0f, 5.9f);
            //}

            //for (int i = 10; i > -5; i -= 2)
            //{
            //    GL.TexCoord2(0, 1); GL.Vertex3((-i) + 1, -5.5f, 6.9f);
            //    GL.TexCoord2(1, 1); GL.Vertex3((-i) + 2 + 1, -5.5f, 6.9f);
            //    GL.TexCoord2(1, 0); GL.Vertex3((-i) + 2 + 1, -3.5f, 6.9f);
            //    GL.TexCoord2(0, 0); GL.Vertex3((-i) + 1, -3.5f, 6.9f);
            //}


            //GL.End();

            GL.BindTexture(TextureTarget.Texture2D, textureIdHouse);
            GL.Begin(BeginMode.Quads);
            for (int i = 10; i > -5; i -= 2)
            {
                GL.TexCoord2(0, 1); GL.Vertex3((-i), -4.0f, 6.9f);
                GL.TexCoord2(1, 1); GL.Vertex3((-i) + 2, -4.0f, 6.9f);
                GL.TexCoord2(1, 0); GL.Vertex3((-i) + 2, -2.0f, 6.9f);
                GL.TexCoord2(0, 0); GL.Vertex3((-i), -2.0f, 6.9f);
            }

            GL.End();

            float h = 4;
            float r = 0.866025f;
            float s = 8;

            for (int row = 0; row < 12; row++)
            {
                int v = row & 1;
                GL.BindTexture(TextureTarget.Texture2D, textureIdGrass);
                GL.Begin(PrimitiveType.Quads);

                for (int i = 0; i < 20; i += 1)
                {
                    GL.TexCoord2(0, 1); GL.Vertex3((i * 34 * r + (row & 1) * r * 16), row * (h + s) * 2, 6.9f + row * 0.1);
                    GL.TexCoord2(1, 1); GL.Vertex3((i * 34 * r + (row & 1) * r * 16 + 32), row * (h + s) * 2, 6.9f + row * 0.1);
                    GL.TexCoord2(1, 0); GL.Vertex3((i * 34 * r + (row & 1) * r * 16 + 32), row * (h + s) * 2 + 32, 6.9f + row * 0.1);
                    GL.TexCoord2(0, 0); GL.Vertex3((i * 34 * r + (row & 1) * r * 16), row * (h + s) * 2 + 32, 6.9f + row * 0.1);
                }

                GL.End();
            }

            GL.BindTexture(TextureTarget.Texture2D, textureIdHouse);
            GL.Begin(BeginMode.Quads);
            //for (int i = 0; i < 10; i += 1)
            //{
            //    GL.TexCoord2(0, 1); GL.Vertex3((i * 64),      64.0f, 17.9f);
            //    GL.TexCoord2(1, 1); GL.Vertex3((i * 64) + 64, 64.0f, 17.9f);
            //    GL.TexCoord2(1, 0); GL.Vertex3((i * 64) + 64, 0.0f, 17.9f);
            //    GL.TexCoord2(0, 0); GL.Vertex3((i * 64),      0.0f, 17.9f);
            //}

            GL.End();
        }
Exemplo n.º 25
0
        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            if (this.DesignMode)
            {
                return;
            }

            if (area.LocationMiddle.Lat == 0 && area.LocationMiddle.Lng == 0)
            {
                return;
            }

            try
            {
                base.OnPaint(e);
            }
            catch { return; }

            double heightscale = (step / 90.0) * 1;

            float yawradians = (float)(Math.PI * (rpy.Z * 1) / 180.0f);

            //radians = 0;

            float mouseY = (float)step / 10f;

            cameraX = center.Lng;                                                                                                                                                // -Math.Sin(yawradians) * mouseY;     // multiplying by mouseY makes the
            cameraY = center.Lat;                                                                                                                                                // -Math.Cos(yawradians) * mouseY;    // camera get closer/farther away with mouseY
            cameraZ = (center.Alt < srtm.getAltitude(center.Lat, center.Lng).alt) ? (srtm.getAltitude(center.Lat, center.Lng).alt + 1) * heightscale : center.Alt * heightscale; // (srtm.getAltitude(lookZ, lookX, 20) + 100) * heighscale;

            lookX = center.Lng + Math.Sin(yawradians) * mouseY;
            lookY = center.Lat + Math.Cos(yawradians) * mouseY;
            lookZ = cameraZ;

            // cameraZ += 0.04;

            GMapProvider   type = GMap.NET.MapProviders.GoogleSatelliteMapProvider.Instance;
            PureProjection prj  = type.Projection;

            int size = (int)(cameraZ * 150000);

            // in front
            PointLatLngAlt leftf = center.newpos(rpy.Z, size);
            // behind
            PointLatLngAlt rightf = center.newpos(rpy.Z, 50);
            // left : 90 allows for 180 degree viewing angle
            PointLatLngAlt left = center.newpos(rpy.Z - 90, size);
            // right
            PointLatLngAlt right = center.newpos(rpy.Z + 90, size);

            double maxlat = Math.Max(left.Lat, Math.Max(right.Lat, Math.Max(leftf.Lat, rightf.Lat)));
            double minlat = Math.Min(left.Lat, Math.Min(right.Lat, Math.Min(leftf.Lat, rightf.Lat)));

            double maxlng = Math.Max(left.Lng, Math.Max(right.Lng, Math.Max(leftf.Lng, rightf.Lng)));
            double minlng = Math.Min(left.Lng, Math.Min(right.Lng, Math.Min(leftf.Lng, rightf.Lng)));

            // if (Math.Abs(area.Lat - maxlat) < 0.001)
            {
            }
            // else
            {
                area = RectLatLng.FromLTRB(minlng, maxlat, maxlng, minlat);
            }

            GPoint topLeftPx     = prj.FromLatLngToPixel(area.LocationTopLeft, zoom);
            GPoint rightButtomPx = prj.FromLatLngToPixel(area.Bottom, area.Right, zoom);
            GPoint pxDelta       = new GPoint(rightButtomPx.X - topLeftPx.X, rightButtomPx.Y - topLeftPx.Y);

            zoom      = 21;
            pxDelta.X = 9999;

            int otherzoomlevel = 12;

            // zoom based on pixel density
            while (pxDelta.X > this.Width)
            {
                zoom--;

                // current area
                topLeftPx     = prj.FromLatLngToPixel(area.LocationTopLeft, zoom);
                rightButtomPx = prj.FromLatLngToPixel(area.Bottom, area.Right, zoom);
                pxDelta       = new GPoint(rightButtomPx.X - topLeftPx.X, rightButtomPx.Y - topLeftPx.Y);
            }

            otherzoomlevel = zoom - 4;

            Console.WriteLine("zoom {0}", zoom);

            // update once per seconds - we only read from disk, so need to let cahce settle
            if (lastrefresh.AddSeconds(0.5) < DateTime.Now)
            {
                // get tiles - bg
                core.Provider = type;
                core.Position = LocationCenter;

                // get zoom 10
                core.Zoom = otherzoomlevel;
                core.OnMapSizeChanged(this.Width, this.Height);

                // get actual current zoom
                core.Zoom = zoom;
                core.OnMapSizeChanged(this.Width, this.Height);

                lastrefresh = DateTime.Now;
            }
            else
            {
                //return;
            }

            float screenscale = this.Width / (float)this.Height;

            MakeCurrent();

            GL.MatrixMode(MatrixMode.Projection);

            OpenTK.Matrix4 projection = OpenTK.Matrix4.CreatePerspectiveFieldOfView(120 * deg2rad, screenscale, 0.00001f, (float)step * 20000);
            GL.LoadMatrix(ref projection);

            Matrix4 modelview = Matrix4.LookAt((float)cameraX, (float)cameraY, (float)cameraZ, (float)lookX, (float)lookY, (float)lookZ, 0, 0, 1);

            GL.MatrixMode(MatrixMode.Modelview);

            // roll
            modelview = Matrix4.Mult(modelview, Matrix4.CreateRotationZ(rpy.X * deg2rad));
            // pitch
            modelview = Matrix4.Mult(modelview, Matrix4.CreateRotationX((rpy.Y - 15) * -deg2rad));

            GL.LoadMatrix(ref modelview);

            GL.ClearColor(Color.CornflowerBlue);

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

            GL.LightModel(LightModelParameter.LightModelAmbient, new float[] { 1f, 1f, 1f, 1f });

            //  GL.Disable(EnableCap.Fog);
            GL.Enable(EnableCap.Fog);
            //GL.Enable(EnableCap.Lighting);
            //GL.Enable(EnableCap.Light0);

            GL.Fog(FogParameter.FogColor, new float[] { 100 / 255.0f, 149 / 255.0f, 237 / 255.0f, 1f });
            //GL.Fog(FogParameter.FogDensity,0.1f);
            GL.Fog(FogParameter.FogMode, (int)FogMode.Linear);
            GL.Fog(FogParameter.FogStart, (float)step * 40);
            GL.Fog(FogParameter.FogEnd, (float)(step * 50));

//            GL.Enable(EnableCap.DepthTest);
            GL.DepthFunc(DepthFunction.Always);

            /*
             * GL.Begin(BeginMode.LineStrip);
             *
             * GL.Color3(Color.White);
             * GL.Vertex3(0, 0, 0);
             *
             * //GL.Color3(Color.Red);
             * GL.Vertex3(area.Bottom, 0, area.Left);
             *
             * //GL.Color3(Color.Yellow);
             * GL.Vertex3(lookX, lookY, lookZ);
             *
             * //GL.Color3(Color.Green);
             * GL.Vertex3(cameraX, cameraY, cameraZ);
             *
             * GL.End();
             */
            /*
             * GL.PointSize(10);
             * GL.Color4(Color.Yellow);
             * GL.LineWidth(5);
             *
             *
             * GL.Begin(PrimitiveType.LineStrip);
             *
             * //GL.Vertex3(new Vector3((float)center.Lng,(float)center.Lat,(float)(center.Alt * heightscale)));
             * //GL.Vertex3(new Vector3(0, 0, 0));
             * //GL.Vertex3(new Vector3((float)cameraX, (float)cameraY, (float)cameraZ));
             * //GL.Color3(Color.Green);
             * //GL.Vertex3(new Vector3((float)lookX, (float)lookY, (float)lookZ));
             *
             * GL.Vertex3(area.LocationTopLeft.Lng, area.LocationTopLeft.Lat, (float)cameraZ);
             * GL.Vertex3(area.LocationTopLeft.Lng, area.LocationRightBottom.Lat, (float)cameraZ);
             * GL.Vertex3(area.LocationRightBottom.Lng, area.LocationRightBottom.Lat, (float)cameraZ);
             * GL.Vertex3(area.LocationRightBottom.Lng, area.LocationTopLeft.Lat, (float)cameraZ);
             * GL.Vertex3(area.LocationTopLeft.Lng, area.LocationTopLeft.Lat, (float)cameraZ);
             *
             * GL.End();
             */
            GL.Finish();

            GL.PointSize((float)(step * 1));
            GL.Color3(Color.Blue);
            GL.Begin(PrimitiveType.Points);
            GL.Vertex3(new Vector3((float)center.Lng, (float)center.Lat, (float)cameraZ));
            GL.End();



            //GL.ClampColor(ClampColorTarget.ClampReadColor, ClampColorMode.True);

            /*
             * GL.Enable(EnableCap.Blend);
             * GL.DepthMask(false);
             * GL.BlendFunc(BlendingFactorSrc.Zero, BlendingFactorDest.Src1Color);
             * GL.DepthMask(true);
             * GL.Disable(EnableCap.Blend);
             */
            // textureid.Clear();

            // get level 10 tiles
            List <GPoint> tileArea1 = prj.GetAreaTileList(area, otherzoomlevel, 1);

            // get type list at new zoom level
            List <GPoint> tileArea2 = prj.GetAreaTileList(area, zoom, 2);

            List <GPoint> tileArea = new List <GPoint>();

            tileArea.AddRange(tileArea1);
            tileArea.AddRange(tileArea2);

            // get tiles & combine into one
            foreach (var p in tileArea)
            {
                int localzoom = zoom;

                core.tileDrawingListLock.AcquireReaderLock();
                core.Matrix.EnterReadLock();
                try
                {
                    if (tileArea1.Contains(p))
                    {
                        localzoom = otherzoomlevel;
                    }

                    topLeftPx = prj.FromLatLngToPixel(area.LocationTopLeft, localzoom);

                    GMap.NET.Internals.Tile t = core.Matrix.GetTileWithNoLock(localzoom, p);

                    if (t.NotEmpty)
                    {
                        foreach (GMapImage img in t.Overlays)
                        {
                            if (!textureid.ContainsKey(p))
                            {
                                generateTexture(p, (Bitmap)img.Img);
                            }
                        }
                    }
                    else
                    {
                    }
                }
                finally
                {
                    core.Matrix.LeaveReadLock();
                    core.tileDrawingListLock.ReleaseReaderLock();
                }

                //GMapImage tile = ((PureImageCache)Maps.MyImageCache.Instance).GetImageFromCache(type.DbId, p, zoom) as GMapImage;

                //if (tile != null && !textureid.ContainsKey(p))
                {
                    //  generateTexture(p, (Bitmap)tile.Img);
                }

                if (textureid.ContainsKey(p))
                {
                    int texture = textureid[p];

                    GL.Enable(EnableCap.Texture2D);
                    GL.BindTexture(TextureTarget.Texture2D, texture);
                }
                else
                {
                    //Console.WriteLine("Missing tile");
                    continue;
                }

                long x = p.X * prj.TileSize.Width - topLeftPx.X;
                long y = p.Y * prj.TileSize.Width - topLeftPx.Y;

                long xr = p.X * prj.TileSize.Width;
                long yr = p.Y * prj.TileSize.Width;

                long x2 = (p.X + 1) * prj.TileSize.Width;
                long y2 = (p.Y + 1) * prj.TileSize.Width;


                GL.LineWidth(0);
                GL.Color3(Color.White);

                // generate terrain
                GL.Begin(PrimitiveType.TriangleStrip);

                var latlng = prj.FromPixelToLatLng(xr, yr, localzoom);

                double heightl = srtm.getAltitude(latlng.Lat, latlng.Lng).alt;
                if (localzoom == 10)
                {
                    heightl = 0;
                }

                //xr - topLeftPx.X, yr - topLeftPx.Y
                GL.TexCoord2(0, 0);
                GL.Vertex3(latlng.Lng, latlng.Lat, heightl * heightscale);


                // next down
                latlng = prj.FromPixelToLatLng(xr, y2, localzoom);

                heightl = srtm.getAltitude(latlng.Lat, latlng.Lng).alt;
                if (localzoom == 10)
                {
                    heightl = 0;
                }

                GL.TexCoord2(0, 1);
                GL.Vertex3(latlng.Lng, latlng.Lat, heightl * heightscale);


                // next right
                latlng = prj.FromPixelToLatLng(x2, yr, localzoom);

                heightl = srtm.getAltitude(latlng.Lat, latlng.Lng).alt;
                if (localzoom == 10)
                {
                    heightl = 0;
                }

                GL.TexCoord2(1, 0);
                GL.Vertex3(latlng.Lng, latlng.Lat, heightl * heightscale);


                // next right down
                latlng = prj.FromPixelToLatLng(x2, y2, localzoom);

                heightl = srtm.getAltitude(latlng.Lat, latlng.Lng).alt;
                if (localzoom == 10)
                {
                    heightl = 0;
                }

                GL.TexCoord2(1, 1);
                GL.Vertex3(latlng.Lng, latlng.Lat, heightl * heightscale);

                GL.End();
            }

            GL.Flush();

            try
            {
                this.SwapBuffers();


                Context.MakeCurrent(null);
            }
            catch { }

            //this.Invalidate();

            return;
        }
Exemplo n.º 26
0
        public override void Show(Main D)
        {
            GL.Begin(PrimitiveType.TriangleFan);
            GL.Vertex2(MainCirclePosition);
            for (int i = 0; i <= CircleSteps; i++)
            {
                float  T     = i / (float)CircleSteps;
                double Angle = T * Math.PI * 2;
                GL.Color4(GetColorFromPosition(T));
                Vector2 V = new Vector2((float)Math.Sin(Angle), -(float)Math.Cos(Angle)) * MainCircleOuterRadius;
                GL.Vertex2(V + MainCirclePosition);
            }
            GL.End();

            GL.Begin(PrimitiveType.Triangles);
            for (int i = 0; i < CurrentPaletteSize; i++)
            {
                double  Angle = PalettePositions[i] * Math.PI * 2;
                Vector2 V1    = new Vector2((float)Math.Sin(Angle - NodeWidth), -(float)Math.Cos(Angle - NodeWidth)) * MainCircleOuterRadius;
                Vector2 V2    = new Vector2((float)Math.Sin(Angle + NodeWidth), -(float)Math.Cos(Angle + NodeWidth)) * MainCircleOuterRadius;
                if (SelectedIndex == i)
                {
                    V1 *= 1.1f;
                    V2 *= 1.1f;
                }
                GL.Color4(ColorPalette[i]);
                GL.Vertex2(MainCirclePosition);
                GL.Vertex2(MainCirclePosition + V1);
                GL.Vertex2(MainCirclePosition + V2);
            }
            GL.End();
            GL.LineWidth(2);
            GL.Begin(PrimitiveType.Lines);


            for (int i = 0; i < CurrentPaletteSize; i++)
            {
                double  Angle = PalettePositions[i] * Math.PI * 2;
                Vector2 V1    = new Vector2((float)Math.Sin(Angle - NodeWidth), -(float)Math.Cos(Angle - NodeWidth)) * MainCircleOuterRadius;
                Vector2 V2    = new Vector2((float)Math.Sin(Angle + NodeWidth), -(float)Math.Cos(Angle + NodeWidth)) * MainCircleOuterRadius;
                if (SelectedIndex == i)
                {
                    V1 *= 1.1f;
                    V2 *= 1.1f;
                }
                GL.Color3(Color.LightGray);
                GL.Vertex2(MainCirclePosition);
                GL.Vertex2(MainCirclePosition + V1);
                GL.Vertex2(MainCirclePosition);
                GL.Vertex2(MainCirclePosition + V2);
            }
            GL.End();

            /*if (IsHoldingCircle)
             * {
             *  GL.Color3(Color.OrangeRed);
             * }
             * else
             * {
             *  GL.Color4(InteriorColor);
             * }*/
            float Rad = InnerCircleRadius;

            if (SelectedIndex == -1)
            {
                Rad *= 1.3f;
            }
            FillCircle(BackgroundColor, MainCircleInnerRadius);
            FillCircle(InteriorColor, Rad);
            DrawCircle(Color.LightGray, Rad);

            IsDraggingCircle = false;
        }
Exemplo n.º 27
0
        public override Image Render(RendererOptions options)
        {
            if (window == null)
            {
                int size = 1;
                window = new GameWindow(size, size, new GraphicsMode(new ColorFormat(8, 8, 8, 8), 24, 0, 0, ColorFormat.Empty, 1), "", GameWindowFlags.Default, DisplayDevice.Default, 3, 0, GraphicsContextFlags.Offscreen)
                {
                    WindowState = WindowState.Fullscreen, Visible = false
                };
                window.TargetRenderPeriod    = 1;
                window.TargetUpdateFrequency = 1;
            }

            GL.ClearColor(Color.Transparent);

            using (Bitmap sourceBitmap = CreateTextureBitmap(options))
            {
                BitmapData data;
                int        size = (int)options.OutputImageSize;
                if (window.ClientSize.Width != size || window.ClientSize.Height != size)
                {
                    window.ClientSize = new Size(size, size);
                    System.Windows.Application.Current.Dispatcher.Invoke(() => System.Windows.Application.Current.MainWindow?.Activate());
                }
                Rectangle rect = new Rectangle(0, 0, sourceBitmap.Width, sourceBitmap.Height);
                data = sourceBitmap.LockBits(rect, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                double crds = 1;
                GL.Viewport(0, 0, size, size);
                GL.MatrixMode(MatrixMode.Projection);
                GL.LoadIdentity();

                GL.Ortho(-crds, crds, -crds, crds, -crds, crds);

                GL.Rotate(90, new Vector3d(0, 0, 1));
                GL.Rotate(90 - options.LatitudeShift, new Vector3d(0, 1, 0));
                GL.Rotate(-options.LongutudeShift, new Vector3d(0, 0, 1));

                GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
                GL.Viewport(0, 0, size, size);
                GL.Color3(Color.White);
                GL.Disable(EnableCap.Lighting);

                GL.DepthMask(true);
                GL.Enable(EnableCap.DepthTest);
                //GL.ClearDepth(1.0f);
                GL.DepthFunc(DepthFunction.Lequal);

                int nx, ny;

                nx = 64;
                ny = 64;

                int texture;

                GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill);
                GL.Enable(EnableCap.Texture2D);
                GL.GenTextures(1, out texture);
                GL.BindTexture(TextureTarget.Texture2D, texture);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
                GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);

                int    ix, iy;
                double x, y, z, sy, cy, sy1, cy1, sx, cx, piy, pix, ay, ay1, ax, tx, ty, ty1, dnx, dny, diy;
                dnx = 1.0 / nx;
                dny = 1.0 / ny;

                GL.Begin(PrimitiveType.QuadStrip);
                piy = Math.PI * dny;
                pix = Math.PI * dnx;
                for (iy = 0; iy < ny; iy++)
                {
                    diy = iy;
                    ay  = diy * piy;
                    sy  = Math.Sin(ay);
                    cy  = Math.Cos(ay);
                    ty  = diy * dny;
                    ay1 = ay + piy;
                    sy1 = Math.Sin(ay1);
                    cy1 = Math.Cos(ay1);
                    ty1 = ty + dny;
                    for (ix = 0; ix <= nx; ix++)
                    {
                        ax = 2.0 * ix * pix;
                        sx = Math.Sin(ax);
                        cx = Math.Cos(ax);
                        x  = sy * cx;
                        y  = sy * sx;
                        z  = cy;
                        tx = ix * dnx;

                        GL.TexCoord2(tx, ty);
                        GL.Vertex3(x, y, z);
                        x = sy1 * cx;
                        y = sy1 * sx;
                        z = cy1;

                        GL.TexCoord2(tx, ty1);
                        GL.Vertex3(x, y, z);
                    }
                }
                GL.End();
                GL.Disable(EnableCap.Texture2D);
                GL.DeleteTexture(texture);

                sourceBitmap.UnlockBits(data);
                return(GraphicsContextToBitmap(size));
            }
        }
Exemplo n.º 28
0
    public static void update()
    {
        deferred_action_run(); //Run deferred actions

        TimeSpan span = DateTime.Now.Subtract(Graphics.last_frame_time);

        if (span < frame_time)
        {
            Thread.Sleep(frame_time.Subtract(span));
        }
        Graphics.last_frame_time = DateTime.Now;

        if (!Window.IsExiting)
        {
            Window.ProcessEvents();
        }

        frame_count++;
        if (frozen)
        {
            return;
        }


        GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
        GL.ClearColor(0f, 0f, 0f, 1.0f);
        GL.Clear(ClearBufferMask.ColorBufferBit);

        sort();
        //Console.WriteLine("new frame ");
        default_viewport.draw();
        foreach (Viewport vp in viewports)
        {
            //Console.WriteLine("drawing viewport: " + vp.z);
            //Console.WriteLine("Viewport z: " + vp.z + (vp.is_default ? " (default)" : ""));
            vp.draw();
        }

        //brightness quad
        if (brightness < 255)
        {
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
            GL.Viewport(0, 0, Graphics.width, Graphics.height);
            GL.MatrixMode(MatrixMode.Projection);
            GL.LoadIdentity();
            GL.Ortho(0, Graphics.width, Graphics.height, 0, -1, 1);

            GL.Enable(EnableCap.Texture2D);
            GL.BindTexture(TextureTarget.Texture2D, 0);

            GL.Color4(0.0f, 0.0f, 0.0f, 1f - ((1f / 255f) * (float)brightness));

            GL.Begin(BeginMode.Quads);

            GL.Vertex3(0, 0, 0.1f);
            GL.Vertex3(width, 0, 0.1f);
            GL.Vertex3(width, height, 0.1f);
            GL.Vertex3(0, height, 0.1f);

            GL.End();
        }

        if (!Window.IsExiting)
        {
            Window.SwapBuffers();
        }
    }
Exemplo n.º 29
0
        protected void DrawScannerTable(Vector3d center)
        {
            List <Vector3d> circT = new List <Vector3d>(360);
            List <Vector3d> circB = new List <Vector3d>(360);
            List <Vector2d> text  = new List <Vector2d>(360);
            double          h     = 5;

            for (int i = 0; i < 361; i++)
            {
                double ang = Utils.DEGREES_TO_RADIANS(i);
                double x   = -Math.Cos(ang);
                double y   = Math.Sin(ang);
                text.Add(new Vector2d(x * TableRadius / 20.0, y * TableRadius / 20.0));
                Vector3d t = new Vector3d(x * TableRadius, 0, y * TableRadius);
                Vector3d b = new Vector3d(x * TableRadius, -h, y * TableRadius);
                circT.Add(t + center);
                circB.Add(b + center);
            }

            using (new GLEnable(EnableCap.Lighting))
            {
                GL.ColorMaterial(MaterialFace.FrontAndBack, ColorMaterialParameter.AmbientAndDiffuse);
                using (new GLEnable(EnableCap.ColorMaterial))
                {
                    GL.ShadeModel(Smooth ? ShadingModel.Smooth : ShadingModel.Flat);
                    GL.Color3(ForeColor.GetStepColor(BackColor, 0.5));
                    using (new GLEnable(EnableCap.CullFace))
                    {
                        GL.CullFace(CullFaceMode.Back);

                        GL.BindTexture(TextureTarget.Texture2D, this.ScannerTextureID);

                        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
                        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);

                        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
                        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

                        using (new GLEnable(EnableCap.Blend))
                        {
                            GL.BlendFunc(BlendingFactorSrc.SrcColor, BlendingFactorDest.SrcColor);

                            using (new GLEnable(EnableCap.Texture2D))
                            {
                                GL.Begin(PrimitiveType.Polygon);
                                GL.Normal3(new Vector3d(0, 1, 0));
                                for (int i = 0; i < circT.Count; i++)
                                {
                                    GL.TexCoord2(text[i]);
                                    //GL.Normal3(new Vector3d(0, 1, 0));
                                    GL.Vertex3(circT[i]);
                                }
                                GL.End();


                                double div = (TableRadius * 16 * Math.PI) / 360;
                                GL.Begin(PrimitiveType.TriangleStrip);
                                for (int i = 0; i < circT.Count; i++)
                                {
                                    GL.Normal3(circT[i].Normalized());
                                    GL.TexCoord2(new Vector2d(i / div, 0));
                                    GL.Vertex3(circT[i]);
                                    GL.TexCoord2(new Vector2d(i / div, 0.5));
                                    GL.Vertex3(circB[i]);
                                }
                                GL.End();


                                GL.Begin(PrimitiveType.Polygon);
                                GL.Normal3(new Vector3d(0, -1, 0));
                                for (int i = circT.Count - 1; i >= 0; i--)
                                {
                                    //GL.Normal3(new Vector3d(0, -1, 0));
                                    GL.TexCoord2(text[i]);
                                    GL.Vertex3(circB[i]);
                                }
                                GL.End();

                                GL.Color3(BackColor.ModifyLuminosity(0.1));
                                GL.Disable(EnableCap.Lighting);
                                GL.Disable(EnableCap.Texture2D);
                                GL.Disable(EnableCap.Blend);

                                GL.Begin(PrimitiveType.TriangleStrip);
                                for (int i = 0; i < circT.Count; i++)
                                {
                                    Vector3d v = new Vector3d(circT[i]);
                                    v.Y     += TableHeight;
                                    circB[i] = v;
                                    GL.Vertex3(circT[i]);
                                    GL.Vertex3(circB[i]);
                                }
                                GL.End();
                                GL.Begin(PrimitiveType.Polygon);
                                GL.Normal3(new Vector3d(0, -1, 0));
                                for (int i = circT.Count - 1; i >= 0; i--)
                                {
                                    GL.Vertex3(circB[i]);
                                }
                                GL.End();
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 30
0
    void RaycastCornerBlit(RenderTexture source, RenderTexture dest, Material mat)
    {
        // Compute Frustum Corners
        float camFar    = _camera.farClipPlane;
        float camFov    = _camera.fieldOfView;
        float camAspect = _camera.aspect;

        float fovWHalf = camFov * 0.5f;

        Vector3 toRight = _camera.transform.right * Mathf.Tan(fovWHalf * Mathf.Deg2Rad) * camAspect;
        Vector3 toTop   = _camera.transform.up * Mathf.Tan(fovWHalf * Mathf.Deg2Rad);

        Vector3 topLeft  = (_camera.transform.forward - toRight + toTop);
        float   camScale = topLeft.magnitude * camFar;

        topLeft.Normalize();
        topLeft *= camScale;

        Vector3 topRight = (_camera.transform.forward + toRight + toTop);

        topRight.Normalize();
        topRight *= camScale;

        Vector3 bottomRight = (_camera.transform.forward + toRight - toTop);

        bottomRight.Normalize();
        bottomRight *= camScale;

        Vector3 bottomLeft = (_camera.transform.forward - toRight - toTop);

        bottomLeft.Normalize();
        bottomLeft *= camScale;

        // Custom Blit, encoding Frustum Corners as additional Texture Coordinates
        RenderTexture.active = dest;

        mat.SetTexture("_MainTex", source);

        GL.PushMatrix();
        GL.LoadOrtho();

        mat.SetPass(0);

        GL.Begin(GL.QUADS);

        GL.MultiTexCoord2(0, 0.0f, 0.0f);
        GL.MultiTexCoord(1, bottomLeft);
        GL.Vertex3(0.0f, 0.0f, 0.0f);

        GL.MultiTexCoord2(0, 1.0f, 0.0f);
        GL.MultiTexCoord(1, bottomRight);
        GL.Vertex3(1.0f, 0.0f, 0.0f);

        GL.MultiTexCoord2(0, 1.0f, 1.0f);
        GL.MultiTexCoord(1, topRight);
        GL.Vertex3(1.0f, 1.0f, 0.0f);

        GL.MultiTexCoord2(0, 0.0f, 1.0f);
        GL.MultiTexCoord(1, topLeft);
        GL.Vertex3(0.0f, 1.0f, 0.0f);

        GL.End();
        GL.PopMatrix();
    }