private static void Draw(Camera camera, float size, IList <Vector4> vertices, IList <Color> colors, Matrix4x4 localToWorld)
        {
            if (camera == null || vertices == null)
            {
                return;
            }
            if (vertices.Count != colors.Count)
            {
                return;
            }

            GL.PushMatrix();

            GL.LoadIdentity();
            GL.modelview = camera.worldToCameraMatrix * localToWorld;
            GL.LoadProjectionMatrix(camera.projectionMatrix);

            LineMaterial.SetPass(0);
            GL.Begin(GL.QUADS);

            switch (Orientation)
            {
            case DRAW_ORIENTATION.XY:
                DrawXY(size, vertices, colors);
                break;

            case DRAW_ORIENTATION.XZ:
                DrawXZ(size, vertices, colors);
                break;
            }

            GL.End();

            GL.PopMatrix();
        }
Esempio n. 2
0
        private void loadGL()
        {
            setupArrays(vertexLength);

            GL.ClearColor(0f, 0f, 0f, 1f);

            GL.Enable(EnableCap.FramebufferSrgb);
            GL.Enable(EnableCap.Blend);
            GL.BlendEquation(BlendEquationMode.FuncAdd);
            GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.DstAlpha);
            // GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
            //GL.BlendFuncSeparate(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha, BlendingFactorSrc.One, BlendingFactorDest.OneMinusSrcAlpha);

            vertexBufferObject = GL.GenBuffer();
            GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferObject);
            GL.BufferData(BufferTarget.ArrayBuffer, vertices.Length * sizeof(float), vertices, BufferUsageHint.StreamDraw);

            elementBufferObject = GL.GenBuffer();
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, elementBufferObject);
            GL.BufferData(BufferTarget.ElementArrayBuffer, indices.Length * sizeof(uint), indices, BufferUsageHint.StreamDraw);

            vertexArrayObject = GL.GenVertexArray();
            GL.BindVertexArray(vertexArrayObject);

            GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferObject);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, elementBufferObject);

            lineMat = new LineMaterial();
        }
        public SpecialLineRendering()
        {
            InitializeComponent();


            // First create HiddenLineMaterial
            _hiddenLineMaterial = new HiddenLineMaterial()
            {
                LineColor     = Colors.Yellow.ToColor4(),
                LineThickness = 1f,
                LinePattern   = 0x1111,
            };

            // Also create a DXEngine's LineMaterial (it will be used by the ScreenSpaceLineNode and to render wireframe object)
            _dxLineMaterial = new LineMaterial()
            {
                LineThickness = 1,
                LineColor     = Colors.Yellow.ToColor4(),
                DepthBias     = 0.1f
                                // Set DepthBias to prevent rendering wireframe at the same depth as the 3D objects. This creates much nicer 3D lines because lines are rendered on top of 3D object and not in the same position as 3D object.
            };

            CreateTest3DObjects();

            MainDXViewportView.DXSceneInitialized += delegate(object sender, EventArgs args)
            {
                if (MainDXViewportView.DXScene == null)
                {
                    return; // Probably WPF 3D rendering
                }
                CreateSceneNodesDictionary();

                // After the DXScene was initialized and the DXEngine's SceneNodes objects are created,
                // we can set advanced DXEngine properties
                ShowVisibleAndHiddenLines();
            };


            // IMPORTANT:
            // It is very important to call Dispose method on DXSceneView after the control is not used any more (see help file for more info)
            this.Unloaded += delegate
            {
                if (_hiddenLineMaterial != null)
                {
                    _hiddenLineMaterial.Dispose();
                    _hiddenLineMaterial = null;
                }

                if (_dxLineMaterial != null)
                {
                    _dxLineMaterial.Dispose();
                    _dxLineMaterial = null;
                }

                MainDXViewportView.Dispose();
            };
        }
