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);
        }
        private void PolyDataGetPoint()
        {
            // Create a sphere
            vtkSphereSource sphereSource = vtkSphereSource.New();

            sphereSource.Update();
            vtkPolyData polydata = sphereSource.GetOutput();

            // Write all of the coordinates of the points in the vtkPolyData to the console.
            for (int i = 0; i < polydata.GetNumberOfPoints(); i++)
            {
                double[] p = polydata.GetPoint(i);
                // This is identical to:
                // double[] p = polydata.GetPoints().GetPoint(i);
                Console.WriteLine("Point " + i + " : (" + p[0] + " " + p[1] + " " + p[2] + ")");
            }
        }
Example #3
0
        private void VectorFieldNonZeroExtraction()
        {
            // Create an image
            vtkImageData image = vtkImageData.New();

            CreateVectorField(ref image);

            // This filter produces a vtkImageData with an array named "Magnitude"
            vtkImageMagnitude magnitudeFilter = vtkImageMagnitude.New();

            magnitudeFilter.SetInputConnection(image.GetProducerPort());
            magnitudeFilter.Update();

            image.GetPointData().AddArray(magnitudeFilter.GetOutput().GetPointData().GetScalars());
            image.GetPointData().SetActiveScalars("Magnitude");

            vtkThresholdPoints thresholdVector = vtkThresholdPoints.New();

            thresholdVector.SetInput(image);
            thresholdVector.SetInputArrayToProcess(
                0,
                0,
                (int)vtkDataObject.FieldAssociations.FIELD_ASSOCIATION_POINTS,
                (int)vtkDataSetAttributes.AttributeTypes.SCALARS,
                "Magnitude");
            thresholdVector.ThresholdByUpper(0.00001);
            thresholdVector.Update();

            // in case you want to save imageData
            //vtkXMLPolyDataWriter writer = vtkXMLPolyDataWriter.New();
            //writer.SetFileName("output.vtp");
            //writer.SetInputConnection(thresholdPoints.GetOutputPort());
            //writer.Write();

            // repesents the pixels
            vtkCubeSource cubeSource = vtkCubeSource.New();

            cubeSource.SetXLength(2.0);
            cubeSource.SetYLength(2.0);
            cubeSource.SetZLength(2.0);
            vtkGlyph3D glyph = vtkGlyph3D.New();

            glyph.SetInput(image);
            glyph.SetSourceConnection(cubeSource.GetOutputPort());
            // don't scale glyphs according to any scalar data
            glyph.SetScaleModeToDataScalingOff();

            vtkPolyDataMapper glyphMapper = vtkPolyDataMapper.New();

            glyphMapper.SetInputConnection(glyph.GetOutputPort());
            // don't color glyphs according to scalar data
            glyphMapper.ScalarVisibilityOff();
            glyphMapper.SetScalarModeToDefault();

            vtkActor actor = vtkActor.New();

            actor.SetMapper(glyphMapper);

            // represent vector field
            vtkGlyph3D        vectorGlyph       = vtkGlyph3D.New();
            vtkArrowSource    arrowSource       = vtkArrowSource.New();
            vtkPolyDataMapper vectorGlyphMapper = vtkPolyDataMapper.New();

            int n = image.GetPointData().GetNumberOfArrays();

            for (int i = 0; i < n; i++)
            {
                Debug.WriteLine("name of array[" + i + "]: " + image.GetPointData().GetArrayName(i));
            }

            vtkPolyData tmp = thresholdVector.GetOutput();

            Debug.WriteLine("number of thresholded points: " + tmp.GetNumberOfPoints());
            vectorGlyph.SetInputConnection(thresholdVector.GetOutputPort());

            // in case you want the point glyphs to be oriented according to
            // scalar values in array "ImageScalars" uncomment the following line
            image.GetPointData().SetActiveVectors("ImageScalars");

            vectorGlyph.SetSourceConnection(arrowSource.GetOutputPort());
            vectorGlyph.SetScaleModeToScaleByVector();
            vectorGlyph.SetVectorModeToUseVector();
            vectorGlyph.ScalingOn();
            vectorGlyph.OrientOn();
            vectorGlyph.SetInputArrayToProcess(
                1,
                0,
                (int)vtkDataObject.FieldAssociations.FIELD_ASSOCIATION_POINTS,
                (int)vtkDataSetAttributes.AttributeTypes.SCALARS,
                "ImageScalars");

            vectorGlyph.Update();

            vectorGlyphMapper.SetInputConnection(vectorGlyph.GetOutputPort());
            vectorGlyphMapper.Update();

            vtkActor vectorActor = vtkActor.New();

            vectorActor.SetMapper(vectorGlyphMapper);


            // get a reference to the renderwindow of our renderWindowControl1
            vtkRenderWindow renderWindow = renderWindowControl1.RenderWindow;
            // renderer
            vtkRenderer renderer = renderWindow.GetRenderers().GetFirstRenderer();

            // set background color
            renderer.SetBackground(.2, .6, .3);
            //Add the actors to the renderer, set the background and size
            renderer.AddActor(actor);
            renderer.AddActor(vectorActor);
        }
