AddTriangle() public method

public AddTriangle ( int index0, int index1, int index2 ) : void
index0 int
index1 int
index2 int
return void
コード例 #1
0
	public static void BuildRectangleMesh(MeshBuilder meshBuilder, 
	                                      float width,
	                                      float height, 
	                                      float wStart,
	                                      float hStart,
	                                      float amount) {
		float fullW;
		float fullH;
		
		if ( width >= height ) {
			fullH = height*amount;
			fullW = width-(height-fullH);
		}
		else {
			fullW = width*amount;
			fullH = height-(width-fullW);
		}

		meshBuilder.Resize(4, 6);
		meshBuilder.ResetIndices();
		
		meshBuilder.AddVertex(new Vector3(fullW,  fullH, 0));
		meshBuilder.AddVertex(new Vector3(fullW, fullH*hStart, 0)); 
		meshBuilder.AddVertex(new Vector3(fullW*wStart, fullH*hStart, 0));
		meshBuilder.AddVertex(new Vector3(fullW*wStart, fullH, 0));
		
		meshBuilder.AddTriangle(0, 1, 2);
		meshBuilder.AddTriangle(0, 2, 3);
		
		meshBuilder.AddRemainingUvs(Vector2.zero);
	}
コード例 #2
0
    /// <summary>
    /// Builds a single quad based on a position offset and width and length vectors.
    /// </summary>
    /// <param name="meshBuilder">The mesh builder currently being added to.</param>
    /// <param name="offset">A position offset for the quad.</param>
    /// <param name="widthDir">The width vector of the quad.</param>
    /// <param name="lengthDir">The length vector of the quad.</param>
    public static void BuildQuad(MeshBuilder meshBuilder, Vector3 offset, Vector3 widthDir, Vector3 lengthDir) {
        Vector3 normal = Vector3.Cross(lengthDir, widthDir).normalized;

        meshBuilder.Vertices.Add(offset);
        meshBuilder.UVs.Add(new Vector2(0.0f, 0.0f));
        meshBuilder.Normals.Add(normal);

        meshBuilder.Vertices.Add(offset + lengthDir);
        meshBuilder.UVs.Add(new Vector2(0.0f, 1.0f));
        meshBuilder.Normals.Add(normal);

        meshBuilder.Vertices.Add(offset + lengthDir + widthDir);
        meshBuilder.UVs.Add(new Vector2(1.0f, 1.0f));
        meshBuilder.Normals.Add(normal);

        meshBuilder.Vertices.Add(offset + widthDir);
        meshBuilder.UVs.Add(new Vector2(1.0f, 0.0f));
        meshBuilder.Normals.Add(normal);

        //we don't know how many verts the meshBuilder is up to, but we only care about the four we just added:
        int baseIndex = meshBuilder.Vertices.Count - 4;

        meshBuilder.AddTriangle(baseIndex, baseIndex + 1, baseIndex + 2);
        meshBuilder.AddTriangle(baseIndex, baseIndex + 2, baseIndex + 3);
    }
コード例 #3
0
	public static void BuildArcMesh(MeshBuilder meshBuilder,
	                               float innerRadius,
	                               float outerRadius,
	                               float startAngle,
	                               float endAngle,
	                               int steps) {
		float angleFull = endAngle - startAngle;
		float angleInc = angleFull / steps;
		float angle = startAngle;

		meshBuilder.Resize((steps+1)*2, steps*6);
		meshBuilder.ResetIndices ();

		for (int i = 0; i <= steps; ++i) {
			float uv = i/(float)steps;

			meshBuilder.AddVertex(GetArcPoint(innerRadius, angle));
			meshBuilder.AddVertex(GetArcPoint(outerRadius, angle));

			meshBuilder.AddUv(new Vector2(uv, 0));
			meshBuilder.AddUv(new Vector2(uv, 1));

			if ( i > 0 ) {
				int vi = meshBuilder.VertexIndex;
				meshBuilder.AddTriangle(vi-3, vi-4, vi-2);
				meshBuilder.AddTriangle(vi-1, vi-3, vi-2);
			}

			angle += angleInc;
		}
	}
コード例 #4
0
    void BuildQuad(MeshBuilder meshBuilder, Vector3 offset, Vector3 widthDir, Vector3 lengthDir, int sizeX, int sizeY)
    {
        Vector3 normal = Vector3.Cross (lengthDir, widthDir).normalized;

        float vx, vy;

        // Define vertices e triangulos
        for (int y = 0; y <= sizeY; y++) {
            for (int x = 0; x <= sizeX; x++) {
                vx = ((float) x / sizeX);
                vy = ((float) y / sizeY);

                meshBuilder.Vertices.Add (offset + vx * lengthDir + vy * widthDir);
                meshBuilder.UVs.Add (new Vector2(vx, vy));
                meshBuilder.Normals.Add (normal);
            }
        }

        int baseIndex = meshBuilder.Vertices.Count - (sizeX+1) * (sizeY+1);

        for (int vi = baseIndex, y = 0; y < sizeY; y++, vi++) {
            for (int x = 0; x < sizeX; x++, vi++) {
                meshBuilder.AddTriangle (vi, vi+1, vi+sizeX+2);
                meshBuilder.AddTriangle (vi, vi+sizeX+2, vi+sizeX+1);
            }
        }
    }
コード例 #5
0
ファイル: QuadTest.cs プロジェクト: jakupklein/martinGame
    void BuildQuad(MeshBuilder meshBuilder, Vector3 offset, Vector3 widthDirection, Vector3 lengthDirection)
    {
        Vector3 normal = Vector3.Cross(lengthDirection, widthDirection).normalized;

        //Set up the vertices and triangles:
        meshBuilder.Vertices.Add(offset);
        meshBuilder.Uvs.Add(new Vector2(0.0f, 0.0f));
        meshBuilder.Normals.Add(normal);

        meshBuilder.Vertices.Add(offset + lengthDirection);
        meshBuilder.Uvs.Add(new Vector2(0.0f, 1.0f));
        meshBuilder.Normals.Add(normal);

        meshBuilder.Vertices.Add(offset + lengthDirection + widthDirection);
        meshBuilder.Uvs.Add(new Vector2(1.0f, 1.0f));
        meshBuilder.Normals.Add(normal);

        meshBuilder.Vertices.Add(offset + widthDirection);
        meshBuilder.Uvs.Add(new Vector2(1.0f, 0.0f));
        meshBuilder.Normals.Add(normal);

        int startPoint = meshBuilder.Vertices.Count - 4;
        if(first){
        meshBuilder.AddTriangle(startPoint, startPoint + 1, startPoint + 2);
        meshBuilder.AddTriangle(startPoint, startPoint + 2, startPoint + 3);
        //first = false;
        }
    }
コード例 #6
0
    //BuildQuad with vectors
    public static Mesh BuildQuad(MeshBuilder meshBuilder, Vector3 offset, Vector3 widthDir, Vector3 lengthDir)
    {
        Vector3 normal = Vector3.Cross(lengthDir, widthDir).normalized;

        meshBuilder.Vertices.Add(offset);
        meshBuilder.UVs.Add(new Vector2(0.0f, 0.0f));
        meshBuilder.Normals.Add(normal);

        meshBuilder.Vertices.Add(offset + lengthDir);
        meshBuilder.UVs.Add(new Vector2(0.0f, 1.0f));
        meshBuilder.Normals.Add(normal);

        meshBuilder.Vertices.Add(offset + lengthDir + widthDir);
        meshBuilder.UVs.Add(new Vector2(1.0f, 1.0f));
        meshBuilder.Normals.Add(normal);

        meshBuilder.Vertices.Add(offset + widthDir);
        meshBuilder.UVs.Add(new Vector2(1.0f, 0.0f));
        meshBuilder.Normals.Add(normal);

        int baseIndex = meshBuilder.Vertices.Count - 4;

        meshBuilder.AddTriangle(baseIndex, baseIndex + 1, baseIndex + 2);
        meshBuilder.AddTriangle(baseIndex, baseIndex + 2, baseIndex + 3);

        Mesh _CreatedMesh = meshBuilder.CreateMesh();
        _CreatedMesh.RecalculateNormals();
        return _CreatedMesh;
    }
コード例 #7
0
 protected void AddQuadTriangles(MeshBuilder meshBuilder, int index0, int index1, int index2, int index3)
 {
     if (meshFace == MeshFace.Front || meshFace == MeshFace.Both) {
         meshBuilder.AddTriangle(index0, index1, index2);
         meshBuilder.AddTriangle(index1, index3, index2);
     }
     if(meshFace == MeshFace.Back || meshFace == MeshFace.Both){
         meshBuilder.AddTriangle(index1, index0, index2);
         meshBuilder.AddTriangle(index1, index2, index3);
     }
 }
コード例 #8
0
 protected virtual void AddTrianglesAtIndex(MeshBuilder meshBuilder, int originIndex, int i)
 {
     if (meshFace == MeshFace.Front || meshFace == MeshFace.Both) {
         meshBuilder.AddTriangle(originIndex,
                                 originIndex + i + 1,
                                 originIndex + (i + 1) % curveVerticesNumber + 1);
     }
     if(meshFace == MeshFace.Back || meshFace == MeshFace.Both){
         meshBuilder.AddTriangle(originIndex,
                                 originIndex + (i + 1) % curveVerticesNumber + 1,
                                 originIndex + i + 1);
     }
 }
コード例 #9
0
    MeshBuilder GenerateCurveTriangles(MeshBuilder meshBuilder, bool doubleTriangles = false)
    {
        int baseIndex = 0;
        int sizeX = 2;
        int sizeY = meshBuilder.Vertices.Count / 3 - 1;

        int vi = baseIndex;

        for (int y = 0; y < sizeY; y++, vi++) {
            for (int x = 0; x < sizeX; x++, vi++) {
                meshBuilder.AddTriangle (vi, vi + sizeX + 1, vi + 1);
                meshBuilder.AddTriangle (vi + 1, vi + sizeX + 1, vi + sizeX + 2);

                if (y == sizeY - 1) {
                    meshBuilder.AddTriangle (vi + sizeX + 1, baseIndex + x, vi + sizeX + 2);
                    meshBuilder.AddTriangle (baseIndex + x + 1, vi + sizeX + 2, baseIndex + x);
                }

                if (doubleTriangles) {
                    meshBuilder.AddTriangle (vi + 1, vi + sizeX + 1, vi);
                    meshBuilder.AddTriangle (vi + sizeX + 2, vi + sizeX + 1, vi + 1);

                    if (y == sizeY - 1) {
                        meshBuilder.AddTriangle (vi + sizeX + 2, baseIndex + x, vi + sizeX + 1);
                        meshBuilder.AddTriangle (baseIndex + x, vi + sizeX + 2, baseIndex + x + 1);
                    }
                }
            }
        }
        return meshBuilder;
    }
コード例 #10
0
    void BuildQuadForGrid(MeshBuilder meshBuilder, Vector3 position, Vector2 uv,
    bool buildTriangles, int vertsPerRow)
    {
        meshBuilder.Vertices.Add(position);
        meshBuilder.UVs.Add(uv);

        if (buildTriangles)
        {
            int baseIndex = meshBuilder.Vertices.Count - 1;

            int index0 = baseIndex;
            int index1 = baseIndex - 1;
            int index2 = baseIndex - vertsPerRow;
            int index3 = baseIndex - vertsPerRow - 1;

            meshBuilder.AddTriangle(index0, index2, index1);
            meshBuilder.AddTriangle(index2, index3, index1);
        }
    }
コード例 #11
0
 private static object buildTri()
 {
     var mb = new MeshBuilder(true, false);
     var p0 = new Point3D(0, 0, 0);
     var p1 = new Point3D(1, 0, 0);
     var p2 = new Point3D(1, 1, 0);
     mb.AddTriangle(p0, p1, p2);
     mb.Normals.ToList().ForEach(x => System.Diagnostics.Trace.WriteLine(x.ToString()));
     return mb.ToMesh();
 }
コード例 #12
0
ファイル: TubeRenderer.cs プロジェクト: jceipek/UnityBase
    static void BuildRing(MeshBuilder meshBuilder, int segmentCount, Vector3 center, float radius,
                           float v, bool buildTriangles, Quaternion rotation)
    {
        // Precomputed Sine/Cosine circle drawing from http://slabode.exofire.net/circle_draw.shtml
        float theta = 2f * Mathf.PI / (float)segmentCount;
        float c = Mathf.Cos(theta);
        float s = Mathf.Sin(theta);
        float t;

        float x = radius;//we start at angle = 0
        float y = 0;

        // Since we haven't added any yet, we don't need to -1
        int ringBaseIndex = meshBuilder.VertexCount;
        for (int i = 0; i < segmentCount; i++) {
            Vector3 unitPosition = Vector3.zero;
            unitPosition.x = x;
            unitPosition.z = y;

            unitPosition = rotation * unitPosition;
            meshBuilder.AddVertex(center + unitPosition);// * radius
            meshBuilder.AddNormal(unitPosition);
            meshBuilder.AddUV(new Vector2((float)i / segmentCount, v));

            if (buildTriangles) {
                int vertsPerRow = segmentCount;
                int index0 = ringBaseIndex + i;
                int index1 = ringBaseIndex + MathHelpers.Mod(i - 1, segmentCount); // before base
                int index2 = ringBaseIndex + i - vertsPerRow; // below base
                int index3 = ringBaseIndex + MathHelpers.Mod(i - 1, segmentCount) - vertsPerRow; // before below base

                // Debug.Log(string.Format("TRI{0}>{1}>{2}", index0, index2, index1));
                meshBuilder.AddTriangle(index0, index2, index1);
                // Debug.Log(string.Format("TRI{0}>{1}>{2}", index2, index3, index1));
                meshBuilder.AddTriangle(index2, index3, index1);
            }

            t = x;
            x = c * x - s * y;
            y = s * t + c * y;
        }
    }
コード例 #13
0
ファイル: ProcQuad.cs プロジェクト: Ideae/SpatialExperiments
    //Initialisation:
    private void Start()
    {
        //Create a new mesh builder:
        MeshBuilder meshBuilder = new MeshBuilder();

        //Add the vertices:
        meshBuilder.Vertices.Add(new Vector3(0.0f, 0.0f, 0.0f));
        meshBuilder.UVs.Add(new Vector2(0.0f, 0.0f));
        meshBuilder.Normals.Add(Vector3.up);

        meshBuilder.Vertices.Add(new Vector3(0.0f, 0.0f, m_Length));
        meshBuilder.UVs.Add(new Vector2(0.0f, 1.0f));
        meshBuilder.Normals.Add(Vector3.up);

        meshBuilder.Vertices.Add(new Vector3(m_Width, 0.0f, m_Length));
        meshBuilder.UVs.Add(new Vector2(1.0f, 1.0f));
        meshBuilder.Normals.Add(Vector3.up);

        meshBuilder.Vertices.Add(new Vector3(m_Width, 0.0f, 0.0f));
        meshBuilder.UVs.Add(new Vector2(1.0f, 0.0f));
        meshBuilder.Normals.Add(Vector3.up);

        //Add the triangles:
        meshBuilder.AddTriangle(0, 1, 2);
        meshBuilder.AddTriangle(0, 2, 3);

        //Create the mesh:
        Mesh mesh = meshBuilder.CreateMesh();

        //Look for a MeshFilter component attached to this GameObject:
        MeshFilter filter = GetComponent<MeshFilter>();

        //If the MeshFilter exists, attach the new mesh to it.
        //Assuming the GameObject also has a renderer attached, our new mesh will now be visible in the scene.
        if (filter != null)
        {
            filter.sharedMesh = mesh;
        }
    }
