public static void GenerateRightMesh(MeshFilter _oldMeshF, MeshRenderer _oldMeshR, SliceData _dataPlane) { GameObject newMesh; CustomMesh mesh = new CustomMesh(out newMesh, "right Mesh", _oldMeshF.transform, _oldMeshR.material); int vertexID = 0; for (int faceID = 1; faceID < _dataPlane.Faces.Count; faceID += 2) { if (!_dataPlane.Faces.ContainsKey(faceID)) { continue; } foreach (Edge e in _dataPlane.Faces[faceID].Edges) { foreach (Vector3 p in _dataPlane.Faces[faceID].GetDistinctsPoints()) { Vector3 vertexPos = _oldMeshF.transform.InverseTransformPoint(p); mesh.vertices.Add(vertexPos); mesh.triangles.Add(vertexID); vertexID++; } } } /*Debug.Log("nb vertices " + mesh.vertices.Count); * Debug.Log("nb triangles " + mesh.triangles.Count);*/ mesh.Recalculate(); mesh.AssignToMesh(newMesh.GetComponent <MeshFilter>()); mesh.AssignToSharedMesh(newMesh.GetComponent <MeshCollider>()); }
public void SetSelectCylinder() { objectAvailable = true; mSelected = mTheCylinder; mTheMesh.gameObject.SetActive(false); mTheCylinder.gameObject.SetActive(true); }
public void MeshVisualizer(Texture2D tex, CustomMesh customMesh) { MeshFilter meshFilter = mesh.GetComponent <MeshFilter>(); MeshRenderer meshRenderer = mesh.GetComponent <MeshRenderer>(); meshFilter.sharedMesh = customMesh.CreateMesh(); meshRenderer.sharedMaterial.mainTexture = tex; }
public void Init() { mf = gameObject.AddComponent <MeshFilter>(); mr = gameObject.AddComponent <MeshRenderer>(); mf.mesh = CustomMesh.Oil(); SetMaterial(Color.red); Deactivate(); }
//Check to see if a given world point exists in the cylinder bool WorldPointInside(ref Mesh mesh) { CustomMesh customMesh = GetComponent <CustomMesh>(); Vector3 worldPoint = new Vector3(0.0f, 1.0f, 0.0f); int[] indices = mesh.triangles; Vector3[] vertices = mesh.vertices; return(customMesh.ContainsWorldPoint(ref worldPoint, ref indices, ref vertices)); }
public static Mesh CreateMesh(Vector3[] vertices) { int[] triangles = new int[vertices.Length]; for (int i = 0; i < triangles.Length; i++) { triangles[i] = i; } return(CustomMesh.CreateMesh(vertices, triangles)); }
private void OpenModelFile(string file) { _mesh = new CustomMesh(file); _mesh.OnAnimationChanged += UpdateAnimationList; Viewport.AddMesh(_mesh); UpdateAnimationList(); }
public static Mesh Hexagon(float[] heights) { Vector3 center = new Vector3(0, 0, 0); int sideCount = 6; float length = 1f; Vector2[] points = new Vector2[sideCount]; float deg = 360f / (float)sideCount; for (int i = 0; i < points.Length; i++) { float radians = (float)i * deg * Mathf.Deg2Rad; float x = length * Mathf.Sin(radians); float y = length * Mathf.Cos(radians); points[i] = new Vector2(x, y); } Mesh hex = CustomMesh.CreateMesh( new Vector3[] { center, new Vector3(points[0].x, heights[0], points[0].y), new Vector3(points[1].x, heights[1], points[1].y), center, new Vector3(points[1].x, heights[1], points[1].y), new Vector3(points[2].x, heights[2], points[2].y), center, new Vector3(points[2].x, heights[2], points[2].y), new Vector3(points[3].x, heights[3], points[3].y), center, new Vector3(points[3].x, heights[3], points[3].y), new Vector3(points[4].x, heights[4], points[4].y), center, new Vector3(points[4].x, heights[4], points[4].y), new Vector3(points[5].x, heights[5], points[5].y), center, new Vector3(points[5].x, heights[5], points[5].y), new Vector3(points[0].x, heights[0], points[0].y) }, new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 } ); return(hex); }
public static Mesh Hexagon() { if (hexagon != null) { return(hexagon); } hexagon = CustomMesh.Hexagon(new float[6] { 0, 0, 0, 0, 0, 0 }); return(hexagon); }
void MakeInnerSide(CustomMesh input) { int vertexHalf = input.vertices.Length / 2; int trisHalf = input.triangles.Length / 2; for (int i = 0; i < trisHalf; i += 3) { input.triangles[i + trisHalf + 2] = input.triangles[i] + vertexHalf; input.triangles[i + trisHalf + 1] = input.triangles[i + 1] + vertexHalf; input.triangles[i + trisHalf] = input.triangles[i + 2] + vertexHalf; } }
public override BlockController Controller() { CustomMesh controller = new CustomMesh(); controller.verts = verts; controller.tris = tris; controller.uvs = uvs; controller.blockName = blockName; return(controller); }
public override BlockController Controller() { CustomMesh controller = new CustomMesh(); controller.verts = verts; controller.tris = tris; controller.uvs = uvs; controller.blockName = blockName; return controller; }
public override BlockController Controller() { CustomMesh controller = new CustomMesh(); controller.blockName = blockName; controller.isSolid = blockIsSolid; if (Application.isPlaying) { CustomMesh.SetUpMeshControllerMesh(meshName, controller, positionOffset); controller.collection = Block.index.textureIndex.GetTextureCollection(texture); } return controller; }
public void AddMesh(CustomMesh mesh) { if (!mesh.IsCreated) { mesh.Create(_device); } _Mesh = mesh; //Change Shader based on model type Shader = (_Mesh.Animated) ? (IEffect) new PosColorNormSkinnedEffect() : new PosColorNormEffect(); Shader.Create(_device); }
public override BlockController Controller() { CustomMesh controller = new CustomMesh(); controller.blockName = blockName; controller.isSolid = blockIsSolid; if (Application.isPlaying) { CustomMesh.SetUpMeshControllerMesh(meshName, controller, positionOffset); controller.collection = Block.index.textureIndex.GetTextureCollection(texture); } return(controller); }
public override void OnInspectorGUI() { CustomMesh cm = (CustomMesh)target; if (DrawDefaultInspector()) //if a value in inspecter is changed { cm.GenerateMesh(); } if (GUILayout.Button("Generate Mesh")) { cm.GenerateMesh(); } }
private static CustomMesh CreateLayer(Vector2 dimension) { CustomMesh mesh = new CustomMesh(); VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[4]; Vector2 halfExtent = dimension / 2; Vector3 v0 = Vector3Helper.Get(-halfExtent.X, 0, -halfExtent.Y); Vector3 v1 = Vector3Helper.Get(-halfExtent.X, 0, halfExtent.Y); Vector3 v2 = Vector3Helper.Get(halfExtent.X, 0, halfExtent.Y); Vector3 v3 = Vector3Helper.Get(halfExtent.X, 0, -halfExtent.Y); vertices[0].Position = v0; vertices[1].Position = v1; vertices[2].Position = v2; vertices[3].Position = v3; for (int i = 0; i < vertices.Length; i++) { vertices[i].Normal = Vector3.UnitY; } vertices[1].TextureCoordinate = new Vector2(0, 1); vertices[0].TextureCoordinate = new Vector2(0, 0); vertices[2].TextureCoordinate = new Vector2(1, 1); vertices[3].TextureCoordinate = new Vector2(1, 0); mesh.VertexDeclaration = new VertexDeclaration(State.Device, VertexPositionNormalTexture.VertexElements); mesh.VertexBuffer = new VertexBuffer(State.Device, VertexPositionNormalTexture.SizeInBytes * vertices.Length, BufferUsage.None); mesh.VertexBuffer.SetData(vertices); short[] indices = new short[6]; indices[0] = 0; indices[1] = 2; indices[2] = 1; indices[3] = 2; indices[4] = 0; indices[5] = 3; mesh.IndexBuffer = new IndexBuffer(State.Device, typeof(short), 6, BufferUsage.None); mesh.IndexBuffer.SetData(indices); mesh.SizeInBytes = VertexPositionNormalTexture.SizeInBytes; mesh.NumberOfVertices = 4; mesh.NumberOfPrimitives = 2; return(mesh); }
public static Mesh Oil() { float half = 0.5f; return(CustomMesh.CreateMesh( new Vector3[] { new Vector3(0, 0, half), new Vector3(-1, 0, -1), new Vector3(1, 0, -1) }, new int[3] { 2, 1, 0 } )); }
public static Mesh Step(float width) { float halfWidth = width * 0.5f; float length = 1f; return(CustomMesh.CreateMesh( new Vector3[] { new Vector3(0, 0, 0), new Vector3(halfWidth, 0, length), new Vector3(-halfWidth, 0, length) }, new int[3] { 2, 1, 0 } )); }
// Use this for initialization void Start() { customMesh = new CustomMesh(); meshRd = gameObject.AddComponent <MeshRenderer>(); meshCol = gameObject.AddComponent <MeshCollider>(); meshCol.convex = true; rb = gameObject.GetComponent <Rigidbody>(); meshRd.material = material; meshFilter = gameObject.AddComponent <MeshFilter>(); /*customMesh.CreateCube(Scaling); * customMesh.AssignToMesh(meshFilter); * customMesh.AssignToSharedMesh(meshCol);*/ }
/// <summary> /// Method to Create Mesh from the Bitmap image provided /// </summary> /// <param name="heightMap"></param> /// <returns></returns> private static CustomMesh CreateMesh(Texture2D heightMap) { CustomMesh terrainMesh = new CustomMesh(); VerticesContent _vertContent = new VerticesContent(State.Device, heightMap); terrainMesh.VertexBuffer = _vertContent._terrainVertexBuffer; terrainMesh.IndexBuffer = _vertContent._terrainIndexBuffer; terrainMesh.VertexDeclaration = _vertContent._terrainVertexDeclaration; terrainMesh.NumberOfVertices = _vertContent._terrainVertices.Length; terrainMesh.PrimitiveType = PrimitiveType.TriangleList; terrainMesh.NumberOfPrimitives = _vertContent._terrainIndices.Length / 3; // Call VerticesContent class to load vertex Content return(terrainMesh); }
void Start() { Ring[] rings = CreateRingsOnHelix(); Vector3[] vs = new Vector3[rings.Length * (ringSideCount * 2) * 3]; int count = 0; for (int i = 0; i < rings.Length - 1; i++) { Vector3[] points = rings[i].GetRingPoints(); Vector3[] points2 = rings[i + 1].GetRingPoints(); for (int j = 0; j < ringSideCount - 1; j++) { vs[count] = points2[j]; vs[count + 1] = points[j + 1]; vs[count + 2] = points[j]; vs[count + 3] = points2[j]; vs[count + 4] = points2[j + 1]; vs[count + 5] = points[j + 1]; count += 6; } vs[count] = points2[ringSideCount - 1]; vs[count + 1] = points[0]; vs[count + 2] = points[ringSideCount - 1]; vs[count + 3] = points2[ringSideCount - 1]; vs[count + 4] = points2[0]; vs[count + 5] = points[0]; count += 6; } Mesh helixTerrain = CustomMesh.CreateMesh(vs); CustomMeshObject c = Instantiate(cmo, Vector3.zero, Quaternion.identity) as CustomMeshObject; c.Init(helixTerrain, Color.green, true); CustomMeshObject c2 = Instantiate(cmo, Vector3.zero, Quaternion.identity) as CustomMeshObject; c2.Init(helixTerrain, Color.white, true); c2.transform.SetLocalEulerAnglesY(180f); }
GameObject PlopMeshIntoScene(CustomMesh customMesh) { GameObject newGameObject = new GameObject(); newGameObject.transform.localScale = new Vector3(-1.0f, 1.0f, 1.0f); MeshFilter meshFilter = newGameObject.AddComponent <MeshFilter>(); MeshRenderer meshRenderer = newGameObject.AddComponent <MeshRenderer>(); meshRenderer.material = brickMaterial; meshFilter.mesh = new Mesh(); meshFilter.mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32; // for meshes with more than 65535 verts (baseplates and such) meshFilter.mesh.vertices = customMesh.vertices; meshFilter.mesh.normals = customMesh.normals; meshFilter.mesh.uv = customMesh.uv; meshFilter.mesh.triangles = customMesh.triangles; return(newGameObject); }
public static void GetAndLoadMeshBlocks() { Mesh[] meshes = Resources.LoadAll<Mesh>(Config.Directories.BlockMeshFolder); foreach (var mesh in meshes) { CustomMesh controller = new CustomMesh(); controller.blockName = mesh.name; controller.verts = mesh.vertices; controller.tris = mesh.triangles; controller.uvs = mesh.uv; controller.collection = Block.index.textureIndex.GetTextureCollection(mesh.name); Block.index.AddBlockType(controller); } }
public Mesh CreateDiamondGrid(int numColumns, int numRows) { CustomMesh ret = new CustomMesh(); List<Vector3> vBuf = new List<Vector3>(); List<int> iBuf = new List<int>(); DiamondSquare sq = new DiamondSquare(); for (int r = -numColumns; r < numColumns; r+=2) { for (int c = -numColumns; c < numColumns; c+=2) { sq.AppendTranslatedSquare(vBuf, iBuf, new Vector3(c, 0, r), DiamondSquare.SquareType.Normal); } } ret.SetVertexData<VertexTypes.Position>(vBuf, iBuf); return ret; }
public static void GetAndLoadMeshBlocks() { Mesh[] meshes = Resources.LoadAll <Mesh>(Config.Directories.BlockMeshFolder); foreach (var mesh in meshes) { CustomMesh controller = new CustomMesh(); controller.blockName = mesh.name; controller.verts = mesh.vertices; controller.tris = mesh.triangles; controller.uvs = mesh.uv; controller.collection = Block.index.textureIndex.GetTextureCollection(mesh.name); Block.index.AddBlockType(controller); } }
public static string MeshToString(CustomMesh m) { int numVertices = 0; StringBuilder sb = new StringBuilder(); foreach (Vector3 v in m.vertices) { numVertices++; sb.Append(string.Format("v {0} {1} {2}\n", v.x, v.y, v.z)); } sb.Append("\n"); foreach (Vector3 v in m.normals) { sb.Append(string.Format("vn {0} {1} {2}\n", v.x, v.y, v.z)); } if (m.uv != null) { sb.Append("\n"); foreach (Vector3 v in m.uv) { sb.Append(string.Format("vt {0} {1}\n", v.x, v.y)); } } sb.Append("\n"); if (m.uv != null) { for (int i = 0; i < m.triangles.Length; i += 3) { sb.Append(string.Format("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\n", m.triangles[i] + 1 + StartIndex, m.triangles[i + 1] + 1 + StartIndex, m.triangles[i + 2] + 1 + StartIndex)); } } else { for (int i = 0; i < m.triangles.Length; i += 3) { sb.Append(string.Format("f {0}//{0} {1}//{1} {2}//{2}\n", m.triangles[i] + 1 + StartIndex, m.triangles[i + 1] + 1 + StartIndex, m.triangles[i + 2] + 1 + StartIndex)); } } StartIndex += numVertices; return(sb.ToString()); }
void CreateMapFloor(Rect mapRect) { Mesh floorMesh = _floor.GetComponent <MeshFilter>().mesh; floorMesh.Clear(); CustomMesh floorMeshData = new CustomMesh(Mathf.CeilToInt(mapRect.width) + 250, Mathf.CeilToInt(mapRect.height) + 250, Mathf.CeilToInt((10.0f / 500.0f) * Mathf.Max(mapRect.width, mapRect.height)), borderSize); floorMeshData.Generate(); floorMesh.vertices = floorMeshData.getVertices(); floorMesh.triangles = floorMeshData.getTriangles(); floorMesh.uv = floorMeshData.getUVs(); MeshCollider floorCollider = _floor.AddComponent <MeshCollider>(); floorCollider.sharedMesh = floorMesh; _floor.transform.position = new Vector3(mapRect.center.x - floorMeshData.width / 2, 0, mapRect.center.y - floorMeshData.height / 2); }
public void SetupAt(Vector2Int position) { if (this.position == position && HasBeenSetUpBefore()) { return; } if (mesh == null) { mesh = new CustomMesh(meshFilter, meshRenderer); } ChunkManager.Instance.chunkEvolver.RemoveChunkToEvolve(this); ChunkManager.Instance.chunkEvolver.RemoveAssistedEvolution(this); EvolveToState(StateManager.State.Empty, true); transform.position = new Vector3(position.x, 0, position.y); this.position = position; }
string MeshToString(CustomMesh m, bool includeUVs) { StringBuilder sb = new StringBuilder(); foreach (Vector3 v in m.vertices) { sb.Append(string.Format("v {0} {1} {2}\n", v.x, v.y, v.z)); } sb.Append("\n"); foreach (Vector3 v in m.normals) { sb.Append(string.Format("vn {0} {1} {2}\n", v.x, v.y, v.z)); } sb.Append("\n"); if (includeUVs) { foreach (Vector3 v in m.uv) { sb.Append(string.Format("vt {0} {1}\n", v.x, v.y)); } sb.Append("\n"); } if (includeUVs) { for (int i = 0; i < m.triangles.Length; i += 3) { sb.Append(string.Format("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\n", m.triangles[i] + 1 + startIndex, m.triangles[i + 1] + 1 + startIndex, m.triangles[i + 2] + 1 + startIndex)); } } else { for (int i = 0; i < m.triangles.Length; i += 3) { sb.Append(string.Format("f {0}//{0} {1}//{1} {2}//{2}\n", m.triangles[i] + 1 + startIndex, m.triangles[i + 1] + 1 + startIndex, m.triangles[i + 2] + 1 + startIndex)); } } startIndex += m.vertices.Length; return(sb.ToString()); }
void RenderInit() { objMesh = new CustomMesh(null, null); if (objMesh.loadFromObjectFile(Application.dataPath + objPath)) { Debug.Log(".obj mesh successfuly loaded."); } else { Debug.LogError(".obj mesh failed to import."); } objMesh.position = new vec3(0, 0, 5); objMesh.rotation = new vec3(0, 0, 0); float fNear = 0.1f; float fFar = 1000.0f; float fFov = 60f; float fAspectRatio = (float)height / (float)width; projMat = RenderMath.Matrix_MakeProjection(fFov, fAspectRatio, fNear, fFar); }
public static CustomMesh GenerateHeightMesh(float[,] noiseMap, float meshHeightModifier, AnimationCurve heightCurve, int lod) { int chunkSize = noiseMap.GetLength(0); int inc = (lod == 0) ? 1 : lod * 2; int vert = (chunkSize - 1) / inc + 1; CustomMesh customMesh = new CustomMesh(chunkSize); //populate verticies for (int v = 0, i = 0; v < chunkSize; v += inc) { for (int u = 0; u < chunkSize; u += inc, i++) { customMesh.verticies[i] = new Vector3(u - (chunkSize - 1) / 2f, heightCurve.Evaluate(noiseMap[u, v]) * meshHeightModifier, v - (chunkSize - 1) / 2f); customMesh.uvs[i] = new Vector2((float)u / chunkSize, (float)v / chunkSize); } } //Generate triangles //Generate triangles for (int v = 0, ti = 0, vi = 0; v < vert - 1; v++, vi++) { for (int u = 0; u < vert - 1; u++, ti += 6, vi++) { //triangle 1 customMesh.triangles[ti] = vi; customMesh.triangles[ti + 1] = vi + vert; customMesh.triangles[ti + 2] = vi + 1; //triangle 2 customMesh.triangles[ti + 3] = vi + 1; customMesh.triangles[ti + 4] = vi + vert; customMesh.triangles[ti + 5] = vi + vert + 1; } } return(customMesh); }
private static CustomMesh CreateShape(Texture2D heightMap) { // Create a primitive mesh for creating our custom pyramid shape CustomMesh terrain = new CustomMesh(); LoadHeightData(heightMap); SetUpVertices(); SetUpIndices(); CalculateNormals(); CopyToBuffers(); terrain.VertexBuffer = myVertexBuffer; terrain.IndexBuffer = myIndexBuffer; terrain.VertexDeclaration = VertexMultiTexture.vertexDeclaration; terrain.NumberOfVertices = t_vertices.Length; terrain.PrimitiveType = PrimitiveType.TriangleList; terrain.NumberOfPrimitives = Indices.Length / 3; Console.WriteLine(terrainWidth.ToString() + " " + terrainHeight.ToString()); return(terrain); }
// Update is called once per frame void Update() { //lineRenderer.SetVertexCount(polygonPoints.Count); //lineRenderer.SetPositions(polygonPoints.ToArray()); if (Input.GetButtonDown("Fire1")) { polygonPoints.Add(new Vector2((Input.mousePosition.x / cam.pixelWidth) * 2 - 1, (Input.mousePosition.y / cam.pixelHeight) * 2 - 1)); Debug.Log(new Vector2((Input.mousePosition.x / cam.pixelWidth), (Input.mousePosition.y / cam.pixelHeight)).ToString() + " : MP"); } if (Input.GetButtonDown("Fire3")) { newMesh = new CustomMesh(polygonPoints, meshMaterial, false, extrusionCount, extrusionDistance, offset); polygonPoints.Clear(); meshObject.AddComponent <MeshFilter>().mesh = newMesh.mesh; meshObject.AddComponent <MeshRenderer>().material = newMesh.material; } }
private static CustomMesh CreateSphere(float radius, int slices, int stacks) { if (slices < 5) throw new ArgumentException("Cannot draw a sphere with slices less than 5"); if (slices > 100) throw new ArgumentException("Cannot draw a sphere with slices greater than 100"); if (stacks < 5) throw new ArgumentException("Cannot draw a sphere with stacks less than 5"); if (stacks > 100) throw new ArgumentException("Cannot draw a sphere with stacks greater than 100"); if (radius <= 0) throw new ArgumentException("Radius has to be greater than 0"); CustomMesh mesh = new CustomMesh(); List<VertexPositionNormalTexture> vertices = new List<VertexPositionNormalTexture>(); double thai = 0, theta = 0; double thaiIncr = Math.PI / stacks; double thetaIncr = Math.PI * 2 / slices; int countB, countA; // Add sphere vertices for (countA = 0, thai = thaiIncr; thai < Math.PI - thaiIncr / 2; thai += thaiIncr, countA++) { for (countB = 0, theta = 0; countB < slices; theta += thetaIncr, countB++) { VertexPositionNormalTexture vert = new VertexPositionNormalTexture(); vert.Position = Vector3Helper.Get((float)(radius * Math.Sin(thai) * Math.Cos(theta)), (float)(radius * Math.Cos(thai)), (float)(radius * Math.Sin(thai) * Math.Sin(theta))); vert.Normal = Vector3.Normalize(vert.Position); vert.TextureCoordinate = new Vector2( (float)Math.Asin(vert.Normal.X) / MathHelper.Pi + 0.5f, (float)Math.Asin(vert.Normal.Y) / MathHelper.Pi + 0.5f); vertices.Add(vert); } } // Add north pole vertex vertices.Add(new VertexPositionNormalTexture(Vector3Helper.Get(0, radius, 0), Vector3Helper.Get(0, 1, 0), new Vector2( (float)Math.Asin(0) / MathHelper.Pi + 0.5f, (float)Math.Asin(1) / MathHelper.Pi + 0.5f))); // Add south pole vertex vertices.Add(new VertexPositionNormalTexture(Vector3Helper.Get(0, -radius, 0), Vector3Helper.Get(0, -1, 0), new Vector2( (float)Math.Asin(0) / MathHelper.Pi + 0.5f, (float)Math.Asin(-1) / MathHelper.Pi + 0.5f))); mesh.VertexDeclaration = VertexPositionNormalTexture.VertexDeclaration; mesh.VertexBuffer = new VertexBuffer(State.Device, typeof(VertexPositionNormalTexture), vertices.Count, BufferUsage.None); mesh.VertexBuffer.SetData(vertices.ToArray()); List<short> indices = new List<short>(); // Create the north and south pole area mesh for (int i = 0, j = (countA - 1) * slices; i < slices - 1; i++, j++) { indices.Add((short)(vertices.Count - 2)); indices.Add((short)i); indices.Add((short)(i + 1)); indices.Add((short)(vertices.Count - 1)); indices.Add((short)(j + 1)); indices.Add((short)j); } indices.Add((short)(vertices.Count - 2)); indices.Add((short)(slices - 1)); indices.Add(0); indices.Add((short)(vertices.Count - 1)); indices.Add((short)((countA - 1) * slices)); indices.Add((short)(vertices.Count - 3)); // Create side of the sphere for (int i = 0; i < countA - 1; i++) { for (int j = 0; j < slices - 1; j++) { indices.Add((short)(i * slices + j)); indices.Add((short)((i + 1) * slices + j)); indices.Add((short)((i + 1) * slices + j + 1)); indices.Add((short)(i * slices + j)); indices.Add((short)((i + 1) * slices + j + 1)); indices.Add((short)(i * slices + j + 1)); } indices.Add((short)((i + 1) * slices - 1)); indices.Add((short)((i + 2) * slices - 1)); indices.Add((short)((i + 1) * slices)); indices.Add((short)((i + 1) * slices - 1)); indices.Add((short)((i + 1) * slices)); indices.Add((short)(i * slices)); } mesh.IndexBuffer = new IndexBuffer(State.Device, typeof(short), indices.Count, BufferUsage.None); mesh.IndexBuffer.SetData(indices.ToArray()); mesh.NumberOfVertices = vertices.Count; mesh.NumberOfPrimitives = indices.Count / 3; return mesh; }
private static CustomMesh CreateTorus(float inner, float outer, int slices, int stacks) { if (slices < 5) throw new ArgumentException("Cannot draw a torus with slices less than 5"); if (slices > 100) throw new ArgumentException("Cannot draw a torus with slices greater than 100"); if (stacks < 5) throw new ArgumentException("Cannot draw a torus with stacks less than 5"); if (stacks > 100) throw new ArgumentException("Cannot draw a torus with stacks greater than 100"); if (inner < 0) throw new ArgumentException("Inner radius has to be greater than or equal to 0"); if (outer <= 0) throw new ArgumentException("Outer radius has to be greater than 0"); if (inner >= outer) throw new ArgumentException("Inner radius has to be less than outer radius"); CustomMesh mesh = new CustomMesh(); List<VertexPositionNormal> vertices = new List<VertexPositionNormal>(); // Add the vertices double thetaIncr = Math.PI * 2 / slices; double thaiIncr = Math.PI * 2 / stacks; int countA, countB = 0; double theta, thai; float c = (outer + inner) / 2; float a = (outer - inner) / 2; double common; Vector3 tubeCenter; for (countA = 0, theta = 0; countA < slices; theta += thetaIncr, countA++) { tubeCenter = Vector3Helper.Get((float)(c * Math.Cos(theta)), 0, (float)(c * Math.Sin(theta))); for (countB = 0, thai = 0; countB < stacks; thai += thaiIncr, countB++) { VertexPositionNormal vert = new VertexPositionNormal(); common = (c + a * Math.Cos(thai)); vert.Position = Vector3Helper.Get((float)(common * Math.Cos(theta)), (float)(a * Math.Sin(thai)), (float)(common * Math.Sin(theta))); vert.Normal = Vector3.Normalize(vert.Position - tubeCenter); vertices.Add(vert); } } mesh.VertexDeclaration = VertexPositionNormal.VertexDeclaration; mesh.VertexBuffer = new VertexBuffer(State.Device, typeof(VertexPositionNormal), vertices.Count, BufferUsage.None); mesh.VertexBuffer.SetData(vertices.ToArray()); List<short> indices = new List<short>(); for (int i = 0; i < slices - 1; i++) { for (int j = 0; j < stacks - 1; j++) { indices.Add((short)(i * stacks + j)); indices.Add((short)((i + 1) * stacks + j)); indices.Add((short)(i * stacks + j + 1)); indices.Add((short)(i * stacks + j + 1)); indices.Add((short)((i + 1) * stacks + j)); indices.Add((short)((i + 1) * stacks + j + 1)); } indices.Add((short)((i + 1) * stacks - 1)); indices.Add((short)((i + 2) * stacks - 1)); indices.Add((short)(i * stacks)); indices.Add((short)(i * stacks)); indices.Add((short)((i + 2) * stacks - 1)); indices.Add((short)((i + 1) * stacks)); } for (int j = 0; j < stacks - 1; j++) { indices.Add((short)((slices - 1) * stacks + j)); indices.Add((short)j); indices.Add((short)((slices - 1) * stacks + j + 1)); indices.Add((short)((slices - 1) * stacks + j + 1)); indices.Add((short)j); indices.Add((short)(j + 1)); } indices.Add((short)(slices * stacks - 1)); indices.Add((short)(slices - 1)); indices.Add((short)((slices - 1) * stacks)); indices.Add((short)((slices - 1) * stacks)); indices.Add((short)(slices - 1)); indices.Add((short)0); mesh.IndexBuffer = new IndexBuffer(State.Device, typeof(short), indices.Count, BufferUsage.None); mesh.IndexBuffer.SetData(indices.ToArray()); mesh.NumberOfVertices = vertices.Count; mesh.NumberOfPrimitives = indices.Count / 3; return mesh; }
/// <summary> /// Gets the mesh file with the given name and adds the mesh's data to the controller /// </summary> public static void SetUpMeshControllerMesh(string meshName, CustomMesh controller, Vector3 positionOffset) { GameObject meshGO = (GameObject)Resources.Load(Config.Directories.BlockMeshFolder + "/" + meshName);//(from m in meshGOs where m.name == meshName select m).First(); for (int GOIndex = 0; GOIndex < meshGO.transform.childCount; GOIndex++) { Mesh mesh = meshGO.transform.GetChild(GOIndex).GetComponent<MeshFilter>().sharedMesh; List<Vector3> verts = new List<Vector3>(); foreach (var vertex in mesh.vertices) { verts.Add(vertex + positionOffset); } List<int> trisUp = new List<int>(); List<int> trisDown = new List<int>(); List<int> trisNorth = new List<int>(); List<int> trisEast = new List<int>(); List<int> trisSouth = new List<int>(); List<int> trisWest = new List<int>(); List<int> trisOther = new List<int>(); // Split the triangles into 7 groups, one for each side they // could be aligned with and one for unaligned triangles for (int i = 0; i < mesh.triangles.Length; i += 3) { //Triangles aligned with top side of mesh if (AlignedWith(verts[mesh.triangles[i]], 1, 0.5f) && AlignedWith(verts[mesh.triangles[i + 1]], 1, 0.5f) && AlignedWith(verts[mesh.triangles[i + 2]], 1, 0.5f)) { trisUp.Add(mesh.triangles[i]); trisUp.Add(mesh.triangles[i + 1]); trisUp.Add(mesh.triangles[i + 2]); } //Triangles aligned with top side of mesh else if (AlignedWith(verts[mesh.triangles[i]], 1, -0.5f) && AlignedWith(verts[mesh.triangles[i + 1]], 1, -0.5f) && AlignedWith(verts[mesh.triangles[i + 2]], 1, -0.5f)) { trisDown.Add(mesh.triangles[i]); trisDown.Add(mesh.triangles[i + 1]); trisDown.Add(mesh.triangles[i + 2]); } //Triangles aligned with top side of mesh else if (AlignedWith(verts[mesh.triangles[i]], 2, 0.5f) && AlignedWith(verts[mesh.triangles[i + 1]], 2, 0.5f) && AlignedWith(verts[mesh.triangles[i + 2]], 2, 0.5f)) { trisNorth.Add(mesh.triangles[i]); trisNorth.Add(mesh.triangles[i + 1]); trisNorth.Add(mesh.triangles[i + 2]); } //Triangles aligned with top side of mesh else if (AlignedWith(verts[mesh.triangles[i]], 0, 0.5f) && AlignedWith(verts[mesh.triangles[i + 1]], 0, 0.5f) && AlignedWith(verts[mesh.triangles[i + 2]], 0, 0.5f)) { trisEast.Add(mesh.triangles[i]); trisEast.Add(mesh.triangles[i + 1]); trisEast.Add(mesh.triangles[i + 2]); } //Triangles aligned with top side of mesh else if (AlignedWith(verts[mesh.triangles[i]], 2, -0.5f) && AlignedWith(verts[mesh.triangles[i + 1]], 2, -0.5f) && AlignedWith(verts[mesh.triangles[i + 2]], 2, -0.5f)) { trisSouth.Add(mesh.triangles[i]); trisSouth.Add(mesh.triangles[i + 1]); trisSouth.Add(mesh.triangles[i + 2]); } //Triangles aligned with top side of mesh else if (AlignedWith(verts[mesh.triangles[i]], 0, -0.5f) && AlignedWith(verts[mesh.triangles[i + 1]], 0, -0.5f) && AlignedWith(verts[mesh.triangles[i + 2]], 0, -0.5f)) { trisWest.Add(mesh.triangles[i]); trisWest.Add(mesh.triangles[i + 1]); trisWest.Add(mesh.triangles[i + 2]); } else { trisOther.Add(mesh.triangles[i]); trisOther.Add(mesh.triangles[i + 1]); trisOther.Add(mesh.triangles[i + 2]); } } trisUp.AddRange(controller.trisUp); controller.trisUp = trisUp.ToArray(); trisDown.AddRange(controller.trisDown); controller.trisDown = trisDown.ToArray(); trisNorth.AddRange(controller.trisNorth); controller.trisNorth = trisNorth.ToArray(); trisEast.AddRange(controller.trisEast); controller.trisEast = trisEast.ToArray(); trisSouth.AddRange(controller.trisSouth); controller.trisSouth = trisSouth.ToArray(); trisWest.AddRange(controller.trisWest); controller.trisWest = trisWest.ToArray(); trisOther.AddRange(controller.trisOther); controller.trisOther = trisOther.ToArray(); controller.verts = mesh.vertices; controller.uvs = mesh.uv; } }
private void CreatePlane(float xdim, float ydim, float texCoordX, float texCoordY, float texCoordWidth, float texCoordHeight) { customMesh = new CustomMesh(); VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[4]; Vector3 halfExtent = new Vector3(); halfExtent.X = xdim / 2; halfExtent.Y = ydim / 2; Vector3 v0 = Vector3Helper.Get(-halfExtent.X, 0, -halfExtent.Y); Vector3 v1 = Vector3Helper.Get(halfExtent.X, 0, -halfExtent.Y); Vector3 v2 = Vector3Helper.Get(-halfExtent.X, 0, halfExtent.Y); Vector3 v3 = Vector3Helper.Get(halfExtent.X, 0, halfExtent.Y); this.vertices.Add(v0); this.vertices.Add(v1); this.vertices.Add(v2); this.vertices.Add(v3); Vector3 pY = Vector3.UnitY; vertices[0].Position = v0; vertices[1].Position = v1; vertices[2].Position = v2; vertices[3].Position = v3; vertices[0].TextureCoordinate = new Vector2(texCoordX, texCoordY); vertices[1].TextureCoordinate = new Vector2(texCoordX + texCoordWidth, texCoordY); vertices[2].TextureCoordinate = new Vector2(texCoordX, texCoordY + texCoordHeight); vertices[3].TextureCoordinate = new Vector2(texCoordX + texCoordWidth, texCoordY + texCoordHeight); for (int i = 0; i < 4; i++) vertices[i].Normal = pY; customMesh.VertexDeclaration = VertexPositionNormalTexture.VertexDeclaration; customMesh.VertexBuffer = new VertexBuffer(State.Device, typeof(VertexPositionNormalTexture), 4, BufferUsage.None); customMesh.VertexBuffer.SetData<VertexPositionNormalTexture>(vertices); short[] indices = new short[6]; indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 2; indices[4] = 1; indices[5] = 3; for (int i = 0; i < indices.Length; ++i) this.indices.Add(indices[i]); customMesh.IndexBuffer = new IndexBuffer(State.Device, typeof(short), 6, BufferUsage.None); customMesh.IndexBuffer.SetData(indices); customMesh.NumberOfVertices = 4; customMesh.NumberOfPrimitives = 2; if (this.vertices.Count == 0) { throw new GoblinException("Corrupted model vertices. Failed to calculate MBB."); } else { boundingBox = BoundingBox.CreateFromPoints(this.vertices); boundingSphere = BoundingSphere.CreateFromPoints(this.vertices); if (offsetTransform.Equals(Matrix.Identity)) offsetTransform.Translation = (boundingBox.Min + boundingBox.Max) / 2; } }
private static CustomMesh CreateChamferCylinder(float radius, float height, int slices) { if(slices < 5) throw new ArgumentException("Cannot draw a capsule with slices less than 5"); if (slices > 100) throw new ArgumentException("Cannot draw a capsule with slices greater than 100"); if (radius <= 0) throw new ArgumentException("radius should be greater than zero"); if (height <= 0) throw new ArgumentException("height should be greater than zero"); CustomMesh mesh = new CustomMesh(); List<VertexPositionNormal> vertices = new List<VertexPositionNormal>(); float halfH = height / 2; Vector3 topCenter = Vector3Helper.Get(0, halfH, 0); Vector3 bottomCenter = Vector3Helper.Get(0, -halfH, 0); double thai = 0, theta = 0; double thaiIncr = Math.PI / slices; double thetaIncr = Math.PI * 2 / slices; int countB, countA; // Add side vertices for (countA = 0, thai = 0; thai <= Math.PI; thai += thaiIncr, countA++) { for (countB = 0, theta = 0; countB < slices; theta += thetaIncr, countB++) { VertexPositionNormal vert = new VertexPositionNormal(); vert.Position = Vector3Helper.Get((float)(halfH * Math.Sin(thai) * Math.Cos(theta) + radius * Math.Cos(theta)), (float)(halfH * Math.Cos(thai)), (float)(halfH * Math.Sin(thai) * Math.Sin(theta) + radius * Math.Sin(theta))); vert.Normal = Vector3.Normalize(vert.Position); vertices.Add(vert); } } // Add north pole vertex vertices.Add(new VertexPositionNormal(topCenter, new Vector3(0, 1, 0))); // Add south pole vertex vertices.Add(new VertexPositionNormal(bottomCenter, new Vector3(0, -1, 0))); mesh.VertexDeclaration = VertexPositionNormal.VertexDeclaration; mesh.VertexBuffer = new VertexBuffer(State.Device, typeof(VertexPositionNormal), vertices.Count, BufferUsage.None); mesh.VertexBuffer.SetData(vertices.ToArray()); List<short> indices = new List<short>(); // Create side of the hemispheres for (int i = 0; i < countA - 1; i++) { for (int j = 0; j < slices - 1; j++) { indices.Add((short)(i * slices + j)); indices.Add((short)((i + 1) * slices + j)); indices.Add((short)((i + 1) * slices + j + 1)); indices.Add((short)(i * slices + j)); indices.Add((short)((i + 1) * slices + j + 1)); indices.Add((short)(i * slices + j + 1)); } indices.Add((short)((i + 1) * slices - 1)); indices.Add((short)((i + 2) * slices - 1)); indices.Add((short)((i + 1) * slices)); indices.Add((short)((i + 1) * slices - 1)); indices.Add((short)((i + 1) * slices)); indices.Add((short)(i * slices )); } // Create the north and south pole area mesh for (int i = 0, j = (countA - 1) * slices; i < slices - 1; i++, j++) { indices.Add((short)(vertices.Count - 2)); indices.Add((short)i); indices.Add((short)(i + 1)); indices.Add((short)(vertices.Count - 1)); indices.Add((short)(j + 1)); indices.Add((short)j); } indices.Add((short)(vertices.Count - 2)); indices.Add((short)(slices - 1)); indices.Add(0); indices.Add((short)(vertices.Count - 1)); indices.Add((short)((countA - 1) * slices)); indices.Add((short)(vertices.Count - 3)); mesh.IndexBuffer = new IndexBuffer(State.Device, typeof(short), indices.Count, BufferUsage.None); mesh.IndexBuffer.SetData(indices.ToArray()); mesh.NumberOfVertices = vertices.Count; mesh.NumberOfPrimitives = indices.Count / 3; return mesh; }
private static CustomMesh CreateCylinder(float bottom, float top, float height, int slices) { if(slices < 3) throw new ArgumentException("Cannot draw a cylinder with slices less than 3"); if (top < 0) throw new ArgumentException("Top has to be a positive natural number"); if (bottom <= 0) throw new ArgumentException("Bottom has to be greater than zero"); if (height <= 0) throw new ArgumentException("Height should be greater than zero"); CustomMesh mesh = new CustomMesh(); List<VertexPositionNormal> vertices = new List<VertexPositionNormal>(); // Add top center vertex VertexPositionNormal topCenter = new VertexPositionNormal(); topCenter.Position = Vector3Helper.Get(0, height / 2, 0); topCenter.Normal = Vector3Helper.Get(0, 1, 0); vertices.Add(topCenter); // Add bottom center vertex VertexPositionNormal bottomCenter = new VertexPositionNormal(); bottomCenter.Position = Vector3Helper.Get(0, -height / 2, 0); bottomCenter.Normal = Vector3Helper.Get(0, -1, 0); vertices.Add(bottomCenter); double angle = 0; double incr = Math.PI * 2 / slices; float cos, sin; bool hasTop = (top > 0); Vector3 u, v; Matrix mat; bool tilted = (top != bottom); float rotAngle = (float)Math.Atan(bottom / height); Vector3 down = -Vector3.UnitY; if (hasTop) { // Add top & bottom side vertices for (int i = 0; i <= slices; i++, angle += incr) { cos = (float)Math.Cos(angle); sin = (float)Math.Sin(angle); VertexPositionNormal topSide = new VertexPositionNormal(); topSide.Position = Vector3Helper.Get(cos * top, height / 2, sin * top); topSide.Normal = Vector3.Normalize(topSide.Position - topCenter.Position); VertexPositionNormal topSide2 = new VertexPositionNormal(); topSide2.Position = Vector3Helper.Get(cos * top, height / 2, sin * top); topSide2.Normal = topCenter.Normal; // Add bottom side vertices VertexPositionNormal bottomSide = new VertexPositionNormal(); bottomSide.Position = Vector3Helper.Get(cos * bottom, -height / 2, sin * bottom); bottomSide.Normal = Vector3.Normalize(bottomSide.Position - bottomCenter.Position); VertexPositionNormal bottomSide2 = new VertexPositionNormal(); bottomSide2.Position = Vector3Helper.Get(cos * bottom, -height / 2, sin * bottom); bottomSide2.Normal = bottomCenter.Normal; if (tilted) { v = topSide.Normal; u = Vector3.Cross(v, down); mat = Matrix.CreateTranslation(v) * Matrix.CreateFromAxisAngle(u, -rotAngle); topSide.Normal = bottomSide.Normal = Vector3.Normalize(mat.Translation); } vertices.Add(topSide); vertices.Add(topSide2); vertices.Add(bottomSide); vertices.Add(bottomSide2); } } else { // Add top & bottom side vertices for (int i = 0; i <= slices; i++, angle += incr) { cos = (float)Math.Cos(angle); sin = (float)Math.Sin(angle); VertexPositionNormal topSide = new VertexPositionNormal(); topSide.Position = topCenter.Position; // Add bottom side vertices VertexPositionNormal bottomSide = new VertexPositionNormal(); bottomSide.Position = Vector3Helper.Get(cos * bottom, -height / 2, sin * bottom); bottomSide.Normal = Vector3.Normalize(bottomSide.Position - bottomCenter.Position); VertexPositionNormal bottomSide2 = new VertexPositionNormal(); bottomSide2.Position = Vector3Helper.Get(cos * bottom, -height / 2, sin * bottom); bottomSide2.Normal = bottomCenter.Normal; v = bottomSide.Normal; u = Vector3.Cross(v, down); mat = Matrix.CreateTranslation(v) * Matrix.CreateFromAxisAngle(u, rotAngle); topSide.Normal = bottomSide.Normal = Vector3.Normalize(mat.Translation); vertices.Add(topSide); vertices.Add(bottomSide); vertices.Add(bottomSide2); } } mesh.VertexDeclaration = VertexPositionNormal.VertexDeclaration; mesh.VertexBuffer = new VertexBuffer(State.Device, typeof(VertexPositionNormal), vertices.Count, BufferUsage.None); mesh.VertexBuffer.SetData(vertices.ToArray()); List<short> indices = new List<short>(); if (hasTop) { // Create top & bottom circle for (int i = 2; i < vertices.Count - 7; i += 4) { indices.Add(0); indices.Add((short)(i + 1)); indices.Add((short)(i + 5)); indices.Add(1); indices.Add((short)(i + 7)); indices.Add((short)(i + 3)); } // Create side for (int i = 2; i < vertices.Count - 7; i += 4) { indices.Add((short)i); indices.Add((short)(i + 2)); indices.Add((short)(i + 4)); indices.Add((short)(i + 4)); indices.Add((short)(i + 2)); indices.Add((short)(i + 6)); } } else { // Create bottom circle for (int i = 2; i < vertices.Count - 5; i += 3) { indices.Add(1); indices.Add((short)(i + 5)); indices.Add((short)(i + 2)); } // Create side for (int i = 2; i < vertices.Count - 5; i += 3) { indices.Add((short)i); indices.Add((short)(i + 1)); indices.Add((short)(i + 4)); } } mesh.IndexBuffer = new IndexBuffer(State.Device, typeof(short), indices.Count, BufferUsage.None); mesh.IndexBuffer.SetData(indices.ToArray()); mesh.NumberOfVertices = vertices.Count; mesh.NumberOfPrimitives = indices.Count / 3; return mesh; }
private static CustomMesh CreateBox(float xdim, float ydim, float zdim) { CustomMesh mesh = new CustomMesh(); VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[24]; Vector3 halfExtent = new Vector3(); halfExtent.X = xdim / 2; halfExtent.Y = ydim / 2; halfExtent.Z = zdim / 2; Vector3 v0 = Vector3Helper.Get(-halfExtent.X, -halfExtent.Y, -halfExtent.Z); Vector3 v1 = Vector3Helper.Get(halfExtent.X, -halfExtent.Y, -halfExtent.Z); Vector3 v2 = Vector3Helper.Get(-halfExtent.X, halfExtent.Y, -halfExtent.Z); Vector3 v3 = Vector3Helper.Get(halfExtent.X, halfExtent.Y, -halfExtent.Z); Vector3 v4 = Vector3Helper.Get(halfExtent.X, halfExtent.Y, halfExtent.Z); Vector3 v5 = Vector3Helper.Get(-halfExtent.X, halfExtent.Y, halfExtent.Z); Vector3 v6 = Vector3Helper.Get(halfExtent.X, -halfExtent.Y, halfExtent.Z); Vector3 v7 = Vector3Helper.Get(-halfExtent.X, -halfExtent.Y, halfExtent.Z); Vector3 nZ = -Vector3.UnitZ; Vector3 pZ = Vector3.UnitZ; Vector3 nX = -Vector3.UnitX; Vector3 pX = Vector3.UnitX; Vector3 nY = -Vector3.UnitY; Vector3 pY = Vector3.UnitY; vertices[0].Position = v0; vertices[1].Position = v1; vertices[2].Position = v2; vertices[3].Position = v3; vertices[4].Position = v0; vertices[5].Position = v7; vertices[6].Position = v2; vertices[7].Position = v5; vertices[8].Position = v4; vertices[9].Position = v5; vertices[10].Position = v7; vertices[11].Position = v6; vertices[12].Position = v4; vertices[13].Position = v3; vertices[14].Position = v1; vertices[15].Position = v6; vertices[16].Position = v2; vertices[17].Position = v4; vertices[18].Position = v5; vertices[19].Position = v3; vertices[20].Position = v0; vertices[21].Position = v1; vertices[22].Position = v6; vertices[23].Position = v7; for (int i = 0; i < 4; i++) vertices[i].Normal = nZ; for (int i = 4; i < 8; i++) vertices[i].Normal = nX; for (int i = 8; i < 12; i++) vertices[i].Normal = pZ; for (int i = 12; i < 16; i++) vertices[i].Normal = pX; for (int i = 16; i < 20; i++) vertices[i].Normal = pY; for (int i = 20; i < 24; i++) vertices[i].Normal = nY; // Assign texture coordinates using positional spherical mapping Vector3 v; for (int i = 0; i < vertices.Length; ++i) { v = vertices[i].Position; v.Normalize(); vertices[i].TextureCoordinate = new Vector2( (float)Math.Asin(v.X) / MathHelper.Pi + 0.5f, (float)Math.Asin(v.Y) / MathHelper.Pi + 0.5f); } mesh.VertexDeclaration = VertexPositionNormalTexture.VertexDeclaration; mesh.VertexBuffer = new VertexBuffer(State.Device, typeof(VertexPositionNormalTexture), 24, BufferUsage.None); mesh.VertexBuffer.SetData<VertexPositionNormalTexture>(vertices); short[] indices = new short[36]; indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 2; indices[4] = 1; indices[5] = 3; indices[6] = 4; indices[7] = 6; indices[8] = 5; indices[9] = 6; indices[10] = 7; indices[11] = 5; indices[12] = 11; indices[13] = 10; indices[14] = 9; indices[15] = 11; indices[16] = 9; indices[17] = 8; indices[18] = 14; indices[19] = 15; indices[20] = 13; indices[21] = 15; indices[22] = 12; indices[23] = 13; indices[24] = 19; indices[25] = 17; indices[26] = 18; indices[27] = 19; indices[28] = 18; indices[29] = 16; indices[30] = 21; indices[31] = 20; indices[32] = 23; indices[33] = 21; indices[34] = 23; indices[35] = 22; mesh.IndexBuffer = new IndexBuffer(State.Device, typeof(short), 36, BufferUsage.None); mesh.IndexBuffer.SetData(indices); mesh.NumberOfVertices = 24; mesh.NumberOfPrimitives = 12; return mesh; }
private static CustomMesh CreateDisk(float inner, float outer, int slices, double start, double sweep, bool twoSided) { if (slices < 3) throw new ArgumentException("Cannot draw a disk with slices less than 3"); if (inner < 0) throw new ArgumentException("Inner radius has to be greater than or equal to 0"); if (outer <= 0) throw new ArgumentException("Outer radius has to be greater than 0"); if (inner >= outer) throw new ArgumentException("Inner radius has to be less than outer radius"); CustomMesh mesh = new CustomMesh(); List<VertexPositionNormal> vertices = new List<VertexPositionNormal>(); double angle = start; double incr = sweep / slices; float cos, sin; bool hasInner = (inner > 0); // Add top & bottom side vertices if (!hasInner) { VertexPositionNormal front = new VertexPositionNormal(); front.Position = Vector3Helper.Get(0, 0, 0); front.Normal = Vector3Helper.Get(0, 1, 0); vertices.Add(front); if (twoSided) { VertexPositionNormal back = new VertexPositionNormal(); back.Position = Vector3Helper.Get(0, 0, 0); back.Normal = Vector3Helper.Get(0, -1, 0); vertices.Add(back); } } // Add inner & outer vertices for (int i = 0; i <= slices; i++, angle += incr) { cos = (float)Math.Cos(angle); sin = (float)Math.Sin(angle); if (hasInner) { VertexPositionNormal inside = new VertexPositionNormal(); inside.Position = Vector3Helper.Get(cos * inner, 0, sin * inner); inside.Normal = Vector3Helper.Get(0, 1, 0); vertices.Add(inside); if (twoSided) vertices.Add(new VertexPositionNormal(inside.Position, Vector3Helper.Get(0, -1, 0))); } VertexPositionNormal outside = new VertexPositionNormal(); outside.Position = Vector3Helper.Get(cos * outer, 0, sin * outer); outside.Normal = Vector3Helper.Get(0, 1, 0); vertices.Add(outside); if (twoSided) vertices.Add(new VertexPositionNormal(outside.Position, Vector3Helper.Get(0, -1, 0))); } mesh.VertexDeclaration = VertexPositionNormal.VertexDeclaration; mesh.VertexBuffer = new VertexBuffer(State.Device, typeof(VertexPositionNormal), vertices.Count, BufferUsage.None); mesh.VertexBuffer.SetData(vertices.ToArray()); List<short> indices = new List<short>(); // Create front side if (twoSided) { if (hasInner) { for (int i = 0; i < vertices.Count - 2; i++) { indices.Add((short)(2 * i)); indices.Add((short)(2 * (i + 2 - (i+1)%2))); indices.Add((short)(2 * (i + 2 - i%2))); indices.Add((short)(2 * i - 1)); indices.Add((short)(2 * (i + 2 - (i + 1) % 2) - 1)); indices.Add((short)(2 * (i + 2 - i % 2) - 1)); } } else { for (int i = 1; i < vertices.Count - 1; i++) { indices.Add((short)0); indices.Add((short)(2 * i)); indices.Add((short)(2 * (i + 1))); indices.Add((short)0); indices.Add((short)(i + 3)); indices.Add((short)(i + 1)); } } } else { if (hasInner) { for (int i = 0; i < vertices.Count - 2; i++) { indices.Add((short)i); indices.Add((short)(i + 2 - (i+1)%2)); indices.Add((short)(i + 2 - i%2)); } } else { for (int i = 1; i < vertices.Count - 1; i++) { indices.Add((short)0); indices.Add((short)(i)); indices.Add((short)(i + 1)); } } } mesh.IndexBuffer = new IndexBuffer(State.Device, typeof(short), indices.Count, BufferUsage.None); mesh.IndexBuffer.SetData(indices.ToArray()); mesh.NumberOfVertices = vertices.Count; mesh.NumberOfPrimitives = indices.Count / 3; return mesh; }
// Use this for initialization void Start () { MyMesh = (CustomMesh)gameObject.GetComponent ("CustomMesh"); //SliceMyMesh (); }
public void SliceMyMesh() { if (MyMesh) { //GameObject SlicedMesh = (GameObject) Instantiate (gameObject, transform.position, Quaternion.identity); // off set the positions after the meshes are created, by finding out the releative bounds difference SlicedCustomMesh1 = (CustomMesh) gameObject.GetComponent("CustomMesh"); //SlicedCustomMesh2 = (CustomMesh) SlicedMesh.GetComponent("CustomMesh"); //SlicedCustomMesh2.IsSingleCube = false; //MyPlaneNormal = MyPlaneRotation.transform.position; MySlicePlane = new Plane(MyPlaneNormal, PlaneDistance); MySlicePlane.SetNormalAndPosition(MyPlaneNormal, new Vector3(0,0.5f,0)); SlicedPoints1 = new List<Vector3>(); SlicedIndicies1 = new List<int>(); SlicedPoints2 = new List<Vector3>(); SlicedIndicies2 = new List<int>(); // Where the plane intersects SlicedIndicies3 = new List<int>(); SlicedIndicies4 = new List<int>(); SlicedPoints4 = new List<Vector3>(); //SlicedMesh.MyCustomMesh // Add all the indicies that intersect with the plane for (int i = 0; i < SlicedCustomMesh1.MyCustomMesh.Indicies.Count; i += 3) { // for all the meshes triangles Vector3 Vertex1 = SlicedCustomMesh1.MyCustomMesh.Verticies[SlicedCustomMesh1.MyCustomMesh.Indicies[i]]; Vector3 Vertex2 = SlicedCustomMesh1.MyCustomMesh.Verticies[SlicedCustomMesh1.MyCustomMesh.Indicies[i+1]]; Vector3 Vertex3 = SlicedCustomMesh1.MyCustomMesh.Verticies[SlicedCustomMesh1.MyCustomMesh.Indicies[i+2]]; if (MySlicePlane.GetSide(Vertex1+MyPlanePosition) && MySlicePlane.GetSide(Vertex2+MyPlanePosition) && MySlicePlane.GetSide(Vertex3+MyPlanePosition)) { // if all 3 verticies are on the same side } else if (!MySlicePlane.GetSide(Vertex1+MyPlanePosition) && !MySlicePlane.GetSide(Vertex2+MyPlanePosition) && !MySlicePlane.GetSide(Vertex3+MyPlanePosition)) { // if they are not on same side, they are intersected by the plane } else { SlicedIndicies3.Add(SlicedCustomMesh1.MyCustomMesh.Indicies[i]); SlicedIndicies3.Add(SlicedCustomMesh1.MyCustomMesh.Indicies[i+1]); SlicedIndicies3.Add(SlicedCustomMesh1.MyCustomMesh.Indicies[i+2]); SlicedPoints3.Add (Vertex1); SlicedPoints3.Add (Vertex2); SlicedPoints3.Add (Vertex3); } } // Now create slices in these triangles for (int i = 0; i < SlicedIndicies3.Count; i += 3) { // for all the meshes triangles Vector3 Vertex1 = SlicedCustomMesh1.MyCustomMesh.Verticies[SlicedIndicies3[i]]; Vector3 Vertex2 = SlicedCustomMesh1.MyCustomMesh.Verticies[SlicedIndicies3[i+1]]; Vector3 Vertex3 = SlicedCustomMesh1.MyCustomMesh.Verticies[SlicedIndicies3[i+2]]; // from a slice through a triangle // we can get a maximum of 5 points // break down 5 points into 3 triangles // test this by chose random points along the triangle lines and adding them vertexes //RaycastHit hit1; Ray Ray1 = new Ray(Vertex1, Vertex1-Vertex2); float RayDistance1 = Vector3.Distance (Vertex1, Vertex2); if (MySlicePlane.Raycast(Ray1, out RayDistance1)) { Debug.Log(" Triangles are sliced 1" ); DebugVector3 (SlicedCustomMesh1.MyCustomMesh.Verticies[SlicedIndicies3[i]]); } else { Debug.Log(i + " Triangles Not Sliced Vertex 1 - "); Debug.Log (" Distance: " + RayDistance1); DebugVector3 (Vertex1); DebugVector3 (Vertex1 + Ray1.direction*RayDistance1); if (RayDistance1 != 0) { SlicedIndicies4.Add (i); SlicedPoints4.Add (Vertex1 + Ray1.direction*RayDistance1); //SlicedCustomMesh1.MyCustomMesh.Verticies[SlicedIndicies3[i]] = Vertex1 + Ray1.direction*RayDistance1; } } Ray Ray2 = new Ray(Vertex2, Vertex2-Vertex3); float RayDistance2 = Vector3.Distance (Vertex1, Vertex2); if (MySlicePlane.Raycast(Ray2, out RayDistance2)) { Debug.Log(" Triangles are sliced 2" ); SlicedCustomMesh1.MyCustomMesh.Verticies[SlicedIndicies3[i]] = Vertex2 + Ray2.direction*RayDistance2; } else { Debug.Log(i + " Triangles Not Sliced 2 - "); Debug.Log (" Distance: " + RayDistance2); DebugVector3 (Vertex2); DebugVector3 (Vertex2 + Ray2.direction*RayDistance2); if (RayDistance2 != 0) { SlicedIndicies4.Add (i+1); SlicedPoints4.Add (Vertex2 + Ray2.direction*RayDistance2); //SlicedCustomMesh1.MyCustomMesh.Verticies[SlicedIndicies3[i]] = Vertex2 + Ray2.direction*RayDistance2; } } Ray Ray3 = new Ray(Vertex3, Vertex3-Vertex1); float RayDistance3 = Vector3.Distance (Vertex3, Vertex1); if (MySlicePlane.Raycast(Ray3, out RayDistance3)) { Debug.Log(" Triangles are sliced 3" ); DebugVector3 (Vertex2); SlicedCustomMesh1.MyCustomMesh.Verticies[SlicedIndicies3[i]] = Vertex3 + Ray3.direction*RayDistance3; } else { Debug.Log(i + " Triangles a Not Sliced 3 -"); Debug.Log (" Distance: " + RayDistance3); DebugVector3 (Vertex3); DebugVector3 (Vertex3 + Ray3.direction*RayDistance3); if (RayDistance3 != 0) { SlicedIndicies4.Add (i+2); SlicedPoints4.Add (Vertex3 + Ray3.direction*RayDistance3); //SlicedCustomMesh1.MyCustomMesh.Verticies[SlicedIndicies3[i]] = Vertex3 + Ray3.direction*RayDistance3; } } //Mathf.Int } // test slice through the middle, where the plane is .5, .5 ,.5 // Concieve a 2d plane that is the slice (sword action pewpew) // find all the intersecting points with the mesh for (int i = 0; i < SlicedCustomMesh1.MyCustomMesh.Indicies.Count; i += 3) { // for all the meshes triangles //SlicedCustomMesh2.MyCustomMesh.Indicies[i] = 0; Vector3 Vertex1 = SlicedCustomMesh1.MyCustomMesh.Verticies[SlicedCustomMesh1.MyCustomMesh.Indicies[i]]; Vector3 Vertex2 = SlicedCustomMesh1.MyCustomMesh.Verticies[SlicedCustomMesh1.MyCustomMesh.Indicies[i+1]]; Vector3 Vertex3 = SlicedCustomMesh1.MyCustomMesh.Verticies[SlicedCustomMesh1.MyCustomMesh.Indicies[i+2]]; // if our vertexes are on the positive side of the plane, add to mesh 1 //if (Vertex1.y > 0.5f) { if (MySlicePlane.GetSide(Vertex1) && MySlicePlane.GetSide(Vertex2) && MySlicePlane.GetSide(Vertex3)) { // if all 3 verticies are on the same side SlicedIndicies1.Add(SlicedCustomMesh1.MyCustomMesh.Indicies[i]); SlicedIndicies1.Add(SlicedCustomMesh1.MyCustomMesh.Indicies[i+1]); SlicedIndicies1.Add(SlicedCustomMesh1.MyCustomMesh.Indicies[i+2]); //} else { } else if (!MySlicePlane.GetSide(Vertex1) && !MySlicePlane.GetSide(Vertex2) && !MySlicePlane.GetSide(Vertex3)){ // if they are not on same side, they are intersected by the plane SlicedIndicies2.Add(SlicedCustomMesh1.MyCustomMesh.Indicies[i]); SlicedIndicies2.Add(SlicedCustomMesh1.MyCustomMesh.Indicies[i+1]); SlicedIndicies2.Add(SlicedCustomMesh1.MyCustomMesh.Indicies[i+2]); } } //for (int i = 0; i < 0 // Add all the points onto 2 new meshes // Add the rest of the meshes points onto the 2 created ones // Instantiate the new objects in the points it was cut // test this with non moving objects for positioning //SlicedCustomMesh1.MyCustomMesh.Verticies = SlicedPoints1; if (IsSlice) { SlicedCustomMesh1.MyCustomMesh.Indicies.Clear (); //SlicedCustomMesh1.MyCustomMesh.Indicies = SlicedIndicies1; SlicedCustomMesh1.MyCustomMesh.Indicies = SlicedIndicies3; //SlicedCustomMesh2.MyCustomMesh.Indicies.Clear (); //SlicedCustomMesh2.MyCustomMesh.Indicies = SlicedIndicies2; //SlicedCustomMesh1.MyCustomMesh.Refresh(SlicedPoints1, SlicedIndicies1, SlicedCustomMesh1.MyCustomMesh.TextureCoordinates); //SlicedCustomMesh2.MyCustomMesh.Refresh(SlicedPoints2, SlicedIndicies2, SlicedCustomMesh2.MyCustomMesh.TextureCoordinates); SlicedCustomMesh1.UpdateMesh(SlicedCustomMesh1.MyCustomMesh); //SlicedCustomMesh2.UpdateMesh(SlicedCustomMesh2.MyCustomMesh); } } }