Example #4
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();
        }
Example #5
0
        private void QuadricDecimation()
        {
            vtkSphereSource sphereSource = vtkSphereSource.New();

            sphereSource.Update();

            vtkPolyData input = vtkPolyData.New();

            input.ShallowCopy(sphereSource.GetOutput());

            Debug.WriteLine("Before decimation" + Environment.NewLine + "------------");
            Debug.WriteLine("There are " + input.GetNumberOfPoints() + " points.");
            Debug.WriteLine("There are " + input.GetNumberOfPolys() + " polygons.");

            vtkQuadricDecimation decimate = vtkQuadricDecimation.New();

#if VTK_MAJOR_VERSION_5
            decimate.SetInputConnection(input.GetProducerPort());
#else
            decimate.SetInputData(input);
#endif
            decimate.Update();

            vtkPolyData decimated = vtkPolyData.New();
            decimated.ShallowCopy(decimate.GetOutput());

            Debug.WriteLine("After decimation" + Environment.NewLine + "------------");

            Debug.WriteLine("There are " + decimated.GetNumberOfPoints() + " points.");
            Debug.WriteLine("There are " + decimated.GetNumberOfPolys() + " polygons.");

            vtkPolyDataMapper inputMapper = vtkPolyDataMapper.New();
#if VTK_MAJOR_VERSION_5
            inputMapper.SetInputConnection(input.GetProducerPort());
#else
            inputMapper.SetInputData(input);
#endif
            vtkActor inputActor = vtkActor.New();
            inputActor.SetMapper(inputMapper);

            vtkPolyDataMapper decimatedMapper = vtkPolyDataMapper.New();
#if VTK_MAJOR_VERSION_5
            decimatedMapper.SetInputConnection(decimated.GetProducerPort());
#else
            decimatedMapper.SetInputData(decimated);
#endif
            vtkActor decimatedActor = vtkActor.New();
            decimatedActor.SetMapper(decimatedMapper);

            vtkRenderWindow renderWindow = renderWindowControl1.RenderWindow;
            this.Size = new System.Drawing.Size(612, 352);

            // Define viewport ranges
            // (xmin, ymin, xmax, ymax)
            double[] leftViewport  = new double[] { 0.0, 0.0, 0.5, 1.0 };
            double[] rightViewport = new double[] { 0.5, 0.0, 1.0, 1.0 };

            // Setup both renderers
            vtkRenderer leftRenderer = vtkRenderer.New();
            renderWindow.AddRenderer(leftRenderer);
            leftRenderer.SetViewport(leftViewport[0], leftViewport[1], leftViewport[2], leftViewport[3]);
            leftRenderer.SetBackground(.6, .5, .4);

            vtkRenderer rightRenderer = vtkRenderer.New();
            renderWindow.AddRenderer(rightRenderer);
            rightRenderer.SetViewport(rightViewport[0], rightViewport[1], rightViewport[2], rightViewport[3]);
            rightRenderer.SetBackground(.4, .5, .6);

            // Add the sphere to the left and the cube to the right
            leftRenderer.AddActor(inputActor);
            rightRenderer.AddActor(decimatedActor);
            leftRenderer.ResetCamera();
            rightRenderer.ResetCamera();
            renderWindow.Render();
        }
