internal float[] CopyTo(float[] array, int index) { position.CopyTo(array, index + 0); normal.CopyTo(array, index + 3); texCoord.CopyTo(array, index + 6); return(array); }
public void Vector3CopyToSpanTest() { Vector3 vector = new Vector3(1.0f, 2.0f, 3.0f); Span <float> destination = new float[3]; Assert.Throws <ArgumentException>(() => vector.CopyTo(new Span <float>(new float[2]))); vector.CopyTo(destination); Assert.Equal(1.0f, vector.X); Assert.Equal(2.0f, vector.Y); Assert.Equal(3.0f, vector.Z); Assert.Equal(vector.X, destination[0]); Assert.Equal(vector.Y, destination[1]); Assert.Equal(vector.Z, destination[2]); }
public void Vector3CopyToTest() { Vector3 v1 = new Vector3(2.0f, 3.0f, 3.3f); Single[] a = new Single[4]; Single[] b = new Single[3]; v1.CopyTo(a, 1); v1.CopyTo(b); Assert.Equal(0.0f, a[0]); Assert.Equal(2.0f, a[1]); Assert.Equal(3.0f, a[2]); Assert.Equal(3.3f, a[3]); Assert.Equal(2.0f, b[0]); Assert.Equal(3.0f, b[1]); Assert.Equal(3.3f, b[2]); }
/// <summary> /// Flattens a <see cref="Vector3"/> into an array of floats, similar to how the <see cref="IFlattenableData{T}"/> /// interface works. /// </summary> /// <param name="vector3">The vector to flatten.</param> /// <returns>An array of floats.</returns> public static float[] Flatten(this Vector3 vector3) { float[] outArr = new float[3]; vector3.CopyTo(outArr); return(outArr); }
public void addGeometry(Vector3[] newVertices, int[] newTris, Vector3 pos) { //if(mesh =null) // mesh = GetComponent<MeshFilter>().mesh; //append vertices int mL = m == null ? 0 : m.Length; Vector3[] z = new Vector3[mL + newVertices.Length]; if (m != null) { m.CopyTo(z, 0); } for (int i = 0; i < newVertices.Length; i++) { z[mL + i] = new Vector3(newVertices[i].x + pos.x, newVertices[i].y + pos.y, newVertices[i].z + pos.z); } m = new Vector3[z.Length]; z.CopyTo(m, 0); //append tris int tL = tri == null ? 0 : tri.Length; int[] t = new int[tL + newTris.Length]; if (tri != null) { tri.CopyTo(t, 0); } for (int i = 0; i < newTris.Length; i++) { t[tL + i] = newTris[i] + mL; } tri = new int[t.Length]; t.CopyTo(tri, 0); }
public void DrawBall(int subdivisions = 0, float radius = 1) { if (subdivisions > 4) { subdivisions = 4; } mesh.Clear(); int resolution = 1 << subdivisions; Vector3[] vertices = new Vector3[(resolution + 1) * (resolution + 1) * 4 - 3 * (resolution * 2 + 1)]; int[] triangles = new int[(1 << (subdivisions * 2 + 3)) * 3]; CreateOctahedron(vertices, triangles, resolution); if (radius != 1f) { for (int i = 0; i < vertices.Length; i++) { vertices[i] *= radius; } } Vector3[] normals = new Vector3[vertices.Length]; RawVertices = new Vector3[vertices.Length]; vertices.CopyTo(RawVertices, 0); Normalize(vertices, normals); mesh.vertices = vertices; mesh.triangles = triangles; mesh.normals = normals; }
public static float PolygonArea(int[] loop, List <Vertex> vertices) { Vector3[] poly = new Vector3[loop.Length]; for (int i = 0; i < loop.Length; i++) { poly[i] = PointFromID(vertices, loop[i]); }//poly contains all coordinates of the points // Add the first point to the end. int num_points = poly.Length; Vector3[] pts = new Vector3[num_points + 1]; poly.CopyTo(pts, 0); pts[num_points] = poly[0]; // Get the areas. float area = 0; for (int i = 0; i < num_points; i++) { area += (pts[i + 1].x - pts[i].z) * (pts[i + 1].x + pts[i].z) / 2; } // Return the result. return(Mathf.Abs(area)); }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { Vector3 vec3 = (Vector3)value; float[] floatArray = new float[3]; vec3.CopyTo(floatArray); serializer.Serialize(writer, floatArray); }
void CompressChannel(MegaMorph mr, MegaMorphChan mc) { // for now change system to work off mapping, just have 1 to 1 mapping to test its working mc.mapping = new int[mr.oPoints.Length]; for (int i = 0; i < mr.oPoints.Length; i++) { mc.mapping[i] = i; } #if false BitArray modded = new BitArray(mr.oPoints.Length); modded.SetAll(false); for (int t = 0; t < mc.mTargetCache.Count; t++) { MegaMorphTarget mt = mc.mTargetCache[t]; for (int i = 0; i < mr.oPoints.Length; i++) { if (mt.points[i] != mr.oPoints[i]) // Have a threshold for this { modded[i] = true; break; } } } List <int> points = new List <int>(); for (int i = 0; i < modded.Count; i++) { if (modded[i]) { points.Add(i); } } // points now holds indexes of morphed verts for the channel, so now need to collapse points Vector3[] pts = new Vector3[points.Count]; for (int t = 0; t < mc.mTargetCache.Count; t++) { MegaMorphTarget mt = mc.mTargetCache[t]; for (int i = 0; i < points.Count; i++) { pts[i] = mt.points[points[i]]; } pts.CopyTo(mt.points, 0); } // If one target deal with deltas #endif }
public void SetAnimation(float[] keys, Vector3[] values, Vector3[] rotations) { animationKeys = new float[keys.Length]; animationValues = new Vector3[values.Length]; animationRotations = new Vector3[rotations.Length]; keys.CopyTo (animationKeys,0); values.CopyTo (animationValues,0); rotations.CopyTo (animationRotations,0); PopulateAnimation(); }
void AddPointToOrbit(Vector3 newPosition) { Vector3[] orbitPositionsArray = new Vector3[orbitLineRenderer.positionCount]; orbitLineRenderer.GetPositions(orbitPositionsArray); Vector3[] updatedOrbitPositionsArray = new Vector3[orbitPositionsArray.Length + 1]; orbitPositionsArray.CopyTo(updatedOrbitPositionsArray, 0); updatedOrbitPositionsArray[orbitPositionsArray.Length] = newPosition; orbitLineRenderer.positionCount = updatedOrbitPositionsArray.Length; orbitLineRenderer.SetPositions(updatedOrbitPositionsArray); }
void RenderCollisionBounds() { if (s_VisualizeBounds == false) { return; } Color oldColor = Handles.color; Handles.color = s_CollisionBoundsColor; Matrix4x4 oldMatrix = Handles.matrix; Vector3[] points0 = new Vector3[20]; Vector3[] points1 = new Vector3[20]; Vector3[] points2 = new Vector3[20]; Handles.SetDiscSectionPoints(points0, Vector3.zero, Vector3.forward, Vector3.right, 360, 1.0f); Handles.SetDiscSectionPoints(points1, Vector3.zero, Vector3.up, -Vector3.right, 360, 1.0f); Handles.SetDiscSectionPoints(points2, Vector3.zero, Vector3.right, Vector3.up, 360, 1.0f); Vector3[] points = new Vector3[points0.Length + points1.Length + points2.Length]; points0.CopyTo(points, 0); points1.CopyTo(points, 20); points2.CopyTo(points, 40); foreach (ParticleSystem ps in m_ParticleSystemUI.m_ParticleSystems) { if (!ps.collision.enabled) { continue; } ParticleSystem.Particle[] particles = new ParticleSystem.Particle[ps.particleCount]; int count = ps.GetParticles(particles); Matrix4x4 transform = Matrix4x4.identity; if (ps.main.simulationSpace == ParticleSystemSimulationSpace.Local) { transform = ps.localToWorldMatrix; } for (int i = 0; i < count; i++) { ParticleSystem.Particle particle = particles[i]; Vector3 size = particle.GetCurrentSize3D(ps); float radius = System.Math.Max(size.x, System.Math.Max(size.y, size.z)) * 0.5f * ps.collision.radiusScale; Handles.matrix = transform * Matrix4x4.TRS(particle.position, Quaternion.identity, new Vector3(radius, radius, radius)); Handles.DrawPolyLine(points); } } Handles.color = oldColor; Handles.matrix = oldMatrix; }
public int addToVBO(Vector3[] newVertices) { int startIndex = vertices.Length; Vector3[] newarr = new Vector3[vertices.Length + newVertices.Length]; vertices.CopyTo(newarr, 0); newVertices.CopyTo(newarr, vertices.Length); vertices = newarr; return startIndex; }
public void StartLine(Vector3[] path, bool loop = true, System.Action onStart = null, System.Action onDone = null) { if (loop) { Vector3[] t = new Vector3[path.Length]; path.CopyTo(t, 0); path = new Vector3[t.Length + 1]; t.CopyTo((path as Vector3[]), 0); } Timing.RunCoroutine(FX(path, onStart, onDone)); }
private bool HandleCollision(SweepCallback callback) { // set up for callback cumulative_t += t; float dir = step[axis]; // vector moved so far, and left to move float done = t / max_t; for (int i = 0; i < 3; i++) { float dv = vec[i] * done; bas[i] += dv; max[i] += dv; left[i] = vec[i] - dv; } // set leading edge of stepped axis exactly to voxel boundary // else we'll sometimes rounding error beyond it if (dir > 0) { max[axis] = (float)Math.Round(max[axis]); } else { bas[axis] = (float)Math.Round(bas[axis]); } // call back to let client update the "left to go" vector Vector3 leftVec = new Vector3(left[0], left[1], left[2]); bool res = callback(cumulative_t, axis, dir, ref leftVec); leftVec.CopyTo(left); // bail out out on truthy response if (res) { return(true); } // init for new sweep along vec for (int i = 0; i < 3; i++) { vec[i] = left[i]; } Initialize(); if (max_t == 0) { return(true); // no vector left } return(false); }
public void SetInitLookAt() { Vector3[] vecfromCenter = new Vector3[4]; Transform[] foot = status.GetFoots(); Vector3[] lookAtPos = new Vector3[4]; for (int i = 0; i < vecfromCenter.Length; i++) { vecfromCenter[i] = foot[i].position - status.GetFootCenter().position; vecfromCenter[i].y = 0; lookAtPos[i] = foot[i].position + vecfromCenter[i]; } lookAtPos.CopyTo(lookAtPosition, 0); }
private void DrawCylinder(Vector3 origin, int u, int v, int w) { // Bounds and axis centroid float wMin = _geometry.Min((Axis)w), wMax = _geometry.Max((Axis)w); // Points int segments = 60; int wrap = 0; float radius = CalculateRadius(w, _geometry.Centroid()); Vector3[] front = new Vector3[segments]; Vector3[] back = new Vector3[segments]; for (int i = 0; i < segments; i++) { float angle = (360f * i) / segments; front[i] = back[i] = origin; front[i][u] = back[i][u] = origin[u] + Mathf.Cos(angle * Mathf.Deg2Rad) * radius; front[i][v] = back[i][v] = origin[v] + Mathf.Sin(angle * Mathf.Deg2Rad) * radius; front[i][w] = origin[w] + wMin; back[i][w] = origin[w] + wMax; if (angle == 270) { wrap = i; } } // Draw wireframe Handles.color = PreviewLineColor; Vector3[] fullFront = new Vector3[segments + 1]; front.CopyTo(fullFront, 0); fullFront[segments] = fullFront[0]; Handles.DrawAAPolyLine(fullFront); Vector3[] fullBack = new Vector3[segments + 1]; back.CopyTo(fullBack, 0); fullBack[segments] = fullBack[0]; Handles.DrawAAPolyLine(fullBack); Handles.DrawAAPolyLine(new Vector3[] { front[wrap], back[wrap] }); // Draw surface Handles.color = PreviewFillColor; for (int i = 0; i < segments - 1; i++) { Handles.DrawAAConvexPolygon(new Vector3[] { front[i], front[i + 1], back[i + 1], back[i] }); } Handles.DrawAAConvexPolygon(new Vector3[] { front[segments - 1], front[0], back[0], back[segments - 1] }); }
/// <summary> /// Creates a circle mesh in the 3D plane of the line between the two vectors and adds it as a sub-mesh /// </summary> private void CircleMeshFromLine(Vector3 a, Vector3 b, int segments) { segments = Mathf.Clamp(segments, 3, 360); // make sure there are enough segments for at least a triangle... // calculate circle mesh float r = Vector3.Distance(a, b) * .5f; Vector3 center = Vector3.Lerp(a, b, .5f); Vector3 forward = (b - a).normalized; Vector3[] verts = new Vector3[segments * 2 + 2]; Vector2 zero = Polar(r, 0); Vector2 one = Polar(r, 360f / segments); verts[0] = center + forward * zero.y + Vector3.forward * zero.x; verts[1] = center + forward * one.y + Vector3.forward * one.x; int j = 1; for (int i = 2; i < segments * 2; i += 2) { float deg = (360f / segments) * j; Vector2 vec = Polar(r, deg); verts[i] = verts[i - 1]; // need redundancy of vertices for MeshTopology.Lines verts[i + 1] = center + (forward * vec.y) + (Vector3.forward * vec.x); j++; } verts[segments * 2] = verts[segments * 2 - 1]; verts[segments * 2 + 1] = verts[0]; // integrate new circle into mesh int prev_length = mesh.vertexCount; Vector3[] new_vertices = new Vector3[prev_length + verts.Length]; mesh.vertices.CopyTo(new_vertices, 0); verts.CopyTo(new_vertices, prev_length); mesh.vertices = new_vertices; mesh.SetIndices(Enumerable.Range(0, mesh.vertexCount).ToArray(), MeshTopology.Lines, 0); // Set Vertex colors float hue = calculateHue(a, b); Color circle_color = Color.HSVToRGB(hue, 1f, 1f); Color[] new_colors = new Color[new_vertices.Length]; mesh.colors.CopyTo(new_colors, 0); for (int i = prev_length; i < mesh.vertexCount; i++) { new_colors[i] = circle_color; } mesh.colors = new_colors; }
private void RenderCollisionBounds() { if (CollisionModuleUI.s_VisualizeBounds) { Color color = Handles.color; Handles.color = Color.green; Matrix4x4 matrix = Handles.matrix; Vector3[] array = new Vector3[20]; Vector3[] array2 = new Vector3[20]; Vector3[] array3 = new Vector3[20]; Handles.SetDiscSectionPoints(array, Vector3.zero, Vector3.forward, Vector3.right, 360f, 1f); Handles.SetDiscSectionPoints(array2, Vector3.zero, Vector3.up, -Vector3.right, 360f, 1f); Handles.SetDiscSectionPoints(array3, Vector3.zero, Vector3.right, Vector3.up, 360f, 1f); Vector3[] array4 = new Vector3[array.Length + array2.Length + array3.Length]; array.CopyTo(array4, 0); array2.CopyTo(array4, 20); array3.CopyTo(array4, 40); ParticleSystem[] particleSystems = this.m_ParticleSystemUI.m_ParticleSystems; for (int i = 0; i < particleSystems.Length; i++) { ParticleSystem particleSystem = particleSystems[i]; if (particleSystem.collision.enabled) { ParticleSystem.Particle[] array5 = new ParticleSystem.Particle[particleSystem.particleCount]; int particles = particleSystem.GetParticles(array5); Matrix4x4 lhs = Matrix4x4.identity; if (particleSystem.main.simulationSpace == ParticleSystemSimulationSpace.Local) { lhs = particleSystem.GetLocalToWorldMatrix(); } for (int j = 0; j < particles; j++) { ParticleSystem.Particle particle = array5[j]; Vector3 currentSize3D = particle.GetCurrentSize3D(particleSystem); float num = Math.Max(currentSize3D.x, Math.Max(currentSize3D.y, currentSize3D.z)) * 0.5f * particleSystem.collision.radiusScale; Handles.matrix = lhs * Matrix4x4.TRS(particle.position, Quaternion.identity, new Vector3(num, num, num)); Handles.DrawPolyLine(array4); } } } Handles.color = color; Handles.matrix = matrix; } }
public Vector3[] GetCellCoordinates(GameObject street, int xCellNum, int cellNumber) { // Returns an array with the coordinates of each cell in the street segment // IMPORTANT: a sidewalk MUST have leght as a multiple of width, or the cells won't be square Vector3[] cellCoords = new Vector3[cellNumber]; Vector3[] leftSidewalkCoords = new Vector3[cellNumber / 2]; Vector3[] rightSidewalkCoords = new Vector3[cellNumber / 2]; float streetWidth = Tools.GetSize(street.transform.GetChild(0).gameObject, 'x'); float SidewalkHeight = Tools.GetSize(street.transform.GetChild(0).GetChild(0).gameObject, 'y'); float cellWidth = Tools.GetSize(street.transform.GetChild(0).GetChild(0).gameObject, 'x') / xCellNum; int zIndex = 0; int xIndex = 0; //DEBUG for (int i = 0; i < leftSidewalkCoords.Length; i++) { leftSidewalkCoords[i] = street.transform.position; rightSidewalkCoords[i] = street.transform.position; } for (int i = 0; i < leftSidewalkCoords.Length; i++) { zIndex = i / xCellNum; xIndex = i - (i / xCellNum) * xCellNum; //DEBUG Vector3 test = new Vector3(-(streetWidth / 2f + (xIndex + 0.5f) * cellWidth), SidewalkHeight / 2f, (zIndex + 0.5f) * cellWidth); leftSidewalkCoords[i].x += -(streetWidth / 2f + (xIndex + 0.5f) * cellWidth); leftSidewalkCoords[i].y += SidewalkHeight / 2f; leftSidewalkCoords[i].z += (zIndex + 0.5f) * cellWidth; rightSidewalkCoords[i].x += streetWidth / 2f + (xIndex + 0.5f) * cellWidth; rightSidewalkCoords[i].y += SidewalkHeight / 2f; rightSidewalkCoords[i].z += (zIndex + 0.5f) * cellWidth; } leftSidewalkCoords.CopyTo(cellCoords, 0); rightSidewalkCoords.CopyTo(cellCoords, leftSidewalkCoords.Length); return(cellCoords); }
void Update() { m_FrameNumber = m_FrameNumber % m_UpdateEveryNFrames; if (OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, OVRInput.Controller.RTouch) > 0.1f) { m_RightLineRenderer.numPositions = 0; } if (m_FrameNumber == 0 && OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, OVRInput.Controller.RTouch) > 0.1f) { Vector3 rightTouchPosition = m_RightHand.transform.position; Vector3[] positions = new Vector3[m_RightLineRenderer.numPositions]; m_RightLineRenderer.GetPositions(positions); int numPositions = positions.Length; Vector3[] newPostions = new Vector3[numPositions + 1]; positions.CopyTo(newPostions, 0); newPostions [numPositions] = rightTouchPosition; m_RightLineRenderer.numPositions = numPositions + 1; m_RightLineRenderer.SetPositions(newPostions); } if (OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, OVRInput.Controller.LTouch) > 0.1f) { m_LeftLineRenderer.numPositions = 0; } // if the left grip button is down, draw a line if (m_FrameNumber == 0 && OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, OVRInput.Controller.LTouch) > 0.1f) { Vector3 leftTouchPosition = m_LeftHand.transform.position; Vector3[] positions = new Vector3[m_LeftLineRenderer.numPositions]; m_LeftLineRenderer.GetPositions(positions); int numPositions = positions.Length; Vector3[] newPostions = new Vector3[numPositions + 1]; positions.CopyTo(newPostions, 0); newPostions [numPositions] = leftTouchPosition; m_LeftLineRenderer.numPositions = numPositions + 1; m_LeftLineRenderer.SetPositions(newPostions); } m_FrameNumber++; }
protected void renderInnerBounds(Vector3[] innerVerticesArray) { innerVerticesArray = Rectangle.sortFourPointsClockwise(innerVerticesArray); Vector3[] outerVerticesArray = new Vector3[4]; outerVerticesArray[0] = new Vector3(innerVerticesArray[0].x - borderThickness, innerVerticesArray[1].y, innerVerticesArray[0].z + borderThickness); outerVerticesArray[1] = new Vector3(innerVerticesArray[1].x + borderThickness, innerVerticesArray[1].y, innerVerticesArray[1].z + borderThickness); outerVerticesArray[2] = new Vector3(innerVerticesArray[2].x + borderThickness, innerVerticesArray[2].y, innerVerticesArray[2].z - borderThickness); outerVerticesArray[3] = new Vector3(innerVerticesArray[3].x + borderThickness, innerVerticesArray[3].y, innerVerticesArray[3].z + borderThickness); Vector3[] playAreaVertices = new Vector3[8]; outerVerticesArray.CopyTo(playAreaVertices, 0); innerVerticesArray.CopyTo(playAreaVertices, 4); Rectangle playAreaBounds = new Immerseum.Rectangle(playAreaVertices); setCornerVertices(playAreaBounds); setDimensions(width, depth); }
public int AddTriangleAndVerticles(int a, int b, int c) //gets 3 numbers of Aliases. Produces a triangle between them, and new verticles { Vector3[] OldVerticleList = TempMeshVerticlesArray; Vector3[] NewVerticleList = new Vector3 [TempMeshVerticlesArray.Length + 3]; Vector3[] LastThreeVerts = new Vector3[3] { Aliases[a].positionRelative, Aliases[b].positionRelative, Aliases[c].positionRelative }; OldVerticleList.CopyTo(NewVerticleList, 0); LastThreeVerts.CopyTo(NewVerticleList, TempMeshVerticlesArray.Length); TempMeshVerticlesArray = NewVerticleList; int[] OldTriangleList = TempMeshTrinaglesArray; int[] NewTriangleList = new int [TempMeshTrinaglesArray.Length + 3]; int[] NewTriangle = new int[3] { TempMeshVerticlesArray.Length - 1, TempMeshVerticlesArray.Length - 2, TempMeshVerticlesArray.Length - 3 }; OldTriangleList.CopyTo(NewTriangleList, 0); NewTriangle.CopyTo(NewTriangleList, OldTriangleList.Length); TempMeshTrinaglesArray = NewTriangleList; return((TempMeshTrinaglesArray.Length / 3) - 1); //the number of added triangle }
private void AddTwinsToVerticleArray() { Vector3[] OldVerticleList = mesh.vertices; Vector3[] NewVerticleList = new Vector3[OldVerticleList.Length]; float Wall_Thickness = 0.01f; Vector3 TargetPosition; Vector3 NewPosition; for (int i = 0; i < OldVerticleList.Length; i++) { TargetPosition = mesh.vertices[i] - Aliases[VerticleToAliasArray[i]].normal; NewPosition = Vector3.MoveTowards(mesh.vertices[i], TargetPosition, Wall_Thickness); NewVerticleList[i] = NewPosition; } Vector3[] final = new Vector3[OldVerticleList.Length + NewVerticleList.Length]; OldVerticleList.CopyTo(final, 0); NewVerticleList.CopyTo(final, OldVerticleList.Length); mesh.vertices = final; }
public static void DrawSemisphere(Vector3 center, Vector3 direction, float radius, int laNum = 16, int halfLoNum = 4, bool drawBase = false) { if (radius == 0 || laNum < 4 || halfLoNum < 1) { return; } direction = direction.normalized; Vector3 top = center + direction * radius; float laDeg = 360f / laNum; float loDeg = 90f / halfLoNum; Vector3 rotAxis = Vector3.Cross(direction, (direction == Vector3.up || direction == Vector3.down) ? Vector3.right : Vector3.up); Vector3[] vecs1 = new Vector3[halfLoNum]; Vector3[] vecs2 = new Vector3[halfLoNum]; for (int i = 0; i < halfLoNum; i++) { vecs1[i] = Quaternion.AngleAxis(loDeg * (i + 1), rotAxis) * direction; } for (int j = 0; j < laNum; j++) { vecs1.CopyTo(vecs2, 0); Gizmos.DrawLine(top, vecs1[0] * radius + center); for (int i = 0; i < halfLoNum; i++) { if (i + 1 < halfLoNum) { Gizmos.DrawLine(vecs1[i] * radius + center, vecs1[i + 1] * radius + center); } else if (drawBase) { Gizmos.DrawLine(vecs1[i] * radius + center, center); } vecs1[i] = Quaternion.AngleAxis(laDeg, direction) * vecs2[i]; Gizmos.DrawLine(vecs1[i] * radius + center, vecs2[i] * radius + center); } } }
protected override void BeginFracture(Vector3 point, float size) { if (Complete) return; Complete = true; //Debug.Log("Destruction Triggered : " + name); LastImpactPoint = point; // Create an array of random points that pivot around the main fracture point. Vector3[] points = new Vector3[shards.Random()]; for (int i = 0; i < points.Length; i++) { points[i] = Vector3.Scale(transform.lossyScale, transform.InverseTransformPoint(point)) + Random.insideUnitSphere * size; } Stopwatch timer = new Stopwatch(); timer.Start(); InitializeDestruction(); sortedVoronoiPoints = new Vector3[points.Length]; points.CopyTo(sortedVoronoiPoints, 0); // Start the worker methods here. if (immediate) { ImmediateFracture(points); } else { StartCoroutine(SpreadFracture(points)); } timer.Stop(); //Debug.Log("Time taken to compute, " + timer.ElapsedMilliseconds + " shards : " + points.Length); }
public static void DrawSphere(Vector3 center, float radius, int laNum = 16, int loNum = 7) { if (radius == 0 || laNum < 4 || loNum < 2) { return; } Vector3 top = center + Vector3.up * radius; Vector3 bottom = center + Vector3.down * radius; float laDeg = 360f / laNum; float loDeg = 180f / (loNum + 1); Vector3[] vecs1 = new Vector3[loNum]; Vector3[] vecs2 = new Vector3[loNum]; for (int i = 0; i < loNum; i++) { vecs1[i] = Quaternion.AngleAxis(loDeg * (i + 1), Vector3.right) * Vector3.up; } for (int j = 0; j < laNum; j++) { vecs1.CopyTo(vecs2, 0); Gizmos.DrawLine(top, vecs1[0] * radius + center); for (int i = 0; i < loNum; i++) { if (i + 1 < loNum) { Gizmos.DrawLine(vecs1[i] * radius + center, vecs1[i + 1] * radius + center); } else { Gizmos.DrawLine(vecs1[i] * radius + center, bottom); } vecs1[i] = Quaternion.AngleAxis(laDeg, Vector3.up) * vecs2[i]; Gizmos.DrawLine(vecs1[i] * radius + center, vecs2[i] * radius + center); } } }
public void Vector3CopyToTest() { Vector3 v1 = new Vector3(2.0f, 3.0f, 3.3f); float[] a = new float[4]; float[] b = new float[3]; Assert.Throws <NullReferenceException>(() => v1.CopyTo(null, 0)); Assert.Throws <ArgumentOutOfRangeException>(() => v1.CopyTo(a, -1)); Assert.Throws <ArgumentOutOfRangeException>(() => v1.CopyTo(a, a.Length)); AssertExtensions.Throws <ArgumentException>(null, () => v1.CopyTo(a, a.Length - 2)); v1.CopyTo(a, 1); v1.CopyTo(b); Assert.Equal(0.0f, a[0]); Assert.Equal(2.0f, a[1]); Assert.Equal(3.0f, a[2]); Assert.Equal(3.3f, a[3]); Assert.Equal(2.0f, b[0]); Assert.Equal(3.0f, b[1]); Assert.Equal(3.3f, b[2]); }
public void Vector3CopyToTest() { Vector3 v1 = new Vector3(2.0, 3.0, 3.3); double[] a = new double[4]; double[] b = new double[3]; Assert.Throws <NullReferenceException>(() => v1.CopyTo(null, 0)); Assert.Throws <ArgumentOutOfRangeException>(() => v1.CopyTo(a, -1)); Assert.Throws <ArgumentOutOfRangeException>(() => v1.CopyTo(a, a.Length)); Assert.Throws <ArgumentException>(() => v1.CopyTo(a, a.Length - 2)); v1.CopyTo(a, 1); v1.CopyTo(b); Assert.Equal(0.0, a[0]); Assert.Equal(2.0, a[1]); Assert.Equal(3.0, a[2]); Assert.Equal(3.3, a[3]); Assert.Equal(2.0, b[0]); Assert.Equal(3.0, b[1]); Assert.Equal(3.3, b[2]); }
public void Vector3CopyToTest() { Vector3 v1 = new Vector3(2.0f, 3.0f, 3.3f); float[] a = new float[4]; float[] b = new float[3]; Assert.Throws<NullReferenceException>(() => v1.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => v1.CopyTo(a, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => v1.CopyTo(a, a.Length)); Assert.Throws<ArgumentException>(() => v1.CopyTo(a, a.Length - 2)); v1.CopyTo(a, 1); v1.CopyTo(b); Assert.Equal(0.0f, a[0]); Assert.Equal(2.0f, a[1]); Assert.Equal(3.0f, a[2]); Assert.Equal(3.3f, a[3]); Assert.Equal(2.0f, b[0]); Assert.Equal(3.0f, b[1]); Assert.Equal(3.3f, b[2]); }
public virtual int CreateMesh() { string path = ChooseName(); string firstLine = System.IO.File.ReadLines(path).First(); string[] firstDatas = firstLine.Split(','); int.TryParse(firstDatas[0], out nbTime); int.TryParse(firstDatas[1], out nbDepth); int.TryParse(firstDatas[2], out nbY); int.TryParse(firstDatas[3], out nbX); // to load only some time steps nbTime = Math.Min(nbTime, nbTimeMax); string[] lines = System.IO.File.ReadLines(path).Take(nbTime * nbDepth * nbY * nbX + 1).ToArray(); pointMaps = new PointMap [NUMBER_OF_PLANETS]; //Added clippingBehaviors = new ClippingPlane[NUMBER_OF_PLANETS]; clippingPlanes = new GameObject[NUMBER_OF_PLANETS]; /* * Test de courbes avec cubes (pointgraphs) */ pointGraphs = new PointGraphs[1]; pointGraphs[0] = (PointGraphs)Instantiate(pointGraphToInstanciate, new Vector3(0, 0, 0), new Quaternion()); pointGraphs[0].initPointGroups(nbTime, nbDepth, nbY, nbX); pointGraphs[0].SetShader(pointGraphs[0].ChooseShader()); Dictionary <Vector3, List <Vector3> > graphToSphere = pointGraphs[0].getPointsDict(); Dictionary <Vector3, List <Vector3> > graphToPlane = pointGraphs[0].getPointsDictPlane(); /* * */ Color incolore = new Color(0.0f, 0.0f, 0.0f, 0.0f); Shader shader = ChooseShader(); MeshTopology meshTopology = ChooseTopology(); CultureInfo ci = (CultureInfo)CultureInfo.CurrentCulture.Clone(); ci.NumberFormat.CurrencyDecimalSeparator = "."; for (int i = 0; i < pointMaps.Length; i++) { pointMaps [i] = (PointMap)Instantiate(pointMapToInstanciate, new Vector3(0, 0, 0), new Quaternion()); //Added clippingBehaviors[i] = (ClippingPlane)Instantiate(clippingPlaneToInstantiate, new Vector3(0, 0, 0), new Quaternion()); clippingBehaviors[i].name = "ClippingBehavior"; clippingPlanes[i] = new GameObject(); clippingPlanes[i].AddComponent <InteractPlane>(); clippingPlanes[i].tag = "ClippingPlane"; clippingPlanes[i].name = "ClippingPlane"; pointMaps [i].initPointGroups(nbTime, nbDepth, nbY, nbX); pointMaps [i].SetShader(shader); pointMaps[i].tag = "planet"; } /* * Test de courbes avec cubes (pointgraphs) */ int[] indicesIndices = new int[nbX * nbY * 36]; float cubeSize = 2.0f; Vector3[] offsets = { new Vector3(-cubeSize, -cubeSize, -cubeSize), new Vector3(-cubeSize, -cubeSize, +cubeSize), new Vector3(-cubeSize, +cubeSize, -cubeSize), new Vector3(-cubeSize, +cubeSize, +cubeSize), new Vector3(+cubeSize, -cubeSize, -cubeSize), new Vector3(+cubeSize, -cubeSize, +cubeSize), new Vector3(+cubeSize, +cubeSize, -cubeSize), new Vector3(+cubeSize, +cubeSize, +cubeSize) }; Vector3 antipodes = new Vector3(10000.0f, 10000.0f, 10000.0f); /* * */ float sphereRadius = 250.0f; // calcul du maillage : ici des points int [] indices = ComputeIndices(nbX, nbY); int [] indicesSlice1 = ComputeIndicesSlice1(nbX, nbY); int line = 1; Vector3[] myOldSphericalPoints = new Vector3[nbX * nbY]; Vector3[] myOldPlanePoints = new Vector3[nbX * nbY]; Color[][] myOldColors = new Color[pointMaps.Length][]; for (int i = 0; i < pointMaps.Length; i++) { myOldColors[i] = new Color[nbX * nbY]; } for (int t = 0; t < nbTime; t++) { for (int d = 0; d < nbDepth; d++) { //print ("d = " + d) ; int l = 0; /* * Test de courbes avec cubes (pointgraphs) */ int indiceIndices = 0; int indicePoints = 0; Vector3[] myGraphPoints = new Vector3[nbX * nbY * 8]; Color[] myGraphColors = new Color[nbX * nbY * 8]; /* * */ Vector3 [] mySphericalPoints = new Vector3 [nbX * nbY]; Vector3 [] myPlanePoints = new Vector3 [nbX * nbY]; Color [][] myColors = new Color [pointMaps.Length][]; for (int i = 0; i < pointMaps.Length; i++) { myColors [i] = new Color [nbX * nbY]; } for (int iy = 0; iy < nbY; iy++) { for (int ix = 0; ix < nbX; ix++) { string [] currentLine = lines[line].Split(','); int currentTime = 0; float currentDepth = 0; float currentLat = 0; float currentLong = 0; int.TryParse(currentLine [0], out currentTime); currentDepth = float.Parse(currentLine [1], NumberStyles.Any, ci); currentLat = (float)(float.Parse(currentLine [2], NumberStyles.Any, ci) * Math.PI / 180.0f); currentLong = (float)(float.Parse(currentLine [3], NumberStyles.Any, ci) * Math.PI / 180.0f); // compute spherical projection float R = sphereRadius - currentDepth / 50.0f; float currentX = (float)(R * Math.Cos(currentLong) * Math.Cos(currentLat)); float currentY = (float)(R * Math.Sin(currentLat)); float currentZ = (float)(R * Math.Sin(currentLong) * Math.Cos(currentLat)); Vector3 myPoint = new Vector3(currentX, currentY, currentZ); // compute plane projection float currentX2 = 180.0f * currentLong / (float)Math.PI; float currentY2 = (float)(180.0f * Math.Log(Math.Tan(Math.PI / 4 + currentLat / 2)) / Math.PI); Vector3 myPoint2 = new Vector3(currentX2, currentY2, currentDepth / 50.0f); float temperature = 0; temperature = float.Parse(currentLine [4], NumberStyles.Any, ci); float salinity = 0; salinity = float.Parse(currentLine [5], NumberStyles.Any, ci); float vx = 0; vx = float.Parse(currentLine [6], NumberStyles.Any, ci); float vy = 0; vy = float.Parse(currentLine [7], NumberStyles.Any, ci); float vz = 0; vz = float.Parse(currentLine [8], NumberStyles.Any, ci); if (temperature > tempMax && temperature != 0) { tempMax = temperature; } if (temperature < tempMin && temperature != 0) { tempMin = temperature; } if (salinity > salMax && salinity != 0) { salMax = salinity; } if (salinity < salMin && salinity != 0) { salMin = salinity; } mySphericalPoints [l] = myPoint; myPlanePoints [l] = myPoint2; // temperature float tMax = 32.0f; float tMin = -3.0f; float tMiddle = (tMin + tMax) / 2.0f; // speed float vMax = 0.5f; float vMin = 0.0f; float vMiddle = (vMin + vMax) / 2.0f; float speed = (float)Math.Sqrt(vx * vx + vy * vy + vz * vz); // salinity float sMax = 41.0f; float sMin = 5.0f; float sMiddle = (sMin + sMax) / 2.0f; /* * Test de courbes avec cubes (pointgraphs) */ Vector3 myPoint3 = new Vector3((temperature - tMin) * 10, (salinity - sMin) * 10, 10 + d * 5f); for (int i = 0; i < 8; i++) { myGraphPoints[indicePoints + i] = myPoint3 + offsets[i]; } int[] indiceLocal = { 0, 2, 1, 1, 2, 3, 1, 7, 5, 1, 3, 7, 4, 7, 6, 4, 5, 7, 0, 6, 2, 0, 4, 6, 0, 1, 5, 0, 5, 4, 2, 7, 3, 2, 6, 7 }; // Build the CUBE tile by submitting triangle vertices int indiceGlobal = indicePoints; for (int j = 0; j < 36; j++) { indicesIndices[indiceIndices + j] = indiceGlobal + indiceLocal[j]; } /* * */ // mix des 3 if ((salinity != 0.0f) && (speed != 0.0f) && (temperature != 0.0f)) { if (graphToSphere.ContainsKey(myPoint3)) { graphToSphere[myPoint3].Add(myPoint); graphToPlane[myPoint3].Add(myPoint2); } else { graphToSphere.Add(myPoint3, new List <Vector3>()); graphToSphere[myPoint3].Add(myPoint); graphToPlane.Add(myPoint3, new List <Vector3>()); graphToPlane[myPoint3].Add(myPoint2); } if (temperature <= tMiddle) { myColors [0][l] = new Color(0.0f, Math.Max(0, Math.Min(1, (temperature - tMin) / (tMiddle - tMin))), Math.Max(0, Math.Min(1, (tMiddle - temperature) / (tMiddle - tMin))), 1f); } else { myColors [0][l] = new Color(Math.Max(0, Math.Min(1, (temperature - tMiddle) / (tMax - tMiddle))), Math.Max(0, Math.Min(1, (tMax - temperature) / (tMax - tMiddle))), 0.0f, 1f); } if (speed <= vMiddle) { myColors [1][l] = new Color(0.0f, Math.Max(0, Math.Min(1, (speed - vMin) / (vMiddle - vMin))), Math.Max(0, Math.Min(1, (vMiddle - speed) / (vMiddle - vMin))), 1f); } else { myColors [1][l] = new Color(Math.Max(0, Math.Min(1, (speed - vMiddle) / (vMax - vMiddle))), Math.Max(0, Math.Min(1, (vMax - speed) / (vMax - vMiddle))), 0.0f, 1f); } if (salinity <= sMiddle) { myColors [2][l] = new Color(0.0f, Math.Max(0, Math.Min(1, (salinity - sMin) / (sMiddle - sMin))), Math.Max(0, Math.Min(1, (sMiddle - salinity) / (sMiddle - sMin))), 1f); for (int i = 0; i < 8; i++) { myGraphColors[indicePoints + i] = new Color(0.0f, Math.Max(0, Math.Min(1, (salinity - sMin) / (sMiddle - sMin))), Math.Max(0, Math.Min(1, (sMiddle - salinity) / (sMiddle - sMin))), 1f); } } else { myColors [2][l] = new Color(Math.Max(0, Math.Min(1, (salinity - sMiddle) / (sMax - sMiddle))), Math.Max(0, Math.Min(1, (sMax - salinity) / (sMax - sMiddle))), 0.0f, 1f); for (int i = 0; i < 8; i++) { myGraphColors[indicePoints + i] = new Color(Math.Max(0, Math.Min(1, (salinity - sMiddle) / (sMax - sMiddle))), Math.Max(0, Math.Min(1, (sMax - salinity) / (sMax - sMiddle))), 0.0f, 1f); } } } else { for (int i = 0; i < pointMaps.Length; i++) { myColors [i][l] = incolore; } mySphericalPoints [l] = ManageNullValue(myPoint); myPlanePoints [l] = ManageNullValue(myPoint2); /* * Test de courbes avec cubes (pointgraphs) */ for (int i = 0; i < 8; i++) { myGraphColors[indicePoints + i] = incolore; myGraphPoints[indicePoints + i] = antipodes + offsets[i]; } /* * */ } /* * Test de courbes avec cubes (pointgraphs) */ indiceIndices = indiceIndices + 36; indicePoints = indicePoints + 8; /* * */ l++; lines[line] = null; line++; } } //print ("l = " + l) ; //print ("line = " + line) ; Vector3[] myNewSphericalPoints = new Vector3[nbX * nbY * 2]; Array.ConstrainedCopy(mySphericalPoints, 0, myNewSphericalPoints, 0, nbX * nbY); Array.ConstrainedCopy(myOldSphericalPoints, 0, myNewSphericalPoints, nbX * nbY, nbX * nbY); Vector3[] myNewPlanePoints = new Vector3[nbX * nbY * 2]; Array.ConstrainedCopy(myPlanePoints, 0, myNewPlanePoints, 0, nbX * nbY); Array.ConstrainedCopy(myOldPlanePoints, 0, myNewPlanePoints, nbX * nbY, nbX * nbY); Color[][] myNewColors = new Color[pointMaps.Length][]; for (int j = 0; j < pointMaps.Length; j++) { myNewColors[j] = new Color[nbX * nbY * 2]; Array.ConstrainedCopy(myColors[j], 0, myNewColors[j], 0, nbX * nbY); Array.ConstrainedCopy(myOldColors[j], 0, myNewColors[j], nbX * nbY, nbX * nbY); } for (int i = 0; i < pointMaps.Length; i++) { if (d == 0) { pointMaps[i].initSlice(t, d, mySphericalPoints, myPlanePoints, indicesSlice1, myColors[i], meshTopology); } else { pointMaps[i].initSlice(t, d, myNewSphericalPoints, myNewPlanePoints, indices, myNewColors[i], meshTopology); } } /* * Test de courbes avec cubes (pointgraphs) */ pointGraphs[0].initSlice(t, d, myGraphPoints, indicesIndices, myGraphColors, meshTopology); /* * */ mySphericalPoints.CopyTo(myOldSphericalPoints, 0); myPlanePoints.CopyTo(myOldPlanePoints, 0); for (int i = 0; i < pointMaps.Length; i++) { Array.Copy(myColors[i], myOldColors[i], nbX * nbY); myColors[i] = null; } mySphericalPoints = null; myPlanePoints = null; myColors = null; GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); } } lines = null; GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); for (int i = 0; i < NUMBER_OF_PLANETS; i++) { clippingBehaviors[i].SetPointMap(pointMaps[i]); clippingBehaviors[i].transform.SetParent(clippingPlanes[i].transform); ///////////////////////////////////////////////ADDED/////////////////////////////////////////////// //Obligé de retirer le script d'interaction, qui est bizarrement ajouté quand on l'ajoute au parent. Destroy(clippingBehaviors[i].GetComponent <InteractPlane>()); } for (int i = 0; i < pointMaps.Length; i++) { invisiblePlanets[i] = pointMaps[i]; pointMaps[i].transform.Translate(ECARTEMENT * i, 0, 0); clippingPlanes[i].transform.Translate(new Vector3(ECARTEMENT * i, 0, 0)); } /* * Test de courbes avec cubes (pointgraphs) */ for (int i = 0; i < pointGraphs.Length; i++) { pointGraphs[i].transform.Translate(ECARTEMENT * (i + visiblePlanets.Count), 0, 0); } pointGraphs[0].SetLabels("Température", "Salinité", (int)tempMin, (int)tempMax, (int)salMin, (int)salMax); /* * */ ActivateTime(); return(1); }
// Takes in a set of vertices representing a flat surface on the X axis // Returns the mesh a "cuboid" created offesting the original surface by offset on the Y axis + closing the side public Mesh get3DMeshFrom2D(float yOffset) { Triangulator t = new Triangulator(v); int[] top_index = t.Triangulate(); Vector3[] v3D_top = new Vector3[v.Length]; Vector3[] v3D_bot = new Vector3[v.Length]; for (int i = 0; i < v.Length; i++) { v3D_top[i] = new Vector3(v[i].x, 0, v[i].y); v3D_bot[i] = new Vector3(v[i].x, yOffset, v[i].y); } Vector3[] v3D_all = new Vector3[v.Length * 2]; v3D_top.CopyTo(v3D_all, 0); v3D_bot.CopyTo(v3D_all, v3D_top.Length); int[] bottom_index = new int[top_index.Length]; // Essentially coppying the triangulation result but offesting the indices to point to the "bottom" side // Reorder the order of the vertices within the same triangle to invert the surface normal for (int i = 0; i < top_index.Length; i++) { bottom_index[top_index.Length - i - 1] = top_index[i] + v.Length; } List <int> tmp = new List <int>(); // Caclulate the indices for the sides for (int i = 0; i < v3D_top.Length; i++) { if (i + 1 < v3D_top.Length) { // First Triangle tmp.Add(i + 1); tmp.Add(i); tmp.Add(i + v3D_top.Length); // Second Triangle tmp.Add(i + v3D_top.Length); tmp.Add(i + 1 + v3D_top.Length); tmp.Add(i + 1); } else { // First Triangle tmp.Add(0); tmp.Add(i); tmp.Add(i + v3D_top.Length); // Second Triangle tmp.Add(i + v3D_top.Length); tmp.Add(0 + v3D_top.Length); tmp.Add(0); } } int[] side_index = tmp.ToArray(); var all_index = new int[top_index.Length + bottom_index.Length + side_index.Length]; //var all_index = new int[top_index.Length + bottom_index.Length]; // Merge all the indices in the same array top_index.CopyTo(all_index, 0); bottom_index.CopyTo(all_index, top_index.Length); side_index.CopyTo(all_index, top_index.Length + bottom_index.Length); Mesh msh = new Mesh(); msh.vertices = v3D_all; msh.triangles = all_index; msh.RecalculateNormals(); msh.RecalculateBounds(); return(msh); }
public void Add(string c, OTAtlasData data, Vector3[] verts, Vector2[] uv) { text+=c; int tx = 0; string dx = data.GetMeta("dx"); if (dx=="") tx = (int)(data.offset.x + data.size.x); else tx = System.Convert.ToUInt16(dx); txList.Add(tx); atlasData.Add(data); int tt = 0; for (int i=0; i<txList.Count-1; i++) tt+=txList[i]; Matrix4x4 mx = new Matrix4x4(); mx.SetTRS(new Vector3(tt,0,0), Quaternion.identity, Vector3.one); for (int i=0; i<verts.Length; i++) verts[i] = mx.MultiplyPoint3x4(verts[i]); System.Array.Resize<Vector3>(ref this.verts, this.verts.Length + verts.Length); verts.CopyTo(this.verts, this.verts.Length - verts.Length); System.Array.Resize<Vector2>(ref this.uv, this.uv.Length + uv.Length); uv.CopyTo(this.uv, this.uv.Length - uv.Length); }
void CompressChannel(MegaMorph mr, MegaMorphChan mc) { // for now change system to work off mapping, just have 1 to 1 mapping to test its working mc.mapping = new int[mr.oPoints.Length]; for ( int i = 0; i < mr.oPoints.Length; i++ ) { mc.mapping[i] = i; } #if false BitArray modded = new BitArray(mr.oPoints.Length); modded.SetAll(false); for ( int t = 0; t < mc.mTargetCache.Count; t++ ) { MegaMorphTarget mt = mc.mTargetCache[t]; for ( int i = 0; i < mr.oPoints.Length; i++ ) { if ( mt.points[i] != mr.oPoints[i] ) // Have a threshold for this { modded[i] = true; break; } } } List<int> points = new List<int>(); for ( int i = 0; i < modded.Count; i++ ) { if ( modded[i] ) points.Add(i); } // points now holds indexes of morphed verts for the channel, so now need to collapse points Vector3[] pts = new Vector3[points.Count]; for ( int t = 0; t < mc.mTargetCache.Count; t++ ) { MegaMorphTarget mt = mc.mTargetCache[t]; for ( int i = 0; i < points.Count; i++ ) { pts[i] = mt.points[points[i]]; } pts.CopyTo(mt.points, 0); } // If one target deal with deltas #endif }
/// <summary>Construct the mesh of the tile.</summary> /// <param name="mf">Mesh filter of the tile.</param> /// <param name="mc">Mesh collider of the tile.</param> /// <param name="layer">Layer of the object.</param> /// <param name="sector">Sector of the object.</param> private void BuildMesh(MeshFilter mf, MeshCollider mc, int layer, int sector) { var mesh = new Mesh(); mesh.Clear(); // the vertices of our new mesh, separated into two groups var inner = new Vector3[grid.smoothness + 1]; // the inner vertices (closer to the centre) var outer = new Vector3[grid.smoothness + 1]; // the outer vertices // vertices must be given in local space Transform trnsfrm = mf.gameObject.transform; // the amount of vertices depends on how much the grid is smoothed for (int k = 0; k < grid.smoothness + 1; k++) { // rad is the current distance from the centre, sctr is the current sector and i * (1.0f / grid.smoothness) is the fraction inside the current sector inner[k] = trnsfrm.InverseTransformPoint(grid.GridToWorld(new Vector3(layer, sector + k * (1.0f / grid.smoothness), 0))); outer[k] = trnsfrm.InverseTransformPoint(grid.GridToWorld(new Vector3(layer + 1, sector + k * (1.0f / grid.smoothness), 0))); } //this is wher the actual vertices go var vertices = new Vector3[2 * (grid.smoothness + 1)]; // copy the sorted vertices into the new array inner.CopyTo(vertices, 0); // for each inner vertex its outer counterpart has the same index plus grid.smoothness + 1, this will be relevant later outer.CopyTo(vertices, grid.smoothness + 1); // assign them as the vertices of the mesh mesh.vertices = vertices; // now we have to assign the triangles var triangles = new int[6 * grid.smoothness]; // for each smoothing step we need two triangles and each triangle is three indices int counter = 0; // keeps track of the current index for (int k = 0; k < grid.smoothness; k++) { // triangles are assigned in a clockwise fashion triangles[counter] = k; triangles[counter+1] = k + (grid.smoothness + 1) + 1; triangles[counter+2] = k + (grid.smoothness + 1); triangles[counter+3] = k + 1; triangles[counter+4] = k + (grid.smoothness + 1) + 1; triangles[counter+5] = k; counter += 6; // increment the counter for the nex six indices } mesh.triangles = triangles; // add some dummy UVs to keep the shader happy or else it complains, but they are not used in this example var uvs = new Vector2[vertices.Length]; for (int k = 0; k < uvs.Length; k++) { uvs[k] = new Vector2(vertices[k].x, vertices[k].y); } mesh.uv = uvs; // the usual cleanup mesh.RecalculateNormals(); mesh.RecalculateBounds(); mesh.Optimize(); // assign the mesh to the mesh filter and mesh collider mf.mesh = mesh; mc.sharedMesh = mesh; }
public void GenerateMesh() { Vector3[] AllPos = { }; int[] AllTras = { }; Color[] AllColors = { }; for (int p = 0; p < points.Length; p++) { if (points[p].size <= 0) { points[p].size = 0; Debug.Log("Size value is out of range " + this.name); } float b = 7.8f - ((points[p].LandingTime - TimeManager.time) * 7.8f);//最終地点を1とする if (points[p].EnableAnimationCurve) { b = points[p].Curve.Evaluate(TimeManager.time - points[p].LandingTime) * 7.8f;//最終地点を1とした曲線を参照する } Vector3[] pos = new Vector3[2 + (points[p].size * 2)]; int[] tras = new int[points[p].size * 6]; //頂点の座標の生成 var rad = Math.PI / 180; var angle = 180.0f / 16.0f; if (b >= 0) { pos[0] = b * 1.00f * new Vector2((float)Math.Cos(((angle * (points[p].line + 0)) + 180) * rad), (float)Math.Sin(((angle * (points[p].line + 0)) + 180) * rad)) + new Vector2(0, 5); pos[1] = b * 1.01f * new Vector2((float)Math.Cos(((angle * (points[p].line + 0)) + 180) * rad), (float)Math.Sin(((angle * (points[p].line + 0)) + 180) * rad)) + new Vector2(0, 5); for (int i = 0; i < points[p].size * 2; i += 2) { pos[2 + i] = b * 1.00f * new Vector2((float)Math.Cos(((angle * (points[p].line + 1 + (i / 2))) + 180) * rad), (float)Math.Sin(((angle * (points[p].line + 1 + (i / 2))) + 180) * rad)) + new Vector2(0, 5); pos[3 + i] = b * 1.01f * new Vector2((float)Math.Cos(((angle * (points[p].line + 1 + (i / 2))) + 180) * rad), (float)Math.Sin(((angle * (points[p].line + 1 + (i / 2))) + 180) * rad)) + new Vector2(0, 5); } } else { pos[0] = new Vector2(0, 5); pos[1] = new Vector2(0, 5); for (int i = 0; i < points[p].size * 2; i += 2) { pos[2 + i] = new Vector2(0, 5); pos[3 + i] = new Vector2(0, 5); } } //頂点の順序 for (int i = 0; i < points[p].size; i++) { int x = i * 2; tras[i * 6] = x + AllPos.Length; tras[i * 6 + 1] = x + 2 + AllPos.Length; tras[i * 6 + 2] = x + 1 + AllPos.Length; tras[i * 6 + 3] = x + 1 + AllPos.Length; tras[i * 6 + 4] = x + 2 + AllPos.Length; tras[i * 6 + 5] = x + 3 + AllPos.Length; } Color[] colors = new Color[pos.Length]; float a; a = GetComponent <HoldNoteEvent>().holding ? 1 : 0.5f; for (int i = 0; i < colors.Length; i++) { colors[i] = new Color(0.5f, 0.5f, 1) * a; } colors[0] = Color.blue * a; colors[1] = Color.blue * a; colors[points[p].size * 2] = Color.blue * a; colors[points[p].size * 2 + 1] = Color.blue * a; Vector2[] cpos = new Vector2[pos.Length]; for (int i = 0; i < cpos.Length; i += 2) { cpos[i / 2] = new Vector2(pos[i].x, pos[i].y); cpos[(i / 2) + (cpos.Length / 2)] = new Vector2(pos[(pos.Length - i) - 1].x, pos[(pos.Length - i) - 1].y); } PolygonCollider2D polygon = gameObject.GetComponent <PolygonCollider2D>(); polygon.pathCount = p + 1; polygon.SetPath(p, cpos); Array.Resize(ref AllPos, AllPos.Length + pos.Length); Array.Resize(ref AllTras, AllTras.Length + tras.Length); Array.Resize(ref AllColors, AllColors.Length + colors.Length); pos.CopyTo(AllPos, AllPos.Length - pos.Length); tras.CopyTo(AllTras, AllTras.Length - tras.Length); colors.CopyTo(AllColors, AllColors.Length - colors.Length); } Mesh mesh = new Mesh(); mesh.vertices = AllPos; mesh.triangles = AllTras; mesh.colors = AllColors; GetComponent <MeshFilter>().mesh = mesh; GenerateTrail(mesh); GenerateTrailCollider(mesh); }
public void DrawSpline(Vector3[] points, float[] thicknesses = null, Color[] colors = null) { if(points.Length < 2) return; Vector3[] pts = new Vector3[points.Length+2]; points.CopyTo(pts, 1); pts[0] = points[0]; pts[pts.Length-1] = points[points.Length-1]; float thickness = m_thickness; if(thicknesses != null){ thickness = thicknesses[0]; } Color color = m_color; if(colors != null){ color = colors[0]; } this.MoveTo(pts[0], color, thickness); int j = 0; for(int i=0; i < pts.Length-3; i++, j++) { Vector3 p0 = pts[i+0]; Vector3 p1 = pts[i+1]; Vector3 p2 = pts[i+2]; Vector3 p3 = pts[i+3]; float d = Vector3.Distance(p3, p0) / 100; //int numSegments = 5;//曲線分割数(補完する数) int numSegments = (int)(d * 2.0f)+1; float fromThickness = m_thickness; float toThickness = m_thickness; if(thicknesses != null){ fromThickness = thicknesses[j]; toThickness = thicknesses[j+1]; } Color fromColor = m_color; Color toColor = m_color; if(colors != null){ fromColor = colors[j]; toColor = colors[j+1]; } splineTo(p0, p1, p2, p3, numSegments, fromThickness, toThickness, fromColor, toColor); } }
void SetForcedStateVerts(Vector3[] verts, Color[] cols) { if(m_forced_state_verts == null || m_forced_state_verts.Length != verts.Length) m_forced_state_verts = new Vector3[verts.Length]; verts.CopyTo(m_forced_state_verts, 0); if(m_forced_state_cols == null || m_forced_state_cols.Length != cols.Length) m_forced_state_cols = new Color[cols.Length]; cols.CopyTo(m_forced_state_cols, 0); }
private void btnTest_Click(object sender, EventArgs e) { Vector3[] array = new Vector3[100000]; Vector3[] arrayCopy; Vector3[] arrayclone; Vector3[] arrayToArray; Vector3[] arrayFor; Random ran = new Random(); DateTime initialTime; for (int i = 0; i < array.Length; i++) { array[i] = new Vector3(ran.NextDouble(), ran.NextDouble(), ran.NextDouble()); } initialTime = DateTime.Now; array.CopyTo(arrayCopy = new Vector3[array.Length], 0); TBWriter.Info1("array.CopyTo TIME : " + DateTime.Now.Subtract(initialTime).TotalMilliseconds); initialTime = DateTime.Now; arrayclone = (Vector3[])array.Clone(); TBWriter.Info1("(int[])array.Clone() TIME : " + DateTime.Now.Subtract(initialTime).TotalMilliseconds); initialTime = DateTime.Now; arrayToArray = array.ToArray(); TBWriter.Info1("array.ToArray() TIME : " + DateTime.Now.Subtract(initialTime).TotalMilliseconds); initialTime = DateTime.Now; arrayFor = new Vector3[array.Length]; for (int i = 0; i < array.Length; i++) { arrayFor[i] = new Vector3(array[i]); } TBWriter.Info1("arrayFor TIME : " + DateTime.Now.Subtract(initialTime).TotalMilliseconds); TBWriter.Info1("array[1] = " + array[1].ToString()); TBWriter.Info1("arrayCopy[1] = " + arrayCopy[1].ToString()); arrayCopy[1].X = (ran.NextDouble()); arrayCopy[1].Y = (ran.NextDouble()); arrayCopy[1].Z = (ran.NextDouble()); TBWriter.Info1("arrayCopy[1] = " + arrayCopy[1].ToString()); TBWriter.Info1("array[1] = " + array[1].ToString()); TBWriter.Info1("arrayclone[1] = " + arrayclone[1].ToString()); TBWriter.Info1("arrayToArray[1] = " + arrayToArray[1].ToString()); TBWriter.Info1("arrayFor[1] = " + arrayFor[1].ToString()); //SceneMaTBWriter.Info1("arrayToArray[1] = " + arrayToArray[1].ToString());nager map = new SceneManager //(); //map.AddNode( new SceneNode( "myNode" , Vector3.UnitX)); //map.Nodes[0].AddFrame( 0, 0, 0.8); //map.Nodes[0].AddFrame(1, 11, 0.8); //map.Nodes.Add( new SceneNode( "myAnotherNode" , new Vector3(2, 2, 2))); //map.Nodes[1].AddFrame(2, 3, 1.8); //map.Nodes[1].AddFrame(2,1, 0); //map.Nodes[1].AddFrame(0, 0, 0); //map.SaveSceneMap(); }
public void mbAddToRenderBuffer(ref Vector3[] vertices, ref Vector2[] uvs, ref Color[] colors) { if (mBufferPtr == mVertices.Length) mbEnlargeBuffers(LayerBlocksize); vertices.CopyTo(mVertices, mBufferPtr); uvs.CopyTo(mUVs, mBufferPtr); colors.CopyTo(mColors, mBufferPtr); int i = (mBufferPtr / 4) * 6; mTriangles[i++] = mBufferPtr; mTriangles[i++] = mBufferPtr + 1; mTriangles[i++] = mBufferPtr + 2; mTriangles[i++] = mBufferPtr + 2; mTriangles[i++] = mBufferPtr + 3; mTriangles[i++] = mBufferPtr; mBufferPtr += 4; }