Esempio n. 4
0
        private static void DrawVerticesAsLines(Camera camera, Color color, IList <Vector4> vertices, Matrix4x4 localToWorld, IList <int> indices)
        {
            if (camera == null || vertices == null)
            {
                return;
            }
            if (vertices.Count < 2)
            {
                return;
            }

            GL.PushMatrix();

            GL.LoadIdentity();
            GL.modelview = camera.worldToCameraMatrix * localToWorld;
            GL.LoadProjectionMatrix(camera.projectionMatrix);

            LineMaterial.SetPass(0);
            GL.Begin(GL.LINES);
            GL.Color(color);

            int vertexCount = vertices.Count;

            if (indices != null)
            {
                for (int i = 0; i < indices.Count / 2; i++)
                {
                    int i0 = indices[i * 2 + 0];
                    int i1 = indices[i * 2 + 1];

                    if (i0 < 0 || i0 >= vertexCount)
                    {
                        continue;
                    }
                    if (i1 < 0 || i1 >= vertexCount)
                    {
                        continue;
                    }

                    GL.Vertex(vertices[i0]);
                    GL.Vertex(vertices[i1]);
                }
            }
            else
            {
                for (int i = 0; i < vertexCount - 1; i++)
                {
                    GL.Vertex(vertices[i]);
                    GL.Vertex(vertices[i + 1]);
                }
            }

            GL.End();

            GL.PopMatrix();
        }
Esempio n. 5
0
        private LineMaterial CreateLineMaterial(bool isPolyLine, Color lineColor)
        {
            var lineMaterial = new LineMaterial()
            {
                LineColor     = lineColor.ToColor4(),
                LineThickness = 10,
                IsPolyLine    = isPolyLine
            };

            return(lineMaterial);
        }
Esempio n. 6
0
 void OnDrawGizmos()
 {
     // Show the mesh outline
     if (Application.isEditor && meshFilter.sharedMesh != null && showMeshOutline)
     {
         CalculateVertexColors();
         GL.wireframe = true;
         LineMaterial.SetPass(0);
         Graphics.DrawMeshNow(meshFilter.sharedMesh, transform.position, transform.rotation);
         GL.wireframe = false;
     }
 }
Esempio n. 7
0
    private void OnRenderObject()
    {
        if (!DebugSubmersion)
        {
            return;
        }

        LineMaterial.SetPass(0);
        GL.PushMatrix();
        GL.Begin(GL.LINES);

        //GL.Color(SubmergLineColor);
        //if (SubmergedPoints.Count > 0)
        //{
        //    for (int i = 0; i < SubmergedPoints.Count; i++)
        //    {
        //        if (i != 0)
        //            GL.Vertex(SubmergedPoints[i]);

        //        GL.Vertex(SubmergedPoints[i]);
        //    }
        //    GL.Vertex(SubmergedPoints[0]);
        //}

        GL.Color(OutlineColor);
        GL.Vertex(CornerVectors[0]);
        GL.Vertex(CornerVectors[1]);
        GL.Vertex(CornerVectors[1]);
        GL.Vertex(CornerVectors[2]);
        GL.Vertex(CornerVectors[2]);
        GL.Vertex(CornerVectors[3]);
        GL.Vertex(CornerVectors[3]);
        GL.Vertex(CornerVectors[0]);



        //GL.Vertex(transform.position);
        //GL.Vertex(transform.position - RawForce * .3f);

        GL.Color(VelocityLineColor);

        GL.Vertex(transform.position);

        var newLine = Vec3.Lerp(_prevVelLine, velocityVector, .1f);

        GL.Vertex(transform.position - newLine * .3f);
        _prevVelLine = velocityVector;
        //GL.Vertex(transform.position);
        //GL.Vertex(transform.TransformPoint(BladeNormal));

        GL.End();
        GL.PopMatrix();
    }
Esempio n. 8
0
        /// <summary>
        /// Default values method
        /// </summary>
        protected override void DefaultValues()
        {
            base.DefaultValues();

            this.meshes        = new List <Mesh>();
            this.boundingBox   = new BoundingBox();
            this.UseWorldSpace = false;
            this.lineType      = LineTypes.LineList;
            this.material      = new LineMaterial(WaveServices.GraphicsDevice.Graphics);
            this.linePoints    = new List <LinePointInfo>();
            this.textureTiling = Vector2.One;
            this.ModelMeshName = "Default";
        }