Example #6
0
        private void ElevationFilter()
        {
            // Created a grid of points (heigh/terrian map)
            vtkPoints points = vtkPoints.New();

            uint GridSize = 10;

            for (uint x = 0; x < GridSize; x++)
            {
                for (uint y = 0; y < GridSize; y++)
                {
                    points.InsertNextPoint(x, y, (x + y) / (y + 1));
                }
            }
            double[] bounds = points.GetBounds();

            // Add the grid points to a polydata object
            vtkPolyData inputPolyData = vtkPolyData.New();

            inputPolyData.SetPoints(points);

            // Triangulate the grid points
            vtkDelaunay2D delaunay = vtkDelaunay2D.New();

#if VTK_MAJOR_VERSION_5
            delaunay.SetInput(inputPolyData);
#else
            delaunay.SetInputData(inputPolyData);
#endif
            delaunay.Update();

            vtkElevationFilter elevationFilter = vtkElevationFilter.New();
            elevationFilter.SetInputConnection(delaunay.GetOutputPort());
            elevationFilter.SetLowPoint(0.0, 0.0, bounds[4]);
            elevationFilter.SetHighPoint(0.0, 0.0, bounds[5]);
            elevationFilter.Update();

            vtkPolyData output = vtkPolyData.New();
            output.ShallowCopy(vtkPolyData.SafeDownCast(elevationFilter.GetOutput()));

            vtkFloatArray elevation =
                vtkFloatArray.SafeDownCast(output.GetPointData().GetArray("Elevation"));

            // Create the color map
            vtkLookupTable colorLookupTable = vtkLookupTable.New();
            colorLookupTable.SetTableRange(bounds[4], bounds[5]);
            colorLookupTable.Build();

            // Generate the colors for each point based on the color map
            vtkUnsignedCharArray colors = vtkUnsignedCharArray.New();
            colors.SetNumberOfComponents(3);
            colors.SetName("Colors");

            for (int i = 0; i < output.GetNumberOfPoints(); i++)
            {
                double val = elevation.GetValue(i);
                Debug.WriteLine("val: " + val);

                double[] dcolor = colorLookupTable.GetColor(val);
                //Debug.WriteLine("dcolor: "
                //          + dcolor[0] + " "
                //          + dcolor[1] + " "
                //          + dcolor[2]);
                byte[] color = new byte[3];
                for (int j = 0; j < 3; j++)
                {
                    color[j] = (byte)(255 * dcolor[j]);
                }
                //Debug.WriteLine("color: "
                //          + color[0] + " "
                //          + color[1] + " "
                //          + color[2]);

                colors.InsertNextTuple3(color[0], color[1], color[2]);
            }

            output.GetPointData().AddArray(colors);

            // Visualize
            vtkPolyDataMapper mapper = vtkPolyDataMapper.New();
#if VTK_MAJOR_VERSION_5
            mapper.SetInputConnection(output.GetProducerPort());
#else
            mapper.SetInputData(output);
#endif

            vtkActor actor = vtkActor.New();
            actor.SetMapper(mapper);

            // get a reference to the renderwindow of our renderWindowControl1
            vtkRenderWindow renderWindow = renderWindowControl1.RenderWindow;
            // renderer
            vtkRenderer renderer = renderWindow.GetRenderers().GetFirstRenderer();
            // set background color
            renderer.SetBackground(0.2, 0.3, 0.4);
            // add our actor to the renderer
            renderer.AddActor(actor);
        }
Example #7
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;
        }
Example #8
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;
        }
Example #9
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>();
        }