コード例 #14
0
    void BuildQuad(MeshBuilder meshBuilder, Vector3 offset)
    {
        meshBuilder.Vertices.Add(new Vector3(0.0f, 0.0f, 0.0f) + offset);
        meshBuilder.UVs.Add(new Vector2(0.0f, 0.0f));
        meshBuilder.Normals.Add(Vector3.up);

        meshBuilder.Vertices.Add(new Vector3(0.0f, 0.0f, spacing) + offset);
        meshBuilder.UVs.Add(new Vector2(0.0f, 1.0f));
        meshBuilder.Normals.Add(Vector3.up);

        meshBuilder.Vertices.Add(new Vector3(spacing, 0.0f, spacing) + offset);
        meshBuilder.UVs.Add(new Vector2(1.0f, 1.0f));
        meshBuilder.Normals.Add(Vector3.up);

        meshBuilder.Vertices.Add(new Vector3(spacing, 0.0f, 0.0f) + offset);
        meshBuilder.UVs.Add(new Vector2(1.0f, 0.0f));
        meshBuilder.Normals.Add(Vector3.up);

        int baseIndex = meshBuilder.Vertices.Count - 4;

        meshBuilder.AddTriangle(baseIndex, baseIndex + 1, baseIndex + 2);
        meshBuilder.AddTriangle(baseIndex, baseIndex + 2, baseIndex + 3);
    }
コード例 #15
0
    void BuildQuad(MeshBuilder meshBuilder, Vector3 offset)
    {
        meshBuilder.Vertices.Add (new Vector3(0f, 0f, 0f) + offset);
        meshBuilder.UVs.Add (new Vector2(0f, 0f));
        meshBuilder.Normals.Add (Vector3.up);

        meshBuilder.Vertices.Add (new Vector3(0f, 0f, meshLength) + offset);
        meshBuilder.UVs.Add (new Vector2(0f, 1f));
        meshBuilder.Normals.Add (Vector3.up);

        meshBuilder.Vertices.Add (new Vector3(meshWidth, 0f, meshLength) + offset);
        meshBuilder.UVs.Add (new Vector2(1f, 1f));
        meshBuilder.Normals.Add (Vector3.up);

        meshBuilder.Vertices.Add (new Vector3(meshWidth, 0f, 0f) + offset);
        meshBuilder.UVs.Add (new Vector2(1f, 0f));
        meshBuilder.Normals.Add (Vector3.up);

        int baseIndex = meshBuilder.Vertices.Count - 4;

        meshBuilder.AddTriangle (baseIndex, baseIndex+1, baseIndex+2);
        meshBuilder.AddTriangle (baseIndex, baseIndex+2, baseIndex+3);
    }
コード例 #16
0
    /// <summary>
    /// Builds a single quad in the XZ plane, facing up the Y axis.
    /// </summary>
    /// <param name="meshBuilder">The mesh builder currently being added to.</param>
    /// <param name="offset">A position offset for the quad.</param>
    /// <param name="width">The width of the quad.</param>
    /// <param name="length">The length of the quad.</param>
    public static void BuildQuad(MeshBuilder meshBuilder, Vector3 offset, float width, float length) {
        meshBuilder.Vertices.Add(new Vector3(0.0f, 0.0f, 0.0f) + offset);
        meshBuilder.UVs.Add(new Vector2(0.0f, 0.0f));
        meshBuilder.Normals.Add(Vector3.up);

        meshBuilder.Vertices.Add(new Vector3(0.0f, 0.0f, length) + offset);
        meshBuilder.UVs.Add(new Vector2(0.0f, 1.0f));
        meshBuilder.Normals.Add(Vector3.up);

        meshBuilder.Vertices.Add(new Vector3(width, 0.0f, length) + offset);
        meshBuilder.UVs.Add(new Vector2(1.0f, 1.0f));
        meshBuilder.Normals.Add(Vector3.up);

        meshBuilder.Vertices.Add(new Vector3(width, 0.0f, 0.0f) + offset);
        meshBuilder.UVs.Add(new Vector2(1.0f, 0.0f));
        meshBuilder.Normals.Add(Vector3.up);

        //we don't know how many verts the meshBuilder is up to, but we only care about the four we just added:
        int baseIndex = meshBuilder.Vertices.Count - 4;

        meshBuilder.AddTriangle(baseIndex, baseIndex + 1, baseIndex + 2);
        meshBuilder.AddTriangle(baseIndex, baseIndex + 2, baseIndex + 3);
    }
コード例 #17
0
        /// <summary>
        /// Including all Geometry Elements
        /// </summary>
        /// <param name="ifcElement"></param>
        /// <param name="context"></param>
        /// <param name="wcsTransformation"></param>
        /// <returns></returns>
        public static MeshGeometry3D WriteAllTriangles(IIfcProduct ifcElement, Xbim3DModelContext context, XbimMatrix3D wcsTransformation)
        {
            MeshBuilder meshBuilder = new MeshBuilder(false, false);

            // var allTriangles = new List<Triangles>();
            foreach (XbimShapeInstance instance in context.ShapeInstancesOf(ifcElement))
            {
                XbimShapeGeometry geometry = context.ShapeGeometry(instance);
                var data = ((IXbimShapeGeometryData)geometry).ShapeData;
                using (var stream = new MemoryStream(data))
                {
                    using (var reader = new BinaryReader(stream))
                    {
                        XbimShapeTriangulation mesh = reader.ReadShapeTriangulation();
                        mesh = mesh.Transform(instance.Transformation);
                        // WCS transforms
                        mesh = mesh.Transform(wcsTransformation);

                        foreach (XbimFaceTriangulation face in mesh.Faces)
                        {
                            var j = 0;
                            for (var i = 0; i < face.TriangleCount; i++)
                            {
                                int k      = i + j;
                                var point1 = new Point3D {
                                    X = mesh.Vertices[face.Indices[k]].X, Y = mesh.Vertices[face.Indices[k]].Y, Z = mesh.Vertices[face.Indices[k]].Z
                                };
                                j++;
                                k = i + j;
                                var point2 = new Point3D {
                                    X = mesh.Vertices[face.Indices[k]].X, Y = mesh.Vertices[face.Indices[k]].Y, Z = mesh.Vertices[face.Indices[k]].Z
                                };
                                j++;
                                k = i + j;
                                var point3 = new Point3D {
                                    X = mesh.Vertices[face.Indices[k]].X, Y = mesh.Vertices[face.Indices[k]].Y, Z = mesh.Vertices[face.Indices[k]].Z
                                };

                                meshBuilder.AddTriangle(point1, point2, point3);
                            }
                        }
                    }
                }
            }
            return(meshBuilder.ToMesh());
            // return allTriangles;
        }
コード例 #18
0
        public void AddTriangle_Normals()
        {
            var mb = new MeshBuilder();
            var p0 = new Point3D(0, 0, 0);
            var p1 = new Point3D(1, 0, 0);
            var p2 = new Point3D(1, 1, 0);

            mb.AddTriangle(p0, p1, p2);

            Assert.IsTrue(mb.HasNormals);
            Assert.AreEqual(3, mb.Normals.Count);

            foreach (Point3D normal in mb.Normals)
            {
                Assert.AreEqual(new Point3D(0, 0, 1), normal);
            }
        }
コード例 #19
0
    // builds the shape
    // build quads for spline
    protected void BuildQuadSpline(MeshBuilder meshBuilder, Vector3 pointA, Vector3 pointB, Vector3 normalA, Vector3 normalB, int total, bool reverse)
    {
        // vertices are arranged in this order by point #
        // (0, 2) O---O (1, 3)

//        if (reverse)
//            normal *= -1;

        meshBuilder.Vertices.Add(pointA);
        meshBuilder.Normals.Add(normalA);

        meshBuilder.Vertices.Add(pointB);
        meshBuilder.Normals.Add(normalB);

        meshBuilder.Vertices.Add(pointA);
        meshBuilder.Normals.Add(-normalA);

        meshBuilder.Vertices.Add(pointB);
        meshBuilder.Normals.Add(-normalB);


        int baseIndex = meshBuilder.Vertices.Count - 8;

        // check if it has enough data to render the quads
        if (baseIndex - total >= 0)
        {
            if (!reverse)
            {
                meshBuilder.AddTriangle(baseIndex + 4, baseIndex + 5, baseIndex);
                meshBuilder.AddTriangle(baseIndex + 5, baseIndex + 1, baseIndex);
                meshBuilder.AddTriangle(baseIndex + 2, baseIndex + 7, baseIndex + 6);
                meshBuilder.AddTriangle(baseIndex + 2, baseIndex + 3, baseIndex + 7);
            }
            else
            {
                meshBuilder.AddTriangle(baseIndex, baseIndex + 5, baseIndex + 4);
                meshBuilder.AddTriangle(baseIndex, baseIndex + 1, baseIndex + 5);
                meshBuilder.AddTriangle(baseIndex + 6, baseIndex + 7, baseIndex + 2);
                meshBuilder.AddTriangle(baseIndex + 7, baseIndex + 3, baseIndex + 2);
            }
        }
    }
コード例 #20
0
        private void LoadWater()
        {
            if (world.Water == null)
            {
                return;
            }

            var waterContainer = new GameObject("water");

            waterContainer.transform.SetParent(baseObject.transform, false);

            var mb = new MeshBuilder();

            mb.AddVertex(new Vector3(-data.InitialSize.x, -world.Water.Level, data.InitialSize.y));
            mb.AddVertex(new Vector3(data.InitialSize.x, -world.Water.Level, data.InitialSize.y));
            mb.AddVertex(new Vector3(-data.InitialSize.x, -world.Water.Level, -data.InitialSize.y));
            mb.AddVertex(new Vector3(data.InitialSize.x, -world.Water.Level, -data.InitialSize.y));

            mb.AddNormal(Vector3.up);
            mb.AddNormal(Vector3.up);
            mb.AddNormal(Vector3.up);
            mb.AddNormal(Vector3.up);

            mb.AddUV(new Vector2(0, data.InitialSize.y / 2f));
            mb.AddUV(new Vector2(data.InitialSize.x / 2f, data.InitialSize.y / 2f));
            mb.AddUV(new Vector2(0, 0));
            mb.AddUV(new Vector2(data.InitialSize.x / 2f, 0));

            mb.AddTriangle(0);
            mb.AddTriangle(1);
            mb.AddTriangle(3);
            mb.AddTriangle(0);
            mb.AddTriangle(3);
            mb.AddTriangle(2);

            var mesh = mb.Build("Water");

            var mf = waterContainer.AddComponent <MeshFilter>();
            var mr = waterContainer.AddComponent <MeshRenderer>();

            var material = AssetDatabase.LoadAssetAtPath <Material>("Assets/Textures/WaterTemp.mat");

            mr.material = material;

            mr.shadowCastingMode    = ShadowCastingMode.Off;
            mr.receiveShadows       = false;
            mr.reflectionProbeUsage = ReflectionProbeUsage.Off;
            mr.lightProbeUsage      = LightProbeUsage.Off;

            mf.sharedMesh = mesh;
        }
コード例 #21
0
    /// <summary>
    /// Builds a single triangle.
    /// </summary>
    /// <param name="meshBuilder">The mesh builder currently being added to.</param>
    /// <param name="corner0">The vertex position at index 0 of the triangle.</param>
    /// <param name="corner1">The vertex position at index 1 of the triangle.</param>
    /// <param name="corner2">The vertex position at index 2 of the triangle.</param>
    protected void BuildTriangle(MeshBuilder meshBuilder, Vector3 corner0, Vector3 corner1, Vector3 corner2)
    {
        Vector3 normal = Vector3.Cross((corner1 - corner0), (corner2 - corner0)).normalized;

        meshBuilder.Vertices.Add(corner0);
        meshBuilder.UVs.Add(new Vector2(0.0f, 0.0f));
        meshBuilder.Normals.Add(normal);

        meshBuilder.Vertices.Add(corner1);
        meshBuilder.UVs.Add(new Vector2(0.0f, 1.0f));
        meshBuilder.Normals.Add(normal);

        meshBuilder.Vertices.Add(corner2);
        meshBuilder.UVs.Add(new Vector2(1.0f, 1.0f));
        meshBuilder.Normals.Add(normal);

        int baseIndex = meshBuilder.Vertices.Count - 3;

        meshBuilder.AddTriangle(baseIndex, baseIndex + 1, baseIndex + 2);
    }
コード例 #22
0
ファイル: MainWindow.xaml.cs プロジェクト: nsmela/Fabolus
        /// <summary>
        /// Colored triangles to visualize overhangs
        /// </summary>
        /// <param name="angle"></param>
        /// <param name="inverted"></param>
        /// <returns></returns>
        private MeshGeometry3D ShowSteepAngles(double angle, bool inverted)
        {
            //to store the outgoing mesh
            var            mesh        = new MeshBuilder(true);
            MeshGeometry3D scannedMesh = bolus.Mesh();

            Vector3D angleDown = new Vector3D(0, 0, -1);

            //reference angle for normals
            if (inverted)
            {
                angleDown = new Vector3D(0, 0, 1);
            }

            //calculate for each triangle
            for (int triangle = 0; triangle < scannedMesh.TriangleIndices.Count; triangle += 3)
            {
                //get the triangle's normal
                int i0 = scannedMesh.TriangleIndices[triangle];
                int i1 = scannedMesh.TriangleIndices[triangle + 1];
                int i2 = scannedMesh.TriangleIndices[triangle + 2];

                Point3D p0 = scannedMesh.Positions[i0];
                Point3D p1 = scannedMesh.Positions[i1];
                Point3D p2 = scannedMesh.Positions[i2];

                var normal = CalculateSurfaceNormal(p0, p1, p2);

                //calculate normal's angle from the ground
                //using the z-axis as to determine how the angle if from the ground
                var degrees = Vector3D.AngleBetween(normal, angleDown);

                //if angle less than steepangle, add the triangle to the overhang mesh
                if (degrees < angle)
                {
                    mesh.AddTriangle(p0, p1, p2);
                }
            }

            return(mesh.ToMesh());
        }