Esempio n. 9
0
        public static Line Choose(
            LineType type,
            LineMaterial materialType,
            double power,
            double cos,
            double length,
            double voltage,
            int deltaVoltage)
        {
            var line = Line.Create(type, materialType, length);

            line.Calculate(power, cos, voltage, deltaVoltage);
            return(line);
        }
        private ScreenSpaceLineNode CreateLinesWithLineMesh(Vector3[] linePositions, bool isLineStrip, bool isLineClosed, Color lineColor, float xOffset, out ScreenSpaceLineMesh screenSpaceLineMesh)
        {
            if (linePositions == null || linePositions.Length < 2)
            {
                screenSpaceLineMesh = null;
                return(null);
            }

            // If line is closed but the first position is not the same as the last position, then add the first position as the last one
            if (isLineClosed && linePositions[0] != linePositions[linePositions.Length - 1])
            {
                Array.Resize(ref linePositions, linePositions.Length + 1);
                linePositions[linePositions.Length - 1] = linePositions[0];
            }


            // If we can easily calculate the bounding box from line positions
            // it is recommended to specify it in the ScreenSpaceLineMesh constructor.
            // If boundingBox is not specified, it will be calculated in the ScreenSpaceLineMesh constructor with checking all the positions.
            //
            // NOTE: If bounding box is not correct then camera's near and far planes can be invalid and this can cut some 3D objects at near or far plane (when DXScene.OptimizeNearAndFarCameraPlanes is true - by default)
            //var boundingBox = new BoundingBox(new Vector3(startX, 0, startZ), new Vector3(startX + linesCount * margin, 0, endZ));

            // Create ScreenSpaceLineMesh - it is used to create DirectX vertex buffer from positions
            screenSpaceLineMesh = new ScreenSpaceLineMesh(linePositions, isLineStrip);

            // When the line positions are changed many times, it is recommended to set CreateDynamicVertexBuffer to true.
            screenSpaceLineMesh.CreateDynamicVertexBuffer = true;

            var lineMaterial = new LineMaterial()
            {
                LineColor     = lineColor.ToColor4(),
                LineThickness = 2
            };

            var screenSpaceLineNode = new ScreenSpaceLineNode(screenSpaceLineMesh, lineMaterial);

            screenSpaceLineNode.Transform = new Transformation(SharpDX.Matrix.Translation(xOffset, 0, 0));

            // To show ScreenSpaceLineNode in DXViewportView we need to put it inside a SceneNodeVisual3D
            var sceneNodeVisual3D = new SceneNodeVisual3D(screenSpaceLineNode);

            MainViewport.Children.Add(sceneNodeVisual3D);

            _disposables.Add(screenSpaceLineMesh);
            _disposables.Add(screenSpaceLineNode);
            _disposables.Add(lineMaterial);

            return(screenSpaceLineNode);
        }
Esempio n. 11
0
        public static Material Create(LineMaterial type)
        {
            switch (type)
            {
            case LineMaterial.Copper:
                return(new CopperMaterial());

            case LineMaterial.Aluminium:
                return(new AluminiumMaterial());

            default:
                return(new CopperMaterial());
            }
        }