Example #10
0
        private void ColoredElevationMap()
        {
            // Create a grid of points (height/terrian map)
            vtkPoints points = vtkPoints.New();

            uint   GridSize = 20;
            double xx, yy, zz;

            for (uint x = 0; x < GridSize; x++)
            {
                for (uint y = 0; y < GridSize; y++)
                {
                    xx = x + vtkMath.Random(-.2, .2);
                    yy = y + vtkMath.Random(-.2, .2);
                    zz = vtkMath.Random(-.5, .5);
                    points.InsertNextPoint(xx, yy, zz);
                }
            }

            // Add the grid points to a polydata object
            vtkPolyData inputPolyData = vtkPolyData.New();

            inputPolyData.SetPoints(points);

            // Triangulate the grid points
            vtkDelaunay2D delaunay = vtkDelaunay2D.New();

#if VTK_MAJOR_VERSION_5
            delaunay.SetInput(inputPolyData);
#else
            delaunay.SetInputData(inputPolyData);
#endif
            delaunay.Update();
            vtkPolyData outputPolyData = delaunay.GetOutput();

            double[] bounds = outputPolyData.GetBounds();

            // Find min and max z
            double minz = bounds[4];
            double maxz = bounds[5];

            Debug.WriteLine("minz: " + minz);
            Debug.WriteLine("maxz: " + maxz);

            // Create the color map
            vtkLookupTable colorLookupTable = vtkLookupTable.New();
            colorLookupTable.SetTableRange(minz, maxz);
            colorLookupTable.Build();

            // Generate the colors for each point based on the color map
            vtkUnsignedCharArray colors = vtkUnsignedCharArray.New();
            colors.SetNumberOfComponents(3);
            colors.SetName("Colors");

            Debug.WriteLine("There are " + outputPolyData.GetNumberOfPoints()
                            + " points.");


#if UNSAFE // fastest way to fill color array
            colors.SetNumberOfTuples(outputPolyData.GetNumberOfPoints());
            unsafe {
                byte *pColor = (byte *)colors.GetPointer(0).ToPointer();

                for (int i = 0; i < outputPolyData.GetNumberOfPoints(); i++)
                {
                    double[] p = outputPolyData.GetPoint(i);

                    double[] dcolor = colorLookupTable.GetColor(p[2]);
                    Debug.WriteLine("dcolor: "
                                    + dcolor[0] + " "
                                    + dcolor[1] + " "
                                    + dcolor[2]);

                    byte[] color = new byte[3];
                    for (uint j = 0; j < 3; j++)
                    {
                        color[j] = (byte)(255 * dcolor[j]);
                    }
                    Debug.WriteLine("color: "
                                    + color[0] + " "
                                    + color[1] + " "
                                    + color[2]);

                    *(pColor + 3 * i)     = color[0];
                    *(pColor + 3 * i + 1) = color[1];
                    *(pColor + 3 * i + 2) = color[2];
                }
            }
#else
            for (int i = 0; i < outputPolyData.GetNumberOfPoints(); i++)
            {
                double[] p = outputPolyData.GetPoint(i);

                double[] dcolor = colorLookupTable.GetColor(p[2]);
                Debug.WriteLine("dcolor: "
                                + dcolor[0] + " "
                                + dcolor[1] + " "
                                + dcolor[2]);

                byte[] color = new byte[3];
                for (uint j = 0; j < 3; j++)
                {
                    color[j] = (byte)(255 * dcolor[j]);
                }
                Debug.WriteLine("color: "
                                + color[0] + " "
                                + color[1] + " "
                                + color[2]);
                colors.InsertNextTuple3(color[0], color[1], color[2]);
                //IntPtr pColor = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(byte)) * 3);
                //Marshal.Copy(color, 0, pColor, 3);
                //colors.InsertNextTupleValue(pColor);
                //Marshal.FreeHGlobal(pColor);
            }
#endif

            outputPolyData.GetPointData().SetScalars(colors);

            // Create a mapper and actor
            vtkPolyDataMapper mapper = vtkPolyDataMapper.New();
#if VTK_MAJOR_VERSION_5
            mapper.SetInputConnection(outputPolyData.GetProducerPort());
#else
            mapper.SetInputData(outputPolyData);
#endif

            vtkActor actor = vtkActor.New();
            actor.SetMapper(mapper);

            // get a reference to the renderwindow of our renderWindowControl1
            vtkRenderWindow renderWindow = renderWindowControl1.RenderWindow;
            // renderer
            vtkRenderer renderer = renderWindow.GetRenderers().GetFirstRenderer();
            // set background color
            renderer.SetBackground(0.2, 0.3, 0.4);
            // add our actor to the renderer
            renderer.AddActor(actor);
        }