コード例 #23
0
        private static void CreatePolygon(VectorTileFeature feature, Pallete pallete, Model3DGroup model3DGroup, Vector2 <int> shiftCoords)
        {
            PointCollection points             = new PointCollection();
            List <List <Vector2 <int> > > list = feature.Geometry <int>();

            foreach (List <Vector2 <int> > item in list)
            {
                points.Clear();

                foreach (Vector2 <int> point in item)
                {
                    points.Add(new Point(point.X + shiftCoords.X, point.Y + shiftCoords.Y));
                }

                points.RemoveAt(points.Count - 1);

                var model       = new GeometryModel3D();
                var meshbuilder = new MeshBuilder(true, true);

                var result = CuttingEarsTriangulator.Triangulate(points);

                List <int> tri = new List <int>();
                for (int i = 0; i < result.Count; i++)
                {
                    tri.Add(result[i]);
                    if (tri.Count == 3)
                    {
                        //Console.WriteLine("Triangle " + (i / 3).ToString() + " : " + tri[0].ToString() + ", " + tri[1].ToString() + ", " + tri[2].ToString());
                        meshbuilder.AddTriangle(new Point3D(points[tri[0]].X, points[tri[0]].Y, 1),
                                                new Point3D(points[tri[1]].X, points[tri[1]].Y, 1),
                                                new Point3D(points[tri[2]].X, points[tri[2]].Y, 1));
                        tri.Clear();
                    }
                }

                model.Geometry = meshbuilder.ToMesh();
                model.Material = MaterialHelper.CreateMaterial(pallete.MainFillColor.ToMediaColor());

                model3DGroup.Children.Add(model);
            }
        }
コード例 #24
0
        public GeometryModel3D GenerateInteractionDiagram(Column column, Color color)
        {
            double scaleXYZ = 10;

            Console.WriteLine("MaxMX = {0}, MaxMy = {1}, MaxP = {2}", batchDesign.MaxMx, batchDesign.MaxMy, batchDesign.MaxP);
            List <Point3D> normalPoints = column.diagramVertices.Select(x => new Point3D(x.X / BatchDesign.MaxMx, x.Y / BatchDesign.MaxMy, -x.Z / BatchDesign.MaxP)).ToList();

            normalPoints = normalPoints.Select(x => new Point3D(scaleXYZ * x.X, scaleXYZ * x.Y, scaleXYZ * x.Z)).ToList();

            var meshBuilder = new MeshBuilder(false, true);

            for (int i = 0; i < normalPoints.Count; i++)
            {
                Point3D pt = normalPoints[i];
                meshBuilder.Positions.Add(pt);
                meshBuilder.TextureCoordinates.Add(new Point());
            }

            for (int i = 0; i < column.diagramFaces.Count; i++)
            {
                var t = column.diagramFaces[i];
                meshBuilder.AddTriangle(new List <int> {
                    column.diagramVertices.IndexOf(t.Points[0]),
                    column.diagramVertices.IndexOf(t.Points[1]),
                    column.diagramVertices.IndexOf(t.Points[2])
                });
                meshBuilder.AddCylinder(normalPoints[column.diagramVertices.IndexOf(t.Points[0])],
                                        normalPoints[column.diagramVertices.IndexOf(t.Points[1])], 0.05, 8);
                meshBuilder.AddCylinder(normalPoints[column.diagramVertices.IndexOf(t.Points[1])],
                                        normalPoints[column.diagramVertices.IndexOf(t.Points[2])], 0.05, 8);
                meshBuilder.AddCylinder(normalPoints[column.diagramVertices.IndexOf(t.Points[0])],
                                        normalPoints[column.diagramVertices.IndexOf(t.Points[2])], 0.05, 8);
            }
            //var mat = new DiffuseMaterial(GradientBrushes.BlueWhiteRed);
            var mesh = new GeometryModel3D(meshBuilder.ToMesh(), MaterialHelper.CreateMaterial(color));

            mesh.BackMaterial = mesh.Material;

            return(mesh);
        }
コード例 #25
0
        public PartMesh(string filename)
        {
            var meshBuilder = new MeshBuilder(false, false);

            var min = new Point3D(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity);
            var max = new Point3D(double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity);

            using (var stream = modelAssembly.GetManifestResourceStream("Hexenstein.Models." + filename))
                using (var reader = new BinaryReader(stream))
                {
                    var header = reader.ReadBytes(80);

                    var num = reader.ReadUInt32();

                    for (int i = 0; i < num; i++)
                    {
                        var normal = ReadPoint(reader);
                        var v1     = ReadPoint(reader);
                        var v2     = ReadPoint(reader);
                        var v3     = ReadPoint(reader);
                        var extra  = reader.ReadInt16();

                        meshBuilder.AddTriangle(v1, v2, v3);

                        min = new Point3D(
                            Math.Min(Math.Min(Math.Min(min.X, v1.X), v2.X), v3.X),
                            Math.Min(Math.Min(Math.Min(min.Y, v1.Y), v2.Y), v3.Y),
                            Math.Min(Math.Min(Math.Min(min.Z, v1.Z), v2.Z), v3.Z));

                        max = new Point3D(
                            Math.Max(Math.Max(Math.Max(max.X, v1.X), v2.X), v3.X),
                            Math.Max(Math.Max(Math.Max(max.Y, v1.Y), v2.Y), v3.Y),
                            Math.Max(Math.Max(Math.Max(max.Z, v1.Z), v2.Z), v3.Z));
                    }
                }

            Centre = ((max - min) / 2 + min);
            Mesh   = meshBuilder.ToMesh(true);
        }
コード例 #26
0
        public void BuildMesh()
        {
            GetDeformedMesh();
            var         modelGroup  = new Model3DGroup();
            MeshBuilder meshBuilder = new MeshBuilder(false, true);

            //List<Point3D> pointDisps = DeformedMesh.Select(p => new Point3D(p.X, p.Y, p.Z)).ToList();
            DeformedMesh.ForEach(p =>
            {
                meshBuilder.Positions.Add(p);
                meshBuilder.TextureCoordinates.Add(new System.Windows.Point());
            });
            results.T3.ForEach(t =>
            {
                meshBuilder.AddTriangle(new List <int> {
                    t[0], t[1], t[2]
                });
                meshBuilder.AddCylinder(DeformedMesh[t[0]], DeformedMesh[t[1]], 0.05, 4);
                meshBuilder.AddCylinder(DeformedMesh[t[1]], DeformedMesh[t[2]], 0.05, 4);
                meshBuilder.AddCylinder(DeformedMesh[t[0]], DeformedMesh[t[2]], 0.05, 4);
            });
            //fem.modelGeo.Beams.ForEach(b =>
            //{
            //    meshBuilder.AddCylinder(new Point3D(b.Start.X, b.Start.Y, b.Start.Z), new Point3D(b.End.X, b.End.Y, b.End.Z), 0.1, 8);
            //});
            results.L2.ForEach(l =>
            {
                var p1 = DeformedMesh[l[0]];
                var p2 = DeformedMesh[l[1]];
                meshBuilder.AddCylinder(p1, p2, 0.1, 8);
            });

            var color = Color.FromArgb(150, 200, 0, 0);
            var mesh  = new GeometryModel3D(meshBuilder.ToMesh(), MaterialHelper.CreateMaterial(color));

            mesh.BackMaterial = mesh.Material;
            modelGroup.Children.Add(mesh);
            Mesh = modelGroup;
        }
コード例 #27
0
        private void gambarproyeksi()
        {
            var tembokrumah   = new MeshBuilder(false, false);
            var ataprumah     = new MeshBuilder(false, false);
            var garisproyeksi = new MeshBuilder(false, false);

            tembokrumah.AddBox(new Point3D((titik2[0].X + titik2[2].X) / 2, (titik2[0].Y + titik2[2].Y) / 2, (titik2[0].Z + titik2[2].Z) / 2), (titik2[2].X - titik2[0].X), (titik2[2].Y - titik2[0].Y), (titik2[2].Z - titik2[0].Z));
            tembokrumah.AddBox(new Point3D((titik2[0].X + titik2[5].X) / 2, (titik2[0].Y + titik2[5].Y) / 2, (titik2[0].Z + titik2[5].Z) / 2), (titik2[5].X - titik2[0].X), (titik2[5].Y - titik2[0].Y), (titik2[5].Z - titik2[0].Z));
            tembokrumah.AddBox(new Point3D((titik2[1].X + titik2[6].X) / 2, (titik2[1].Y + titik2[6].Y) / 2, (titik2[1].Z + titik2[6].Z) / 2), (titik2[6].X - titik2[1].X), (titik2[6].Y - titik2[1].Y), (titik2[6].Z - titik2[1].Z));
            tembokrumah.AddBox(new Point3D((titik2[2].X + titik2[7].X) / 2, (titik2[2].Y + titik2[7].Y) / 2, (titik2[2].Z + titik2[7].Z) / 2), (titik2[7].X - titik2[2].X), (titik2[7].Y - titik2[2].Y), (titik2[7].Z - titik2[2].Z));
            tembokrumah.AddBox(new Point3D((titik2[3].X + titik2[4].X) / 2, (titik2[3].Y + titik2[4].Y) / 2, (titik2[3].Z + titik2[4].Z) / 2), (titik2[4].X - titik2[3].X), (titik2[4].Y - titik2[3].Y), (titik2[4].Z - titik2[3].Z));
            ataprumah.AddTriangle(titik2[4], titik2[5], titik2[8]);
            ataprumah.AddTriangle(titik2[6], titik2[7], titik2[9]);
            ataprumah.AddTriangle(titik2[5], titik2[6], titik2[8]);
            ataprumah.AddTriangle(titik2[7], titik2[4], titik2[8]);
            ataprumah.AddTriangle(titik2[9], titik2[8], titik2[6]);
            ataprumah.AddTriangle(titik2[8], titik2[9], titik2[7]);
            var titikproyeksi = new Point3D(0, 0, Convert.ToDouble(TextBox_titiklenyapz.Text));

            garisproyeksi.AddPipe(titikproyeksi, titik[0], 0, 0.02, 90);
            garisproyeksi.AddPipe(titikproyeksi, titik[1], 0, 0.02, 90);
            garisproyeksi.AddPipe(titikproyeksi, titik[2], 0, 0.02, 90);
            garisproyeksi.AddPipe(titikproyeksi, titik[3], 0, 0.02, 90);
            garisproyeksi.AddPipe(titikproyeksi, titik[4], 0, 0.02, 90);
            garisproyeksi.AddPipe(titikproyeksi, titik[5], 0, 0.02, 90);
            garisproyeksi.AddPipe(titikproyeksi, titik[6], 0, 0.02, 90);
            garisproyeksi.AddPipe(titikproyeksi, titik[7], 0, 0.02, 90);
            garisproyeksi.AddPipe(titikproyeksi, titik[8], 0, 0.02, 90);
            garisproyeksi.AddPipe(titikproyeksi, titik[9], 0, 0.02, 90);
            objects.Children.Add(new GeometryModel3D
            {
                Geometry = garisproyeksi.ToMesh(true),
                Material = MaterialHelper.CreateMaterial(Colors.Yellow)
            });
            objects.Children.Add(new GeometryModel3D
            {
                Geometry = tembokrumah.ToMesh(true),
                Material = MaterialHelper.CreateMaterial(Colors.DarkGray)
            });
            objects.Children.Add(new GeometryModel3D
            {
                Geometry = ataprumah.ToMesh(true),
                Material = MaterialHelper.CreateMaterial(Colors.DarkGray)
            });
            placedobjects.Content = objects;
        }
コード例 #28
0
    MeshBuilder GenerateCurveTriangles(MeshBuilder meshBuilder, bool doubleTriangles = false)
    {
        int baseIndex = 0;
        int sizeX     = 2;
        int sizeY     = meshBuilder.Vertices.Count / 3 - 1;

        int vi = baseIndex;

        for (int y = 0; y < sizeY; y++, vi++)
        {
            for (int x = 0; x < sizeX; x++, vi++)
            {
                meshBuilder.AddTriangle(vi, vi + sizeX + 1, vi + 1);
                meshBuilder.AddTriangle(vi + 1, vi + sizeX + 1, vi + sizeX + 2);

                if (y == sizeY - 1)
                {
                    meshBuilder.AddTriangle(vi + sizeX + 1, baseIndex + x, vi + sizeX + 2);
                    meshBuilder.AddTriangle(baseIndex + x + 1, vi + sizeX + 2, baseIndex + x);
                }

                if (doubleTriangles)
                {
                    meshBuilder.AddTriangle(vi + 1, vi + sizeX + 1, vi);
                    meshBuilder.AddTriangle(vi + sizeX + 2, vi + sizeX + 1, vi + 1);

                    if (y == sizeY - 1)
                    {
                        meshBuilder.AddTriangle(vi + sizeX + 2, baseIndex + x, vi + sizeX + 1);
                        meshBuilder.AddTriangle(baseIndex + x, vi + sizeX + 2, baseIndex + x + 1);
                    }
                }
            }
        }
        return(meshBuilder);
    }
コード例 #29
0
    // build quads for spline
    protected void BuildQuadSpline(MeshBuilder meshBuilder, Vector3 point, Vector3 normal, int total, Vector3 startOffset, Vector3 endOffset, int pointOffset, bool reverse)
    {
        // vertices are arranged in this order by point #
        //   (0, 1) O---O (2, 3)
        // (n, n+1) O---O (n+2, n+3)
        if (reverse)
        {
            normal *= -1;
        }

        meshBuilder.Vertices.Add(point + startOffset);
        meshBuilder.Normals.Add(normal);

        meshBuilder.Vertices.Add(point + endOffset);
        meshBuilder.Normals.Add(-normal);

        int baseIndex = meshBuilder.Vertices.Count - total - 4;

        if (baseIndex - pointOffset >= 0 && ((baseIndex - pointOffset + 2) % total) != 0)
        {
            if (!reverse)
            {
                meshBuilder.AddTriangle(baseIndex, baseIndex + 2, baseIndex + total);
                meshBuilder.AddTriangle(baseIndex + total + 2, baseIndex + total, baseIndex + 2);
                meshBuilder.AddTriangle(baseIndex + total + 1, baseIndex + 3, baseIndex + 1);
                meshBuilder.AddTriangle(baseIndex + 3, baseIndex + total + 1, baseIndex + total + 3);
            }
            else
            {
                meshBuilder.AddTriangle(baseIndex + total, baseIndex + 2, baseIndex);
                meshBuilder.AddTriangle(baseIndex + 2, baseIndex + total, baseIndex + total + 2);
                meshBuilder.AddTriangle(baseIndex + +1, baseIndex + 3, baseIndex + total + 1);
                meshBuilder.AddTriangle(baseIndex + total + 3, baseIndex + total + 1, baseIndex + 3);
            }
        }
    }