Esempio n. 12
0
        private static Line Create(LineType type, LineMaterial materialType, double length)
        {
            var material = Material.Create(materialType);

            switch (type)
            {
            case LineType.Air:
                return(new AirLine(material, length));

            case LineType.AirCable:
                return(new AirCableLine(material, length));

            default:
                return(new GroundCableLine(material, length));
            }
        }
        public SpecialLineRendering()
        {
            InitializeComponent();


            // First create HiddenLineMaterial
            _hiddenLineMaterial = new HiddenLineMaterial()
            {
                LineColor     = Colors.Yellow.ToColor4(),
                LineThickness = 1f, // Use very small line thickness (smaller than 1)
                LinePattern   = 0x1111,
            };

            CreateTest3DObjects();

            MainDXViewportView.DXSceneInitialized += delegate(object sender, EventArgs args)
            {
                CreateSceneNodesDictionary();

                // After the DXScene was initialized and the DXEngine's SceneNodes objects are created,
                // we can set advanced DXEngine properties
                ShowVisibleAndHiddenLines();
            };


            // IMPORTANT:
            // It is very important to call Dispose method on DXSceneView after the control is not used any more (see help file for more info)
            this.Unloaded += delegate
            {
                if (_hiddenLineMaterial != null)
                {
                    _hiddenLineMaterial.Dispose();
                    _hiddenLineMaterial = null;
                }

                if (_dxLineMaterial != null)
                {
                    _dxLineMaterial.Dispose();
                    _dxLineMaterial = null;
                }

                MainDXViewportView.Dispose();
            };
        }
Esempio n. 14
0
        private void AddLines(Point3D startPosition, int positionsCount, Color lineColor, bool readZBuffer = true, bool writeZBuffer = true, RenderingQueue customRenderingQueue = null)
        {
            Vector3[] positions = new Vector3[positionsCount * 2];
            Vector3   position  = startPosition.ToVector3();

            int index = 0;

            for (int i = 0; i < positionsCount; i++)
            {
                positions[index]     = position;
                positions[index + 1] = position + new Vector3(40, 0, 0);

                index    += 2;
                position += new Vector3(0, 0, 10);
            }

            // ThickLineEffect that renders the 3D lines can use the ReadZBuffer and WriteZBuffer values from LineMaterial.
            //
            // When ReadZBuffer is false (true by default), then line is rendered without checking the depth buffer -
            // so it is always rendered even it is is behind some other 3D object and should not be visible from the camera).
            //
            // When WriteZBuffer is false (true by default), then when rendering the 3D line, the depth of the line is not
            // written to the depth buffer. So No other object will be made hidden by the line even if that object is behind the line.
            var lineMaterial = new LineMaterial()
            {
                LineColor     = lineColor.ToColor4(),
                LineThickness = 2,
                ReadZBuffer   = readZBuffer,
                WriteZBuffer  = writeZBuffer
            };

            _disposables.Add(lineMaterial);


            var screenSpaceLineNode = new ScreenSpaceLineNode(positions, isLineStrip: false, isLineClosed: false, lineMaterial: lineMaterial);

            // It is also needed that the 3D line is put to the Background or Overlay rendering queue so that it is rendered before or after other 3D objects.
            screenSpaceLineNode.CustomRenderingQueue = customRenderingQueue;

            var sceneNodeVisual3D = new SceneNodeVisual3D(screenSpaceLineNode);

            MainViewport.Children.Add(sceneNodeVisual3D);
        }