Example #11
0
        private void WeightedTransformFilter()
        {
            // Use a sphere as a basis of the shape
            vtkSphereSource sphere = vtkSphereSource.New();

            sphere.SetPhiResolution(40);
            sphere.SetThetaResolution(40);
            sphere.Update();

            vtkPolyData sphereData = sphere.GetOutput();

            // Create a data array to hold the weighting coefficients
            vtkFloatArray tfarray = vtkFloatArray.New();
            int           npoints = sphereData.GetNumberOfPoints();

            tfarray.SetNumberOfComponents(2);
            tfarray.SetNumberOfTuples(npoints);

            // Parameterize the sphere along the z axis, and fill the weights
            // with (1.0-a, a) to linearly interpolate across the shape
            IntPtr pPoint = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(double)) * 3);

            double[] point = new double[3];
            for (int i = 0; i < npoints; i++)
            {
                sphereData.GetPoint(i, pPoint);
                Marshal.Copy(pPoint, point, 0, 3);
                double x = point[0];
                double y = point[1];
                double z = point[2];

                double zn  = z + 0.5;
                double zn1 = 1.0 - zn;
                if (zn > 1.0)
                {
                    zn = 1.0;
                }
                if (zn1 < 0.0)
                {
                    zn1 = 0.0;
                }

                tfarray.SetComponent(i, 0, zn1);
                tfarray.SetComponent(i, 1, zn);
            }
            Marshal.FreeHGlobal(pPoint);

            // Create field data to hold the array, and bind it to the sphere
            vtkFieldData fd = vtkFieldData.New();

            tfarray.SetName("weights");
            sphereData.GetPointData().AddArray(tfarray);

            // Use an ordinary transform to stretch the shape
            vtkTransform stretch = vtkTransform.New();

            stretch.Scale(1, 1, 3.2);

            vtkTransformFilter stretchFilter = vtkTransformFilter.New();

            stretchFilter.SetInputConnection(sphereData.GetProducerPort());
            stretchFilter.SetTransform(stretch);

            // Now, for the weighted transform stuff
            vtkWeightedTransformFilter weightedTrans = vtkWeightedTransformFilter.New();

            // Create two transforms to interpolate between
            vtkTransform identity = vtkTransform.New();

            identity.Identity();

            vtkTransform rotated      = vtkTransform.New();
            double       rotatedAngle = 45;

            rotated.RotateX(rotatedAngle);

            weightedTrans.SetNumberOfTransforms(2);
            weightedTrans.SetTransform(identity, 0);
            weightedTrans.SetTransform(rotated, 1);
            // which data array should the filter use ?
            weightedTrans.SetWeightArray("weights");

            weightedTrans.SetInputConnection(stretchFilter.GetOutputPort());

            vtkPolyDataMapper weightedTransMapper = vtkPolyDataMapper.New();

            weightedTransMapper.SetInputConnection(weightedTrans.GetOutputPort());
            vtkActor weightedTransActor = vtkActor.New();

            weightedTransActor.SetMapper(weightedTransMapper);
            weightedTransActor.GetProperty().SetDiffuseColor(0.8, 0.8, 0.1);
            weightedTransActor.GetProperty().SetRepresentationToSurface();

            // get a reference to the renderwindow of our renderWindowControl1
            vtkRenderWindow renderWindow = renderWindowControl1.RenderWindow;
            // renderer
            vtkRenderer renderer = renderWindow.GetRenderers().GetFirstRenderer();

            // set background color
            renderer.SetBackground(0.2, 0.3, 0.4);
            // add our actor to the renderer
            renderer.AddActor(weightedTransActor);

            renderer.ResetCamera();
            renderer.GetActiveCamera().Azimuth(90);
            renderer.GetActiveCamera().Dolly(1);
        }
Example #12
0
        public bool Read_Poly_Data_File(string filename)
        {
            //Initalize VTK Reader
            vtkXMLPolyDataReader reader = new vtkXMLPolyDataReader();

            reader.SetFileName(filename);

            reader.Update();

            vtkPolyData polydata = reader.GetOutput();

            if (polydata == null)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Invalid Poly data Input");

                return(false);
            }

            // Read Point Coordinates
            int numPoints = (int)polydata.GetNumberOfPoints();

            List <Vector3d> point_dat = new List <Vector3d>();

            if (numPoints != 0)
            {
                double[] pt;

                for (int i = 0; i < numPoints; i++)
                {
                    pt = polydata.GetPoint(i);

                    point_dat.Add(new Vector3d((float)pt[0], (float)pt[1], (float)pt[2]));
                }
                if (this.vertex_data.ContainsKey("vertices"))
                {
                    this.vertex_data["vertices"] = point_dat;
                }
                else
                {
                    this.vertex_data.Add("vertices", point_dat);
                }
                Console.WriteLine("All points read in correctly!");
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("---------------No Points existent");
            }

            // Read Point Indices
            int numpolydatacells = (int)polydata.GetNumberOfCells();

            vtkCell   polydataCell;
            vtkIdList pts;

            if (numpolydatacells != 0)
            {
                int counter = 0;
                cells.SetNumberOfCells(numpolydatacells);

                for (int i = 0; i < numpolydatacells; i++)
                {
                    polydataCell = polydata.GetCell(i);

                    int numCellPoints = (int)polydataCell.GetNumberOfPoints();
                    cells.InsertNextCell(polydataCell);

                    Vector3 trianglePoints = new Vector3();
                    if (numCellPoints == 3)
                    {
                        pts = polydataCell.GetPointIds();

                        int one   = (int)pts.GetId(0);
                        int two   = (int)pts.GetId(1);
                        int three = (int)pts.GetId(2);
                        //this.Get_Triangle(counter, pts);
                        trianglePoints = new Vector3(one, two, three);
                        counter++;
                    }
                    triangleList.Add(trianglePoints);
                }
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("---------------No Triangles existent");
            }

            // Read point data
            vtkPointData pointData = polydata.GetPointData();

            // Load point attributes
            this.Load_Point_Attributes(pointData);

            return(true);
        }