コード例 #30
0
        private void CreateVisual()
        {
            _initialSeed = _curData.Seed;

            if (_curData.IsInGame)
            {
                var builder = new MeshBuilder(true, false);

                List <Tripper.Tools.Math.Vector3> verts;
                List <int> indices;

                if (!RDPathfinder.UseNewGetTris)
                {
                    RDPathfinder.GetTris(_curData.CachedTerrainData, 2, out verts, out indices);                     // 2 is the walkable value used for pathfinding
                }
                else
                {
                    RDPathfinder.GetTris2(_curData.CachedTerrainData, 2, out verts, out indices, out var rects);                     // 2 is the walkaloe value used for pathfinding
                }

                for (int i = 0; i < indices.Count - 3; i += 3)
                {
                    var p0 = verts[indices[i + 2]];
                    var p1 = verts[indices[i + 1]];
                    var p2 = verts[indices[i + 0]];

                    // We need to swap Y/Z for display purposes.
                    builder.AddTriangle(new Point3D(p0.X, p0.Z, p0.Y), new Point3D(p1.X, p1.Z, p1.Y), new Point3D(p2.X, p2.Z, p2.Y));
                }

                LokiPoe.BeginDispatchIfNecessary(View.Dispatcher,
                                                 () => (Visual as MeshVisual3D).Content = new GeometryModel3D(builder.ToMesh(true), Materials.White));
            }
            else
            {
                LokiPoe.BeginDispatchIfNecessary(View.Dispatcher, () => (Visual as MeshVisual3D).Content = null);
            }
        }
コード例 #31
0
    /// <summary>
    /// Method for building cone at the specified center. Tip length specifies the length of the needle tip
    /// </summary>
    public void BuildTip(MeshBuilder meshBuilder, int m_RadialSegmentCount, Vector3 centre, float m_Radius, Vector3 normal, float tipLength)
    {
        //one vertex in the center:
        meshBuilder.Vertices.Add(centre + tipLength * normal);
        meshBuilder.Normals.Add(Vector3.up);
        meshBuilder.UVs.Add(new Vector2(0.5f, 0.5f));

        int centreVertexIndex = meshBuilder.Vertices.Count - 1;

        Quaternion rotation = Quaternion.FromToRotation(Vector3.up, normal);

        //vertices around the edge:
        float angleInc = (Mathf.PI * 2.0f) / m_RadialSegmentCount;

        for (int i = 0; i <= m_RadialSegmentCount; i++)
        {
            float angle = angleInc * i;

            Vector3 unitPosition = Vector3.zero;
            unitPosition.x = Mathf.Cos(angle);
            unitPosition.z = Mathf.Sin(angle);

            unitPosition = rotation * unitPosition;

            meshBuilder.Vertices.Add(centre + unitPosition * m_Radius);
            meshBuilder.Normals.Add(unitPosition);

            Vector2 uv = new Vector2(unitPosition.x + 1.0f, unitPosition.z + 1.0f) * 0.5f;
            meshBuilder.UVs.Add(uv);

            //build a triangle:
            if (i > 0)
            {
                int baseIndex = meshBuilder.Vertices.Count - 1;
                meshBuilder.AddTriangle(centreVertexIndex, baseIndex, baseIndex - 1);
            }
        }
    }
コード例 #32
0
        private void CreateSubdividedIcosahedron()
        {
            ClearModels();
            var builder = new MeshBuilder();

            Vector3 ToVector3(System.Numerics.Vector3 vec) =>
            new Vector3(vec.X, vec.Y, vec.Z);

            var icosahedronCreator = new IcosahedronCreator(IcosahedronSubdivision);

            icosahedronCreator.Generate();
            foreach (var trianglePositions in icosahedronCreator.Faces)
            {
                builder.AddTriangle(ToVector3(trianglePositions[0]), ToVector3(trianglePositions[1]), ToVector3(trianglePositions[2]));
            }

            var mesh   = builder.ToMeshGeometry3D();
            var random = new Random();

            mesh.Colors = new Color4Collection(mesh.TextureCoordinates.Select(x => random.NextColor().ToColor4()));
            Model       = mesh;
            RaisePropertyChanged(nameof(Model));
        }
コード例 #33
0
        public bool VisualizeMesh(MeshBuilder meshBuilder, MeshGeometry3D mesh, DiffuseMaterial mat)
        {
            // Output on console
            var points = new List <Point3D>();

            foreach (var item in mesh.Positions)
            {
                points.Add(new Point3D {
                    X = item.X, Y = item.Y, Z = item.Z
                });
            }

            for (var i = 0; i < mesh.TriangleIndices.Count; i += 3)
            {
                meshBuilder.AddTriangle(points[mesh.TriangleIndices[i]], points[mesh.TriangleIndices[i + 1]],
                                        points[mesh.TriangleIndices[i + 2]]);
            }

            var myGeometryModel = new GeometryModel3D
            {
                //Material = new DiffuseMaterial(new SolidColorBrush(Colors.Aqua)),
                //BackMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Red)),
                Material = mat,
                Geometry = meshBuilder.ToMesh(true)
                           // In case that you have to rotate the model ...
                           // Transform = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(1, 0, 0), 90))
            };

            var element = new ModelUIElement3D {
                Model = myGeometryModel
            };

            // Add the Mesh to the ViewPort
            _viewPort.Children.Add(element);

            return(true);
        }
コード例 #34
0
    /// <summary>
    /// Builds a ring as part of a sphere. Normals are calculated as directions from the sphere's centre.
    /// </summary>
    /// <param name="meshBuilder">The mesh builder currently being added to.</param>
    /// <param name="segmentCount">The number of segments in this ring.</param>
    /// <param name="centre">The position at the centre of the ring.</param>
    /// <param name="radius">The radius of the ring.</param>
    /// <param name="v">The V coordinate for this ring.</param>
    /// <param name="buildTriangles">Should triangles be built for this ring? This value should be false if this is the first ring in the cylinder.</param>
    public static void BuildRingForSphere(MeshBuilder meshBuilder, int segmentCount, Vector3 centre, float radius, float v, bool buildTriangles) {
        float angleInc = (Mathf.PI * 2.0f) / segmentCount;

        for (int i = 0; i <= segmentCount; i++) {
            float angle = angleInc * i;

            Vector3 unitPosition = Vector3.zero;
            unitPosition.x = Mathf.Cos(angle);
            unitPosition.z = Mathf.Sin(angle);

            Vector3 vertexPosition = centre + unitPosition * radius;

            meshBuilder.Vertices.Add(vertexPosition);
            meshBuilder.Normals.Add(vertexPosition.normalized);
            meshBuilder.UVs.Add(new Vector2((float)i / segmentCount, v));

            if (i > 0 && buildTriangles) {
                int baseIndex = meshBuilder.Vertices.Count - 1;

                int vertsPerRow = segmentCount + 1;

                int index0 = baseIndex;
                int index1 = baseIndex - 1;
                int index2 = baseIndex - vertsPerRow;
                int index3 = baseIndex - vertsPerRow - 1;

                meshBuilder.AddTriangle(index0, index2, index1);
                meshBuilder.AddTriangle(index2, index3, index1);
            }
        }
    }
コード例 #35
0
    /// <summary>
    /// Builds a ring as part of a Bezier Curve.
    /// </summary>
    /// <param name="meshBuilder">The mesh builder currently being added to.</param>
    /// <param name="segmentCount">The number of segments in this ring.</param>
    /// <param name="centre">The position at the centre of the ring.</param>
    /// <param name="radius">The radius of the ring.</param>
    /// <param name="v">The V coordinate for this ring.</param>
    /// <param name="buildTriangles">Should triangles be built for this ring? This value should be false if this is the first ring in the cylinder.</param>
    /// <param name="rotation">A rotation value to be applied to the whole ring.</param>
    /// <param name="slope">The normalised slope (rise and run) of the cylinder at this height.</param>
    public static void BuildBezierCurveRing(MeshBuilder meshBuilder, int segmentCount, Vector3 center, float radius, float v, bool buildTriangles, Quaternion rotation) {
        float angleInc = (Mathf.PI * 2.0f) / segmentCount;

        for (int i = 0; i <= segmentCount; i++) {
            float angle = angleInc * i;

            Vector3 unitPosition = Vector3.zero;
            unitPosition.x = Mathf.Cos(angle);
            unitPosition.y = Mathf.Sin(angle);

            unitPosition = rotation * unitPosition;
            Vector3 normal = unitPosition;

            meshBuilder.Vertices.Add(center + unitPosition * radius);
            meshBuilder.Normals.Add(normal);
            //meshBuilder.UVs.Add(new Vector2((float)i / segmentCount, v));
            meshBuilder.UVs.Add(new Vector2((float)i / segmentCount, v));

            if (i > 0 && buildTriangles) {
                //Debug.Log ("buildTriangles!");
                int baseIndex = meshBuilder.Vertices.Count - 1;

                int vertsPerRow = segmentCount + 1;

                int index0 = baseIndex;
                int index1 = baseIndex - 1;
                int index2 = baseIndex - vertsPerRow;
                int index3 = baseIndex - vertsPerRow - 1;

                meshBuilder.AddTriangle(index1, index2, index0);
                meshBuilder.AddTriangle(index1, index3, index2);
            }
        }
    }
コード例 #36
0
 /// <summary>
 /// Adds the triangle.
 /// </summary>
 /// <param name="bulder">The bulder.</param>
 /// <param name="p1">The p1.</param>
 /// <param name="p2">The p2.</param>
 /// <param name="p3">The p3.</param>
 public static void AddTriangle(this MeshBuilder bulder, Point p1, Point p2, Point p3)
 {
     bulder.AddTriangle(p1.ToPoint3D(), p2.ToPoint3D(), p3.ToPoint3D());
 }
コード例 #37
0
        public void MakeBlades3()
        {
            var splines = GetSplines();
            var spars   = GetSpars();

            MeshBuilder builder = new MeshBuilder(true, true);

            for (int i = 0; i < splines.Length; i++)
            {
                var currSpline = splines[i];
                if (i < splines.Length - 1)
                {
                    var nextSpline = splines[i + 1];
                    for (int j = 0; j < currSpline.Count; j++)
                    {
                        Point3D currPoint = currSpline[j];
                        Point3D pt1, pt2;
                        Find2NN(currPoint, nextSpline, out pt1, out pt2);
                        builder.AddTriangle(currPoint, pt1, pt2);

                        if (j > 0)
                        {
                            Point3D prevPoint = currSpline[j - 1];
                            Point3D pt3       = FindNN(currPoint, prevPoint, nextSpline);
                            builder.AddTriangle(currPoint, prevPoint, pt3);
                        }

                        if (j < currSpline.Count - 1)
                        {
                            Point3D nextPoint = currSpline[j + 1];
                            Point3D pt3       = FindNN(currPoint, nextPoint, nextSpline);
                            builder.AddTriangle(currPoint, nextPoint, pt3);
                        }
                    }
                }
                if (i > 0)
                {
                    var prevSpline = splines[i - 1];
                    for (int j = 0; j < currSpline.Count; j++)
                    {
                        Point3D currPoint = currSpline[j];
                        Point3D pt1, pt2;
                        Find2NN(currPoint, prevSpline, out pt1, out pt2);
                        builder.AddTriangle(currPoint, pt1, pt2);

                        if (j > 0)
                        {
                            Point3D prevPoint = currSpline[j - 1];
                            Point3D pt3       = FindNN(currPoint, prevPoint, prevSpline);
                            builder.AddTriangle(currPoint, prevPoint, pt3);
                        }
                        if (j < currSpline.Count - 1)
                        {
                            Point3D nextPoint = currSpline[j + 1];
                            Point3D pt3       = FindNN(currPoint, nextPoint, prevSpline);
                            builder.AddTriangle(currPoint, nextPoint, pt3);
                        }
                    }
                }
            }
            bladePlot.MeshGeometry = builder.ToMesh();
        }
コード例 #38
0
    public void Generate()
    {
        MeshFilter filter = gameObject.GetComponent <MeshFilter>();

        MeshBuilder meshBuilder = new MeshBuilder();

        // Face 0 - Front
        meshBuilder.Vertices.Add(new Vector3(0, 0, 0f));
        meshBuilder.Vertices.Add(new Vector3(1f, 0f, 0f));
        meshBuilder.Vertices.Add(new Vector3(0f, 1f, 0f));
        meshBuilder.Vertices.Add(new Vector3(1f, 1f, 0f));
        meshBuilder.AddTriangle(0, 1, 2);
        meshBuilder.AddTriangle(1, 3, 2);

        // Face 1 - Up
        meshBuilder.Vertices.Add(new Vector3(0.5f, 1f, 0.5f));
        meshBuilder.Vertices.Add(new Vector3(0f, 1f, 1f));
        meshBuilder.Vertices.Add(new Vector3(1f, 1f, 1f));
        meshBuilder.AddTriangle(2, 3, 4);
        meshBuilder.AddTriangle(5, 2, 4);
        meshBuilder.AddTriangle(4, 3, 6);
        meshBuilder.AddTriangle(4, 6, 5);

        // Face 2 - Left
        meshBuilder.Vertices.Add(new Vector3(0f, 0f, 1f));
        meshBuilder.AddTriangle(0, 2, 5);
        meshBuilder.AddTriangle(7, 0, 5);

        // Face 3 - Back
        meshBuilder.Vertices.Add(new Vector3(1f, 0f, 1f));
        meshBuilder.AddTriangle(5, 8, 7);
        meshBuilder.AddTriangle(6, 8, 5);

        // Face 4 - Right
        meshBuilder.AddTriangle(3, 1, 6);
        meshBuilder.AddTriangle(6, 1, 8);

        // Face 5 - Down
        meshBuilder.Vertices.Add(new Vector3(0.5f, 0f, 0.5f));
        meshBuilder.AddTriangle(9, 1, 0);
        meshBuilder.AddTriangle(9, 8, 1);
        meshBuilder.AddTriangle(9, 7, 8);
        meshBuilder.AddTriangle(9, 0, 7);

        MeshProcessing.SubdivideTrianglesIn4(meshBuilder);
        MeshProcessing.SubdivideTrianglesIn4(meshBuilder);
        MeshProcessing.SubdivideTrianglesIn4(meshBuilder);
        MeshProcessing.SubdivideTrianglesIn4(meshBuilder);
        // MeshProcessing.SubdivideTriangles(meshBuilder);
        // MeshProcessing.SubdivideTriangles(meshBuilder);
        // MeshProcessing.SubdivideTriangles(meshBuilder);
        // MeshProcessing.SubdivideTriangles(meshBuilder);

        for (int i = 0; i < meshBuilder.Vertices.Count; i++)
        {
            Vector3 v = (meshBuilder.Vertices[i] - 0.5f * Vector3.one).normalized;

            Vector2 longlat = new Vector2(Mathf.Atan2(v.x, v.z) + Mathf.PI, Mathf.Acos(v.y));
            Vector2 uv      = new Vector2(longlat.x / (2f * Mathf.PI), longlat.y / Mathf.PI);
            uv.y = 1f - uv.y;
            uv.x = 1f - uv.x;

            meshBuilder.UVs.Add(uv);
        }

        int[] triangles = meshBuilder.GetTriangles();

        int v1, v2, v3, t1, t2, t3;

        float uv1, uv2, uv3;

        for (int i = 0; i < triangles.Length / 3; i++)
        {
            t1 = 3 * i;
            t2 = 3 * i + 1;
            t3 = 3 * i + 2;

            v1 = triangles[t1];
            v2 = triangles[t2];
            v3 = triangles[t3];

            uv1 = meshBuilder.UVs[v1].x;
            uv2 = meshBuilder.UVs[v2].x;
            uv3 = meshBuilder.UVs[v3].x;

            if (!VerifyWrongTriangleUV(uv1, uv2, uv3, v2, v3, t2, t3, meshBuilder))
            {
                if (!VerifyWrongTriangleUV(uv2, uv1, uv3, v1, v3, t1, t3, meshBuilder))
                {
                    VerifyWrongTriangleUV(uv3, uv2, uv1, v2, v1, t2, t1, meshBuilder);
                }
            }
        }

        Mesh mesh = meshBuilder.CreateMesh();

        mesh.RecalculateBounds();
        filter.mesh = mesh;
    }