Esempio n. 15
0
 public void OnRenderObject()
 {
     if (_Player != null || (!thirdPerson && pl != null))
     {
         LineMaterial.SetPass(0);
         GL.LoadOrtho();
         GL.Begin(GL.LINES);
         GL.Color(Color.green);
         foreach (var a in list)
         {
             var v = new Vector3(Screen.width, Screen.height) / 2 + new Vector3(a.x, a.y);
             v   += a.normalized * (1 + pl.gun.cursorOffset);
             v.x /= Screen.width;
             v.y /= Screen.height;
             GL.Vertex(v);
         }
         GL.End();
     }
 }
    public override void OnDebugElementRenderObject()
    {
        LineMaterial.SetPass(0);

        GL.PushMatrix();
        GL.Begin(GL.TRIANGLES);

        foreach (PathEntry entry in entries)
        {
            foreach (var pair in entry.Nodes)
            {
                NodeType type = pair.Value.type;
                GL.Color(Colors[type]);

                DrawHexagon(Utility.AxialToWorldPosition(pair.Key));
            }
        }

        GL.End();
        GL.PopMatrix();
    }
        private ScreenSpaceLineNode CreateLinesWithPositions(Vector3[] linePositions, bool isLineStrip, bool isLineClosed, Color lineColor, float xOffset)
        {
            var lineMaterial = new LineMaterial()
            {
                LineColor     = lineColor.ToColor4(),
                LineThickness = 2
            };

            var screenSpaceLineNode = new ScreenSpaceLineNode(linePositions, isLineStrip, isLineClosed, lineMaterial);

            screenSpaceLineNode.Transform = new Transformation(SharpDX.Matrix.Translation(xOffset, 0, 0));

            // To show ScreenSpaceLineNode in DXViewportView we need to put it inside a SceneNodeVisual3D
            var sceneNodeVisual3D = new SceneNodeVisual3D(screenSpaceLineNode);

            MainViewport.Children.Add(sceneNodeVisual3D);

            _disposables.Add(screenSpaceLineNode);
            _disposables.Add(lineMaterial);

            return(screenSpaceLineNode);
        }
        private void AddTestModels()
        {
            // Load teapot model from obj file
            var readerObj       = new ReaderObj();
            var geometryModel3D = readerObj.ReadModel3D(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resources\Models\teapot.obj")) as GeometryModel3D;

            if (geometryModel3D == null)
            {
                return;
            }

            _objectGeometry3D = (MeshGeometry3D)geometryModel3D.Geometry;



            int positionsCount = _objectGeometry3D.Positions.Count;

            // Create and fill the _positionColorsArray with the last color (light blue)
            _positionColorsArray = new Color4[positionsCount];

            var lastColor = _gradientColor4Array[_gradientColor4Array.Length - 1];

            FillPositionColorsArray(lastColor);

            // Now create the VertexColorMaterial that will be used instead of standard material
            // and will make the model render with special effect where each vertex can have its own color.
            _vertexColorMaterial = new VertexColorMaterial()
            {
                PositionColors      = _positionColorsArray, // The PositionColors property is used to specify colors for each vertex
                CreateDynamicBuffer = true,                 // Because we will update the _positionColorsArray on each frame, it is better to create a dynamic DirectX buffer

                // To show specular effect set the specular data here:
                //SpecularPower = 16,
                //SpecularColor = Color3.White,
                //HasSpecularColor = true
            };

            // Create standard WPF material and set the _vertexColorMaterial to be used when the model is rendered in DXEngine.
            var vertexColorDiffuseMaterial = new DiffuseMaterial();

            vertexColorDiffuseMaterial.SetUsedDXMaterial(_vertexColorMaterial);


            // Create a GeometryModel3D that will be rendered with _vertexColorMaterial
            _vertexColorGeometryModel3D = new GeometryModel3D(_objectGeometry3D, vertexColorDiffuseMaterial);

            var vertexColorModelVisual3D = new ModelVisual3D()
            {
                Content = _vertexColorGeometryModel3D
            };

            MainViewport.Children.Add(vertexColorModelVisual3D);



            // Show the same MeshGeometry3D but this time with wireframe material
            var wireframeWpfMaterial = new DiffuseMaterial();

            _lineMaterial = new LineMaterial()
            {
                LineThickness = 1,
                LineColor     = Color4.Black,
                DepthBias     = 0.1f,
            };

            wireframeWpfMaterial.SetUsedDXMaterial(_lineMaterial);


            var wireframeGeometryModel3D = new GeometryModel3D(_objectGeometry3D, wireframeWpfMaterial);

            var wireframeModelVisual3D = new ModelVisual3D()
            {
                Content = wireframeGeometryModel3D
            };

            MainViewport.Children.Add(wireframeModelVisual3D);
        }
        public VertexColorRenderingSample()
        {
            InitializeComponent();

            CreateGradientColorsArray();

            // Use CameraControllerInfo to show that we can use left mouse button to set custom beam destination on the 3D model
            CameraControllerInfo.AddCustomInfoLine(0, MouseCameraController.MouseAndKeyboardConditions.LeftMouseButtonPressed, "SET BEAM DESTINATION");

            // When the ViewportBorder size is change the size of the overlay Canvas (drawn over the 3D scene)
            ViewportBorder.SizeChanged += delegate(object sender, SizeChangedEventArgs args)
            {
                UpdateOverlayCanvasSize();
            };


            // Process mouse events
            ViewportBorder.MouseLeftButtonDown += delegate(object sender, MouseButtonEventArgs e)
            {
                // Start user beam control
                _isUserBeamControl = true;

                ViewportBorder.CaptureMouse();

                var position = e.GetPosition(ViewportBorder);
                ProcessMouseHit(position);
            };

            ViewportBorder.MouseLeftButtonUp += delegate(object sender, MouseButtonEventArgs e)
            {
                // Stop user beam control
                _isUserBeamControl = false;
                ViewportBorder.ReleaseMouseCapture();

                ProcessMouseOutOfModel();
            };

            // Subscribe to MouseMove to allow user to specify the beam target
            ViewportBorder.MouseMove += delegate(object sender, MouseEventArgs e)
            {
                if (_isUserBeamControl)
                {
                    ProcessMouseHit(e.GetPosition(ViewportBorder));
                }
                else
                {
                    ProcessMouseOutOfModel();
                }
            };


            // Start animating the beam position
            CompositionTarget.Rendering += CompositionTargetOnRendering;


            // We add test models after the DXScene is initialized (this is required because specifal effects require DirectX device)
            MainDXViewportView.DXSceneInitialized += delegate(object sender, EventArgs e)
            {
                if (MainDXViewportView.DXScene == null)
                {
                    return; // Probably WPF 3D rendering
                }
                // Get _vertexColorEffect that will be used to render model with vertex colors (note that this field must be disposed when it is not used any more - here in Unloaded event handler)

                AddTestModels();
            };

            // Cleanup
            this.Unloaded += delegate(object sender, RoutedEventArgs args)
            {
                CompositionTarget.Rendering -= CompositionTargetOnRendering;

                if (_vertexColorMaterial != null)
                {
                    _vertexColorMaterial.Dispose();
                    _vertexColorMaterial = null;
                }

                if (_lineMaterial != null)
                {
                    _lineMaterial.Dispose();
                    _lineMaterial = null;
                }

                MainDXViewportView.Dispose();
            };
        }
        public static SceneNode CreateLineSceneNodes(Point3D center, Size3D size, bool useSingleColor, int xCount, int yCount, int zCount, DisposeList disposables)
        {
            var rootSceneNode = new SceneNode();

            float xStep = (float)(size.X / xCount);
            float yStep = (float)(size.Y / yCount);
            float zStep = (float)(size.Z / zCount);

            float xHalfLineSize = xStep * 0.3f;
            //float yHalfLineSize = xStep * 0.3f;
            float zHalfLineSize = xStep * 0.3f;

            var singleColorLineMaterial = new LineMaterial()
            {
                LineColor     = Colors.Orange.ToColor4(),
                LineThickness = 2
            };

            if (disposables != null)
            {
                disposables.Add(singleColorLineMaterial);
            }



            for (int z = 0; z < zCount; z++)
            {
                float zPos     = (float)(center.Z - (size.Z / 2.0) + (z * zStep));
                float zPercent = (float)z / (float)zCount;

                for (int y = 0; y < yCount; y++)
                {
                    float yPos     = (float)(center.Y - (size.Y / 2.0) + (y * yStep));
                    float yPercent = (float)y / (float)yCount;

                    for (int x = 0; x < xCount; x++)
                    {
                        float xPos = (float)(center.X - (size.X / 2.0) + (x * xStep));

                        var linePositions = new Vector3[]
                        {
                            new Vector3(xPos - xHalfLineSize, yPos, zPos - zHalfLineSize),
                            new Vector3(xPos + xHalfLineSize, yPos, zPos + zHalfLineSize),
                            new Vector3(xPos - xHalfLineSize, yPos, zPos + zHalfLineSize),
                            new Vector3(xPos + xHalfLineSize, yPos, zPos - zHalfLineSize),
                        };

                        LineMaterial usedLineMaterial;

                        if (useSingleColor)
                        {
                            // Using single color improved performance by 30% because we do not need to update per-object constant buffer for each line.
                            usedLineMaterial = singleColorLineMaterial;
                        }
                        else
                        {
                            usedLineMaterial = new LineMaterial()
                            {
                                LineColor     = new Color4((float)x / (float)xCount, yPercent, zPercent, 1),
                                LineThickness = 2
                            };

                            if (disposables != null)
                            {
                                disposables.Add(usedLineMaterial);
                            }
                        }

                        // NOTE:
                        // The sample can also show many instances of ScreenSpaceLineNode to simulate showing many different 3D lines.
                        // It would be much better to use a single ScreenSpaceLineNode and set all line positions to that object.

                        var screenSpaceLineNode = new ScreenSpaceLineNode(linePositions, isLineStrip: false, isLineClosed: false, lineMaterial: usedLineMaterial);

                        rootSceneNode.AddChild(screenSpaceLineNode);
                    }
                }
            }

            return(rootSceneNode);
        }
        private void CreateTeapotWireframeModel(Point3D centerPosition, Size3D size, DiffuseMaterial material)
        {
            // The most common way to show wireframe models in DXEngine is to use WireframeVisual3D from Ab3d.PowerToys - see commented code below:
            //var wireframeVisual3D = new WireframeVisual3D()
            //{
            //    WireframeType = WireframeVisual3D.WireframeTypes.WireframeWithOriginalSolidModel,
            //    UseModelColor = false,
            //    LineThickness = 1,
            //    LineColor = Colors.Yellow,
            //    Transform = new TranslateTransform3D(0, 0, -50)
            //};
            //
            //wireframeVisual3D.OriginalModel = teapotModel;
            //// Set LineDepthBias to prevent rendering wireframe at the same depth as the 3D objects.
            //// This creates much nicer 3D lines. See the LineDepthBiasSample for more information.
            //wireframeVisual3D.SetDXAttribute(DXAttributeType.LineDepthBias, 0.1);

            // But in this sample we show special line rendering.
            // Therefore we will create standard WPF GeometryModel3D and then apply LineMaterial to it so the model will be rendered with wireframe lines

            // First read teapot model from Teapot.obj file
            var readerObj   = new Ab3d.ReaderObj();
            var teapotModel = readerObj.ReadModel3D(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resources\Models\Teapot.obj")) as GeometryModel3D;

            if (teapotModel == null)
            {
                return;
            }

            // Get the teapot MeshGeometry3D
            var meshGeometry3D = (MeshGeometry3D)teapotModel.Geometry;


            // Get transformation to scale and position the model to the centerPosition and size
            var bounds = meshGeometry3D.Bounds;

            double scaleX = size.X / bounds.SizeX;
            double scaleY = size.Y / bounds.SizeY;
            double scaleZ = size.Z / bounds.SizeZ;

            double minScale = Math.Min(scaleX, Math.Min(scaleY, scaleZ));

            scaleX = scaleY = scaleZ = minScale;

            var scaleTransform3D = new ScaleTransform3D(scaleX, scaleY, scaleZ);

            bounds = scaleTransform3D.TransformBounds(bounds);


            double cx = bounds.X + bounds.SizeX * 0.5;
            double cy = bounds.Y + bounds.SizeY * 0.5;
            double cz = bounds.Z + bounds.SizeZ * 0.5;

            var translateTransform3D = new TranslateTransform3D(centerPosition.X - cx, centerPosition.Y - cy, centerPosition.Z - cz);

            var transform3DGroup = new Transform3DGroup();

            transform3DGroup.Children.Add(scaleTransform3D);
            transform3DGroup.Children.Add(translateTransform3D);



            // First create the standard solid model with the specified material
            var geometryModel3D = new GeometryModel3D(meshGeometry3D, material);

            geometryModel3D.Transform = transform3DGroup;

            var modelVisual3D = new ModelVisual3D()
            {
                Content = geometryModel3D
            };

            TestObjectsModelVisual3D.Children.Add(modelVisual3D);


            // To render wireframe object, we first create a DXEngine material that is used to rendered lines or wireframe
            if (_dxLineMaterial == null)
            {
                _dxLineMaterial = new LineMaterial()
                {
                    LineThickness = 1,
                    LineColor     = Colors.Yellow.ToColor4(),
                    DepthBias     = 0.1f
                                    // Set DepthBias to prevent rendering wireframe at the same depth as the 3D objects. This creates much nicer 3D lines because lines are rendered on top of 3D object and not in the same position as 3D object.
                };
            }
            else
            {
                _dxLineMaterial.ReadZBuffer = true;
            }

            // Now create standard WPF material and assign DXEngine's LineMaterial to it.
            // This will use the dxLineMaterial when the wpfLineMaterial will be rendered in DXEngine
            var wpfWireframeMaterial = new DiffuseMaterial(Brushes.Red);

            wpfWireframeMaterial.SetUsedDXMaterial(_dxLineMaterial);


            // Finally, create another GeometryModel3D, but this time we will use DXEngine's LineMaterial to render it
            _wireframeGeometryModel3D           = new GeometryModel3D(meshGeometry3D, wpfWireframeMaterial);
            _wireframeGeometryModel3D.Transform = transform3DGroup;

            modelVisual3D = new ModelVisual3D()
            {
                Content = _wireframeGeometryModel3D
            };

            TestObjectsModelVisual3D.Children.Add(modelVisual3D);
        }
Esempio n. 22
0
        private static void DrawVerticesAsTetrahedron(Camera camera, Color color, IList <Vector4> vertices, Matrix4x4 localToWorld, IList <int> indices)
        {
            if (camera == null || vertices == null)
            {
                return;
            }
            if (vertices.Count < 4)
            {
                return;
            }

            GL.PushMatrix();

            GL.LoadIdentity();
            GL.MultMatrix(camera.worldToCameraMatrix);
            GL.LoadProjectionMatrix(camera.projectionMatrix);

            LineMaterial.SetPass(0);
            GL.Begin(GL.LINES);
            GL.Color(color);

            int vertexCount = vertices.Count;

            if (indices != null)
            {
                for (int i = 0; i < indices.Count / 4; i++)
                {
                    int i0 = indices[i * 4 + 0];
                    int i1 = indices[i * 4 + 1];
                    int i2 = indices[i * 4 + 2];
                    int i3 = indices[i * 4 + 3];

                    if (i0 < 0 || i0 >= vertexCount)
                    {
                        continue;
                    }
                    if (i1 < 0 || i1 >= vertexCount)
                    {
                        continue;
                    }
                    if (i2 < 0 || i2 >= vertexCount)
                    {
                        continue;
                    }
                    if (i3 < 0 || i3 >= vertexCount)
                    {
                        continue;
                    }

                    GL.Vertex(vertices[i0]);
                    GL.Vertex(vertices[i1]);

                    GL.Vertex(vertices[i0]);
                    GL.Vertex(vertices[i2]);

                    GL.Vertex(vertices[i0]);
                    GL.Vertex(vertices[i3]);

                    GL.Vertex(vertices[i1]);
                    GL.Vertex(vertices[i2]);

                    GL.Vertex(vertices[i3]);
                    GL.Vertex(vertices[i2]);

                    GL.Vertex(vertices[i1]);
                    GL.Vertex(vertices[i3]);
                }
            }
            else
            {
                for (int i = 0; i < vertexCount / 4; i++)
                {
                    Vector3 v0 = vertices[i * 4 + 0];
                    Vector3 v1 = vertices[i * 4 + 1];
                    Vector3 v2 = vertices[i * 4 + 2];
                    Vector3 v3 = vertices[i * 4 + 3];


                    GL.Vertex(v0);
                    GL.Vertex(v1);

                    GL.Vertex(v0);
                    GL.Vertex(v2);

                    GL.Vertex(v0);
                    GL.Vertex(v3);

                    GL.Vertex(v1);
                    GL.Vertex(v2);

                    GL.Vertex(v3);
                    GL.Vertex(v2);

                    GL.Vertex(v1);
                    GL.Vertex(v3);
                }
            }

            GL.End();

            GL.PopMatrix();
        }