Beispiel #1
0
        public static void GetRectData(vtkPolyData data, Rectangle rect)
        {
            var points     = vtkPoints.New();
            var colorArray = vtkUnsignedCharArray.New();

            colorArray.SetNumberOfComponents(3);

            RectImageData = vtkImageData.New();
            RectImageData.SetExtent(0, rect.Size.Width - 1, 0, rect.Size.Height - 1, 0, 0);
            RectImageData.SetNumberOfScalarComponents(1);
            RectImageData.SetScalarTypeToUnsignedChar();

            for (var i = rect.Top; i < rect.Bottom; i++)
            {
                for (var j = rect.Left; j < rect.Right; j++)
                {
                    double[] p = data.GetPoint(i * ImageWidth + j);
                    points.InsertNextPoint(j - rect.Left, i - rect.Top, p[2]);

                    double[] c = data.GetPointData().GetScalars().GetTuple3(i * ImageWidth + j);
                    colorArray.InsertNextTuple3(c[0], c[1], c[2]);

                    RectImageData.SetScalarComponentFromDouble(j - rect.Left, i - rect.Top, 0, 0, c[0]);
                }
            }


            RectPolyData = vtkPolyData.New();
            RectPolyData.SetPoints(points);
            RectPolyData.GetPointData().SetScalars(colorArray);
            RectPolyData.Update();
        }