コード例 #39
0
    public void Draw()
    {
        bool[] processed = new bool[8];

        foreach (CubeNode nd in Vertices())
        {
            if (debug)
            {
                GD.Print(nd.x, " ", nd.y, " ", nd.z, " ", nd.IsIn());
            }

            if (processed[nd.Index()])
            {
                continue;
            }

            HashSet <CubeNode> connected = nd.AllConnected();
            if (debug)
            {
                GD.Print(connected.Count);
            }

            if (connected.Count == 1)
            {
                if (debug)
                {
                    GD.Print("Single");
                }

                meshBuilder.AddTriangle(cubeIndex, nd, 0, nd, 1, nd, 2);
                processed[nd.Index()] = true;
                continue;
            }

            if (connected.Count == 2)
            {
                IEnumerator <CubeNode> e = connected.GetEnumerator();
                e.MoveNext();
                CubeNode n1 = e.Current;
                e.MoveNext();
                CubeNode n2 = e.Current;

                int nbAxis = n1.WhichAxis(n2);

                meshBuilder.AddTriangle(cubeIndex, n1, (nbAxis + 1) % 3, n2, (nbAxis + 1) % 3, n2, (nbAxis + 2) % 3);
                meshBuilder.AddTriangle(cubeIndex, n2, (nbAxis + 2) % 3, n1, (nbAxis + 2) % 3, n1, (nbAxis + 1) % 3);

                if (debug)
                {
                    GD.Print("Double");
                }

                processed[n1.Index()] = true;
                processed[n2.Index()] = true;
                continue;
            }

            if (connected.Count == 3)
            {
                // find middle elem
                CubeNode md = nd;
                foreach (CubeNode n in connected)
                {
                    if (n.CountNbs() == 2)
                    {
                        md = n;
                    }
                }
                int axis = 0;
                for (int i = 0; i < 3; i++)
                {
                    if (md.Nb(i).IsIn() != md.IsIn())
                    {
                        axis = i;
                    }
                }
                CubeNode nb1           = md.Nb((axis + 1) % 3);
                CubeNode nb2           = md.Nb((axis + 2) % 3);
                Vector3  intermediate1 = nb1.Intermediate(axis);
                Vector3  intermediate2 = nb2.Intermediate(axis);

                // parallel
                meshBuilder.AddTriangle(cubeIndex, md, axis, nb1, axis, nb2, axis);
                // part 1
                meshBuilder.AddTriangle(cubeIndex, nb1, axis, nb2, axis, nb1, (axis + 2) % 3);
                // part 2
                meshBuilder.AddTriangle(cubeIndex, nb1, (axis + 2) % 3, nb2, (axis + 1) % 3, nb2, axis);

                if (debug)
                {
                    GD.Print("Trio");
                }

                processed[md.Index()]  = true;
                processed[nb1.Index()] = true;
                processed[nb2.Index()] = true;
                continue;
            }

            if (connected.Count > 4)
            {
                foreach (CubeNode c in connected)
                {
                    processed[c.Index()] = true;
                }
                continue;
            }

            if (!nd.IsIn())
            {
                foreach (CubeNode c in connected)
                {
                    processed[c.Index()] = true;
                }
                continue;
            }

            // connected.Count is 4
            // square, tetra or line

            CubeNode mid   = nd;
            bool     tetra = false;

            foreach (CubeNode c in connected)
            {
                if (c.CountNbs() == 3)
                {
                    // tetra
                    mid   = c;
                    tetra = true;
                }
            }

            if (tetra)
            {
                CubeNode n0 = mid.Nb(0);
                CubeNode n1 = mid.Nb(1);
                CubeNode n2 = mid.Nb(2);

                meshBuilder.AddTriangle(cubeIndex, n0, 1, n1, 0, n1, 2);
                meshBuilder.AddTriangle(cubeIndex, n0, 1, n1, 2, n0, 2);
                meshBuilder.AddTriangle(cubeIndex, n1, 2, n0, 2, n2, 1);
                meshBuilder.AddTriangle(cubeIndex, n0, 2, n2, 1, n2, 0);

                if (debug)
                {
                    GD.Print("Tetra");
                }

                processed[mid.Index()] = true;
                processed[n0.Index()]  = true;
                processed[n1.Index()]  = true;
                processed[n2.Index()]  = true;
                continue;
            }

            bool sameX = true, sameY = true, sameZ = true;
            foreach (CubeNode n in connected)
            {
                if (n.x != nd.x)
                {
                    sameX = false;
                }
                if (n.y != nd.y)
                {
                    sameY = false;
                }
                if (n.z != nd.z)
                {
                    sameZ = false;
                }
            }

            if (sameX || sameY || sameZ)
            {
                int axis = 0;
                if (sameY)
                {
                    axis = 1;
                }
                if (sameZ)
                {
                    axis = 2;
                }

                // plane
                meshBuilder.AddTriangle(cubeIndex,
                                        nd, axis,
                                        nd.Nb((axis + 1) % 3), axis,
                                        nd.Nb((axis + 2) % 3), axis);
                meshBuilder.AddTriangle(cubeIndex,
                                        nd.Nb((axis + 1) % 3), axis,
                                        nd.Nb((axis + 2) % 3), axis,
                                        nd.Nb((axis + 1) % 3).Nb((axis + 2) % 3), axis);

                if (debug)
                {
                    GD.Print("Plane");
                }
                foreach (CubeNode c in connected)
                {
                    processed[c.Index()] = true;
                }
                continue;
            }

            // line
            CubeNode l1 = nd, l2 = nd, l3 = nd, l4 = nd;
            foreach (CubeNode n in connected)
            {
                if (n.CountNbs() == 1)
                {
                    l1 = n;
                }
            }
            foreach (CubeNode n in connected)
            {
                if (l1.WhichAxis(n) != -1)
                {
                    l2 = n;
                }
            }
            foreach (CubeNode n in connected)
            {
                if (n.Index() != l1.Index() && l2.WhichAxis(n) != -1)
                {
                    l3 = n;
                }
            }
            foreach (CubeNode n in connected)
            {
                if (n.Index() != l2.Index() && l3.WhichAxis(n) != -1)
                {
                    l4 = n;
                }
            }

            int axis1 = l1.WhichAxis(l2);
            int axis2 = l2.WhichAxis(l3);
            int axis3 = l3.WhichAxis(l4);

            meshBuilder.AddTriangle(cubeIndex, l1, axis3, l2, axis3, l1, axis2);
            meshBuilder.AddTriangle(cubeIndex, l1, axis2, l3, axis1, l4, axis1);
            meshBuilder.AddTriangle(cubeIndex, l2, axis3, l1, axis2, l4, axis1);
            meshBuilder.AddTriangle(cubeIndex, l2, axis3, l4, axis1, l4, axis2);

            if (debug)
            {
                GD.Print("Line");
            }

            foreach (CubeNode c in connected)
            {
                processed[c.Index()] = true;
            }
            continue;
        }

        // geometry.End();
    }
コード例 #40
0
    public static MeshBuilder AddVerticesAndTriangles(this MeshBuilder builder, int configuration)
    {
        switch (configuration)
        {
        case 0b0001: return(builder.AddTriangle(zero, up * 0.5f, right * 0.5f));

        case 0b0010: return(builder.AddTriangle(right * 0.5f, new Vector3(1f, 0.5f), right));

        case 0b0011:
            return(builder.AddTriangle(zero, up * 0.5f, new Vector3(1f, 0.5f))
                   .AddTriangle(zero, new Vector3(1f, 0.5f), right));

        case 0b0100:
            return(builder.AddTriangle(new Vector3(1f, 1f), new Vector3(1f, 0.5f),
                                       new Vector3(0.5f, 1f)));

        case 0b0101:
            return(builder.AddTriangle(up * 0.5f, right * 0.5f, zero)
                   .AddTriangle(new Vector3(0.5f, 1f), new Vector3(1f, 1f), new Vector3(1f, 0.5f)));

        case 0b0110:
            return(builder.AddTriangle(new Vector3(0.5f, 0f), new Vector3(1f, 1f), right)
                   .AddTriangle(new Vector3(0.5f, 0f), new Vector3(0.5f, 1f), new Vector3(1f, 1f)));

        case 0b0111:
            return(builder.AddTriangle(zero, new Vector3(0f, 0.5f), new Vector3(0.5f, 1f))
                   .AddTriangle(zero, new Vector3(0.5f, 1f), new Vector3(1f, 1f))
                   .AddTriangle(zero, new Vector3(1f, 1f), right));

        case 0b1000: return(builder.AddTriangle(up, new Vector3(0.5f, 1f), up * 0.5f));

        case 0b1001:
            return(builder.AddTriangle(zero, new Vector3(0.5f, 1f), new Vector3(0.5f, 0f))
                   .AddTriangle(zero, up, new Vector3(0.5f, 1f)));

        case 0b1010:
            return(builder.AddTriangle(new Vector3(0.5f, 0f), new Vector3(1f, 0.5f), right)
                   .AddTriangle(new Vector3(0f, 0.5f), up, new Vector3(0.5f, 1f)));

        case 0b1011:
            return(builder.AddTriangle(zero, up, right)
                   .AddTriangle(up, new Vector3(1f, 0.5f), right)
                   .AddTriangle(up, new Vector3(0.5f, 1f), new Vector3(1f, 0.5f)));

        case 0b1100:
            return(builder.AddTriangle(up, new Vector3(1f, 1f), new Vector3(0f, 0.5f))
                   .AddTriangle(new Vector3(0f, 0.5f), new Vector3(1f, 1f), new Vector3(1f, 0.5f)));

        case 0b1101:
            return(builder.AddTriangle(zero, up, new Vector3(1f, 1f))
                   .AddTriangle(zero, new Vector3(1f, 1f), new Vector3(1f, 0.5f))
                   .AddTriangle(zero, new Vector3(1f, 0.5f), new Vector3(0.5f, 0f)));

        case 0b1110:
            return(builder.AddTriangle(new Vector3(0f, 0.5f), right, new Vector3(0.5f, 0f))
                   .AddTriangle(new Vector3(0f, 0.5f), up, right)
                   .AddTriangle(up, new Vector3(1f, 1f), right));

        case 0b1111:
            return(builder.AddTriangle(zero, new Vector3(1f, 1f), right)
                   .AddTriangle(zero, up, new Vector3(1f, 1f)));

        default: return(builder);
        }
    }
コード例 #41
0
    public void BuildLinkBezier(MeshBuilder meshBuilder, BezierCurve connectionBezier, float widthStart, float widthEnd, Color colorStart, Color colorEnd)
    {
        List <int> verticesList = new List <int>();

        float m_splineStartRadius        = widthStart;
        float m_splineEndRadius          = widthEnd;
        int   m_splineHeightSegmentCount = 8;
        int   m_splineRadialSegmentCount = 4;

        float tInc = 1f / m_splineHeightSegmentCount; // How many subdivisions along the length of the spline

        for (int i = 0; i <= m_splineHeightSegmentCount; i++)
        {
            float   t          = tInc * (float)i;
            Vector3 ringCenter = connectionBezier.GetPoint(t);
            //Quaternion rot = Quaternion.identity;
            Vector3    dir = connectionBezier.GetDirection(t);
            Quaternion rot = Quaternion.identity;
            if (dir != Vector3.zero)
            {
                rot.SetLookRotation(dir);
            }
            float radius = ((1f - t) * m_splineStartRadius) + (t * m_splineEndRadius);
            // Construct the mesh Ring!
            //BuildBezierCurveRing(meshBuilder, m_splineRadialSegmentCount, ringCenter, radius, t, i > 0, rot);
            //protected void BuildBezierCurveRing(MeshBuilder meshBuilder, int segmentCount, Vector3 center, float radius, float v, bool buildTriangles, Quaternion rotation) {
            float angleInc = (Mathf.PI * 2.0f) / m_splineRadialSegmentCount;

            for (int j = 0; j <= m_splineRadialSegmentCount; j++)
            {
                float angle = angleInc * j;

                Vector3 unitPosition = Vector3.zero;
                unitPosition.x = Mathf.Cos(angle);
                unitPosition.y = Mathf.Sin(angle);

                unitPosition = rot * unitPosition;
                Vector3 normal = unitPosition;

                meshBuilder.Vertices.Add(ringCenter + unitPosition * radius);
                meshBuilder.Normals.Add(normal);
                //meshBuilder.UVs.Add(new Vector2((float)i / segmentCount, v));
                meshBuilder.UVs.Add(new Vector2((float)j / m_splineRadialSegmentCount, t));
                verticesList.Add(meshBuilder.Vertices.Count - 1);
                meshBuilder.Colors.Add(Color.Lerp(colorStart, colorEnd, t));

                if (j > 0 && i > 0)
                {
                    //Debug.Log ("buildTriangles!");
                    int baseIndex = meshBuilder.Vertices.Count - 1;

                    int vertsPerRow = m_splineRadialSegmentCount + 1;

                    int index0 = baseIndex;
                    int index1 = baseIndex - 1;
                    int index2 = baseIndex - vertsPerRow;
                    int index3 = baseIndex - vertsPerRow - 1;

                    meshBuilder.AddTriangle(index1, index2, index0);
                    meshBuilder.AddTriangle(index1, index3, index2);
                }
            }
        }
        connectionVertexList.Add(verticesList);  // keep track of Connection's vertices so their color can be changed without rebuilding every frame
    }