Example #13
0
        private void SelectAreaClick(vtkObject sender, vtkObjectEventArgs e)
        {
            int[]         clickPos = Inter.GetEventPosition();
            vtkAreaPicker picker   = vtkAreaPicker.New();

            picker.AreaPick(clickPos[0], clickPos[1], clickPos[0] + 100, clickPos[1] + 100, Viewport);

            if (picker.GetActor() != null)
            {
                vtkPlanes          Boundary = picker.GetFrustum();
                vtkExtractGeometry Box      = vtkExtractGeometry.New();
                Box.SetImplicitFunction(Boundary);
                Box.SetInput(picker.GetActor().GetMapper().GetInput());

                vtkVertexGlyphFilter glyphFilter = vtkVertexGlyphFilter.New();
                glyphFilter.SetInputConnection(Box.GetOutputPort());
                glyphFilter.Update();

                vtkPolyData         selected = glyphFilter.GetOutput();
                vtkPoints           points   = vtkPoints.New();
                vtkUnstructuredGrid grid     = vtkUnstructuredGrid.New();
                for (int i = 0; i < selected.GetNumberOfPoints(); i++)
                {
                    points.InsertNextPoint(selected.GetPoint(i)[0], selected.GetPoint(i)[1], selected.GetPoint(i)[2]);
                }
                grid.SetPoints(points);
                vtkSphereSource sphere = vtkSphereSource.New();
                sphere.SetPhiResolution(6);
                sphere.SetThetaResolution(6);
                sphere.SetRadius(0.1);
                vtkGlyph3D glyph3D = vtkGlyph3D.New();
                glyph3D.SetInput(grid);
                glyph3D.SetSourceConnection(sphere.GetOutputPort());

                vtkPolyDataMapper mapper = vtkPolyDataMapper.New();
                mapper.SetInputConnection(glyph3D.GetOutputPort());

                //double[] P = new double[3];
                //bool selected = false;
                //vtkPoints points = Faces.GetPoints();
                //double[] ClickedPoint = PointPicker.GetActor().GetMapper().GetInput().GetPoint(PointPicker.GetPointId());
                //for (int i = 0; i < points.GetNumberOfPoints(); i++)
                //{
                //    if (Math.Abs(points.GetPoint(i)[0] - ClickedPoint[0]) < 1e-6 &&
                //        Math.Abs(points.GetPoint(i)[1] - ClickedPoint[1]) < 1e-6 &&
                //        Math.Abs(points.GetPoint(i)[2] - ClickedPoint[2]) < 1e-6)
                //    {
                //        selected = true;
                //        P = points.GetPoint(i);
                //        break;
                //    }
                //}
                //
                //if (selected == true)
                //{
                //    SelectionPoints.InsertNextPoint(P[0], P[1], P[2]);
                //
                //    SelectionGlyph = vtkGlyph3D.New();
                //    SelectionGlyph.SetInput(SelectionPolyData);
                //    SelectionGlyph.SetSourceConnection(SelectionSphere.GetOutputPort());
                //    SelectionMapper.SetInputConnection(SelectionGlyph.GetOutputPort());
                //
                //    // Refresh Viewport
                //    Refresh();
                //}
            }
        }