Beispiel #2
0
        public static void SaveRectData(string filename, vtkPolyData polyData, Rectangle rect)
        {
            try
            {
                SimplePointFile.OpenWriteFile(filename);

                var color = polyData.GetPointData().GetScalars();

                for (var i = 0; i < rect.Height; i++)
                {
                    for (var j = 0; j < rect.Width; j++)
                    {
                        var data = polyData.GetPoint(i * rect.Width + j);
                        var c    = color.GetComponent(i * rect.Width + j, 0);

                        SimplePointFile.Writeline(new[] { data[0], data[1], data[2], c, c, c });
                    }
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                SimplePointFile.CloseWriteFile();
            }
        }
Beispiel #3
0
        private void Vertex()
        {
            vtkPoints points = vtkPoints.New();

            points.InsertNextPoint(0, 0, 0);

            vtkVertex vertex = vtkVertex.New();

            vertex.GetPointIds().SetId(0, 0);

            vtkCellArray vertices = vtkCellArray.New();

            vertices.InsertNextCell(vertex);

            vtkPolyData polydata = vtkPolyData.New();

            polydata.SetPoints(points);
            polydata.SetVerts(vertices);

            // Visualize
            vtkPolyDataMapper mapper = vtkPolyDataMapper.New();

            mapper.SetInputConnection(polydata.GetProducerPort());
            vtkActor actor = vtkActor.New();

            actor.SetMapper(mapper);
            actor.GetProperty().SetPointSize(10);
            vtkRenderWindow renderWindow = renderWindowControl1.RenderWindow;
            vtkRenderer     renderer     = renderWindow.GetRenderers().GetFirstRenderer();

            renderer.SetBackground(0.2, 0.3, 0.4);
            // Add the actor to the scene
            renderer.AddActor(actor);
        }
Beispiel #4
0
        public void WriteVTP(string filePath, List <Vector3d> point_data, List <Vector3> cellPointsList, Dictionary <String, vtkDataArray> scalar_dataArray, List <String> arrayNames)
        {
            vtkPoints points = vtkPoints.New();

            for (int i = 0; i < point_data.Count(); i++)
            {
                points.InsertNextPoint(point_data[i].X, point_data[i].Y, point_data[i].Z);
            }

            vtkPolyData polyData = vtkPolyData.New();

            polyData.SetPoints(points);

            vtkCellArray cellArrayOne = vtkCellArray.New();

            for (int i = 0; i < cellPointsList.Count(); i++)
            {
                vtkTetra tetra = vtkTetra.New();

                tetra.GetPointIds().SetId(0, (long)cellPointsList[i][0]);
                tetra.GetPointIds().SetId(1, (long)cellPointsList[i][1]);
                tetra.GetPointIds().SetId(2, (long)cellPointsList[i][2]);
                tetra.GetPointIds().SetId(3, (long)cellPointsList[i][2]);
                cellArrayOne.InsertNextCell(tetra);
            }

            polyData.SetPolys(cellArrayOne);

            int numberOfScalarData = scalar_dataArray.Count();

            for (int i = 0; i < numberOfScalarData; i++)
            {
                scalar_dataArray.TryGetValue(arrayNames[i], out vtkDataArray scalars);
                polyData.GetPointData().AddArray(scalars);
            }

            vtkXMLPolyDataWriter writer = vtkXMLPolyDataWriter.New();

            // add file ending if it is not existent
            string suffix = (".vtp");

            if (!(filePath.EndsWith(suffix)))
            {
                filePath += suffix;
            }

            writer.SetFileName(filePath);
            writer.SetInput(polyData);
            writer.Write();

            // Read and display file for verification that it was written correctly
            vtkXMLStructuredGridReader reader = vtkXMLStructuredGridReader.New();

            if (reader.CanReadFile(filePath) == 0)
            {
                //MessageBox.Show("Cannot read file \"" + filePath + "\"", "Error", MessageBoxButtons.OK);
                return;
            }
            Console.WriteLine("VTP file was writen and is saved at {0}", filePath);
        }
Beispiel #5
0
        public void ReadDataByLine(string filename)
        {
            try
            {
                var dataStrings = File.ReadAllLines(filename);
                points = vtkPoints.New();
                points.SetNumberOfPoints(dataStrings.Length);

                var colorArray = vtkUnsignedCharArray.New();
                colorArray.SetNumberOfComponents(3);

                for (var i = 0; i < dataStrings.Length; i++)
                {
                    var data = dataStrings[i].Split(' ');

                    if (data.Length < 6)
                    {
                        continue;
                    }

                    points.SetPoint(i, int.Parse(data[0]), int.Parse(data[1]), int.Parse(data[2]));
                    colorArray.InsertNextTuple3(double.Parse(data[3]), double.Parse(data[4]), double.Parse(data[5]));
                }

                PolyData = vtkPolyData.New();
                PolyData.SetPoints(points);
                PolyData.GetPointData().SetScalars(colorArray);
                PolyData.Update();
            }
            catch (Exception)
            {
                throw;
            }
        }
Beispiel #6
0
            internal void CreatePolydata(ref vtkPolyData polydata)
            {
                vtkPoints points = vtkPoints.New();

                points.InsertNextPoint(this.origin[0], this.origin[1], this.origin[2]);

                float[] x = new float[3];
                float[] y = new float[3];
                float[] z = new float[3];

                Add(this.origin, this.xDirection, ref x);
                Add(this.origin, this.yDirection, ref y);
                Add(this.origin, this.zDirection, ref z);

                points.InsertNextPoint(x[0], x[1], x[2]);
                points.InsertNextPoint(y[0], y[1], y[2]);
                points.InsertNextPoint(z[0], z[1], z[2]);

                polydata.SetPoints(points);

                vtkVertexGlyphFilter vertexGlyphFilter = vtkVertexGlyphFilter.New();

#if VTK_MAJOR_VERSION_5
                vertexGlyphFilter.AddInput(polydata);
#else
                vertexGlyphFilter.AddInputData(polydata);
#endif
                vertexGlyphFilter.Update();
                polydata.ShallowCopy(vertexGlyphFilter.GetOutput());
            }
        // Draw poly data: earth demo
        private void earthToolStripMenuItem_Click(object sender, EventArgs e)
        {
            vtkEarthSource    source = new vtkEarthSource();
            vtkPolyDataMapper map    = vtkPolyDataMapper.New();
            vtkPolyData       poly   = new vtkPolyData();
            vtkActor          actor  = new vtkActor();

            vtkPoints    pts   = new vtkPoints();
            vtkCellArray strip = new vtkCellArray();

            // 定义三个点
            pts.InsertNextPoint(0, 0, 0);
            pts.InsertNextPoint(1, 0, 0);
            pts.InsertNextPoint(1, 1, 0);

            // 定义一个单元
            strip.InsertCellPoint(3);
            strip.InsertNextCell(0);
            strip.InsertNextCell(1);
            strip.InsertNextCell(2);
            // 定义vtkPolyData为点集
            poly.SetPoints(pts);
            poly.SetVerts(strip);// 用SetVerts函数定义点, Verts即Vertices(顶点,Vertex的复数)
            // 定义mapper
            map.SetInput(poly);
            map.SetInput(source.GetOutput());
            actor.SetMapper(map);
            m_Renderer.SetBackground(.5, .5, 1);
            imgPropList.Add(actor);
            m_Renderer.AddActor(actor);
            //Rerender the screen
            m_RenderWindow.Render();
            m_Renderer.Render();
        }
Beispiel #8
0
        public void ReplacePolyData(vtkPolyData polyData)
        {
            this.PolyData = polyData;

            _polyDataMapper.SetInput(polyData);
            _polyDataMapper.Modified();
        }
        internal OrientationEnumPackage(vtkPolyData polyData, vtkRenderWindow renwin, vtkRenderer mainRenderer)
        {
            this._renwin       = renwin;
            this._mainRenderer = mainRenderer;

            int oldNumberOfRenderer = renwin.GetNumberOfLayers();

            Console.WriteLine(string.Format("oldNumberOfRenderer = {0}", oldNumberOfRenderer));
            int newNumberOfRenderer = oldNumberOfRenderer + 1;

            mainRenderer.SetLayer(0);

            _topRenderer = vtkRenderer.New();
            _topRenderer.SetViewport(0, 0, 0.2, 0.2);
            _topRenderer.SetLayer(newNumberOfRenderer - 1);
            _topRenderer.InteractiveOff();

            _xmlPolyDataPackage = new XmlPolyDataPackage(polyData, _topRenderer);
            //xmlPolyDataPackage.SetOpacity(0.8);
            //xmlPolyDataPackage.Actor.GetProperty().ShadingOn();
            //xmlPolyDataPackage.Actor.GetProperty().SetAmbient(0.8);
            //xmlPolyDataPackage.SetColor(1, 1, 0.5);
            _xmlPolyDataPackage.SetColor(255 / 255.0, 204 / 255.0, 102 / 255.0);

            renwin.SetNumberOfLayers(newNumberOfRenderer);
            renwin.AddRenderer(_topRenderer);

            //_topRenderer.SetActiveCamera(mainRenderer.GetActiveCamera());
        }
Beispiel #10
0
        public void ExtractFeatures()
        {
            Filter = vtkDataSetSurfaceFilter.New();
            Filter.SetInput(Grid);
            Filter.Update();
            Faces = Filter.GetOutput();

            vtkFeatureEdges FeatureEdges = vtkFeatureEdges.New();

            FeatureEdges.SetInput(Filter.GetOutput());
            FeatureEdges.Update();

            FeatureEdges.BoundaryEdgesOn();
            FeatureEdges.FeatureEdgesOn();
            FeatureEdges.ManifoldEdgesOn();
            FeatureEdges.NonManifoldEdgesOn();

            // Change Edge color
            FeatureEdges.SetColoring(0);

            // Update
            FeatureEdges.Update();

            vtkPolyDataMapper EdgeMapper = vtkPolyDataMapper.New();

            EdgeMapper.SetInput(FeatureEdges.GetOutput());
            EdgeMapper.ScalarVisibilityOff();

            Edges.SetMapper(EdgeMapper);
            Edges.GetProperty().SetEdgeColor(0, 0, 0);
            Edges.GetProperty().SetColor(0.0, 0.0, 0.0);
            Edges.GetProperty().SetLineWidth((float)1.0);   // Set default edge thickness
            Edges.SetVisibility(0);
        }
Beispiel #11
0
        public static void SetDelaunay2D(vtkPolyData polyData)
        {
            var delaunay = vtkDelaunay2D.New();

            delaunay.SetTolerance(0.001);
            delaunay.SetInput(polyData);
            delaunay.Update();

            var triDataMapper = vtkPolyDataMapper.New();

            triDataMapper.SetInputConnection(delaunay.GetOutputPort());
            triDataMapper.Update();

            var polyDataActor = vtkActor.New();

            polyDataActor.SetMapper(triDataMapper);
            polyDataActor.SetPosition(-polyDataActor.GetCenter()[0], -polyDataActor.GetCenter()[1],
                                      -polyDataActor.GetCenter()[2]);

            var polyDataRenderer = RenWinControl3D.RenderWindow.GetRenderers().GetFirstRenderer();

            polyDataRenderer.RemoveAllViewProps();
            polyDataRenderer.LightFollowCameraOn();
            polyDataRenderer.SetBackground(1, 1, 1);
            polyDataRenderer.SetAmbient(1, 1, 1);
            polyDataRenderer.AddActor(polyDataActor);
            polyDataRenderer.ResetCamera();
            polyDataRenderer.Render();
        }
Beispiel #12
0
        public static void SetVertexGlyph(vtkPolyData polyData)
        {
            var filter = vtkVertexGlyphFilter.New();

            filter.SetInput(polyData);
            filter.Update();

            var polyDataMapper = vtkPolyDataMapper.New();

            polyDataMapper.SetInputConnection(filter.GetOutputPort());
            polyDataMapper.SetScalarModeToDefault();
            polyDataMapper.SetScalarRange(0, 255);
            polyDataMapper.SetScalarVisibility(1);
            polyDataMapper.Update();

            var polyDataActor = vtkActor.New();

            polyDataActor.SetMapper(polyDataMapper);
            polyDataActor.GetProperty().SetPointSize(1.5f);
            polyDataActor.SetPosition(-polyDataActor.GetCenter()[0], -polyDataActor.GetCenter()[1],
                                      -polyDataActor.GetCenter()[2]);

            var polyDataRenderer = RenWinControl3D.RenderWindow.GetRenderers().GetFirstRenderer();

            polyDataRenderer.RemoveAllViewProps();
            polyDataRenderer.AddActor(polyDataActor);
            polyDataRenderer.SetBackground(1, 1, 1);
            polyDataRenderer.ResetCamera();
            polyDataRenderer.Render();
        }
Beispiel #13
0
        static public vtkPolyData ArrayList2PolyData(int type, List <Point3D> centers, double[] trueScale, double[] centroidScale
                                                     , double[] scale, int clock, int clock_y, int clock_x)//ArrayList转成可视化PolyData
        {
            vtkPolyData polydata = new vtkPolyData();

            vtkPoints    SourcePoints   = new vtkPoints();
            vtkCellArray SourceVertices = new vtkCellArray();

            int[] pid = new int[1];
            if (type == 1)
            {
                for (int i = 0; i < centers.Count; i++)
                {
                    //if (!centers[i].isFilter)
                    //{
                    //pid[0] = SourcePoints.InsertNextPoint(centers[i].tmp_X, centers[i].tmp_Y, centers[i].tmp_Z);
                    pid[0] = SourcePoints.InsertNextPoint(centers[i].tmp_X, centers[i].tmp_Y, 0);
                    SourceVertices.InsertNextCell(1, pid);
                    //}
                }
            }
            polydata.SetPoints(SourcePoints); //把点导入的polydata中去
            polydata.SetVerts(SourceVertices);
            return(polydata);
        }
Beispiel #14
0
        private void renderScene()
        {
            vtkCamera camera;

            if (toShow != null)
            {
                this.geometryPoints();

                vtkPolyData polydata = vtkPolyData.New();
                polydata.SetPoints(pontosVTK);

                vtkDelaunay2D del = vtkDelaunay2D.New();
                del.AddInput(polydata);

                vtkPolyDataMapper mapMesh = vtkPolyDataMapper.New();
                mapMesh.SetInput(del.GetOutput());

                vtkActor meshActor = vtkActor.New();
                meshActor.SetMapper(mapMesh);
                meshActor.GetProperty().SetColor(0.5d, 0.5d, 0d);

                windowVTK.AddRenderer(rendererVTK);
                rendererVTK.AddActor(meshActor);

                windowVTK.Render();
                rendererVTK.Render();

                meshActor.Render(rendererVTK, mapMesh);
                camera = rendererVTK.GetActiveCamera();
                camera.Zoom(1.0d);

                rendererVTK.ResetCamera();
            }
        }
Beispiel #15
0
            internal void ApplyTransform(ref vtkTransform transform, string filename)
            {
                vtkPolyData polydata = vtkPolyData.New();

                CreatePolydata(ref polydata);

                vtkTransformFilter transformFilter = vtkTransformFilter.New();

#if VTK_MAJOR_VERSION_5
                transformFilter.SetInputConnection(polydata.GetProducerPort());
#else
                transformFilter.SetInputData(polydata);
#endif
                transformFilter.SetTransform(transform);
                transformFilter.Update();

                vtkXMLPolyDataWriter writer = vtkXMLPolyDataWriter.New();
                writer.SetFileName(filename);
#if VTK_MAJOR_VERSION_5
                writer.SetInputConnection(transformFilter.GetOutputPort());
#else
                writer.SetInputData(transformFilter);
#endif
                writer.Write();
            }
Beispiel #16
0
        private static void NullPoint()
        {
            vtkPoints points = vtkPoints.New();

            points.InsertNextPoint(1, 1, 1);
            points.InsertNextPoint(2, 2, 2);
            points.InsertNextPoint(3, 3, 3);

            vtkPolyData polydata = vtkPolyData.New();

            polydata.SetPoints(points);

            vtkFloatArray floatArray = vtkFloatArray.New();

            floatArray.SetNumberOfValues(3);
            floatArray.SetNumberOfComponents(1);
            floatArray.SetName("FloatArray");
            for (int i = 0; i < 3; i++)
            {
                floatArray.SetValue(i, 2);
            }
            polydata.GetPointData().AddArray(floatArray);

            vtkIntArray intArray = vtkIntArray.New();

            intArray.SetNumberOfValues(3);
            intArray.SetNumberOfComponents(1);
            intArray.SetName("IntArray");
            for (int i = 0; i < 3; i++)
            {
                intArray.SetValue(i, 2);
            }

            polydata.GetPointData().AddArray(intArray);

            Console.WriteLine("PointIdx   x y z " + "floatArray" + " " + "intArray");
            Console.WriteLine("----------------------------------------");
            for (int i = 0; i < 3; i++)
            {
                double[]      p = polydata.GetPoint(i);
                vtkFloatArray pointsFloatArray = vtkFloatArray.SafeDownCast(polydata.GetPointData().GetArray("FloatArray"));
                vtkIntArray   pointsIntArray   = vtkIntArray.SafeDownCast(polydata.GetPointData().GetArray("IntArray"));
                Console.WriteLine("   " + i + "       " + p[0] + " " + p[1] + " " + p[2] + "    "
                                  + pointsFloatArray.GetValue(i) + "          " + pointsIntArray.GetValue(i));
            }

            polydata.GetPointData().NullPoint(1);
            polydata.Modified();
            Console.WriteLine("");

            for (int i = 0; i < 3; i++)
            {
                double[]      p = polydata.GetPoint(i);
                vtkFloatArray pointsFloatArray = vtkFloatArray.SafeDownCast(polydata.GetPointData().GetArray("FloatArray"));
                vtkIntArray   pointsIntArray   = vtkIntArray.SafeDownCast(polydata.GetPointData().GetArray("IntArray"));
                Console.WriteLine("   " + i + "       " + p[0] + " " + p[1] + " " + p[2] + "    "
                                  + pointsFloatArray.GetValue(i) + "          " + pointsIntArray.GetValue(i));
            }
        }
Beispiel #17
0
        public static void SavePolyData(string filename, vtkPolyData polydata)
        {
            var w = vtkXMLPolyDataWriter.New();

            w.SetInput(polydata);
            w.SetFileName(filename);
            w.Update();
        }
Beispiel #18
0
        public void InitializeFaces()
        {
            vtkCleanPolyData Clean = vtkCleanPolyData.New();

            Clean.SetInputConnection(AppendFaces.GetOutputPort());
            Clean.Update();
            Faces = Clean.GetOutput();
        }
Beispiel #19
0
        public ExtruedActor(ModelType type, ModelingBaseInfo baseinfo)
        {
            m_modelType     = type;
            m_modelBaseInfo = baseinfo;
            vtkPolyData polydata = ModelingFactory.CreateModelingInstance(type, baseinfo);

            ConstructActor(polydata);
        }
Beispiel #20
0
        void Test()
        {
            foreach (var actor in m_actorDict.Keys)
            {
                int xmin    = 0;
                int xlength = 1000;
                int xmax    = xmin + xlength;
                int ymin    = 0;
                int ylength = 1000;
                int ymax    = ymin + ylength;

                int[] pos = { xmin, xmin + xlength, ymin, ymin + ylength };
                #region RECT
                vtkPoints pts = vtkPoints.New();
                pts.InsertPoint(0, xmin, ymin, 0);
                pts.InsertPoint(1, xmax, ymin, 0);
                pts.InsertPoint(2, xmax, ymax, 0);
                pts.InsertPoint(3, xmin, ymax, 0);
                vtkCellArray rect = vtkCellArray.New();
                rect.InsertNextCell(5);
                rect.InsertCellPoint(0);
                rect.InsertCellPoint(1);
                rect.InsertCellPoint(2);
                rect.InsertCellPoint(3);
                rect.InsertCellPoint(0);
                vtkPolyData selectRect = vtkPolyData.New();
                selectRect.SetPoints(pts);
                selectRect.SetLines(rect);
                vtkPolyDataMapper2D rectMapper = vtkPolyDataMapper2D.New();
                rectMapper.SetInput(selectRect);
                vtkActor2D rectActor = vtkActor2D.New();
                rectActor.SetMapper(rectMapper);
                m_render.AddActor(rectActor);
                #endregion
                vtkIdFilter ids = vtkIdFilter.New();
                ids.SetInput(actor.GetMapper().GetInput());
                //ids.SetInputConnection( actor.GetMapper().GetOutputPort());
                ids.PointIdsOn();
                ids.FieldDataOn();

                vtkSelectVisiblePoints visPts = vtkSelectVisiblePoints.New();
                visPts.SetInput(ids.GetOutput());
                visPts.SetRenderer(m_render);
                visPts.SelectInvisibleOn();
                visPts.SelectionWindowOn();
                //visPts.SelectInvisibleOff();
                visPts.SetSelection(pos[0], pos[1], pos[2], pos[3]);

                vtkLabeledDataMapper labelMapper = vtkLabeledDataMapper.New();
                labelMapper.SetInputConnection(visPts.GetOutputPort());
                // labelMapper.SetInput(visPts.GetInput());
                labelMapper.SetLabelModeToLabelFieldData();
                vtkActor2D actor2d = vtkActor2D.New();
                actor2d.SetMapper(labelMapper);
                m_render.AddActor(actor2d);
            }
            m_render.Render();
        }
Beispiel #21
0
        private void CreateViewportBorder(vtkRenderer renderer, double[] color)
        {
            ModelLoaded = false;

            // points start at upper right and proceed anti-clockwise
            vtkPoints points = vtkPoints.New();

            points.SetNumberOfPoints(4);
            points.InsertPoint(0, 1, 1, 0);
            points.InsertPoint(1, 1e-3, 1, 0);
            points.InsertPoint(2, 1e-3, 1e-3, 0);
            points.InsertPoint(3, 1, 1e-3, 0);

            // create cells, and lines
            vtkCellArray cells = vtkCellArray.New();

            cells.Initialize();

            vtkPolyLine lines = vtkPolyLine.New();

            lines.GetPointIds().SetNumberOfIds(5);
            for (int i = 0; i < 4; ++i)
            {
                lines.GetPointIds().SetId(i, i);
            }
            lines.GetPointIds().SetId(4, 0);
            cells.InsertNextCell(lines);

            // now make tge polydata and display it
            vtkPolyData poly = vtkPolyData.New();

            poly.Initialize();
            poly.SetPoints(points);
            poly.SetLines(cells);

            // use normalized viewport coordinates since
            // they are independent of window size
            vtkCoordinate coordinate = vtkCoordinate.New();

            coordinate.SetCoordinateSystemToNormalizedViewport();

            vtkPolyDataMapper2D mapper = vtkPolyDataMapper2D.New();

            mapper.SetInput(poly);
            mapper.SetTransformCoordinate(coordinate);

            vtkActor2D actor = vtkActor2D.New();

            actor.SetMapper(mapper);
            actor.GetProperty().SetColor(color[0], color[1], color[2]);
            // line width should be at least 2 to be visible at extremes

            actor.GetProperty().SetLineWidth((float)2.0); // Line Width

            renderer.AddViewProp(actor);
        }
Beispiel #22
0
        public static vtkActor CreateBulletInstance(ModelType type, ModelingBaseInfo info)
        {//根据传入参数来创建不同的弹体
            vtkActor actor = vtkActor.New();

            try
            {
                switch (type)
                {
                case ModelType.FULL_DEGREE_2D:
                {
                    vtkPolyData polyData = GetBulletSection(info, SECTIONTYPE.SECTION_FULL);        //获取整个截面
                    actor = FormActor2D(polyData, info);
                }
                break;

                case ModelType.HALF_DEGREE_2D:
                {
                    vtkPolyData polyData = GetBulletSection(info, SECTIONTYPE.SECTION_HALF);        //获取一半的截面
                    actor = FormActor2D(polyData, info);
                }
                break;

                case ModelType.DEGREE_360_3D:
                {                                                                            //对截面映射360度,旋转平移
                    vtkPolyData polyData = GetBulletSection(info, SECTIONTYPE.SECTION_HALF); //获取一半的截面
                    actor = FormActor3D(360, polyData, info);
                }
                break;

                case ModelType.DEGREE_180_3D:
                {                                                                            //对截面映射180度
                    vtkPolyData polyData = GetBulletSection(info, SECTIONTYPE.SECTION_HALF); //获取一半的截面
                    actor = FormActor3D(180, polyData, info);
                }
                break;

                case ModelType.DEGREE_90_3D:
                {                                                                            //对截面映射90度
                    vtkPolyData polyData = GetBulletSection(info, SECTIONTYPE.SECTION_HALF); //获取一半的截面
                    actor = FormActor3D(90, polyData, info);
                }
                break;

                default: break;
                }
                //
                //vtkPolyDataMapper mapper = (vtkPolyDataMapper)actor.GetMapper();
                //vtkPolyData polyd = mapper.GetInput();
                //vtkPoints points = polyd.GetPoints();
            }
            catch (Exception e)
            {
                TinyFem.Utils.Logger.WriteLogMessage("BulletFactory:CreateBulletInstance:" + e.Message);
            }
            return(actor);
        }
Beispiel #23
0
        public static void SetColorByImage(vtkPolyData data, vtkImageData image, Rectangle rect)
        {
            for (int i = 0; i < rect.Width * rect.Height; i++)
            {
                float c = image.GetScalarComponentAsFloat(i % rect.Width, i / rect.Width, 0, 0);
                data.GetPointData().GetScalars().SetTuple3(i, c, c, c);
            }

            data.Modified();
        }
        private static void IterateOverLines()
        {
            double[] origin = new double[] { 0.0, 0.0, 0.0 };
            double[,] p = new double[, ] {
                { 1.0, 0.0, 0.0 },
                { 0.0, 1.0, 0.0 },
                { 0.0, 1.0, 2.0 },
                { 1.0, 2.0, 3.0 }
            };

            // Create a vtkPoints object and store the points in it
            vtkPoints points = vtkPoints.New();

            points.InsertNextPoint(origin[0], origin[1], origin[2]);
            for (int i = 0; i < 4; i++)
            {
                points.InsertNextPoint(p[i, 0], p[i, 1], p[i, 2]);
            }

            // Create a cell array to store the lines in and add the lines to it
            vtkCellArray lines = vtkCellArray.New();

            // Create four lines
            for (int i = 0; i < 4; i++)
            {
                vtkLine line = vtkLine.New();
                line.GetPointIds().SetId(0, i);
                line.GetPointIds().SetId(1, i + 1);
                lines.InsertNextCell(line);
            }

            // Create a polydata to store everything in
            vtkPolyData linesPolyData = vtkPolyData.New();

            // Add the points to the dataset
            linesPolyData.SetPoints(points);

            // Add the lines to the dataset
            linesPolyData.SetLines(lines);

            Console.WriteLine("There are " + linesPolyData.GetNumberOfLines() + " lines.");
            linesPolyData.GetLines().InitTraversal();
            vtkIdList idList = vtkIdList.New();

            while (linesPolyData.GetLines().GetNextCell(idList) != 0)
            {
                Console.WriteLine("Line has " + idList.GetNumberOfIds() + " points.");

                for (int pointId = 0; pointId < idList.GetNumberOfIds(); pointId++)
                {
                    Console.Write(idList.GetId(pointId) + " ");
                }
                Console.Write(Environment.NewLine);
            }
        }
Beispiel #25
0
        private void DrawTriangle()
        {
            //创建点数据
            vtkPoints points = vtkPoints.New();

            points.InsertNextPoint(1.0, 0.0, 0.0);
            points.InsertNextPoint(0.0, 1.0, 0.0);
            points.InsertNextPoint(0.0, 0.0, 0.0);

            //每两个坐标之间分别创建一条线
            //SetId()的第一个参数是线段的端点ID,第二参数是连接的的点的ID
            vtkLine line0 = vtkLine.New();

            line0.GetPointIds().SetId(0, 0);
            line0.GetPointIds().SetId(1, 1);

            vtkLine line1 = vtkLine.New();

            line1.GetPointIds().SetId(0, 1);
            line1.GetPointIds().SetId(1, 2);

            vtkLine line2 = vtkLine.New();

            line2.GetPointIds().SetId(0, 2);
            line2.GetPointIds().SetId(1, 0);

            //创建单元数组,用于存储以上创建的线段
            vtkCellArray lines = vtkCellArray.New();

            lines.InsertNextCell(line0);
            lines.InsertNextCell(line1);
            lines.InsertNextCell(line2);

            //将点和线加入数据集中,前者定义数据集的几何结构,后者定义拓扑结构
            //创建vtkPolyData类型的数据,是一种数据集
            vtkPolyData polyData = vtkPolyData.New();

            //将创建的点数据加入vtkPolyData数据里
            polyData.SetPoints(points); //点数据定义了polydata数据集的几何结构。
            polyData.SetLines(lines);   //定义拓扑结构

            //显示数据
            vtkPolyDataMapper mapper = vtkPolyDataMapper.New();

            mapper.SetInputData(polyData);
            vtkActor actor = vtkActor.New();

            actor.SetMapper(mapper);
            actor.GetProperty().SetColor(1.0, 0.0, 0.0);
            vtkRenderWindow renWin   = myRenderWindowControl.RenderWindow;
            vtkRenderer     renderer = renWin.GetRenderers().GetFirstRenderer();

            renderer.SetBackground(1.0, 1.0, 1.0);
            renderer.AddActor(actor);
        }
Beispiel #26
0
        public XmlPolyDataPackage(string vtpFile, vtkRenderer renderer)
        {
            //Console.WriteLine(string.Format("VTP文件 = {0}", vtpFile));

            if (File.Exists(vtpFile))
            {
                if (vtpFile.EndsWith(".vtp"))
                {
                    //Console.WriteLine(string.Format("VTP文件 = {0}已存在", vtpFile));
                    reader = vtkXMLPolyDataReader.New();
                    reader.SetFileName(vtpFile);
                    reader.Update();

                    PolyData = reader.GetOutput();
                }
                else if (vtpFile.EndsWith(".stl"))
                {
                    PolyData = VTKUtil.ReadSTLPolyData(vtpFile);
                }

                vtkCamera camera = vtkCamera.New();

                var sortPolydata = new vtkDepthSortPolyData();
                sortPolydata.SetInput(PolyData);
                sortPolydata.SetCamera(camera);
                sortPolydata.SetDirectionToFrontToBack();
                sortPolydata.SetVector(1, 1, 1);
                sortPolydata.SetSortScalars(1);
                sortPolydata.Update();

                _polyDataMapper = vtkPolyDataMapper.New();
                _polyDataMapper.ScalarVisibilityOff();
                _polyDataMapper.SetInput(sortPolydata.GetOutput());
                _polyDataMapper.Update();

                actor = vtkActor.New();
                actor.SetMapper(_polyDataMapper);
                actor.GetProperty().SetColor(1, 1, 1);

                //marchingCubeActor.GetProperty().BackfaceCullingOn();
                //marchingCubeActor.GetProperty().FrontfaceCullingOn();
                //marchingCubeActor.GetProperty().BackfaceCullingOff();

                // now, tell the renderer our actors
                renderer.AddActor(actor);

                this.renderer = renderer;
            }
            else
            {
                throw new Exception(string.Format("VTP文件 = {0}不存在。", vtpFile));
            }

            //正面观();
        }
Beispiel #27
0
        private void PolyLine()
        {
            // Create five points
            double[,] p = new double[, ] {
                { 0.0, 0.0, 0.0 },
                { 1.0, 0.0, 0.0 },
                { 0.0, 1.0, 0.0 },
                { 0.0, 1.0, 2.0 },
                { 0.0, 3.0, 3.0 }
            };

            // Create the points
            vtkPoints points = vtkPoints.New();

            for (int i = 0; i < 5; i++)
            {
                points.InsertNextPoint(p[i, 0], p[i, 1], p[i, 2]);
            }


            vtkPolyLine polyLine = vtkPolyLine.New();

            polyLine.GetPointIds().SetNumberOfIds(5);
            for (int i = 0; i < 5; i++)
            {
                polyLine.GetPointIds().SetId(i, i);
            }

            // Create a cell array to store the lines in and add the lines to it
            vtkCellArray cells = vtkCellArray.New();

            cells.InsertNextCell(polyLine);

            // Create a polydata to store everything in
            vtkPolyData polyData = vtkPolyData.New();

            // Add the points to the dataset
            polyData.SetPoints(points);

            // Add the lines to the dataset
            polyData.SetLines(cells);
            //Create an actor and mapper
            vtkPolyDataMapper mapper = vtkPolyDataMapper.New();

            mapper.SetInput(polyData);
            vtkActor actor = vtkActor.New();

            actor.SetMapper(mapper);
            vtkRenderWindow renderWindow = renderWindowControl1.RenderWindow;
            vtkRenderer     renderer     = renderWindow.GetRenderers().GetFirstRenderer();

            renderer.SetBackground(0.2, 0.3, 0.4);
            renderer.AddActor(actor);
        }
Beispiel #28
0
        /// <summary>
        /// 进行三维结构的转换
        /// </summary>
        /// <param name="degree"></param>
        /// <param name="polyData"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        private static vtkActor FormActor3D(float degree, vtkPolyData polyData, ModelingBaseInfo info)
        {//旋转拉伸一个截面, 先绕Z拉伸后旋转一定攻角,再平移
            vtkActor actor = vtkActor.New();

            vtkPolyData       polydata = Extrude3DSection(degree, polyData, info);
            vtkPolyDataMapper mapper   = vtkPolyDataMapper.New();

            mapper.SetInput(polyData);
            actor.SetMapper(mapper);
            return(actor);
        }
        public static List <double[]> ReadPolyDataPoints(this vtkPolyData polyData)
        {
            List <double[]> ret = new List <double[]>();

            for (int i = 0; i < polyData.GetNumberOfPoints(); ++i)
            {
                ret.Add(polyData.GetPoint(i));
            }

            return(ret);
        }
Beispiel #30
0
        /// <summary>
        /// Crée un acteur pour l'objet fourni et l'ajoute au renderer
        /// </summary>
        /// <param name="polydata"></param>
        private void addActor(vtkPolyData polydata)
        {
            vtkPolyDataMapper mapper = vtkPolyDataMapper.New();

            mapper.SetInput(polydata);

            vtkActor act = vtkActor.New();

            act.SetMapper(mapper);

            _renderer.AddActor(act);
        }
Beispiel #31
0
 public void Update(vtkPolyData pd)
 {
     _pds = Subdivide(pd);
     Meshes = new List<Mesh>(_pds.Count);
     foreach (var subPd in _pds)
     {
         var subMesh = PolyDataToMesh(subPd);
         if (subMesh == null)
         {
             Debug.LogWarning("Submesh null!");
             continue;
         }
         Meshes.Add(subMesh);
     }
 }
        private static void FindAllData(ref vtkPolyData polydata)
        {
            Console.WriteLine("Normals: " + polydata.GetPointData().GetNormals());

             int numberOfPointArrays = polydata.GetPointData().GetNumberOfArrays();
             Console.WriteLine("Number of PointData arrays: " + numberOfPointArrays);

             int numberOfCellArrays = polydata.GetCellData().GetNumberOfArrays();
             Console.WriteLine("Number of CellData arrays: " + numberOfCellArrays);

             Console.WriteLine(
            Environment.NewLine +
            "Type table/key: " +
            Environment.NewLine +
            "-------------------------");
             //more values can be found in <VTK_DIR>/Common/vtkSetGet.h

             Console.WriteLine(3 + " unsigned char");
             Console.WriteLine(7 + " unsigned int");
             Console.WriteLine(10 + " float");
             Console.WriteLine(11 + " double" + Environment.NewLine);

             for(int i = 0; i < numberOfPointArrays; i++) {
            // The following two lines are equivalent
            //arrayNames.push_back(polydata.GetPointData().GetArray(i).GetName());
            //arrayNames.push_back(polydata.GetPointData().GetArrayName(i));
            int dataTypeID = polydata.GetPointData().GetArray(i).GetDataType();
            string dataTypeAsString = polydata.GetPointData().GetArray(i).GetDataTypeAsString();
            Console.WriteLine("Array " + i + ": "
               + polydata.GetPointData().GetArrayName(i)
               + " (type: " + dataTypeID + ")"
               + " (type as string: " + dataTypeAsString + ")" + Environment.NewLine);
             }

             for(int i = 0; i < numberOfCellArrays; i++) {
            // The following two lines are equivalent
            //polydata.GetPointData().GetArray(i).GetName();
            //polydata.GetPointData().GetArrayName(i);
            int dataTypeID = polydata.GetCellData().GetArray(i).GetDataType();
            string dataTypeAsString = polydata.GetPointData().GetArray(i).GetDataTypeAsString();
            Console.WriteLine("Array " + i + ": "
               + polydata.GetCellData().GetArrayName(i)
               + " (type: " + dataTypeID + ")"
               + " (type as string: " + dataTypeAsString + ")");
             }
        }
Beispiel #33
0
        public VTKDataModel(SimulationModel sm)
        {
            simModel = sm;

            int numCells = sm.Cells.Count;

            cellIDs = vtkIntArray.New();
            cellIDs.SetNumberOfComponents(1);
            cellIDs.SetNumberOfValues(numCells);
            cellIDs.SetName(cellIdsArrayName);

            cellTypes = vtkIntArray.New();
            cellTypes.SetNumberOfComponents(1);
            cellTypes.SetNumberOfValues(numCells);
            cellTypes.SetName(cellTypeArrayName);

            points = vtkPoints.New();
            points.SetNumberOfPoints(numCells);

            verts = vtkCellArray.New();
            verts.Allocate(verts.EstimateSize(1, numCells), 1000);
            verts.InsertNextCell(numCells);

            foreach (MotileCell cell in sm.Cells)
            {
                int i = cell.CellId;
                int c = cell.CellType;
                double[] p = cell.Position;
                points.SetPoint(i, p[0], p[1], p[2]);
                cellIDs.SetValue(i, i);
                cellTypes.SetValue(i, c);
                verts.InsertCellPoint(i);
            }

            poly = vtkPolyData.New();
            poly.SetPoints(points);
            poly.SetVerts(verts);
            poly.GetPointData().AddArray(cellIDs);
            poly.GetPointData().AddArray(cellTypes);
        }
    /// <summary>
    /// Entry Point
    /// </summary>
    /// <param name="argv"></param>
    public static void Main(String[] argv)
    {
        // This example demonstrates how to use the vtkLineWidget to seed
        // and manipulate streamlines. Two line widgets are created. One is
        // invoked by pressing 'W', the other by pressing 'L'. Both can exist
        // together.
        // Start by loading some data.
        pl3d = vtkMultiBlockPLOT3DReader.New();
        pl3d.SetXYZFileName("../../../combxyz.bin");
        pl3d.SetQFileName("../../../combq.bin");
        pl3d.SetScalarFunctionNumber(100);
        pl3d.SetVectorFunctionNumber(202);
        pl3d.Update();
        // The line widget is used seed the streamlines.
        lineWidget = vtkLineWidget.New();
        seeds = vtkPolyData.New();

        lineWidget.SetInput(pl3d.GetOutput());
        lineWidget.SetAlignToYAxis();
        lineWidget.PlaceWidget();
        lineWidget.GetPolyData(seeds);
        lineWidget.ClampToBoundsOn();

        rk4 = vtkRungeKutta4.New();
        streamer = vtkStreamLine.New();
        streamer.SetInputData((vtkDataSet)pl3d.GetOutput().GetBlock(0));
        streamer.SetSource(seeds);
        streamer.SetMaximumPropagationTime(100);
        streamer.SetIntegrationStepLength(.2);
        streamer.SetStepLength(.001);
        streamer.SetNumberOfThreads(1);
        streamer.SetIntegrationDirectionToForward();
        streamer.VorticityOn();
        streamer.SetIntegrator(rk4);

        rf = vtkRibbonFilter.New();
        rf.SetInputConnection(streamer.GetOutputPort());
        rf.SetWidth(0.1);
        rf.SetWidthFactor(5);

        streamMapper = vtkPolyDataMapper.New();
        streamMapper.SetInputConnection(rf.GetOutputPort());
        streamMapper.SetScalarRange(pl3d.GetOutput().GetScalarRange()[0], pl3d.GetOutput().GetScalarRange()[1]);
        streamline = vtkActor.New();
        streamline.SetMapper(streamMapper);
        streamline.VisibilityOff();

        // The second line widget is used seed more streamlines.
        lineWidget2 = vtkLineWidget.New();
        seeds2 = vtkPolyData.New();
        lineWidget2.SetInput(pl3d.GetOutput());
        lineWidget2.PlaceWidget();
        lineWidget2.GetPolyData(seeds2);
        lineWidget2.SetKeyPressActivationValue((sbyte)108);

        streamer2 = vtkStreamLine.New();
        streamer2.SetInputDaat((vtkDataSet)pl3d.GetOutput().GetBlock(0));
        streamer2.SetSource(seeds2);
        streamer2.SetMaximumPropagationTime(100);
        streamer2.SetIntegrationStepLength(.2);
        streamer2.SetStepLength(.001);
        streamer2.SetNumberOfThreads(1);
        streamer2.SetIntegrationDirectionToForward();
        streamer2.VorticityOn();
        streamer2.SetIntegrator(rk4);

        rf2 = vtkRibbonFilter.New();
        rf2.SetInputConnection(streamer2.GetOutputPort());
        rf2.SetWidth(0.1);
        rf2.SetWidthFactor(5);

        streamMapper2 = vtkPolyDataMapper.New();
        streamMapper2.SetInputConnection(rf2.GetOutputPort());
        streamMapper2.SetScalarRange(pl3d.GetOutput().GetScalarRange()[0], pl3d.GetOutput().GetScalarRange()[1]);

        streamline2 = vtkActor.New();
        streamline2.SetMapper(streamMapper2);
        streamline2.VisibilityOff();

        outline = vtkStructuredGridOutlineFilter.New();
        outline.SetInputData((vtkDataSet)pl3d.GetOutput().GetBlock(0));

        outlineMapper = vtkPolyDataMapper.New();
        outlineMapper.SetInputConnection(outline.GetOutputPort());
        outlineActor = vtkActor.New();
        outlineActor.SetMapper(outlineMapper);

        // Create the RenderWindow, Renderer and both Actors
        ren1 = vtkRenderer.New();
        renWin = vtkRenderWindow.New();
        renWin.AddRenderer(ren1);
        iren = vtkRenderWindowInteractor.New();
        iren.SetRenderWindow(renWin);

        // Associate the line widget with the interactor
        lineWidget.SetInteractor(iren);
        lineWidget.StartInteractionEvt += new vtkObject.vtkObjectEventHandler(BeginInteraction);
        lineWidget.InteractionEvt += new vtkObject.vtkObjectEventHandler(GenerateStreamlines);
        lineWidget2.SetInteractor(iren);
        lineWidget2.StartInteractionEvt += new vtkObject.vtkObjectEventHandler(BeginInteraction2);
        lineWidget2.EndInteractionEvt += new vtkObject.vtkObjectEventHandler(GenerateStreamlines2);

        // Add the actors to the renderer, set the background and size
        ren1.AddActor(outlineActor);
        ren1.AddActor(streamline);
        ren1.AddActor(streamline2);

        ren1.SetBackground(1, 1, 1);
        renWin.SetSize(300, 300);
        ren1.SetBackground(0.1, 0.2, 0.4);

        cam1 = ren1.GetActiveCamera();
        cam1.SetClippingRange(3.95297, 50);
        cam1.SetFocalPoint(9.71821, 0.458166, 29.3999);
        cam1.SetPosition(2.7439, -37.3196, 38.7167);
        cam1.SetViewUp(-0.16123, 0.264271, 0.950876);

        // render the image
        renWin.Render();
        lineWidget2.On();
        iren.Initialize();
        iren.Start();

        //Clean Up
        deleteAllVTKObjects();
    }
 ///<summary> A Set Method for Static Variables </summary>
 public static void SetTubes(vtkPolyData[] toSet)
 {
     Tubes = toSet;
 }
    /// <summary>
    /// The main entry method called by the CSharp driver
    /// </summary>
    /// <param name="argv"></param>
    public static void AVTestRectilinearGridToTetrahedra(String[] argv)
    {
        //Prefix Content is: ""

        //## SetUp the pipeline[]
        FormMesh = new vtkRectilinearGridToTetrahedra();
        FormMesh.SetInput((double)4, (double)2, (double)2, (double)1, (double)1, (double)1, (double)0.001);
        FormMesh.RememberVoxelIdOn();
        TetraEdges = new vtkExtractEdges();
        TetraEdges.SetInputConnection((vtkAlgorithmOutput)FormMesh.GetOutputPort());
        tubes = new vtkTubeFilter();
        tubes.SetInputConnection((vtkAlgorithmOutput)TetraEdges.GetOutputPort());
        tubes.SetRadius((double)0.05);
        tubes.SetNumberOfSides((int)6);
        //## Run the pipeline 3 times, with different conversions to TetMesh[]
        Tubes[0] = new vtkPolyData();
        FormMesh.SetTetraPerCellTo5();
        tubes.Update();
        Tubes[0].DeepCopy((vtkDataObject)tubes.GetOutput());
        Tubes[1] = new vtkPolyData();
        FormMesh.SetTetraPerCellTo6();
        tubes.Update();
        Tubes[1].DeepCopy((vtkDataObject)tubes.GetOutput());
        Tubes[2] = new vtkPolyData();
        FormMesh.SetTetraPerCellTo12();
        tubes.Update();
        Tubes[2].DeepCopy((vtkDataObject)tubes.GetOutput());
        //## Run the pipeline once more, this time converting some cells to[]
        //## 5 and some data to 12 TetMesh[]
        //## Determine which cells are which[]

        DivTypes = new vtkIntArray();
        numCell = (long)((vtkDataSet)FormMesh.GetInput()).GetNumberOfCells();
        DivTypes.SetNumberOfValues((int)numCell);

        i = 0;
        while ((i) < numCell)
        {
            DivTypes.SetValue((int)i, (int)5 + (7 * (i % 4)));
            i = i + 1;
        }

        //## Finish this pipeline[]
        Tubes[3] = new vtkPolyData();
        FormMesh.SetTetraPerCellTo5And12();
        ((vtkRectilinearGrid)FormMesh.GetInput()).GetCellData().SetScalars(DivTypes);
        tubes.Update();
        Tubes[3].DeepCopy((vtkDataObject)tubes.GetOutput());
        //## Finish the 4 pipelines[]
        i = 1;
        while ((i) < 5)
        {
            mapEdges[i] = vtkPolyDataMapper.New();
            mapEdges[i].SetInputData((vtkPolyData)Tubes[i - 1]);
            edgeActor[i] = new vtkActor();
            edgeActor[i].SetMapper((vtkMapper)mapEdges[i]);
            edgeActor[i].GetProperty().SetColor((double)0.2000, 0.6300, 0.7900);
            edgeActor[i].GetProperty().SetSpecularColor((double)1, (double)1, (double)1);
            edgeActor[i].GetProperty().SetSpecular((double)0.3);
            edgeActor[i].GetProperty().SetSpecularPower((double)20);
            edgeActor[i].GetProperty().SetAmbient((double)0.2);
            edgeActor[i].GetProperty().SetDiffuse((double)0.8);
            ren[i] = vtkRenderer.New();
            ren[i].AddActor((vtkProp)edgeActor[i]);
            ren[i].SetBackground((double)0, (double)0, (double)0);
            ren[i].ResetCamera();
            ren[i].GetActiveCamera().Zoom((double)1);
            ren[i].GetActiveCamera().SetPosition((double)1.73906, (double)12.7987, (double)-0.257808);
            ren[i].GetActiveCamera().SetViewUp((double)0.992444, (double)0.00890284, (double)-0.122379);
            ren[i].GetActiveCamera().SetClippingRange((double)9.36398, (double)15.0496);
            i = i + 1;
        }

        // Create graphics objects[]
        // Create the rendering window, renderer, and interactive renderer[]
        renWin = vtkRenderWindow.New();
        renWin.AddRenderer(ren[1]);
        renWin.AddRenderer(ren[2]);
        renWin.AddRenderer(ren[3]);
        renWin.AddRenderer(ren[4]);
        renWin.SetSize(600, 300);
        iren = new vtkRenderWindowInteractor();
        iren.SetRenderWindow((vtkRenderWindow)renWin);
        // Add the actors to the renderer, set the background and size[]
        ren[1].SetViewport((double).75, (double)0, (double)1, (double)1);
        ren[2].SetViewport((double).50, (double)0, (double).75, (double)1);
        ren[3].SetViewport((double).25, (double)0, (double).50, (double)1);
        ren[4].SetViewport((double)0, (double)0, (double).25, (double)1);
        // render the image[]
        //[]
        iren.Initialize();
        // prevent the tk window from showing up then start the event loop[]

        //deleteAllVTKObjects();
    }
 ///<summary> A Set Method for Static Variables </summary>
 public static void Setpd(vtkPolyData[] toSet)
 {
     pd = toSet;
 }
    /// <summary>
    /// The main entry method called by the CSharp driver
    /// </summary>
    /// <param name="argv"></param>
    public static void AVmultipleIso(String [] argv)
    {
        //Prefix Content is: ""

          // get the interactor ui[]
          //# Graphics stuff[]
          // Create the RenderWindow, Renderer and both Actors[]
          //[]
          ren1 = vtkRenderer.New();
          renWin = vtkRenderWindow.New();
          renWin.AddRenderer((vtkRenderer)ren1);
          iren = new vtkRenderWindowInteractor();
          iren.SetRenderWindow((vtkRenderWindow)renWin);
          pl3d = new vtkPLOT3DReader();
          pl3d.SetXYZFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/combxyz.bin");
          pl3d.SetQFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/combq.bin");
          pl3d.SetScalarFunctionNumber((int)100);
          pl3d.SetVectorFunctionNumber((int)202);
          pl3d.Update();
          range = pl3d.GetOutput().GetPointData().GetScalars().GetRange();
          min = (double)(lindex(range,0));
          max = (double)(lindex(range,1));
          value = (min+max)/2.0;
          cf = new vtkContourFilter();
          cf.SetInputConnection((vtkAlgorithmOutput)pl3d.GetOutputPort());
          cf.SetValue((int)0,(double)value);
          cf.UseScalarTreeOn();
          numberOfContours = 5;
          epsilon = (double)(max-min)/(double)(numberOfContours*10);
          min = min+epsilon;
          max = max-epsilon;
          i = 1;
          while((i) <= numberOfContours)
        {
          cf.SetValue((int)0,(double)min+((i-1)/(double)(numberOfContours-1))*(max-min));
          cf.Update();
          pd[i] = new vtkPolyData();
          pd[i].CopyStructure((vtkDataSet)cf.GetOutput());
          pd[i].GetPointData().DeepCopy((vtkFieldData)cf.GetOutput().GetPointData());
          mapper[i] = vtkPolyDataMapper.New();
          mapper[i].SetInput((vtkPolyData)pd[i]);
          mapper[i].SetScalarRange((double)((vtkDataSet)pl3d.GetOutput()).GetPointData().GetScalars().GetRange()[0],
          (double)((vtkDataSet)pl3d.GetOutput()).GetPointData().GetScalars().GetRange()[1]);
          actor[i] = new vtkActor();
          actor[i].AddPosition((double)0,(double)i*12,(double)0);
          actor[i].SetMapper((vtkMapper)mapper[i]);
          ren1.AddActor((vtkProp)actor[i]);
          i = i + 1;
        }

          // Add the actors to the renderer, set the background and size[]
          //[]
          ren1.SetBackground((double).3,(double).3,(double).3);
          renWin.SetSize((int)450,(int)150);
          cam1 = ren1.GetActiveCamera();
          ren1.GetActiveCamera().SetPosition((double)-36.3762,(double)32.3855,(double)51.3652);
          ren1.GetActiveCamera().SetFocalPoint((double)8.255,(double)33.3861,(double)29.7687);
          ren1.GetActiveCamera().SetViewAngle((double)30);
          ren1.GetActiveCamera().SetViewUp((double)0,(double)0,(double)1);
          ren1.ResetCameraClippingRange();
          iren.Initialize();
          // render the image[]
          //[]
          // prevent the tk window from showing up then start the event loop[]

        //deleteAllVTKObjects();
    }
    /// <summary>
    /// The main entry method called by the CSharp driver
    /// </summary>
    /// <param name="argv"></param>
    public static void AVclosedSplines(String [] argv)
    {
        //Prefix Content is: ""

          // get the interactor ui[]
          // Now create the RenderWindow, Renderer and Interactor[]
          //[]
          ren1 = vtkRenderer.New();
          renWin = vtkRenderWindow.New();
          renWin.AddRenderer((vtkRenderer)ren1);
          iren = new vtkRenderWindowInteractor();
          iren.SetRenderWindow((vtkRenderWindow)renWin);
          math = new vtkMath();
          numberOfInputPoints = 30;
          aKSplineX = new vtkKochanekSpline();
          aKSplineX.ClosedOn();
          aKSplineY = new vtkKochanekSpline();
          aKSplineY.ClosedOn();
          aKSplineZ = new vtkKochanekSpline();
          aKSplineZ.ClosedOn();
          aCSplineX = new vtkCardinalSpline();
          aCSplineX.ClosedOn();
          aCSplineY = new vtkCardinalSpline();
          aCSplineY.ClosedOn();
          aCSplineZ = new vtkCardinalSpline();
          aCSplineZ.ClosedOn();
          // add some points[]
          inputPoints = new vtkPoints();
          x = -1.0;
          y = -1.0;
          z = 0.0;
          aKSplineX.AddPoint((double)0,(double)x);
          aKSplineY.AddPoint((double)0,(double)y);
          aKSplineZ.AddPoint((double)0,(double)z);
          aCSplineX.AddPoint((double)0,(double)x);
          aCSplineY.AddPoint((double)0,(double)y);
          aCSplineZ.AddPoint((double)0,(double)z);
          inputPoints.InsertPoint((int)0,(double)x,(double)y,(double)z);
          x = 1.0;
          y = -1.0;
          z = 0.0;
          aKSplineX.AddPoint((double)1,(double)x);
          aKSplineY.AddPoint((double)1,(double)y);
          aKSplineZ.AddPoint((double)1,(double)z);
          aCSplineX.AddPoint((double)1,(double)x);
          aCSplineY.AddPoint((double)1,(double)y);
          aCSplineZ.AddPoint((double)1,(double)z);
          inputPoints.InsertPoint((int)1,(double)x,(double)y,(double)z);
          x = 1.0;
          y = 1.0;
          z = 0.0;
          aKSplineX.AddPoint((double)2,(double)x);
          aKSplineY.AddPoint((double)2,(double)y);
          aKSplineZ.AddPoint((double)2,(double)z);
          aCSplineX.AddPoint((double)2,(double)x);
          aCSplineY.AddPoint((double)2,(double)y);
          aCSplineZ.AddPoint((double)2,(double)z);
          inputPoints.InsertPoint((int)2,(double)x,(double)y,(double)z);
          x = -1.0;
          y = 1.0;
          z = 0.0;
          aKSplineX.AddPoint((double)3,(double)x);
          aKSplineY.AddPoint((double)3,(double)y);
          aKSplineZ.AddPoint((double)3,(double)z);
          aCSplineX.AddPoint((double)3,(double)x);
          aCSplineY.AddPoint((double)3,(double)y);
          aCSplineZ.AddPoint((double)3,(double)z);
          inputPoints.InsertPoint((int)3,(double)x,(double)y,(double)z);
          inputData = new vtkPolyData();
          inputData.SetPoints((vtkPoints)inputPoints);
          balls = new vtkSphereSource();
          balls.SetRadius((double).04);
          balls.SetPhiResolution((int)10);
          balls.SetThetaResolution((int)10);
          glyphPoints = new vtkGlyph3D();
          glyphPoints.SetInput((vtkDataObject)inputData);
          glyphPoints.SetSource((vtkPolyData)balls.GetOutput());
          glyphMapper = vtkPolyDataMapper.New();
          glyphMapper.SetInputConnection((vtkAlgorithmOutput)glyphPoints.GetOutputPort());
          glyph = new vtkActor();
          glyph.SetMapper((vtkMapper)glyphMapper);
          glyph.GetProperty().SetDiffuseColor((double) 1.0000, 0.3882, 0.2784 );
          glyph.GetProperty().SetSpecular((double).3);
          glyph.GetProperty().SetSpecularPower((double)30);
          ren1.AddActor((vtkProp)glyph);
          Kpoints = new vtkPoints();
          Cpoints = new vtkPoints();
          profileKData = new vtkPolyData();
          profileCData = new vtkPolyData();
          numberOfInputPoints = 5;
          numberOfOutputPoints = 100;
          offset = 1.0;
          //method moved
          fit();
          lines = new vtkCellArray();
          lines.InsertNextCell((int)numberOfOutputPoints);
          i = 0;
          while((i) < numberOfOutputPoints)
        {
          lines.InsertCellPoint((int)i);
          i = i + 1;
        }

          profileKData.SetPoints((vtkPoints)Kpoints);
          profileKData.SetLines((vtkCellArray)lines);
          profileCData.SetPoints((vtkPoints)Cpoints);
          profileCData.SetLines((vtkCellArray)lines);
          profileKTubes = new vtkTubeFilter();
          profileKTubes.SetNumberOfSides((int)8);
          profileKTubes.SetInput((vtkDataObject)profileKData);
          profileKTubes.SetRadius((double).01);
          profileKMapper = vtkPolyDataMapper.New();
          profileKMapper.SetInputConnection((vtkAlgorithmOutput)profileKTubes.GetOutputPort());
          profileK = new vtkActor();
          profileK.SetMapper((vtkMapper)profileKMapper);
          profileK.GetProperty().SetDiffuseColor((double) 0.8900, 0.8100, 0.3400 );
          profileK.GetProperty().SetSpecular((double).3);
          profileK.GetProperty().SetSpecularPower((double)30);
          ren1.AddActor((vtkProp)profileK);
          profileCTubes = new vtkTubeFilter();
          profileCTubes.SetNumberOfSides((int)8);
          profileCTubes.SetInput((vtkDataObject)profileCData);
          profileCTubes.SetRadius((double).01);
          profileCMapper = vtkPolyDataMapper.New();
          profileCMapper.SetInputConnection((vtkAlgorithmOutput)profileCTubes.GetOutputPort());
          profileC = new vtkActor();
          profileC.SetMapper((vtkMapper)profileCMapper);
          profileC.GetProperty().SetDiffuseColor((double) 0.2000, 0.6300, 0.7900 );
          profileC.GetProperty().SetSpecular((double).3);
          profileC.GetProperty().SetSpecularPower((double)30);
          ren1.AddActor((vtkProp)profileC);
          ren1.ResetCamera();
          ren1.GetActiveCamera().Dolly((double)1.5);
          ren1.ResetCameraClippingRange();
          renWin.SetSize((int)300,(int)300);
          // render the image[]
          //[]
          iren.Initialize();
          // prevent the tk window from showing up then start the event loop[]
          //method moved
          //method moved
          //method moved
          //method moved
          //method moved
          //method moved

        //deleteAllVTKObjects();
    }
Beispiel #40
0
        /// <summary>
        /// Generates a Unity Mesh from a vtkPolyData.
        /// </summary>
        /// <param name="pd">The vtk poly data.</param>
        /// <returns>The Unity Mesh (without colors).</returns>
        private static Mesh PolyDataToMesh(vtkPolyData pd)
        {
            if (pd == null)
            {
                Debug.LogWarning("No PolyData passed!");
                return null;
            }

            var numVertices = pd.GetNumberOfPoints();
            if (numVertices == 0)
            {
                Debug.LogWarning("No vertices to convert!");
                return null;
            }

            var mesh = new Mesh();

            // Points / Vertices
            var vertices = new Vector3[numVertices];
            for (var i = 0; i < numVertices; ++i)
            {
                var pnt = pd.GetPoint(i);
                // Flip z-up to y-up
                vertices[i] = new Vector3(-(float) pnt[0], (float) pnt[2], (float) pnt[1]);
            }
            mesh.vertices = vertices;

            // Normals
            var vtkNormals = pd.GetPointData().GetNormals();
            if (vtkNormals != null)
            {
                var numNormals = vtkNormals.GetNumberOfTuples();
                var normals = new Vector3[numNormals];
                for (var i = 0; i < numNormals; i++)
                {
                    var normal = vtkNormals.GetTuple3(i);
                    // flip normals ?
                    normals[i] = new Vector3(-(float) normal[0], -(float) normal[1], -(float) normal[2]);
                }
                mesh.normals = normals;
            }
            else
            {
                Debug.Log("No Normals!");
            }

            // Texture coordinates
            var vtkTexCoords = pd.GetPointData().GetTCoords();
            if (vtkTexCoords != null)
            {
                var numCoords = vtkTexCoords.GetNumberOfTuples();
                var uvs = new Vector2[numCoords];
                for (var i = 0; i < numCoords; ++i)
                {
                    var texCoords = vtkTexCoords.GetTuple2(i);
                    uvs[i] = new Vector2((float) texCoords[0], (float) texCoords[1]);
                }
                mesh.uv = uvs;
            }

            // Triangles / Cells
            var numTriangles = pd.GetNumberOfPolys();
            var polys = pd.GetPolys();
            if (polys.GetNumberOfCells() > 0)
            {
                var triangles = new int[numTriangles*3];
                var prim = 0;
                var pts = vtkIdList.New();
                polys.InitTraversal();
                while (polys.GetNextCell(pts) != 0)
                {
                    for (var i = 0; i < pts.GetNumberOfIds(); ++i)
                        triangles[prim*3 + i] = pts.GetId(i);

                    ++prim;
                }
                mesh.SetTriangles(triangles, 0);
                //Mesh.RecalculateNormals();
                mesh.RecalculateBounds();
                return mesh;
            }

            // Lines
            var lines = pd.GetLines();
            if (lines.GetNumberOfCells() > 0)
            {
                var idList = new ArrayList();
                var pts = vtkIdList.New();
                lines.InitTraversal();
                while (lines.GetNextCell(pts) != 0)
                {
                    for (var i = 0; i < pts.GetNumberOfIds() - 1; ++i)
                    {
                        idList.Add(pts.GetId(i));
                        idList.Add(pts.GetId(i + 1));
                    }
                }

                mesh.SetIndices(idList.ToArray(typeof (int)) as int[], MeshTopology.Lines, 0);
                mesh.RecalculateBounds();
                return mesh;
            }

            // Points
            var points = pd.GetVerts();
            var numPointCells = points.GetNumberOfCells();
            if (numPointCells > 0)
            {
                var idList = new ArrayList();
                var pts = vtkIdList.New();
                points.InitTraversal();
                while (points.GetNextCell(pts) != 0)
                {
                    for (int i = 0; i < pts.GetNumberOfIds(); ++i)
                    {
                        idList.Add(pts.GetId(i));
                    }
                }

                mesh.SetIndices(idList.ToArray(typeof (int)) as int[], MeshTopology.Points, 0);
                mesh.RecalculateBounds();
            }

            return mesh;
        }
Beispiel #41
0
        protected virtual void Initialize()
        {
            //InitAlgorithmModifiedEvent();

            if (_vtkMesh == null)
                _vtkMesh = new VtkMesh();
            if (_gameObject == null)
            {
                _gameObject = new GameObject(Name);
                _gameObject.transform.parent = transform;
                _gameObject.transform.localPosition = new Vector3();
            //				_gameObject.AddComponent<MeshFilter>();
            //				var meshRenderer = _gameObject.AddComponent<MeshRenderer>();
            }

            if (_triangleFilter == null)
                _triangleFilter = vtkTriangleFilter.New();

            if (_polyDataOutput == null)
                _polyDataOutput = _triangleFilter.GetOutput();
        }
Beispiel #42
0
        /// <summary>
        /// Subdivides a vtkPolyData into pieces containing max. MaxVertices.
        /// </summary>
        /// <param name="pd">The pd.</param>
        /// <returns>A list of vtkPolyData</returns>
        private static List<vtkPolyData> Subdivide(vtkPolyData pd)
        {
            var pds = new List<vtkPolyData>();
            if (pd.GetNumberOfPoints() <= MaxVertices)
            {
            //				Debug.Log("No subdivide neccessary. " + pd.GetNumberOfPoints());
                pds.Add(pd);
                return pds;
            }

            var dicer = vtkOBBDicer.New();
            dicer.SetInput(pd);
            dicer.SetNumberOfPointsPerPiece(MaxVertices);
            dicer.SetDiceModeToNumberOfPointsPerPiece();
            dicer.Update();
            //			Debug.Log("Subdivided into " + dicer.GetNumberOfActualPieces() + " pieces.");

            var threshold = vtkThreshold.New();
            pd = vtkPolyData.SafeDownCast(dicer.GetOutput());
            threshold.SetInput(pd);
            threshold.SetInputArrayToProcess(0, 0, 0,
                (int)vtkDataObject.FieldAssociations.FIELD_ASSOCIATION_POINTS,
                "vtkOBBDicer_GroupIds");
            var geometry = vtkGeometryFilter.New();
            geometry.SetInputConnection(threshold.GetOutputPort());

            for(var i = 0; i < dicer.GetNumberOfActualPieces(); i++)
            {
                threshold.ThresholdBetween(i, i);
                geometry.Update();
                // Last submesh needs not to be copied
                if (i == dicer.GetNumberOfActualPieces() - 1)
                    pds.Add(geometry.GetOutput());
                else
                {
                    var copiedOutput = new vtkPolyData();
                    copiedOutput.DeepCopy(geometry.GetOutput());
                    pds.Add(copiedOutput);
                }
            }

            return pds;
        }
Beispiel #43
0
        private void UpdateVtk(VtkAlgorithm algorithm, tkDefaultContext context)
        {
            if (!IsInitialized())
                return;
            if (_input)
            {
                _algorithm.SetInputConnection(_input.Algorithm.GetOutputPort());
                _input.UpdateVtk(_input, null);
            }

            if (_triangleFilter == null || _algorithm == null || _vtkMesh == null ||
                _gameObject == null)
                return;
            _algorithm.Update();
            _output = (vtkDataSet)_algorithm.GetOutputDataObject(0);
            // Input connection has to be set here because _algorithm address changes somehow
            // because of FullInspector serialization
            if (OutputDataDataType != DataType.vtkPolyData)
            {
                if (_geometryFilter == null)
                    _geometryFilter = vtkGeometryFilter.New();
                //_geometryFilter.MergingOff();
                _geometryFilter.SetInputConnection(_algorithm.GetOutputPort());
                _triangleFilter.SetInputConnection(_geometryFilter.GetOutputPort());
            }
            else
                _triangleFilter.SetInputConnection(_algorithm.GetOutputPort());
            _triangleFilter.PassVertsOn();
            _triangleFilter.PassLinesOn();
            _triangleFilter.Update();
            _polyDataOutput = _triangleFilter.GetOutput();

            if (_polyDataOutput == null ||
                _polyDataOutput.GetNumberOfPoints() == 0 ||
                _polyDataOutput.GetNumberOfCells() == 0)
            {
                // Debug.Log("Polydata output empty!");
                return;
            }

            if (GenerateNormals && !VtkNormalsHelper.GetPointNormals(_polyDataOutput))
            {
                if (_normalsFilter == null)
                    _normalsFilter = vtkPolyDataNormals.New();
                _normalsFilter.SetInputConnection(_triangleFilter.GetOutputPort());
                _normalsFilter.ComputePointNormalsOn();
                _normalsFilter.ComputeCellNormalsOff();
                _normalsFilter.Update();
                _polyDataOutput = _normalsFilter.GetOutput();
            }

            _arrayNames = GetArrayNames(_polyDataOutput);
            _arrayLabels = _arrayNames.Select(t => new GUIContent(t)).ToArray();

            if(!GenerateMesh)
                return;

            _vtkMesh.Update(_polyDataOutput);
            UpdateMeshColors(_selectedArrayIndex);
            DestroyImmediate(_gameObject.GetComponent<MeshRenderer>());
            DestroyImmediate(_gameObject.GetComponent<MeshFilter>());
            if (_vtkMesh.Meshes.Count == 1)
            {
                _gameObject.AddComponent<MeshFilter>().sharedMesh = _vtkMesh.Meshes[0];
                var meshRenderer = _gameObject.AddComponent<MeshRenderer>();
                meshRenderer.material =
                    new Material(Shader.Find("Diffuse")) { color = Color.gray };
                for(var i = 0; i < _gameObject.transform.childCount; i++)
                    DestroyImmediate(_gameObject.transform.GetChild(i));
            }
            else
            {
                for (var i = 0; i < _vtkMesh.Meshes.Count; i++)
                {
                    var currentName = Name + "-" + i;
                    GameObject child;
                    var childTransform = _gameObject.transform.FindChild(currentName);
                    if (childTransform == null)
                    {
                        child = new GameObject(currentName);
                        child.transform.parent = _gameObject.transform;
                        child.transform.localPosition = new Vector3();
                        child.AddComponent<MeshFilter>();
                        var meshRenderer = child.AddComponent<MeshRenderer>();
                        meshRenderer.material =
                            new Material(Shader.Find("Diffuse")) {color = Color.gray};
                    }
                    else
                        child = childTransform.gameObject;
                    child.GetComponent<MeshFilter>().sharedMesh = _vtkMesh.Meshes[i];
                }
                while (_vtkMesh.Meshes.Count < _gameObject.transform.childCount)
                    DestroyImmediate(_gameObject.transform.GetChild(
                        _gameObject.transform.childCount - 1));
            }
            if(MaterialProperties == null)
                MaterialProperties = _gameObject.AddComponent<MaterialProperties>();
        }
Beispiel #44
0
    /// <summary>
    /// Entry Point
    /// </summary>
    /// <param name="argv"></param>
    public static void Main(String[] argv)
    {
        // This example demonstrates how to use 2D Delaunay triangulation.
        // We create a fancy image of a 2D Delaunay triangulation. Points are
        // randomly generated.
        // first we load in the standard vtk packages into tcl
        // Generate some random points
        math = vtkMath.New();
        points = vtkPoints.New();
        for(int i = 0; i < 50; i++)
        {
            points.InsertPoint(i, vtkMath.Random(0, 1), vtkMath.Random(0, 1), 0.0);
        }

        // Create a polydata with the points we just created.
        profile = vtkPolyData.New();
        profile.SetPoints(points);

        // Perform a 2D Delaunay triangulation on them.
        del = vtkDelaunay2D.New();
        del.SetInput(profile);
        del.SetTolerance(0.001);

        mapMesh = vtkPolyDataMapper.New();
        mapMesh.SetInputConnection(del.GetOutputPort());

        meshActor = vtkActor.New();
        meshActor.SetMapper(mapMesh);
        meshActor.GetProperty().SetColor(.1, .2, .4);

        // We will now create a nice looking mesh by wrapping the edges in tubes,
        // and putting fat spheres at the points.
        extract = vtkExtractEdges.New();
        extract.SetInputConnection(del.GetOutputPort());

        tubes = vtkTubeFilter.New();
        tubes.SetInputConnection(extract.GetOutputPort());
        tubes.SetRadius(0.01);
        tubes.SetNumberOfSides(6);

        mapEdges = vtkPolyDataMapper.New();
        mapEdges.SetInputConnection(tubes.GetOutputPort());

        edgeActor = vtkActor.New();
        edgeActor.SetMapper(mapEdges);
        edgeActor.GetProperty().SetColor(0.2000, 0.6300, 0.7900);
        edgeActor.GetProperty().SetSpecularColor(1, 1, 1);
        edgeActor.GetProperty().SetSpecular(0.3);
        edgeActor.GetProperty().SetSpecularPower(20);
        edgeActor.GetProperty().SetAmbient(0.2);
        edgeActor.GetProperty().SetDiffuse(0.8);

        ball = vtkSphereSource.New();
        ball.SetRadius(0.025);
        ball.SetThetaResolution(12);
        ball.SetPhiResolution(12);

        balls = vtkGlyph3D.New();
        balls.SetInputConnection(del.GetOutputPort());
        balls.SetSourceConnection(ball.GetOutputPort());

        mapBalls = vtkPolyDataMapper.New();
        mapBalls.SetInputConnection(balls.GetOutputPort());

        ballActor = vtkActor.New();
        ballActor.SetMapper(mapBalls);
        ballActor.GetProperty().SetColor(1.0000, 0.4118, 0.7059);
        ballActor.GetProperty().SetSpecularColor(1, 1, 1);
        ballActor.GetProperty().SetSpecular(0.3);
        ballActor.GetProperty().SetSpecularPower(20);
        ballActor.GetProperty().SetAmbient(0.2);
        ballActor.GetProperty().SetDiffuse(0.8);

        // Create graphics objects
        // Create the rendering window, renderer, and interactive renderer
        ren1 = vtkRenderer.New();
        renWin = vtkRenderWindow.New();
        renWin.AddRenderer(ren1);
        iren = vtkRenderWindowInteractor.New();
        iren.SetRenderWindow(renWin);

        // Add the actors to the renderer, set the background and size
        ren1.AddActor(ballActor);
        ren1.AddActor(edgeActor);
        ren1.SetBackground(1, 1, 1);
        renWin.SetSize(150, 150);

        // render the image
        ren1.ResetCamera();
        ren1.GetActiveCamera().Zoom(1.5);
        iren.Initialize();
        iren.Start();

        // Clean Up
        deleteAllVTKObjects();
    }
            internal void CreatePolydata(ref vtkPolyData polydata)
            {
                vtkPoints points = vtkPoints.New();

                points.InsertNextPoint(this.origin[0], this.origin[1], this.origin[2]);

                float[] x = new float[3];
                float[] y = new float[3];
                float[] z = new float[3];

                Add(this.origin, this.xDirection, ref x);
                Add(this.origin, this.yDirection, ref y);
                Add(this.origin, this.zDirection, ref z);

                points.InsertNextPoint(x[0], x[1], x[2]);
                points.InsertNextPoint(y[0], y[1], y[2]);
                points.InsertNextPoint(z[0], z[1], z[2]);

                polydata.SetPoints(points);

                vtkVertexGlyphFilter vertexGlyphFilter = vtkVertexGlyphFilter.New();
                #if VTK_MAJOR_VERSION_5
                vertexGlyphFilter.AddInput(polydata);
                #else
                vertexGlyphFilter.AddInputData(polydata);
                #endif
                vertexGlyphFilter.Update();
                polydata.ShallowCopy(vertexGlyphFilter.GetOutput());
            }
 ///<summary> A Set Method for Static Variables </summary>
 public static void SetinputData(vtkPolyData toSet)
 {
     inputData = toSet;
 }
Beispiel #47
0
        //private void CommonInit(Sequence BinarySubImageSeq)
        //{
        //    vtkImageData ImageData1 = new vtkImageData();
        //    ImageData1.SetDimensions(BinarySubImageSeq.Width, BinarySubImageSeq.Height, BinarySubImageSeq.Depth);
        //    ImageData1.SetNumberOfScalarComponents(1);
        //    ImageData1.SetSpacing(BinarySubImageSeq.XResolution, BinarySubImageSeq.YResolution, BinarySubImageSeq.ZResolution);
        //    ImageData1.SetScalarTypeToFloat();
        //    vtkFloatArray array1 = new vtkFloatArray();
        //    for (int i = 0; i < BinarySubImageSeq.ImageSize; i++)
        //        array1.InsertTuple1(i, BinarySubImageSeq[0].Data[0][i]);
        //    ImageData1.GetPointData().SetScalars(array1);
        //    vtkExtractVOI VOI = new vtkExtractVOI();
        //    VOI.SetInput(ImageData1);
        //    VOI.SetSampleRate(1, 1, 1);
        //    vtkMarchingCubes ContourObject = vtkMarchingCubes.New();
        //    vtk_PolyDataMapper = vtkPolyDataMapper.New();
        //    //ContourActor = new vtkActor();
        //    VOI.SetVOI(0, BinarySubImageSeq.Width - 1, 0, BinarySubImageSeq.Height - 1, 0, BinarySubImageSeq.Depth - 1);
        //    ContourObject.SetInput(VOI.GetOutput());
        //    ContourObject.SetValue(0, 0.5);
        //    vtk_PolyDataMapper.SetInput(ContourObject.GetOutput());
        //    vtk_PolyDataMapper.ScalarVisibilityOn();
        //    vtk_PolyDataMapper.SetScalarModeToUseFieldData();
        //}
        ///// <summary>
        ///// Generate a 3D mesh using marching-cubes algorithm. If voxel value is lower than 1 it is consider as background, else as object
        ///// </summary>
        ///// <param name="BinarySubImageSeq">The binary image</param>
        ///// <param name="Colour">Mesh color</param>
        ///// <param name="Pos">Postion of the object in the world</param>
        //public void Generate(Sequence BinarySubImageSeq, Color Colour, cPoint3D Pos)
        //{
        //    vtkImageData ImageData1 = new vtkImageData();
        //    ImageData1.SetDimensions(BinarySubImageSeq.Width, BinarySubImageSeq.Height, BinarySubImageSeq.Depth);
        //    ImageData1.SetNumberOfScalarComponents(1);
        //    ImageData1.SetSpacing(BinarySubImageSeq.XResolution, BinarySubImageSeq.YResolution, BinarySubImageSeq.ZResolution);
        //    ImageData1.SetScalarTypeToFloat();
        //    vtkFloatArray array1 = new vtkFloatArray();
        //    for (int i = 0; i < BinarySubImageSeq.ImageSize; i++)
        //        array1.InsertTuple1(i, BinarySubImageSeq[0].Data[0][i]);
        //    ImageData1.GetPointData().SetScalars(array1);
        //    vtkExtractVOI VOI = new vtkExtractVOI();
        //    VOI.SetInput(ImageData1);
        //    VOI.SetSampleRate(1, 1, 1);
        //    vtkMarchingCubes ContourObject = vtkMarchingCubes.New();
        //    vtk_PolyDataMapper = vtkPolyDataMapper.New();
        //    //ContourActor = new vtkActor();
        //    VOI.SetVOI(0, BinarySubImageSeq.Width - 1, 0, BinarySubImageSeq.Height - 1, 0, BinarySubImageSeq.Depth - 1);
        //    // perform the amrching cubes
        //    ContourObject.SetInput(VOI.GetOutput());
        //    ContourObject.SetValue(0, 0.5);
        //    //vtkDecimatePro deci
        //    //deci SetInputConnection [fran GetOutputPort]
        //    //deci SetTargetReduction 0.9
        //    //deci PreserveTopologyOn
        //    if (MeshSmoother!=null)
        //    {
        //        vtkSmoothPolyDataFilter smoother = new vtkSmoothPolyDataFilter();
        //        smoother.SetInputConnection(ContourObject.GetOutputPort());// [deci GetOutputPort]
        //        smoother.SetNumberOfIterations(50);
        //        vtk_PolyData = smoother.GetOutput();
        //    }
        //    else
        //    {
        //        vtk_PolyData = ContourObject.GetOutput();
        //    }
        //    vtk_PolyDataMapper.SetInput(vtk_PolyData);
        //    vtk_PolyDataMapper.ScalarVisibilityOn();
        //    vtk_PolyDataMapper.SetScalarModeToUseFieldData();
        //    this.Position = new cPoint3D(Pos.X, Pos.Y, Pos.Z);
        //    this.Colour = Colour;
        //    CreateVTK3DObject(1);
        //    vtk_PolyData = ContourObject.GetOutput();
        //    // compute convex hull
        //    hullFilter = vtkHull.New();
        //    hullFilter.SetInputConnection(ContourObject.GetOutputPort());
        //    hullFilter.AddRecursiveSpherePlanes(1);
        //    hullFilter.Update();
        //    //  this.BackfaceCulling(false);
        //    Information = new cInformation(ContourObject, this, hullFilter);
        //}
        public void Generate(cImage BinarySubImageSeq, Color Colour, cPoint3D Pos/*, List<cBiological3DObject> Containers, int ContainerMode*/)
        {
            vtkImageData ImageData1 = new vtkImageData();

            ImageData1.SetDimensions(BinarySubImageSeq.Width, BinarySubImageSeq.Height, BinarySubImageSeq.Depth);
            ImageData1.SetNumberOfScalarComponents(1);
            ImageData1.SetSpacing(BinarySubImageSeq.Resolution.X, BinarySubImageSeq.Resolution.Y, BinarySubImageSeq.Resolution.Z);
            ImageData1.SetScalarTypeToFloat();

            vtkFloatArray array1 = new vtkFloatArray();
            for (int i = 0; i < BinarySubImageSeq.ImageSize; i++)
                array1.InsertTuple1(i, BinarySubImageSeq.SingleChannelImage[0].Data[i]);
            ImageData1.GetPointData().SetScalars(array1);

            vtkExtractVOI VOI = new vtkExtractVOI();
            VOI.SetInput(ImageData1);
            VOI.SetSampleRate(1, 1, 1);

            vtkMarchingCubes ContourObject = vtkMarchingCubes.New();
            vtk_PolyDataMapper = vtkPolyDataMapper.New();
            //ContourActor = new vtkActor();

            VOI.SetVOI(0, BinarySubImageSeq.Width - 1, 0, BinarySubImageSeq.Height - 1, 0, BinarySubImageSeq.Depth - 1);
            ContourObject.SetInput(VOI.GetOutput());
            ContourObject.SetValue(0, 0.5);

            vtkAlgorithmOutput AlgoOutPut = null;

            if (MeshSmoother != null)
            {
                //vtkSmoothPolyDataFilter smoother = new vtkSmoothPolyDataFilter();
                vtkWindowedSincPolyDataFilter smoother = new vtkWindowedSincPolyDataFilter();
                smoother.SetInputConnection(ContourObject.GetOutputPort());// [deci GetOutputPort]
                smoother.SetNumberOfIterations(MeshSmoother.NumberOfIterations);
                vtk_PolyData = smoother.GetOutput();
                //smoother.GetOutputPort();
                AlgoOutPut = smoother.GetOutputPort();
            }
            else
            {
                vtk_PolyData = ContourObject.GetOutput();
                AlgoOutPut = ContourObject.GetOutputPort();
            }

            vtk_PolyDataMapper.SetInput(vtk_PolyData);
            vtk_PolyDataMapper.ScalarVisibilityOn();
            vtk_PolyDataMapper.SetScalarModeToUseFieldData();

            vtkActor TmpActor = vtkActor.New();
            TmpActor.SetMapper(vtk_PolyDataMapper);
            TmpActor.SetPosition(Pos.X, Pos.Y, Pos.Z);

            //Console.WriteLine("PosX"+Pos.X+" PosY"+Pos.Y+" PosZ"+Pos.Z);

            #region deal with the containers

            if (this.Containers != null)
            {
                if (this.Containers.ContainerMode == 0)
                {
                    cPoint3D Centroid = new cPoint3D((float)TmpActor.GetCenter()[0], (float)TmpActor.GetCenter()[1], (float)TmpActor.GetCenter()[2]);
                    bool IsInside = false;

                    for (int Idx = 0; Idx < Containers.Containers.Count; Idx++)
                    {
                        cBiological3DVolume CurrentContainer = (cBiological3DVolume)(Containers.Containers[Idx]);

                        if (CurrentContainer.IsPointInside(Centroid))
                        {
                            IsInside = true;
                            ContainerIdx = Idx;
                            break;
                        }
                    }
                    if (IsInside)
                    {
                        this.SetPosition(new cPoint3D(Pos.X, Pos.Y, Pos.Z));
                        this.Colour = Colour;
                        CreateVTK3DObject(1);
                        //   vtk_PolyData = ContourObject.GetOutput();

                        // compute convex hull
                        hullFilter = vtkHull.New();
                        hullFilter.SetInputConnection(AlgoOutPut);
                        hullFilter.AddRecursiveSpherePlanes(0);
                        hullFilter.Update();

                        Information = new cInformation(AlgoOutPut, this, hullFilter);
                        this.Detected = true;
                    }
                    else
                    {
                        this.Detected = false;
                    }
                }
                else if (Containers.ContainerMode == 1)
                {
                    this.Detected = true;
                    //bool IsInside = false;
                    for (int Idx = 0; Idx < Containers.Containers.Count; Idx++)
                    {
                        cBiological3DVolume CurrentContainer = (cBiological3DVolume)(Containers.Containers[Idx]);

                        if (CurrentContainer.IsPointInside(Pos))
                        {
                            //IsInside = false;
                            this.Detected = false;
                            return;
                        }
                    }
                    this.SetPosition(new cPoint3D(Pos.X, Pos.Y, Pos.Z));
                    this.Colour = Colour;

                    CreateVTK3DObject(1);
                    // vtk_PolyData = ContourObject.GetOutput();

                    // compute convex hull
                    hullFilter = vtkHull.New();
                    hullFilter.SetInputConnection(AlgoOutPut);
                    hullFilter.AddRecursiveSpherePlanes(0);
                    hullFilter.Update();

                    Information = new cInformation(AlgoOutPut, this, hullFilter);
                    this.Detected = true;
                }
            }
            else
            {
                this.SetPosition(new cPoint3D(Pos.X, Pos.Y, Pos.Z));
                this.Colour = Colour;

                CreateVTK3DObject(1);

                //  vtk_PolyData = ContourObject.GetOutput();

                // compute convex hull
                hullFilter = vtkHull.New();
                hullFilter.SetInputConnection(AlgoOutPut);
                hullFilter.AddRecursiveSpherePlanes(1);
                hullFilter.Update();

                //  this.BackfaceCulling(false);
                Information = new cInformation(AlgoOutPut, this, hullFilter);

            }

            #endregion
        }
Beispiel #48
0
        /// <summary>
        /// 增加mesh的网格密度,根据numberOfAlgorithm选择所使用算法,numberOfSubdivision为细分的参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bt_subdivision_Click(object sender, EventArgs e)
        {
            int numberOfSubdivision = 2;
            int numberOfAlgorithm = 0;
            //建立一个超类指针(vtkPolyDataAlgorithm)来更加容易的使用不同类型的细分滤波器
            //但是通常情况下,建立一个所使用所滤波器类型的指针
            //例如:<vtkLinearSubdivisionFilter> subdivisionFilter=<vtkLInearSubdivisionFilter>.New();
            vtkPolyDataAlgorithm subdivisionFilter;
            switch (numberOfAlgorithm) {
                case 0:
                    subdivisionFilter = vtkLinearSubdivisionFilter.New();
                    ((vtkLinearSubdivisionFilter)subdivisionFilter).SetNumberOfSubdivisions(numberOfSubdivision);
                    break;
                case 1:
                    subdivisionFilter = vtkLoopSubdivisionFilter.New();
                    ((vtkLoopSubdivisionFilter)subdivisionFilter).SetNumberOfSubdivisions(numberOfSubdivision);
                    break;
                case 2:
                    subdivisionFilter = vtkButterflySubdivisionFilter.New();
                    ((vtkButterflySubdivisionFilter)subdivisionFilter).SetNumberOfSubdivisions(numberOfSubdivision);
                    break;
                default:
                    subdivisionFilter = vtkButterflySubdivisionFilter.New();
                    ((vtkButterflySubdivisionFilter)subdivisionFilter).SetNumberOfSubdivisions(numberOfSubdivision);
                    break;
            }
            //subdivisionFilter.SetInput(originalMesh);
            subdivisionFilter.SetInputConnection(originalMesh.GetProducerPort());
            subdivisionFilter.Update();
            //更新orginalMesh数据
            originalMesh = subdivisionFilter.GetOutput();
            mapper.SetInput(originalMesh);
            //mapper.SetInputConnection(subdivisionFilter.GetOutputPort());
            renderWindow.Render();

            //更新显示点数
            vtkPolyData temp = vtkPolyData.New();
            temp = subdivisionFilter.GetOutput();
            tb_numOfPoint.Text = temp.GetNumberOfPoints().ToString();
        }
        void GenerateData(ref vtkPolyData input)
        {
            // Create a sphere
            vtkSphereSource sphereSource = vtkSphereSource.New();
            sphereSource.Update();

            // Remove some cells
            vtkIdTypeArray ids = vtkIdTypeArray.New();
            ids.SetNumberOfComponents(1);

            // Set values
            ids.InsertNextValue(2);
            ids.InsertNextValue(10);

            vtkSelectionNode selectionNode = vtkSelectionNode.New();

            selectionNode.SetFieldType((int)vtkSelectionNode.SelectionField.CELL);
            selectionNode.SetContentType((int)vtkSelectionNode.SelectionContent.INDICES);
            selectionNode.SetSelectionList(ids);
            selectionNode.GetProperties().Set(vtkSelectionNode.INVERSE(), 1); //invert the selection

            vtkSelection selection = vtkSelection.New();
            selection.AddNode(selectionNode);

            vtkExtractSelection extractSelection = vtkExtractSelection.New();
            extractSelection.SetInputConnection(0, sphereSource.GetOutputPort());
            #if VTK_MAJOR_VERSION_5
            extractSelection.SetInput(1, selection);
            #else
            extractSelection.SetInputData(1, selection);
            #endif
            extractSelection.Update();

            // In selection
            vtkDataSetSurfaceFilter surfaceFilter = vtkDataSetSurfaceFilter.New();
            surfaceFilter.SetInputConnection(extractSelection.GetOutputPort());
            surfaceFilter.Update();

            input.ShallowCopy(surfaceFilter.GetOutput());
        }
Beispiel #50
0
        /// <summary>
        /// 读取stl文件,并在窗口进行显示,并设置全局变量originalMesh
        /// </summary>
        private void ReadSTL()
        {
            //Path to vtk data must be set as an environment variable
            //VTK_DATA_ROOT=""
            vtkSTLReader reader = vtkSTLReader.New();
            reader.SetFileName(FileFullName);
            reader.Update();
            mapper = vtkPolyDataMapper.New();
            mapper.SetInputConnection(reader.GetOutputPort());

            actor = vtkActor.New();
            actor.SetMapper(mapper);
            //get a reference to the renderwindow of our renderWindowControll
            renderWindow = renderWindowControl1.RenderWindow;
            //renderer
            renderer = renderWindow.GetRenderers().GetFirstRenderer();
            //移除之前所有prop
            renderer.RemoveAllViewProps();
            //set background color
            renderer.SetBackground(0.2, 0.3, 0.4);
            //add our actor to the renderer
            renderer.AddActor(actor);
            originalMesh = vtkPolyData.New();
            originalMesh.DeepCopy(reader.GetOutput());
            tb_numOfPoint.Text = originalMesh.GetNumberOfPoints().ToString();

            //creat a cell picker
            picker = vtkCellPicker.New();
            vtkRenderWindowInteractor iren = renderWindow.GetInteractor();
            iren.SetPicker(picker);

            renderer.ResetCamera();
            renderWindow.Render();
        }
Beispiel #51
0
        public void Generate(CImage3D BinarySubImageSeq, Color Colour, cPoint3D Pos)
        {
            vtkImageData ImageData1 = new vtkImageData();

            ImageData1.SetDimensions(BinarySubImageSeq.Width, BinarySubImageSeq.Height, BinarySubImageSeq.Depth);
            ImageData1.SetNumberOfScalarComponents(1);
            //ImageData1.SetSpacing(BinarySubImageSeq.XResolution, BinarySubImageSeq.YResolution, BinarySubImageSeq.ZResolution);
            ImageData1.SetScalarTypeToFloat();

            vtkFloatArray array1 = new vtkFloatArray();
            for (int i = 0; i < BinarySubImageSeq.ImageSize; i++)
                array1.InsertTuple1(i, BinarySubImageSeq.Data[i]);
            ImageData1.GetPointData().SetScalars(array1);

            vtkExtractVOI VOI = new vtkExtractVOI();
            VOI.SetInput(ImageData1);
            VOI.SetSampleRate(1, 1, 1);

            vtkMarchingCubes ContourObject = vtkMarchingCubes.New();
            vtk_PolyDataMapper = vtkPolyDataMapper.New();
            //ContourActor = new vtkActor();

            VOI.SetVOI(0, BinarySubImageSeq.Width - 1, 0, BinarySubImageSeq.Height - 1, 0, BinarySubImageSeq.Depth - 1);
            ContourObject.SetInput(VOI.GetOutput());
            ContourObject.SetValue(0, 0.5);

            vtkAlgorithmOutput AlgoOutPut = null;

            vtk_PolyData = ContourObject.GetOutput();
            AlgoOutPut = ContourObject.GetOutputPort();

            vtk_PolyDataMapper.SetInput(vtk_PolyData);
            vtk_PolyDataMapper.ScalarVisibilityOn();
            vtk_PolyDataMapper.SetScalarModeToUseFieldData();

            vtkActor TmpActor = vtkActor.New();
            TmpActor.SetMapper(vtk_PolyDataMapper);
            TmpActor.SetPosition(Pos.X, Pos.Y, Pos.Z);

            //Console.WriteLine("PosX"+Pos.X+" PosY"+Pos.Y+" PosZ"+Pos.Z);

            #region deal with the containers

            this.Position = new cPoint3D(Pos.X, Pos.Y, Pos.Z);
            this.Colour = Colour;

            CreateVTK3DObject(1);

            //  vtk_PolyData = ContourObject.GetOutput();

            // compute convex hull
            hullFilter = vtkHull.New();
            hullFilter.SetInputConnection(AlgoOutPut);
            hullFilter.AddRecursiveSpherePlanes(1);
            hullFilter.Update();

            //  this.BackfaceCulling(false);
            Information = new cInformation(AlgoOutPut, this, hullFilter);

            #endregion
        }
 ///<summary> A Set Method for Static Variables </summary>
 public static void SetprofileKData(vtkPolyData toSet)
 {
     profileKData = toSet;
 }