コード例 #42
0
            /// <summary>
            ///     To the helix mesh.
            /// </summary>
            /// <param name="mesh">The mesh.</param>
            /// <returns></returns>
            protected virtual MeshGeometry3D OnCreateHelixMesh(Mesh mesh)
            {
                var hVertices = new Vector3Collection(mesh.Vertices.Select(x => x.ToSharpDXVector3()));
                var builder   = new MeshBuilder(false, false);

                builder.Positions.AddRange(hVertices);
                for (var i = 0; i < mesh.FaceCount; ++i)
                {
                    if (!mesh.Faces[i].HasIndices)
                    {
                        continue;
                    }
                    if (mesh.Faces[i].IndexCount == 3)
                    {
                        builder.AddTriangle(mesh.Faces[i].Indices);
                    }
                    else if (mesh.Faces[i].IndexCount == 4)
                    {
                        builder.AddTriangleFan(mesh.Faces[i].Indices);
                    }
                }
                var hMesh = new MeshGeometry3D {
                    Positions = hVertices, Indices = builder.TriangleIndices
                };

                if (mesh.HasNormals && mesh.Normals.Count == hMesh.Positions.Count)
                {
                    hMesh.Normals = new Vector3Collection(mesh.Normals.Select(x => Vector3.Normalize(x.ToSharpDXVector3())));
                }
                else
                {
                    hMesh.Normals = hMesh.CalculateNormals();
                }
                if (mesh.HasVertexColors(0))
                {
                    hMesh.Colors =
                        new Color4Collection(mesh.VertexColorChannels[0].Select(x => new Color4(x.R, x.G, x.B, x.A)));
                }
                if (mesh.HasTextureCoords(0))
                {
                    hMesh.TextureCoordinates =
                        new Vector2Collection(mesh.TextureCoordinateChannels[0].Select(x => x.ToSharpDXVector2()));
                }
                if (mesh.HasTangentBasis && mesh.Tangents.Count == hMesh.Positions.Count && mesh.BiTangents.Count == hMesh.Positions.Count)
                {
                    hMesh.Tangents   = new Vector3Collection(mesh.Tangents.Select(x => x.ToSharpDXVector3()));
                    hMesh.BiTangents = new Vector3Collection(mesh.BiTangents.Select(x => x.ToSharpDXVector3()));
                }
                else
                {
                    builder.Normals            = hMesh.Normals;
                    builder.TextureCoordinates = hMesh.TextureCoordinates;
                    builder.ComputeTangents(MeshFaces.Default);
                    hMesh.Tangents   = builder.Tangents;
                    hMesh.BiTangents = builder.BiTangents;
                }

                hMesh.UpdateBounds();
                if (configuration.BuildOctree)
                {
                    hMesh.UpdateOctree();
                }
                return(hMesh);
            }
コード例 #43
0
ファイル: GenHelper.cs プロジェクト: davidbohunek/LunarLander
    /// <summary>
    /// builds a wall with the normal pointing inwards if vertices are given clockwise
    /// based off terrian of: http://jayelinda.com/wp/modelling-by-numbers-part-1a/
    /// </summary>
    public void BuildWall(MeshBuilder meshBuilder, IList<Vector2> vertices)
    {
        if (vertices == null || vertices.Count < 1)
            return;

        Vector2 vector2;
        int segments = vertices.Count - 1;
        for (int index = 0; index < vertices.Count; index++)
        {
            // Add vertex
            vector2 = vertices[index];
            bool isDistinctVertex = (vertices.IndexOf(vector2) == index);
            if (isDistinctVertex) // add new vertex
            {
                meshBuilder.Vertices.Add(Vector2to3(vector2, -4));
                meshBuilder.Vertices.Add(Vector2to3(vector2, 4));

                Vector2 lipPoint = getWallLipAt(vertices, index);
                meshBuilder.Vertices.Add(Vector2to3(lipPoint, -4));
            }
            else // make use of existing vertex.
            {
                if (existingVertexIndex != -1)
                    Debug.Log("BuildWall is reusing too many vertices");
                existingVertexIndex = vertices.IndexOf(vector2)
                    * 3 // because there are 3 vertices added per vector2 (z of 4, 4 & -4)
                        + 1; // use the non-lip z of 4 vertex
            }

            //init UV map with values for index == 0
            Vector2 uvFront = new Vector2(0, 0),
                uvBack = new Vector2(0, 1);

            //connect with previous vertice
            if (index > 0)
            {
                uvFront.x = uvBack.x = (1.0f / segments) * index;

                int[] indices = wallSegmentIndices(isDistinctVertex, meshBuilder.Vertices.Count);
                if (indices == null)
                    continue; //skip adding triangles for this vertex iteration

                // 0-1-4  vertex index layout
                // | | |
                // 2-3-5
                int index0 = indices[0],
                    index1 = indices[1],
                    index2 = indices[2],
                    index3 = indices[3],
                    lip4 = indices[4],
                    lip5 = indices[5];

                meshBuilder.AddTriangle(index0, index2, index1);
                meshBuilder.AddTriangle(index2, index3, index1);

                //create lip on positive z-index
                //				meshBuilder.AddTriangle(lip4, lip5, index0);
                //				meshBuilder.AddTriangle(lip5, index2, index0);
                //create lip on negative z-index
                meshBuilder.AddTriangle(index1, index3, lip4);
                meshBuilder.AddTriangle(index3, lip5, lip4);
            }

            meshBuilder.UVs.Add(uvFront);
            meshBuilder.UVs.Add(uvBack);
        }
    }
コード例 #44
0
        void AddFakeVariablesDebug()
        {
            dg_Variables.BeginningEdit -= dg_Variables_BeginningEdit;
            dg_Variables.BeginningEdit += dg_Variables_BeginningEdit_DEBUG;

            // datagrid objs
            DataGridObject obj = new DataGridObject()
            {
                Name = "Points"
            };

            DataGridObject sphere = new DataGridObject()
            {
                Name = "Sphere"
            };

            DataGridObject mesh = new DataGridObject()
            {
                Name = "Mesh"
            };

            DataGridObject line = new DataGridObject()
            {
                Name = "Line"
            };

            List <DataGridObject> objs = new List <DataGridObject>()
            {
                obj, sphere, line, mesh
            };

            dg_Variables.ItemsSource = objs;


            // pnts
            PointsVisual3D points = new PointsVisual3D();
            Random         rand   = new Random();

            for (int i = 0; i < 10; i++)
            {
                Point3D p = new Point3D(rand.NextDouble(), rand.NextDouble(), rand.NextDouble());
                points.Points.Add(p);
            }
            points.Size = PropertyServer.PointSize;

            _dict.Add("Points", points);
            hv.Items.Add(points);

            // sphere
            SphereVisual3D sph = new SphereVisual3D()
            {
                Center = new Point3D(0, 0, 0),
                Radius = 0.1,
            };

            _dict.Add("Sphere", sph);
            hv.Items.Add(sph);

            // mesh
            MeshBuilder builder = new MeshBuilder(true, true);

            builder.AddTriangle(new Point3D(1, 1, 1), new Point3D(2, 2, 4), new Point3D(5, 3, 3));

            MeshVisual3D m = new MeshVisual3D()
            {
                Mesh = new Mesh3D(builder.Positions, Enumerable.Range(0, builder.Positions.Count))
            };

            _dict.Add("Mesh", m);
            hv.Items.Add(m);

            // line
            LinesVisual3D l = new LinesVisual3D();

            l.Points.Add(new Point3D(4, 5, 7));
            l.Points.Add(new Point3D(4, 8, 5));
            _dict.Add("Line", l);
            hv.Items.Add(l);
        }
コード例 #45
0
 void AddDodecahedronFace(MeshBuilder meshBuilder, int v1, int v2, int v3, int v4, int v5)
 {
     meshBuilder.AddTriangle(v1, v4, v5);
     meshBuilder.AddTriangle(v2, v4, v1);
     meshBuilder.AddTriangle(v3, v4, v2);
 }
コード例 #46
0
ファイル: MapDrawer.cs プロジェクト: DtheC/OpenMaps-Drawing
    private void GenerateWayMesh(IList<MapWay> wayList)
    {
        IList<Color32> colours = new List<Color32> ();

        //Create MeshBuilder
        MeshBuilder meshBuilder = new MeshBuilder();
        int currentTriangleCount = 0;

        foreach (MapWay mapway in wayList) {
            if (OnlyDrawHighways){
                if (!mapway._tags.ContainsKey("highway")){
                    continue;
                }
            }

            MapNode to = null;
            MapNode from = null;
            //Color randomCol = new Color (Random.Range (0.00f, 1.00f),Random.Range (0.00f, 1.00f),Random.Range (0.00f, 1.00f));
            for (int i=0; i < mapway._nodesInWay.Count; i++){
                //Get nodes
                to = _mapController.GetMapNodeById(mapway._nodesInWay[i]._id);
                if (to == null){
                    continue;
                }
                if (from == null){
                    from = to;
                    continue;
                }
                //Debug.DrawLine(from.LocationInUnits, to.LocationInUnits, randomCol, 2000, false);

                //Draw Mesh
                Vector3 newVec = to.LocationInUnits - from.LocationInUnits;
                Vector3 newVector = Vector3.Cross (newVec, Vector3.down);
                newVector.Normalize ();

                Vector3 c = RoadWidth * newVector + to.LocationInUnits;
                Vector3 d = -RoadWidth * newVector + to.LocationInUnits;

                Vector3 e = RoadWidth * newVector + from.LocationInUnits;
                Vector3 f = -RoadWidth * newVector + from.LocationInUnits;

                //MeshBuilder from http://jayelinda.com/
                meshBuilder.Vertices.Add(e);
                meshBuilder.UVs.Add(new Vector2(0.0f, 0.0f));
                meshBuilder.Normals.Add(Vector3.up);

                meshBuilder.Vertices.Add(f);
                meshBuilder.UVs.Add(new Vector2(1.0f, 0.0f));
                meshBuilder.Normals.Add(Vector3.up);

                meshBuilder.Vertices.Add(d);
                meshBuilder.UVs.Add(new Vector2(1.0f, 1.0f));
                meshBuilder.Normals.Add(Vector3.up);

                meshBuilder.Vertices.Add(c);
                meshBuilder.UVs.Add(new Vector2(0.0f, 1.0f));
                meshBuilder.Normals.Add(Vector3.up);

                //Don't edit colours here- do it in the GenerateMeshColours function below!
                byte needColor;
                Color32 vertexColor;

                if (NeedToColour == Needs.Food)
                {
                    needColor = (byte)((from.NeedAmounts[Needs.Food] + from.NearbyNeedAmounts[Needs.Food]) * 255);
                    vertexColor = new Color32(needColor, 0, 0, 255);
                } else
                {
                    needColor = (byte)((from.NeedAmounts[Needs.Water] + from.NearbyNeedAmounts[Needs.Water]) * 255);
                    vertexColor = new Color32(0, 0, needColor, 255);
                }

                colours.Add (vertexColor);
                colours.Add (vertexColor);

                //Other side
                if (NeedToColour == Needs.Food)
                {
                    needColor = (byte)((to.NeedAmounts[Needs.Food] + to.NearbyNeedAmounts[Needs.Food]) * 255);
                    vertexColor = new Color32(needColor, 0, 0, 255);
                }
                else
                {
                    needColor = (byte)((to.NeedAmounts[Needs.Water] + to.NearbyNeedAmounts[Needs.Water]) * 255);
                    vertexColor = new Color32(0, 0, needColor, 255);
                }

                colours.Add (vertexColor);
                colours.Add (vertexColor);

                //Add the triangles:
                meshBuilder.AddTriangle(currentTriangleCount, currentTriangleCount+1, currentTriangleCount+2);
                meshBuilder.AddTriangle(currentTriangleCount, currentTriangleCount+2, currentTriangleCount+3);
                currentTriangleCount+=4;

                from = to;
            }
        }
        //Create the mesh:
        Mesh mesh = meshBuilder.CreateMesh();
        _wayMesh = mesh;
        _wayColours = colours;
        GenerateNeedMeshColours (wayList);
    }
コード例 #47
0
    public void BuildNodeSphere(MeshBuilder meshBuilder, Vector3 offset, float m_Radius, Color color)
    {
        List <int> verticesList = new List <int>();

        int m_HeightSegmentCount = 4;
        int m_RadialSegmentCount = 4;
        //float m_Radius = 1f;
        float      m_VerticalScale = 1f;
        Quaternion rotation        = Quaternion.identity;

        //the angle increment per height segment:
        float angleInc = Mathf.PI / m_HeightSegmentCount;

        //the vertical (scaled) radius of the sphere:
        float verticalRadius = m_Radius * m_VerticalScale;

        //build the rings:
        for (int i = 0; i <= m_HeightSegmentCount; i++)
        {
            Vector3 centrePos = Vector3.zero;

            //calculate a height offset and radius based on a vertical circle calculation:
            centrePos.y = -Mathf.Cos(angleInc * i);
            float radius = Mathf.Sin(angleInc * i);

            //calculate the slope of the shpere at this ring based on the height and radius:
            Vector2 slope = new Vector3(-centrePos.y / m_VerticalScale, radius);
            slope.Normalize();

            //multiply the unit height by the vertical radius, and then add the radius to the height to make this sphere originate from its base rather than its centre:
            centrePos.y = centrePos.y * verticalRadius + verticalRadius;

            //scale the radius by the one stored in the partData:
            radius *= m_Radius;

            //calculate the final position of the ring centre:
            Vector3 finalRingCentre = rotation * centrePos + offset;

            //V coordinate:
            float v = (float)i / m_HeightSegmentCount;

            //build the ring:
            //BuildRing(meshBuilder, m_RadialSegmentCount, finalRingCentre, radius, v, i > 0, rotation, slope);
            float angleIncrement = (Mathf.PI * 2.0f) / m_RadialSegmentCount;

            for (int j = 0; j <= m_RadialSegmentCount; j++)
            {
                float angle = angleIncrement * j;

                Vector3 unitPosition = Vector3.zero;
                unitPosition.x = Mathf.Cos(angle);
                unitPosition.z = Mathf.Sin(angle);

                float normalVertical   = -slope.x;
                float normalHorizontal = slope.y;

                Vector3 normal = unitPosition * normalHorizontal;
                normal.y = normalVertical;

                normal = rotation * normal;

                unitPosition = rotation * unitPosition;

                meshBuilder.Vertices.Add(finalRingCentre + unitPosition * radius);
                meshBuilder.Normals.Add(normal);
                meshBuilder.UVs.Add(new Vector2((float)j / m_RadialSegmentCount, v));
                verticesList.Add(meshBuilder.Vertices.Count - 1);
                meshBuilder.Colors.Add(color);

                if (j > 0 && i > 0)
                {
                    int baseIndex = meshBuilder.Vertices.Count - 1;

                    int vertsPerRow = m_RadialSegmentCount + 1;

                    int index0 = baseIndex;
                    int index1 = baseIndex - 1;
                    int index2 = baseIndex - vertsPerRow;
                    int index3 = baseIndex - vertsPerRow - 1;

                    meshBuilder.AddTriangle(index0, index2, index1);
                    meshBuilder.AddTriangle(index2, index3, index1);
                }
            }
        }
        nodeVertexList.Add(verticesList);  // keep track of Node's vertices so their color can be changed without rebuilding every frame
    }
コード例 #48
0
    public void BuildLink(MeshBuilder meshBuilder, Vector3 fromPos, Vector3 toPos, float width, Color color) {
        List<int> verticesList = new List<int>();

        Vector3 normal = new Vector3(0f, 0f, 1f); // Vector3.Cross(lengthDir, widthDir).normalized;
        Vector3 linkVector = new Vector3(toPos.x - fromPos.x, toPos.y - fromPos.y, toPos.z - fromPos.z);
        Vector3 widthVector = new Vector3(new Vector2(linkVector.y, -linkVector.x).normalized.x, new Vector2(linkVector.y, -linkVector.x).normalized.y, 0f) * width;        
        Vector3 cornerPos = new Vector3(fromPos.x - widthVector.x * 0.5f, fromPos.y - widthVector.y * 0.5f, -0.01f);
        //Vector3 offset = new Vector3(cornerPos.x, cornerPos.y, 0f);

        meshBuilder.Vertices.Add(cornerPos);
        meshBuilder.UVs.Add(new Vector2(0.0f, 0.0f));
        meshBuilder.Normals.Add(normal);
        verticesList.Add(meshBuilder.Vertices.Count - 1);
        meshBuilder.Colors.Add(color);

        meshBuilder.Vertices.Add(cornerPos + linkVector);
        meshBuilder.UVs.Add(new Vector2(0.0f, 1.0f));
        meshBuilder.Normals.Add(normal);
        verticesList.Add(meshBuilder.Vertices.Count - 1);
        meshBuilder.Colors.Add(color);

        meshBuilder.Vertices.Add(cornerPos + linkVector + widthVector);
        meshBuilder.UVs.Add(new Vector2(1.0f, 1.0f));
        meshBuilder.Normals.Add(normal);
        verticesList.Add(meshBuilder.Vertices.Count - 1);
        meshBuilder.Colors.Add(color);

        meshBuilder.Vertices.Add(cornerPos + widthVector);
        meshBuilder.UVs.Add(new Vector2(1.0f, 0.0f));
        meshBuilder.Normals.Add(normal);
        verticesList.Add(meshBuilder.Vertices.Count - 1);
        meshBuilder.Colors.Add(color);

        connectionVertexList.Add(verticesList);  // keep track of Connection's vertices so their color can be changed without rebuilding every frame

        //we don't know how many verts the meshBuilder is up to, but we only care about the four we just added:
        int baseIndex = meshBuilder.Vertices.Count - 4;

        meshBuilder.AddTriangle(baseIndex, baseIndex + 1, baseIndex + 2);
        meshBuilder.AddTriangle(baseIndex, baseIndex + 2, baseIndex + 3);
        
    }
コード例 #49
0
        private void CreateModel()
        {
            var points    = new Point3DCollection();
            var edges     = new Int32Collection();
            var triangles = new Int32Collection();

            switch (CurrentModelType)
            {
            case ModelTypes.StellatedOctahedron:
            case ModelTypes.Tetrahedron:
                points.Add(+1, +1, +1);
                points.Add(-1, -1, 1);
                points.Add(-1, +1, -1);
                points.Add(+1, -1, -1);
                edges.Add(0, 1, 1, 2, 2, 0, 0, 3, 1, 3, 2, 3);
                triangles.Add(0, 1, 2, 0, 3, 1, 1, 3, 2, 2, 3, 0);
                break;
            }
            switch (CurrentModelType)
            {
            case ModelTypes.StellatedOctahedron:
                // http://en.wikipedia.org/wiki/Compound_of_two_tetrahedra
                points.Add(-1, +1, +1);
                points.Add(1, -1, 1);
                points.Add(1, +1, -1);
                points.Add(-1, -1, -1);
                edges.Add(4, 5, 5, 6, 6, 4, 4, 7, 5, 7, 6, 7);
                triangles.Add(4, 5, 6, 4, 7, 5, 5, 7, 6, 6, 7, 4);
                break;
            }

            var m = new Model3DGroup();

            // Add the nodes
            var gm = new MeshBuilder();

            foreach (var p in points)
            {
                gm.AddSphere(p, 0.1);
            }
            m.Children.Add(new GeometryModel3D(gm.ToMesh(), Materials.Gold));

            // Add the triangles
            var tm = new MeshBuilder();

            for (int i = 0; i < triangles.Count; i += 3)
            {
                tm.AddTriangle(points[triangles[i]], points[triangles[i + 1]], points[triangles[i + 2]]);
            }
            m.Children.Add(new GeometryModel3D(tm.ToMesh(), Materials.Red)
            {
                BackMaterial = Materials.Blue
            });

            // Add the edges
            var em = new MeshBuilder();

            for (int i = 0; i < edges.Count; i += 2)
            {
                em.AddCylinder(points[edges[i]], points[edges[i + 1]], 0.08, 10);
            }
            m.Children.Add(new GeometryModel3D(em.ToMesh(), Materials.Gray));

            Model = m;
        }
コード例 #50
0
    public void BuildNode(MeshBuilder meshBuilder, Vector3 offset, Vector3 widthDir, Vector3 lengthDir, Color color) {
        List<int> verticesList = new List<int>();
        Vector3 normal = Vector3.Cross(lengthDir, widthDir).normalized;
        //Color red = new Color(1f, 0f, 0f, 1f);

        meshBuilder.Vertices.Add(offset);
        meshBuilder.UVs.Add(new Vector2(0.0f, 0.0f));
        meshBuilder.Normals.Add(normal);
        verticesList.Add(meshBuilder.Vertices.Count - 1);
        meshBuilder.Colors.Add(color);

        meshBuilder.Vertices.Add(offset + lengthDir);
        meshBuilder.UVs.Add(new Vector2(0.0f, 1.0f));
        meshBuilder.Normals.Add(normal);
        verticesList.Add(meshBuilder.Vertices.Count - 1);
        meshBuilder.Colors.Add(color);

        meshBuilder.Vertices.Add(offset + lengthDir + widthDir);
        meshBuilder.UVs.Add(new Vector2(1.0f, 1.0f));
        meshBuilder.Normals.Add(normal);
        verticesList.Add(meshBuilder.Vertices.Count - 1);
        meshBuilder.Colors.Add(color);

        meshBuilder.Vertices.Add(offset + widthDir);
        meshBuilder.UVs.Add(new Vector2(1.0f, 0.0f));
        meshBuilder.Normals.Add(normal);
        verticesList.Add(meshBuilder.Vertices.Count - 1);
        meshBuilder.Colors.Add(color);

        nodeVertexList.Add(verticesList);  // keep track of Node's vertices so their color can be changed without rebuilding every frame

        //we don't know how many verts the meshBuilder is up to, but we only care about the four we just added:
        int baseIndex = meshBuilder.Vertices.Count - 4;

        meshBuilder.AddTriangle(baseIndex, baseIndex + 1, baseIndex + 2);
        meshBuilder.AddTriangle(baseIndex, baseIndex + 2, baseIndex + 3);
    }
コード例 #51
0
 private static MeshGeometry3D MeshFromTriangle(Point3D p1, Point3D p2, Point3D p3)
 {
     var mb = new MeshBuilder(false, false);
     mb.AddTriangle(p1, p2, p3);
     return mb.ToMesh();
 }
コード例 #52
0
ファイル: Dodecahedron.cs プロジェクト: isaveu/MeshGeneration
 void AddDodecahedronFace(MeshBuilder meshBuilder, int v1, int v2, int v3, int v4, int v5)
 {
     meshBuilder.AddTriangle(v1, v4, v5);
     meshBuilder.AddTriangle(v2, v4, v1);
     meshBuilder.AddTriangle(v3, v4, v2);
 }
コード例 #53
0
        public void RenderMesh(WLD wld,IEnumerable<Mesh> meshes, TrackAnimationBuilder animation = null, int textureNum = 0, int face = 0)
        {
            if (meshes == null) return;
            Model3DGroup group = Model as Model3DGroup;

            group.Children.Clear();
            Dictionary<BitmapImage, List<EQEmu.Files.WLD.Polygon>> polysbyTex = new Dictionary<BitmapImage, List<EQEmu.Files.WLD.Polygon>>();
            List<EQEmu.Files.WLD.Polygon> untexturedPolys = new List<EQEmu.Files.WLD.Polygon>();
            foreach (var mesh in meshes)
            {
                foreach (var p in mesh.Polygons)
                {
                    if (p.BitmapInfo != null)
                    {
                        if (polysbyTex.ContainsKey(p.BitmapInfo.Image))
                        {
                            polysbyTex[p.BitmapInfo.Image].Add(p);
                        }
                        else
                        {
                            polysbyTex[p.BitmapInfo.Image] = new List<EQEmu.Files.WLD.Polygon>();
                            polysbyTex[p.BitmapInfo.Image].Add(p);
                        }
                    }
                    else
                    {
                        untexturedPolys.Add(p);
                    }
                }
            }

            Material mat = null;
            foreach (var polytex in polysbyTex)
            {
                MeshBuilder builder = new MeshBuilder();
                if (mat == null)
                {
                    if (polytex.Value.ElementAt(0).BitmapInfo != null)
                    {
                        //mat = HelixToolkit.Wpf.MaterialHelper.CreateImageMaterial(polytex.Value.ElementAt(0).Image, 100.0);
                        BitmapImage img = polytex.Value.ElementAt(0).BitmapInfo.Image;
                        if (textureNum > 0 || face > 0)
                        {
                            string baseTexture = polytex.Value.ElementAt(0).BitmapInfo.Name;
                            var textureStr = String.Format("{0:d2}", textureNum);
                            var faceStr = String.Format("{0:d1}", face);

                            var index = baseTexture.IndexOf("00");
                            if (index < 0) index = baseTexture.IndexOf("01");

                            if (index > 0)
                            {
                                var faceAndTexture = baseTexture.Substring(0, index) + textureStr + faceStr + baseTexture.Substring(index + textureStr.Length + faceStr.Length);
                                var textureOnly = baseTexture.Substring(0, index) + textureStr + baseTexture.Substring(index + textureStr.Length);
                                var faceOnly = baseTexture.Substring(0, index + textureStr.Length) + faceStr + baseTexture.Substring(index + textureStr.Length + faceStr.Length);

                                if (wld.ImageMapping.ContainsKey(faceAndTexture))
                                {
                                    img = wld.ImageMapping[faceAndTexture].Image;
                                }
                                else if (wld.ImageMapping.ContainsKey(textureOnly))
                                {
                                    img = wld.ImageMapping[textureOnly].Image;
                                }
                                else if (wld.ImageMapping.ContainsKey(faceOnly))
                                {
                                    img = wld.ImageMapping[faceOnly].Image;
                                }
                            }
                        }

                        var brush = new System.Windows.Media.ImageBrush(img);
                        brush.ViewportUnits = System.Windows.Media.BrushMappingMode.Absolute;
                        //brush.TileMode
                        brush.TileMode = System.Windows.Media.TileMode.Tile;
                        //brush.Stretch = System.Windows.Media.Stretch.Fill;
                        mat = HelixToolkit.Wpf.MaterialHelper.CreateMaterial(brush);
                    }
                    else
                    {
                        mat = Materials.LightGray;
                    }
                }
                foreach (var poly in polytex.Value)
                {
                    Point3D p1 = new Point3D(poly.V1.X, poly.V1.Y, poly.V1.Z);
                    Point3D p2 = new Point3D(poly.V2.X, poly.V2.Y, poly.V2.Z);
                    Point3D p3 = new Point3D(poly.V3.X, poly.V3.Y, poly.V3.Z);

                    if (animation != null)
                    {
                        if (animation.SkeletonPieceTransforms.ContainsKey(poly.V1.BodyPiece))
                        {
                            var atrans = animation.SkeletonPieceTransforms[poly.V1.BodyPiece];
                            p1 = atrans.Transform(p1);
                        }

                        if (animation.SkeletonPieceTransforms.ContainsKey(poly.V2.BodyPiece))
                        {
                            var atrans = animation.SkeletonPieceTransforms[poly.V2.BodyPiece];
                            p2 = atrans.Transform(p2);
                        }

                        if (animation.SkeletonPieceTransforms.ContainsKey(poly.V3.BodyPiece))
                        {
                            var atrans = animation.SkeletonPieceTransforms[poly.V3.BodyPiece];
                            p3 = atrans.Transform(p3);
                        }
                    }

                    var rotate = new RotateTransform3D();
                    rotate.Rotation = new AxisAngleRotation3D(new Vector3D(0, 0, 1), 90);
                    p1 = rotate.Transform(p1);
                    p2 = rotate.Transform(p2);
                    p3 = rotate.Transform(p3);

                    if (!Clipping.DrawPoint(p1) || !Clipping.DrawPoint(p2) || !Clipping.DrawPoint(p3))
                    {
                        continue;
                    }

                    //v coordinate - negate it to convert from opengl coordinates to directx
                    var t1 = new System.Windows.Point(poly.V1.U, 1 - poly.V1.V);
                    var t2 = new System.Windows.Point(poly.V2.U, 1 - poly.V2.V);
                    var t3 = new System.Windows.Point(poly.V3.U, 1 - poly.V3.V);

                    //var t1 = new System.Windows.Point(0.0, 0.0);
                    //var t2 = new System.Windows.Point(2.0, 0.0);
                    //var t3 = new System.Windows.Point(0.0, 2.0);
                    //builder.AddTriangle(p3, p2, p1, t3, t2, t1);
                    builder.AddTriangle(p3, p2, p1, t3, t2, t1);
                }
                group.Children.Add(new GeometryModel3D(builder.ToMesh(), mat));
                mat = null;
            }

            //create the untextured polygons... basically a copy and paste from above which sucks... TODO
            var bbuilder = new MeshBuilder();
            mat = Materials.LightGray;
            foreach (var poly in untexturedPolys)
            {
                Point3D p1 = new Point3D(poly.V1.X, poly.V1.Y, poly.V1.Z);
                Point3D p2 = new Point3D(poly.V2.X, poly.V2.Y, poly.V2.Z);
                Point3D p3 = new Point3D(poly.V3.X, poly.V3.Y, poly.V3.Z);
                var rotate = new RotateTransform3D();
                rotate.Rotation = new AxisAngleRotation3D(new Vector3D(0, 0, 1), 90);
                p1 = rotate.Transform(p1);
                p2 = rotate.Transform(p2);
                p3 = rotate.Transform(p3);

                if (!Clipping.DrawPoint(p1) || !Clipping.DrawPoint(p2) || !Clipping.DrawPoint(p3))
                {
                    continue;
                }
                bbuilder.AddTriangle(p3, p2, p1);
            }
            group.Children.Add(new GeometryModel3D(bbuilder.ToMesh(), mat));
        }
コード例 #54
0
    /// <summary>
    /// Builds a single triangle.
    /// </summary>
    /// <param name="meshBuilder">The mesh builder currently being added to.</param>
    /// <param name="corner0">The vertex position at index 0 of the triangle.</param>
    /// <param name="corner1">The vertex position at index 1 of the triangle.</param>
    /// <param name="corner2">The vertex position at index 2 of the triangle.</param>
    public static void BuildTriangle(MeshBuilder meshBuilder, Vector3 corner0, Vector3 corner1, Vector3 corner2) {
        Vector3 normal = Vector3.Cross((corner1 - corner0), (corner2 - corner0)).normalized;

        meshBuilder.Vertices.Add(corner0);
        meshBuilder.UVs.Add(new Vector2(0.0f, 0.0f));
        meshBuilder.Normals.Add(normal);

        meshBuilder.Vertices.Add(corner1);
        meshBuilder.UVs.Add(new Vector2(0.0f, 1.0f));
        meshBuilder.Normals.Add(normal);

        meshBuilder.Vertices.Add(corner2);
        meshBuilder.UVs.Add(new Vector2(1.0f, 1.0f));
        meshBuilder.Normals.Add(normal);

        int baseIndex = meshBuilder.Vertices.Count - 3;

        meshBuilder.AddTriangle(baseIndex, baseIndex + 1, baseIndex + 2);
    }
コード例 #55
0
    public void BuildLinkBezier(MeshBuilder meshBuilder, BezierCurve connectionBezier, float widthStart, float widthEnd, Color colorStart, Color colorEnd) {
        List<int> verticesList = new List<int>();

        float m_splineStartRadius = widthStart;
        float m_splineEndRadius = widthEnd;
        int m_splineHeightSegmentCount = 8;
        int m_splineRadialSegmentCount = 4;

        float tInc = 1f / m_splineHeightSegmentCount; // How many subdivisions along the length of the spline

        for (int i = 0; i <= m_splineHeightSegmentCount; i++) {
            float t = tInc * (float)i;
            Vector3 ringCenter = connectionBezier.GetPoint(t);
            //Quaternion rot = Quaternion.identity;
            Vector3 dir = connectionBezier.GetDirection(t);
            Quaternion rot = Quaternion.identity;
            if (dir != Vector3.zero) {
                rot.SetLookRotation(dir);
            }
            float radius = ((1f - t) * m_splineStartRadius) + (t * m_splineEndRadius);
            // Construct the mesh Ring!
            //BuildBezierCurveRing(meshBuilder, m_splineRadialSegmentCount, ringCenter, radius, t, i > 0, rot); 
            //protected void BuildBezierCurveRing(MeshBuilder meshBuilder, int segmentCount, Vector3 center, float radius, float v, bool buildTriangles, Quaternion rotation) {
            float angleInc = (Mathf.PI * 2.0f) / m_splineRadialSegmentCount;

            for (int j = 0; j <= m_splineRadialSegmentCount; j++) {
                float angle = angleInc * j;

                Vector3 unitPosition = Vector3.zero;
                unitPosition.x = Mathf.Cos(angle);
                unitPosition.y = Mathf.Sin(angle);

                unitPosition = rot * unitPosition;
                Vector3 normal = unitPosition;

                meshBuilder.Vertices.Add(ringCenter + unitPosition * radius);
                meshBuilder.Normals.Add(normal);
                //meshBuilder.UVs.Add(new Vector2((float)i / segmentCount, v));
                meshBuilder.UVs.Add(new Vector2((float)j / m_splineRadialSegmentCount, t));
                verticesList.Add(meshBuilder.Vertices.Count - 1);
                meshBuilder.Colors.Add(Color.Lerp(colorStart, colorEnd, t));

                if (j > 0 && i > 0) {
                    //Debug.Log ("buildTriangles!");
                    int baseIndex = meshBuilder.Vertices.Count - 1;

                    int vertsPerRow = m_splineRadialSegmentCount + 1;

                    int index0 = baseIndex;
                    int index1 = baseIndex - 1;
                    int index2 = baseIndex - vertsPerRow;
                    int index3 = baseIndex - vertsPerRow - 1;

                    meshBuilder.AddTriangle(index1, index2, index0);
                    meshBuilder.AddTriangle(index1, index3, index2);
                }
            }            
        }
        connectionVertexList.Add(verticesList);  // keep track of Connection's vertices so their color can be changed without rebuilding every frame
    }
コード例 #56
0
 void AddInternalCubeFace(MeshBuilder meshBuilder, int v1, int v2, int v3, int v4)
 {
     meshBuilder.AddTriangle(v4, v3, v1);
     meshBuilder.AddTriangle(v3, v2, v1);
 }
コード例 #57
0
    public void BuildNodeSphere(MeshBuilder meshBuilder, Vector3 offset, float m_Radius, Color color) {
        List<int> verticesList = new List<int>();

        int m_HeightSegmentCount = 4;
        int m_RadialSegmentCount = 4;
        //float m_Radius = 1f;
        float m_VerticalScale = 1f;
        Quaternion rotation = Quaternion.identity;
        
        //the angle increment per height segment:
        float angleInc = Mathf.PI / m_HeightSegmentCount;

        //the vertical (scaled) radius of the sphere:
        float verticalRadius = m_Radius * m_VerticalScale;

        //build the rings:
        for (int i = 0; i <= m_HeightSegmentCount; i++) {
            Vector3 centrePos = Vector3.zero;

            //calculate a height offset and radius based on a vertical circle calculation:
            centrePos.y = -Mathf.Cos(angleInc * i);
            float radius = Mathf.Sin(angleInc * i);

            //calculate the slope of the shpere at this ring based on the height and radius:
            Vector2 slope = new Vector3(-centrePos.y / m_VerticalScale, radius);
            slope.Normalize();

            //multiply the unit height by the vertical radius, and then add the radius to the height to make this sphere originate from its base rather than its centre:
            centrePos.y = centrePos.y * verticalRadius + verticalRadius;

            //scale the radius by the one stored in the partData:
            radius *= m_Radius;

            //calculate the final position of the ring centre:
            Vector3 finalRingCentre = rotation * centrePos + offset;

            //V coordinate:
            float v = (float)i / m_HeightSegmentCount;

            //build the ring:
            //BuildRing(meshBuilder, m_RadialSegmentCount, finalRingCentre, radius, v, i > 0, rotation, slope);
            float angleIncrement = (Mathf.PI * 2.0f) / m_RadialSegmentCount;

            for (int j = 0; j <= m_RadialSegmentCount; j++) {
                float angle = angleIncrement * j;

                Vector3 unitPosition = Vector3.zero;
                unitPosition.x = Mathf.Cos(angle);
                unitPosition.z = Mathf.Sin(angle);

                float normalVertical = -slope.x;
                float normalHorizontal = slope.y;

                Vector3 normal = unitPosition * normalHorizontal;
                normal.y = normalVertical;

                normal = rotation * normal;

                unitPosition = rotation * unitPosition;

                meshBuilder.Vertices.Add(finalRingCentre + unitPosition * radius);
                meshBuilder.Normals.Add(normal);
                meshBuilder.UVs.Add(new Vector2((float)j / m_RadialSegmentCount, v));                
                verticesList.Add(meshBuilder.Vertices.Count - 1);
                meshBuilder.Colors.Add(color);

                if (j > 0 && i > 0) {
                    int baseIndex = meshBuilder.Vertices.Count - 1;

                    int vertsPerRow = m_RadialSegmentCount + 1;

                    int index0 = baseIndex;
                    int index1 = baseIndex - 1;
                    int index2 = baseIndex - vertsPerRow;
                    int index3 = baseIndex - vertsPerRow - 1;

                    meshBuilder.AddTriangle(index0, index2, index1);
                    meshBuilder.AddTriangle(index2, index3, index1);
                }
            }
        }
        nodeVertexList.Add(verticesList);  // keep track of Node's vertices so their color can be changed without rebuilding every frame
    }
コード例 #58
0
    /// <summary>
    /// Builds a ring as part of a cylinder.
    /// </summary>
    /// <param name="meshBuilder">The mesh builder currently being added to.</param>
    /// <param name="segmentCount">The number of segments in this ring.</param>
    /// <param name="centre">The position at the centre of the ring.</param>
    /// <param name="radius">The radius of the ring.</param>
    /// <param name="v">The V coordinate for this ring.</param>
    /// <param name="buildTriangles">Should triangles be built for this ring? This value should be false if this is the first ring in the cylinder.</param>
    /// <param name="rotation">A rotation value to be applied to the whole ring.</param>
    /// <param name="slope">The normalised slope (rise and run) of the cylinder at this height.</param>
    public static void BuildRingZ(MeshBuilder meshBuilder, int segmentCount, Vector3 centre, float radius, float v, bool buildTriangles, Quaternion rotation, Vector2 slope) {
        float angleInc = (Mathf.PI * 2.0f) / segmentCount;

        for (int i = 0; i <= segmentCount; i++) {
            float angle = angleInc * i;

            Vector3 unitPosition = Vector3.zero;
            unitPosition.x = Mathf.Cos(angle);
            unitPosition.y = Mathf.Sin(angle);

            float normalVertical = -slope.x;
            float normalHorizontal = slope.y;

            Vector3 normal = unitPosition * normalHorizontal;
            normal.z = normalVertical;

            normal = rotation * normal;

            unitPosition = rotation * unitPosition;

            meshBuilder.Vertices.Add(centre + unitPosition * radius);
            meshBuilder.Normals.Add(normal);
            meshBuilder.UVs.Add(new Vector2((float)i / segmentCount, v));

            if (i > 0 && buildTriangles) {
                int baseIndex = meshBuilder.Vertices.Count - 1;

                int vertsPerRow = segmentCount + 1;

                int index0 = baseIndex;
                int index1 = baseIndex - 1;
                int index2 = baseIndex - vertsPerRow;
                int index3 = baseIndex - vertsPerRow - 1;

                meshBuilder.AddTriangle(index0, index2, index1);
                meshBuilder.AddTriangle(index2, index3, index1);
            }
        }
    }
コード例 #59
0
    public MeshBuilder Create(MeshBuilder mb1, MeshBuilder mb2, bool round = true)
    {
        MeshBuilder meshBuilder = new MeshBuilder();

        float segmentSize = size / totalSegments;

        if (mb1.GetVertices("border").Count == mb2.GetVertices("border").Count)
        {
            Debug.Log("GilLog - MeshUnion::Create - round " + round + " 1 ");

            int totalVertices = mb1.GetVertices("border").Count;

            Debug.Log("GilLog - MeshUnion::Create - mb1 " + mb1 + " mb2 " + mb2 + " round " + round + "  - totalVertices " + totalVertices + "  - segmentSize " + segmentSize + " ");

            for (int i = 0; i < totalVertices; i++)
            {
                // Debug.Log("GilLog - MeshUnion::Create - mb1 " + mb1 + " mb2 " + mb2 + " round " + round + "  - mb1.GetVertices(border)[i] " + mb1.GetVertices("border")[i] + "  - mb2.GetVertices(border)[i] " + mb2.GetVertices("border")[i] + " ");
                Vector3 diffVector = (mb1.GetVertices("border")[i] - mb2.GetVertices("border")[i]).normalized;

                for (int s = 0; s < totalSegments; s++)
                {
                    meshBuilder.AddVertice(
                        mb1.GetVertices("border")[i] + s * segmentSize * diffVector
                        );

                    if (i < totalVertices - 1 || round)
                    {
                        int nextIndex = (i + 1) % totalVertices;
                        meshBuilder.AddTriangle(
                            i * (totalSegments + 1) + s,
                            i * (totalSegments + 1) + s + 1,
                            nextIndex * (totalSegments + 1) + s
                            );
                        meshBuilder.AddTriangle(
                            i * (totalSegments + 1) + s + 1,
                            nextIndex * (totalSegments + 1) + s + 1,
                            nextIndex * (totalSegments + 1) + s

                            );
                    }
                }

                meshBuilder.AddVertice(mb2.GetVertices("border")[i]);
            }
        }
        else
        {
            MeshBuilder tmp = null;

            if (mb1.GetVertices("border").Count > mb2.GetVertices("border").Count)
            {
                tmp = mb1;
                mb1 = mb2;
                mb2 = tmp;
            }

            int totalVertices1 = mb1.GetVertices("border").Count;
            int totalVertices2 = mb2.GetVertices("border").Count;

            int vertices2ForEachV1 = totalVertices2 / totalVertices1;

            int currentVertice2 = 0;

            int v1Index = 0;

            for (int i = 0; i < totalVertices1; i++)
            {
                v1Index = meshBuilder.Vertices.Count;
                meshBuilder.AddVertice(
                    mb1.GetVertices("border")[i]
                    );

                for (int v2 = currentVertice2; (i == totalVertices1 - 1 && v2 < totalVertices2) || v2 < currentVertice2 + vertices2ForEachV1; v2++)
                {
                    Debug.Log("GilLog - MeshUnion::Create - mb1 " + mb1 + " mb2 " + mb2 + " round " + round + "  - v2 " + v2 + " ");
                    Vector3 diffVector = (mb1.GetVertices("border")[i] - mb2.GetVertices("border")[v2]).normalized;

                    for (int s = 0; s < totalSegments; s++)
                    {
                        if (s > 0)
                        {
                            meshBuilder.AddVertice(
                                mb1.GetVertices("border")[i] + s * segmentSize * diffVector
                                );
                        }

                        if (v2 < totalVertices2 - 1 || round)
                        {
                            int nextIndex = (v2 + 1) % totalVertices2;
                            meshBuilder.AddTriangle(
                                v1Index,
                                v1Index + v2 * totalSegments + s + 1,
                                v1Index + v2 * totalSegments + s + 2
                                );
                        }
                    }

                    meshBuilder.AddVertice(mb2.GetVertices("border")[v2]);
                }

                currentVertice2 = currentVertice2 + vertices2ForEachV1;
            }
        }

        return(meshBuilder);
    }
コード例 #60
0
ファイル: Dodecahedron.cs プロジェクト: isaveu/MeshGeneration
 void AddInternalCubeFace(MeshBuilder meshBuilder, int v1, int v2, int v3, int v4)
 {
     meshBuilder.AddTriangle(v4, v3, v1);
     meshBuilder.AddTriangle(v3, v2, v1);
 }