System.Collections.Generic.List.Add(Vector3)

Here are the examples of the csharp api System.Collections.Generic.List.Add(Vector3) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1597 Examples 7

19 Source : CapsuleHand.cs
with MIT License
from 39M

private Mesh generateCylinderMesh(float length) {
      Mesh mesh = new Mesh();
      mesh.name = "GeneratedCylinder";
      mesh.hideFlags = HideFlags.DontSave;

      List<Vector3> verts = new List<Vector3>();
      List<Color> colors = new List<Color>();
      List<int> tris = new List<int>();

      Vector3 p0 = Vector3.zero;
      Vector3 p1 = Vector3.forward * length;
      for (int i = 0; i < _cylinderResolution; i++) {
        float angle = (Mathf.PI * 2.0f * i) / _cylinderResolution;
        float dx = CYLINDER_RADIUS * Mathf.Cos(angle);
        float dy = CYLINDER_RADIUS * Mathf.Sin(angle);

        Vector3 spoke = new Vector3(dx, dy, 0);

        verts.Add((p0 + spoke) * transform.lossyScale.x);
        verts.Add((p1 + spoke) * transform.lossyScale.x);

        colors.Add(Color.white);
        colors.Add(Color.white);

        int triStart = verts.Count;
        int triCap = _cylinderResolution * 2;

        tris.Add((triStart + 0) % triCap);
        tris.Add((triStart + 2) % triCap);
        tris.Add((triStart + 1) % triCap);

        tris.Add((triStart + 2) % triCap);
        tris.Add((triStart + 3) % triCap);
        tris.Add((triStart + 1) % triCap);
      }

      mesh.SetVertices(verts);
      mesh.SetIndices(tris.ToArray(), MeshTopology.Triangles, 0);
      mesh.RecalculateBounds();
      mesh.RecalculateNormals();
      ;
      mesh.UploadMeshData(true);

      return mesh;
    }

19 Source : RuntimeGizmoManager.cs
with MIT License
from 39M

private void generateMeshes() {
      _cubeMesh = new Mesh();
      _cubeMesh.name = "RuntimeGizmoCube";
      _cubeMesh.hideFlags = HideFlags.HideAndDontSave;

      List<Vector3> verts = new List<Vector3>();
      List<int> indexes = new List<int>();

      Vector3[] faces = new Vector3[] { Vector3.forward, Vector3.right, Vector3.up };
      for (int i = 0; i < 3; i++) {
        addQuad(verts, indexes, faces[(i + 0) % 3], -faces[(i + 1) % 3], faces[(i + 2) % 3]);
        addQuad(verts, indexes, -faces[(i + 0) % 3], faces[(i + 1) % 3], faces[(i + 2) % 3]);
      }

      _cubeMesh.SetVertices(verts);
      _cubeMesh.SetIndices(indexes.ToArray(), MeshTopology.Quads, 0);
      _cubeMesh.RecalculateNormals();
      _cubeMesh.RecalculateBounds();
      _cubeMesh.UploadMeshData(true);

      _wireCubeMesh = new Mesh();
      _wireCubeMesh.name = "RuntimeWireCubeMesh";
      _wireCubeMesh.hideFlags = HideFlags.HideAndDontSave;

      verts.Clear();
      indexes.Clear();

      for (int dx = 1; dx >= -1; dx -= 2) {
        for (int dy = 1; dy >= -1; dy -= 2) {
          for (int dz = 1; dz >= -1; dz -= 2) {
            verts.Add(0.5f * new Vector3(dx, dy, dz));
          }
        }
      }

      addCorner(indexes, 0, 1, 2, 4);
      addCorner(indexes, 3, 1, 2, 7);
      addCorner(indexes, 5, 1, 4, 7);
      addCorner(indexes, 6, 2, 4, 7);

      _wireCubeMesh.SetVertices(verts);
      _wireCubeMesh.SetIndices(indexes.ToArray(), MeshTopology.Lines, 0);
      _wireCubeMesh.RecalculateBounds();
      _wireCubeMesh.UploadMeshData(true);

      _wireSphereMesh = new Mesh();
      _wireSphereMesh.name = "RuntimeWireSphereMesh";
      _wireSphereMesh.hideFlags = HideFlags.HideAndDontSave;

      verts.Clear();
      indexes.Clear();

      int totalVerts = CIRCLE_RESOLUTION * 3;
      for (int i = 0; i < CIRCLE_RESOLUTION; i++) {
        float angle = Mathf.PI * 2 * i / CIRCLE_RESOLUTION;
        float dx = 0.5f * Mathf.Cos(angle);
        float dy = 0.5f * Mathf.Sin(angle);

        for (int j = 0; j < 3; j++) {
          indexes.Add((i * 3 + j + 0) % totalVerts);
          indexes.Add((i * 3 + j + 3) % totalVerts);
        }

        verts.Add(new Vector3(dx, dy, 0));
        verts.Add(new Vector3(0, dx, dy));
        verts.Add(new Vector3(dx, 0, dy));
      }

      _wireSphereMesh.SetVertices(verts);
      _wireSphereMesh.SetIndices(indexes.ToArray(), MeshTopology.Lines, 0);
      _wireSphereMesh.RecalculateBounds();
      _wireSphereMesh.UploadMeshData(true);
    }

19 Source : RuntimeGizmoManager.cs
with MIT License
from 39M

private void addQuad(List<Vector3> verts, List<int> indexes, Vector3 normal, Vector3 axis1, Vector3 axis2) {
      indexes.Add(verts.Count + 0);
      indexes.Add(verts.Count + 1);
      indexes.Add(verts.Count + 2);
      indexes.Add(verts.Count + 3);

      verts.Add(0.5f * (normal + axis1 + axis2));
      verts.Add(0.5f * (normal + axis1 - axis2));
      verts.Add(0.5f * (normal - axis1 - axis2));
      verts.Add(0.5f * (normal - axis1 + axis2));
    }

19 Source : RuntimeGizmoManager.cs
with MIT License
from 39M

private void generateMeshes() {
      _cubeMesh = new Mesh();
      _cubeMesh.name = "RuntimeGizmoCube";
      _cubeMesh.hideFlags = HideFlags.HideAndDontSave;

      List<Vector3> verts = new List<Vector3>();
      List<int> indexes = new List<int>();

      Vector3[] faces = new Vector3[] { Vector3.forward, Vector3.right, Vector3.up };
      for (int i = 0; i < 3; i++) {
        addQuad(verts, indexes, faces[(i + 0) % 3], -faces[(i + 1) % 3], faces[(i + 2) % 3]);
        addQuad(verts, indexes, -faces[(i + 0) % 3], faces[(i + 1) % 3], faces[(i + 2) % 3]);
      }

      _cubeMesh.SetVertices(verts);
      _cubeMesh.SetIndices(indexes.ToArray(), MeshTopology.Quads, 0);
      _cubeMesh.RecalculateNormals();
      _cubeMesh.RecalculateBounds();
      _cubeMesh.UploadMeshData(true);

      _wireCubeMesh = new Mesh();
      _wireCubeMesh.name = "RuntimeWireCubeMesh";
      _wireCubeMesh.hideFlags = HideFlags.HideAndDontSave;

      verts.Clear();
      indexes.Clear();

      for (int dx = 1; dx >= -1; dx -= 2) {
        for (int dy = 1; dy >= -1; dy -= 2) {
          for (int dz = 1; dz >= -1; dz -= 2) {
            verts.Add(0.5f * new Vector3(dx, dy, dz));
          }
        }
      }

      addCorner(indexes, 0, 1, 2, 4);
      addCorner(indexes, 3, 1, 2, 7);
      addCorner(indexes, 5, 1, 4, 7);
      addCorner(indexes, 6, 2, 4, 7);

      _wireCubeMesh.SetVertices(verts);
      _wireCubeMesh.SetIndices(indexes.ToArray(), MeshTopology.Lines, 0);
      _wireCubeMesh.RecalculateBounds();
      _wireCubeMesh.UploadMeshData(true);

      _wireSphereMesh = new Mesh();
      _wireSphereMesh.name = "RuntimeWireSphereMesh";
      _wireSphereMesh.hideFlags = HideFlags.HideAndDontSave;

      verts.Clear();
      indexes.Clear();

      int totalVerts = CIRCLE_RESOLUTION * 3;
      for (int i = 0; i < CIRCLE_RESOLUTION; i++) {
        float angle = Mathf.PI * 2 * i / CIRCLE_RESOLUTION;
        float dx = 0.5f * Mathf.Cos(angle);
        float dy = 0.5f * Mathf.Sin(angle);

        for (int j = 0; j < 3; j++) {
          indexes.Add((i * 3 + j + 0) % totalVerts);
          indexes.Add((i * 3 + j + 3) % totalVerts);
        }

        verts.Add(new Vector3(dx, dy, 0));
        verts.Add(new Vector3(0, dx, dy));
        verts.Add(new Vector3(dx, 0, dy));
      }

      _wireSphereMesh.SetVertices(verts);
      _wireSphereMesh.SetIndices(indexes.ToArray(), MeshTopology.Lines, 0);
      _wireSphereMesh.RecalculateBounds();
      _wireSphereMesh.UploadMeshData(true);
    }

19 Source : RiggedHand.cs
with MIT License
from 39M

[ContextMenu("StoreJointsStartPose")]
    public void StoreJointsStartPose() {
      foreach (Transform t in palm.parent.GetComponentsInChildren<Transform>()) {
        jointList.Add(t);
        localRotations.Add(t.localRotation);
        localPositions.Add(t.localPosition);
      }
    }

19 Source : PlyHandler.cs
with MIT License
from 3DBear

private static PlyResult ParseAscii(List<string> plyFile, PlyHeader header)
        {
            var vertices = new List<Vector3>();
            var triangles = new List<int>();
            var colors = new List<Color>();
            var headerEndIndex = plyFile.IndexOf("end_header");
            var vertexStartIndex = headerEndIndex + 1;
            var faceStartIndex = vertexStartIndex + header.VertexCount + 1;
            plyFile.GetRange(vertexStartIndex, header.VertexCount).ForEach(vertex =>
            {
                var xyzrgb = vertex.Split(' ');
                vertices.Add(ParseVertex(xyzrgb, header));
                colors.Add(ParseColor(xyzrgb, header));
            });

            plyFile.GetRange(faceStartIndex, header.FaceCount).ForEach(face =>
            {
                triangles.AddRange(GetTriangles(face, header));
            });
            return new PlyResult(vertices, triangles, colors);
        }

19 Source : PlyHandler.cs
with MIT License
from 3DBear

private static List<Vector3> GetVertices(byte[] bytes, PlyHeader header, out List<Color> colors)
        {
            var vertices = new List<Vector3>();
            colors = new List<Color>();
            int bpvc = 4; // bytes per vertex component
            int bpcc = 1; // bytes per color component
            bool hasColor = header.RedIndex.HasValue && header.GreenIndex.HasValue && header.BlueIndex.HasValue;
            // todo: support other types than just float for vertex components and byte for color components
            int bytesPerVertex = GetByteCountPerVertex(header);

            for (int i = 0; i < header.VertexCount; i++)
            {
                int byteIndex = i * bytesPerVertex;
                var x = System.BitConverter.ToSingle(bytes.SubArray(byteIndex + 0 * bpvc, bpvc), 0);
                var y = System.BitConverter.ToSingle(bytes.SubArray(byteIndex + 1 * bpvc, bpvc), 0);
                var z = System.BitConverter.ToSingle(bytes.SubArray(byteIndex + 2 * bpvc, bpvc), 0);
                if (hasColor)
                {
                    byte r, g, b, a = 255;
                    r = bytes[byteIndex + 3 * bpvc + 0 * bpcc];
                    g = bytes[byteIndex + 3 * bpvc + 1 * bpcc];
                    b = bytes[byteIndex + 3 * bpvc + 2 * bpcc];
                    if (header.AlphaIndex.HasValue)
                    {
                        a = bytes[byteIndex + 3 * bpvc + 3 * bpcc];
                    }
                    colors.Add(new Color(r/255f, g/255f, b/255f, a/255f));
                }


                vertices.Add(new Vector3(x, y, z));
            }
            return vertices;
        }

19 Source : ParticlePainter.cs
with MIT License
from 734843327

public void ARFrameUpdated(UnityARCamera camera)
    {
        Matrix4x4 matrix = new Matrix4x4();
        matrix.SetColumn(3, camera.worldTransform.column3);
      
        Vector3 currentPositon = UnityARMatrixOps.GetPosition(matrix) + (Camera.main.transform.forward * penDistance);
        if (Vector3.Distance (currentPositon, previousPosition) > minDistanceThreshold) {
            if (paintMode == 2) currentPaintVertices.Add (currentPositon);
            frameUpdated = true;
            previousPosition = currentPositon;
        }
    }

19 Source : BaseBoundarySystem.cs
with Apache License 2.0
from abist-co-ltd

public GameObject GetTrackedAreaVisualization()
        {
            if (!Application.isPlaying) { return null; }

            if (currentTrackedAreaObject != null)
            {
                return currentTrackedAreaObject;
            }

            MixedRealityBoundaryVisualizationProfile profile = ConfigurationProfile as MixedRealityBoundaryVisualizationProfile;
            if (profile == null) { return null; }

            if (Bounds.Length == 0)
            {
                // If we do not have boundary edges, we cannot render them.
                return null;
            }

            // Get the line vertices
            List<Vector3> lineVertices = new List<Vector3>();
            for (int i = 0; i < Bounds.Length; i++)
            {
                lineVertices.Add(new Vector3(Bounds[i].PointA.x, 0f, Bounds[i].PointA.y));
            }
            // Add the first vertex again to ensure the loop closes.
            lineVertices.Add(lineVertices[0]);

            // We use an empty object and attach a line renderer.
            currentTrackedAreaObject = new GameObject("Tracked Area")
            {
                layer = ignoreRaycastLayerValue
            };
            currentTrackedAreaObject.AddComponent<LineRenderer>();
            currentTrackedAreaObject.transform.Translate(new Vector3(
                MixedRealityPlayspace.Position.x,
                boundaryObjectRenderOffset,
                MixedRealityPlayspace.Position.z));
            currentPlayAreaObject.layer = TrackedAreaPhysicsLayer;

            // Configure the renderer properties.
            float lineWidth = 0.01f;
            LineRenderer lineRenderer = currentTrackedAreaObject.GetComponent<LineRenderer>();
            lineRenderer.sharedMaterial = profile.TrackedAreaMaterial;
            lineRenderer.useWorldSpace = false;
            lineRenderer.startWidth = lineWidth;
            lineRenderer.endWidth = lineWidth;
            lineRenderer.positionCount = lineVertices.Count;
            lineRenderer.SetPositions(lineVertices.ToArray());

            currentTrackedAreaObject.transform.parent = BoundaryVisualizationParent.transform;

            return currentTrackedAreaObject;
        }

19 Source : StripMeshLineRenderer.cs
with Apache License 2.0
from abist-co-ltd

protected override void UpdateLine()
        {
            if (stripMeshRenderer == null)
            {
                Debug.LogError("Strip mesh renderer has been destroyed - disabling");
                enabled = false;
            }

            if (!LineDataSource.enabled)
            {
                stripMeshRenderer.enabled = false;
                return;
            }

            stripMeshRenderer.enabled = true;
            positions.Clear();
            forwards.Clear();
            colors.Clear();
            widths.Clear();
            
            for (int i = 0; i <= LineStepCount; i++)
            {
                float normalizedDistance = GetNormalizedPointAlongLine(i);
                positions.Add(LineDataSource.GetPoint(normalizedDistance));
                colors.Add(GetColor(normalizedDistance));
                widths.Add(GetWidth(normalizedDistance));
                forwards.Add(LineDataSource.GetVelocity(normalizedDistance));
            }

            GenerateStripMesh(positions, colors, widths, uvOffset, forwards, stripMesh, LineDataSource.LineTransform.up);
        }

19 Source : ProximityEffect.cs
with Apache License 2.0
from abist-co-ltd

public void UpdateScaling(Vector3 boundsCenter, Vector3 boundsExtents)
        {
            // early out if effect is disabled
            if (config.ProximityEffectActive == false || !IsAnyRegisteredObjectVisible())
            {
                return;
            }

            proximityPointers.Clear();
            proximityPoints.Clear();

            // Find all valid pointers
            foreach (var inputSource in CoreServices.InputSystem.DetectedInputSources)
            {
                foreach (var pointer in inputSource.Pointers)
                {
                    // don't use IsInteractionEnabled for near pointers as the pointers might have a different radius when deciding
                    // if they can interact with a near-by object - we might still want to show proximity scaling even if
                    // eg. grab pointer decides it's too far away to actually perform the interaction
                    if (pointer.IsActive && !proximityPointers.Contains(pointer))
                    {
                        proximityPointers.Add(pointer);
                    }
                }
            }

            // Get the max radius possible of our current bounds and extent the range to include proximity scaled objects. This is done by adjusting the original bounds to include the ObjectMediumProximity range in x, y and z axis
            float squareMaxLength = boundsExtents.sqrMagnitude + (3 * config.ObjectMediumProximity * config.ObjectMediumProximity);

            // Grab points within sphere of influence from valid pointers
            foreach (var pointer in proximityPointers)
            {
                if (IsPointWithinBounds(boundsCenter, pointer.Position, squareMaxLength))
                {
                    proximityPoints.Add(pointer.Position);
                }
                
                if (pointer.Result?.CurrentPointerTarget != null)
                { 
                    Vector3? point = pointer.Result?.Details.Point;
                    if (point.HasValue && IsPointWithinBounds(boundsCenter, pointer.Result.Details.Point, squareMaxLength))
                    {
                        proximityPoints.Add(pointer.Result.Details.Point);
                    }
                }
            }

            // Loop through all objects and find closest one
            Transform closestObject = null;
            float closestDistanceSqr = float.MaxValue;
            foreach (var point in proximityPoints)
            {

                foreach (var keyValuePair in registeredObjects)
                {

                    foreach (var item in keyValuePair.Value)
                    {
                        // If object can't be visible, skip calculations
                        if (!keyValuePair.Key.IsActive)
                        {
                            continue;
                        }

                        // Perform comparison on sqr distance since sqrt() operation is expensive in Vector3.Distance()
                        float sqrDistance = (item.ScaledObject.transform.position - point).sqrMagnitude;
                        if (sqrDistance < closestDistanceSqr)
                        {
                            closestObject = item.ScaledObject;
                            closestDistanceSqr = sqrDistance;
                        }
                    }
                }
            }

            // Loop through all objects and update visual state based on closest point
            foreach (var keyValuePair in registeredObjects)
            {
                foreach (var item in keyValuePair.Value)
                {
                    ProximityState newState = (closestObject == item.ScaledObject) ? GetProximityState(closestDistanceSqr) : ProximityState.FullsizeNoProximity;
                    IProximityEffectObjectProvider provider = keyValuePair.Key;

                    // Only apply updates if object is in a new state or closest object needs to lerp scaling
                    if (item.ProximityState != newState)
                    {
                        // Update and save new state
                        item.ProximityState = newState;

                        if (item.ObjectVisualRenderer)
                        {
                            item.ObjectVisualRenderer.material = newState == ProximityState.CloseProximity ? provider.GetHighlightedMaterial() : provider.GetBaseMaterial();
                        }
                    }

                    ScaleObject(newState, item.ScaledObject, provider.GetObjectSize(), true);
                }
            }
        }

19 Source : BoundingBoxHelper.cs
with Apache License 2.0
from abist-co-ltd

public void UpdateNonAABoundsCornerPositions(BoxCollider colliderBounds, List<Vector3> boundsPoints)
        {
            if (colliderBounds != targetBounds || rawBoundingCornersObtained == false)
            {
                GetRawBoundsCorners(colliderBounds);
            }

            if (colliderBounds == targetBounds && rawBoundingCornersObtained)
            {
                boundsPoints.Clear();
                for (int i = 0; i < rawBoundingCorners.Count; ++i)
                {
                    boundsPoints.Add(colliderBounds.transform.localToWorldMatrix.MultiplyPoint(rawBoundingCorners[i]));
                }

                worldBoundingCorners.Clear();
                worldBoundingCorners.AddRange(boundsPoints);
            }
        }

19 Source : TeleportAimHandlerLaser.cs
with MIT License
from absurd-joy

public override void GetPoints(List<Vector3> points)
	{
		Ray aimRay;
		LocomotionTeleport.InputHandler.GetAimData(out aimRay);
		points.Add(aimRay.origin);
		points.Add(aimRay.origin + aimRay.direction * Range);
	}

19 Source : TeleportAimHandlerParabolic.cs
with MIT License
from absurd-joy

public override void GetPoints(List<Vector3> points)
	{
		Ray startRay;

		LocomotionTeleport.InputHandler.GetAimData(out startRay);

		var aimPosition = startRay.origin;
		var aimDirection = startRay.direction * AimVelocity;
		var rangeSquared = Range * Range;
		do
		{
			points.Add(aimPosition);

			var aimVector = aimDirection;
			aimVector.y = aimVector.y + Gravity * 0.0111111111f * AimStep;
			aimDirection = aimVector;
			aimPosition += aimVector * AimStep;

		} while ((aimPosition.y - startRay.origin.y > MinimumElevation) && ((startRay.origin - aimPosition).sqrMagnitude <= rangeSquared));
	}

19 Source : OVROverlayMeshGenerator.cs
with MIT License
from absurd-joy

public static void BuildSphere(List<Vector3> verts, List<Vector2> uv, List<int> triangles, Vector3 position, Quaternion rotation, Vector3 scale, Rect rect, float worldScale = 800, int lareplacedudes = 128, int longitudes = 128, float expand_coef = 1.0f)
    {
        position = Quaternion.Inverse(rotation) * position;

        lareplacedudes = Mathf.CeilToInt(lareplacedudes * rect.height);
        longitudes = Mathf.CeilToInt(longitudes * rect.width);

        float minTheta = Mathf.PI * 2 * ( rect.x);
        float minPhi = Mathf.PI * (0.5f - rect.y - rect.height);

        float thetaScale = Mathf.PI * 2 * rect.width / longitudes;
        float phiScale = Mathf.PI * rect.height / lareplacedudes;

        for (int j = 0; j < lareplacedudes + 1; j += 1)
        {
            for (int k = 0; k < longitudes + 1; k++)
            {
                float theta = minTheta + k * thetaScale;
                float phi = minPhi + j * phiScale;

                Vector2 suv = GetSphereUV(theta, phi, expand_coef);
                uv.Add(new Vector2((suv.x - rect.x) / rect.width, (suv.y - rect.y) / rect.height));
                Vector3 vert = GetSphereVert(theta, phi);
                vert.x = (worldScale * vert.x - position.x) / scale.x;
                vert.y = (worldScale * vert.y - position.y) / scale.y;
                vert.z = (worldScale * vert.z - position.z) / scale.z;
                verts.Add(vert);
            }
        }

        for (int j = 0; j < lareplacedudes; j++)
        {
            for (int k = 0; k < longitudes; k++)
            {
                triangles.Add((j * (longitudes + 1)) + k);
                triangles.Add(((j + 1) * (longitudes + 1)) + k);
                triangles.Add(((j + 1) * (longitudes + 1)) + k + 1);
                triangles.Add(((j + 1) * (longitudes + 1)) + k + 1);
                triangles.Add((j * (longitudes + 1)) + k + 1);
                triangles.Add((j * (longitudes + 1)) + k);
            }
        }
    }

19 Source : OVROverlayMeshGenerator.cs
with MIT License
from absurd-joy

public static void BuildCube(List<Vector3> verts, List<Vector2> uv, List<int> triangles, Vector3 position, Quaternion rotation, Vector3 scale, float worldScale = 800, int subQuads = 1, float expand_coef = 1.01f)
    {
        position = Quaternion.Inverse(rotation) * position;

        int vertsPerSide = (subQuads + 1) * (subQuads + 1);

        for (int i = 0; i < (int)CubeFace.COUNT; i++)
        {
            for(int j = 0; j < subQuads + 1; j++)
            {
                for(int k = 0; k < subQuads + 1; k++)
                {
                    float u = j / (float)subQuads;
                    float v = k / (float)subQuads;

                    uv.Add(GetCubeUV((CubeFace)i, new Vector2(u, v), expand_coef));
                    Vector3 vert = GetCubeVert((CubeFace)i, new Vector2(u, v), expand_coef);
                    vert.x = (worldScale * vert.x - position.x) / scale.x;
                    vert.y = (worldScale * vert.y - position.y) / scale.y;
                    vert.z = (worldScale * vert.z - position.z) / scale.z;
                    verts.Add(vert);
                }
            }

            for(int j = 0; j < subQuads; j++)
            {
                for(int k = 0; k < subQuads; k++)
                {
                    triangles.Add(vertsPerSide * i + ((j + 1) * (subQuads + 1)) + k);
                    triangles.Add(vertsPerSide * i + (j * (subQuads + 1)) + k);
                    triangles.Add(vertsPerSide * i + ((j + 1) * (subQuads + 1)) + k + 1);
                    triangles.Add(vertsPerSide * i + ((j + 1) * (subQuads + 1)) + k + 1);
                    triangles.Add(vertsPerSide * i + (j * (subQuads + 1)) + k);
                    triangles.Add(vertsPerSide * i + (j * (subQuads + 1)) + k + 1);
                }
            }
        }
    }

19 Source : OVROverlayMeshGenerator.cs
with MIT License
from absurd-joy

public static void BuildQuad(List<Vector3> verts, List<Vector2> uv, List<int> triangles, Rect rect)
    {        
        verts.Add(new Vector3(rect.x - 0.5f, (1 - rect.y - rect.height) - 0.5f, 0));
        verts.Add(new Vector3(rect.x - 0.5f, (1 - rect.y) - 0.5f, 0));
        verts.Add(new Vector3(rect.x + rect.width - 0.5f, (1 - rect.y) - 0.5f, 0));
        verts.Add(new Vector3(rect.x + rect.width - 0.5f, (1 - rect.y - rect.height) - 0.5f, 0));

        uv.Add(new Vector2(0, 0));
        uv.Add(new Vector2(0, 1));
        uv.Add(new Vector2(1, 1));
        uv.Add(new Vector2(1, 0));

        triangles.Add(0);
        triangles.Add(1);
        triangles.Add(2);
        triangles.Add(2);
        triangles.Add(3);
        triangles.Add(0);
    }

19 Source : OVROverlayMeshGenerator.cs
with MIT License
from absurd-joy

public static void BuildHemicylinder(List<Vector3> verts, List<Vector2> uv, List<int> triangles, Vector3 scale, Rect rect, int longitudes = 128)
    {
        float height = Mathf.Abs(scale.y) * rect.height;
        float radius = scale.z;
        float arcLength = scale.x * rect.width;

        float arcAngle = arcLength / radius;
        float minAngle = scale.x * (-0.5f + rect.x) / radius;
        
        int columns = Mathf.CeilToInt(longitudes * arcAngle / (2 * Mathf.PI));

        // we don't want super tall skinny triangles because that can lead to artifacting.
        // make triangles no more than 2x taller than wide

        float triangleWidth = arcLength / columns;
        float ratio = height / triangleWidth;

        int rows = Mathf.CeilToInt(ratio / 2);

        for (int j = 0; j < rows + 1; j += 1)
        {
            for (int k = 0; k < columns + 1; k++)
            {
                uv.Add(new Vector2((k / (float)columns), 1 - (j / (float)rows)));

                Vector3 vert = Vector3.zero;
                // because the scale is used to control the parameters, we need
                // to reverse multiply by scale to appear correctly
                vert.x = (Mathf.Sin(minAngle + (k * arcAngle / columns)) * radius) / scale.x;

                vert.y = (0.5f - rect.y - rect.height + rect.height * (1 - j / (float)rows));
                vert.z = (Mathf.Cos(minAngle + (k * arcAngle / columns)) * radius) / scale.z;
                verts.Add(vert);
            }
        }

        for (int j = 0; j < rows; j++)
        {
            for (int k = 0; k < columns; k++)
            {
                triangles.Add((j * (columns + 1)) + k);
                triangles.Add(((j + 1) * (columns + 1)) + k + 1);
                triangles.Add(((j + 1) * (columns + 1)) + k);
                triangles.Add(((j + 1) * (columns + 1)) + k + 1);
                triangles.Add((j * (columns + 1)) + k);
                triangles.Add((j * (columns + 1)) + k + 1);
            }
        }
    }

19 Source : CharacterCapsule.cs
with MIT License
from absurd-joy

void Update ()
	{
	    if (_character == null)
	    {
	        _character = GetComponentInParent<CharacterController>();
	        if (_character == null)
	        {
	            return;
	        }
	    }

	    if (_height == _character.height 
            && _radius == _character.radius 
            && _subdivisionU == SubdivisionsU 
            && _subdivisionV == SubdivisionsV)
	    {
	        return;
	    }

        _height = _character.height;
	    _radius = _character.radius;
	    _subdivisionU = SubdivisionsU;
	    _subdivisionV = SubdivisionsV;

        List<Vector3> verts = new List<Vector3>();

        var vector = new Vector3(1,0,0);

        // Generate the mesh
        var topOffset = new Vector3(0, _height/2.0f - _radius, 0);
        var bottomOffset = new Vector3(0, _radius - _height/2.0f, 0);

        // Add all the necessary vertices
        verts.Add(new Vector3(0, _height/2.0f, 0));

	    for (int u = SubdivisionsU - 1; u >= 0; u--)
	    {
	        float uf = (float) u / (float) SubdivisionsU;
            for (int v = 0; v < SubdivisionsV; v++)
            {
                float vf = (float) v / (float) SubdivisionsV;
                var q = Quaternion.Euler(0, vf * 360.0f, uf * 90.0f);
                var vert = q * vector;
                vert *= _radius;
                var v1 = vert + topOffset;
                verts.Add(v1);
	        }
        }

	    for (int u = 0; u < SubdivisionsU; u++)
	    {
            float uf = (float)u / (float)SubdivisionsU;
	        for (int v = 0; v < SubdivisionsV; v++)
	        {
	            float vf = (float)v / (float)SubdivisionsV;
	            var q = Quaternion.Euler(0, vf * 360.0f + 180.0f, uf * 90.0f);
	            var vert = q * vector;
	            vert *= _radius;
	            var v2 = bottomOffset - vert;
	            verts.Add(v2);
	        }
	    }
	    verts.Add(new Vector3(0, -_height / 2.0f, 0));


        // Setup all the triangles

        List<int> tris = new List<int>();
	    int index;
	    int i;

        // top cap
	    for (int v = 0; v < SubdivisionsV; v++)
	    {
	        i = 0;
	        tris.Add(i);
	        tris.Add(v);
	        tris.Add(v+1);
	    }
	    tris.Add(0);
        tris.Add(SubdivisionsV);
	    tris.Add(1);

        // top hemisphere
        for (int u = 0; u < SubdivisionsU - 1; u++)
	    {
	        index = u * SubdivisionsV + 1;
	        for (int v = 0; v < SubdivisionsV - 1; v++)
            {
                i = index + v;
                tris.Add(i);
                tris.Add(i + SubdivisionsV);
                tris.Add(i + 1);

                tris.Add(i + 1);
                tris.Add(i + SubdivisionsV);
                tris.Add(i + SubdivisionsV + 1);
           }
	        i = index + SubdivisionsV - 1;
	        tris.Add(i);
	        tris.Add(i + SubdivisionsV);
	        tris.Add(i + 1 - SubdivisionsV);

            tris.Add(i + 1 - SubdivisionsV);
            tris.Add(i + SubdivisionsV);
	        tris.Add(i + 1);
        }

        // center tube
        index = (SubdivisionsU - 1) * SubdivisionsV + 1;
	    for (int v = 0; v < SubdivisionsV - 1; v++)
	    {
	        i = index + v;
	        tris.Add(i);
	        tris.Add(i + SubdivisionsV);
	        tris.Add(i + 1);

	        tris.Add(i + 1);
	        tris.Add(i + SubdivisionsV);
	        tris.Add(i + SubdivisionsV + 1);
	    }
	    i = index + SubdivisionsV - 1;
	    tris.Add(i);
	    tris.Add(i + SubdivisionsV);
	    tris.Add(i + 1 - SubdivisionsV);

	    tris.Add(i + 1 - SubdivisionsV);
	    tris.Add(i + SubdivisionsV);
	    tris.Add(i + 1);

        // bottom hemisphere
        for (int u = 0; u < SubdivisionsU - 1; u++)
	    {
	        index = u * SubdivisionsV + (SubdivisionsU * SubdivisionsV) + 1;
	        for (int v = 0; v < SubdivisionsV - 1; v++)
	        {
	            i = index + v;
	            tris.Add(i);
	            tris.Add(i + SubdivisionsV);
	            tris.Add(i + 1);

	            tris.Add(i + 1);
	            tris.Add(i + SubdivisionsV);
	            tris.Add(i + SubdivisionsV + 1);
	        }
	        i = index + SubdivisionsV - 1;
	        tris.Add(i);
	        tris.Add(i + SubdivisionsV);
	        tris.Add(i + 1 - SubdivisionsV);

	        tris.Add(i + 1 - SubdivisionsV);
	        tris.Add(i + SubdivisionsV);
	        tris.Add(i + 1); 
	    }

        // bottom cap
	    var last = verts.Count - 1;
	    var lastRow = last - SubdivisionsV;
	    for (int v = 0; v < SubdivisionsV; v++)
	    {
	        i = 0;
	        tris.Add(last);
	        tris.Add(lastRow + v + 1);
	        tris.Add(lastRow + v);
	    }
	    tris.Add(last);
	    tris.Add(lastRow);
	    tris.Add(last - 1);


        _vertices = verts.ToArray();
	    _triangles = tris.ToArray();

	    _meshFilter = gameObject.GetComponent<MeshFilter>();
        _meshFilter.mesh = new Mesh();
        _meshFilter.sharedMesh.vertices = _vertices;
	    _meshFilter.sharedMesh.triangles = _triangles;
        _meshFilter.sharedMesh.RecalculateNormals();
	}

19 Source : CharacterCapsule.cs
with MIT License
from absurd-joy

void Update ()
	{
	    if (_character == null)
	    {
	        _character = GetComponentInParent<CharacterController>();
	        if (_character == null)
	        {
	            return;
	        }
	    }

	    if (_height == _character.height 
            && _radius == _character.radius 
            && _subdivisionU == SubdivisionsU 
            && _subdivisionV == SubdivisionsV)
	    {
	        return;
	    }

        _height = _character.height;
	    _radius = _character.radius;
	    _subdivisionU = SubdivisionsU;
	    _subdivisionV = SubdivisionsV;

        List<Vector3> verts = new List<Vector3>();

        var vector = new Vector3(1,0,0);

        // Generate the mesh
        var topOffset = new Vector3(0, _height/2.0f - _radius, 0);
        var bottomOffset = new Vector3(0, _radius - _height/2.0f, 0);

        // Add all the necessary vertices
        verts.Add(new Vector3(0, _height/2.0f, 0));

	    for (int u = SubdivisionsU - 1; u >= 0; u--)
	    {
	        float uf = (float) u / (float) SubdivisionsU;
            for (int v = 0; v < SubdivisionsV; v++)
            {
                float vf = (float) v / (float) SubdivisionsV;
                var q = Quaternion.Euler(0, vf * 360.0f, uf * 90.0f);
                var vert = q * vector;
                vert *= _radius;
                var v1 = vert + topOffset;
                verts.Add(v1);
	        }
        }

	    for (int u = 0; u < SubdivisionsU; u++)
	    {
            float uf = (float)u / (float)SubdivisionsU;
	        for (int v = 0; v < SubdivisionsV; v++)
	        {
	            float vf = (float)v / (float)SubdivisionsV;
	            var q = Quaternion.Euler(0, vf * 360.0f + 180.0f, uf * 90.0f);
	            var vert = q * vector;
	            vert *= _radius;
	            var v2 = bottomOffset - vert;
	            verts.Add(v2);
	        }
	    }
	    verts.Add(new Vector3(0, -_height / 2.0f, 0));


        // Setup all the triangles

        List<int> tris = new List<int>();
	    int index;
	    int i;

        // top cap
	    for (int v = 0; v < SubdivisionsV; v++)
	    {
	        i = 0;
	        tris.Add(i);
	        tris.Add(v);
	        tris.Add(v+1);
	    }
	    tris.Add(0);
        tris.Add(SubdivisionsV);
	    tris.Add(1);

        // top hemisphere
        for (int u = 0; u < SubdivisionsU - 1; u++)
	    {
	        index = u * SubdivisionsV + 1;
	        for (int v = 0; v < SubdivisionsV - 1; v++)
            {
                i = index + v;
                tris.Add(i);
                tris.Add(i + SubdivisionsV);
                tris.Add(i + 1);

                tris.Add(i + 1);
                tris.Add(i + SubdivisionsV);
                tris.Add(i + SubdivisionsV + 1);
           }
	        i = index + SubdivisionsV - 1;
	        tris.Add(i);
	        tris.Add(i + SubdivisionsV);
	        tris.Add(i + 1 - SubdivisionsV);

            tris.Add(i + 1 - SubdivisionsV);
            tris.Add(i + SubdivisionsV);
	        tris.Add(i + 1);
        }

        // center tube
        index = (SubdivisionsU - 1) * SubdivisionsV + 1;
	    for (int v = 0; v < SubdivisionsV - 1; v++)
	    {
	        i = index + v;
	        tris.Add(i);
	        tris.Add(i + SubdivisionsV);
	        tris.Add(i + 1);

	        tris.Add(i + 1);
	        tris.Add(i + SubdivisionsV);
	        tris.Add(i + SubdivisionsV + 1);
	    }
	    i = index + SubdivisionsV - 1;
	    tris.Add(i);
	    tris.Add(i + SubdivisionsV);
	    tris.Add(i + 1 - SubdivisionsV);

	    tris.Add(i + 1 - SubdivisionsV);
	    tris.Add(i + SubdivisionsV);
	    tris.Add(i + 1);

        // bottom hemisphere
        for (int u = 0; u < SubdivisionsU - 1; u++)
	    {
	        index = u * SubdivisionsV + (SubdivisionsU * SubdivisionsV) + 1;
	        for (int v = 0; v < SubdivisionsV - 1; v++)
	        {
	            i = index + v;
	            tris.Add(i);
	            tris.Add(i + SubdivisionsV);
	            tris.Add(i + 1);

	            tris.Add(i + 1);
	            tris.Add(i + SubdivisionsV);
	            tris.Add(i + SubdivisionsV + 1);
	        }
	        i = index + SubdivisionsV - 1;
	        tris.Add(i);
	        tris.Add(i + SubdivisionsV);
	        tris.Add(i + 1 - SubdivisionsV);

	        tris.Add(i + 1 - SubdivisionsV);
	        tris.Add(i + SubdivisionsV);
	        tris.Add(i + 1); 
	    }

        // bottom cap
	    var last = verts.Count - 1;
	    var lastRow = last - SubdivisionsV;
	    for (int v = 0; v < SubdivisionsV; v++)
	    {
	        i = 0;
	        tris.Add(last);
	        tris.Add(lastRow + v + 1);
	        tris.Add(lastRow + v);
	    }
	    tris.Add(last);
	    tris.Add(lastRow);
	    tris.Add(last - 1);


        _vertices = verts.ToArray();
	    _triangles = tris.ToArray();

	    _meshFilter = gameObject.GetComponent<MeshFilter>();
        _meshFilter.mesh = new Mesh();
        _meshFilter.sharedMesh.vertices = _vertices;
	    _meshFilter.sharedMesh.triangles = _triangles;
        _meshFilter.sharedMesh.RecalculateNormals();
	}

19 Source : SetupModel.cs
with GNU Affero General Public License v3.0
from ACEmulator

public override void Unpack(BinaryReader reader)
        {
            Id = reader.ReadUInt32();

            Flags = (SetupFlags)reader.ReadUInt32();

            AllowFreeHeading    = (Flags & SetupFlags.AllowFreeHeading) != 0;
            HasPhysicsBSP       = (Flags & SetupFlags.HasPhysicsBSP) != 0;

            // Get all the GraphicsObjects in this SetupModel. These are all the 01-types.
            uint numParts = reader.ReadUInt32();
            for (int i = 0; i < numParts; i++)
                Parts.Add(reader.ReadUInt32());

            if ((Flags & SetupFlags.HasParent) != 0)
            {
                for (int i = 0; i < numParts; i++)
                    ParentIndex.Add(reader.ReadUInt32());
            }

            if ((Flags & SetupFlags.HasDefaultScale) != 0)
            {
                for (int i = 0; i < numParts; i++)
                    DefaultScale.Add(reader.ReadVector3());
            }

            HoldingLocations.Unpack(reader);
            ConnectionPoints.Unpack(reader);

            int placementsCount = reader.ReadInt32();
            for (int i = 0; i < placementsCount; i++)
            {
                int key = reader.ReadInt32();
                // there is a frame for each Part
                var placementType = new PlacementType();
                placementType.Unpack(reader, (uint)Parts.Count);
                PlacementFrames.Add(key, placementType);
            }

            CylSpheres.Unpack(reader);

            Spheres.Unpack(reader);

            Height          = reader.ReadSingle();
            Radius          = reader.ReadSingle();
            StepUpHeight    = reader.ReadSingle();
            StepDownHeight  = reader.ReadSingle();

            SortingSphere.Unpack(reader);
            SelectionSphere.Unpack(reader);

            Lights.Unpack(reader);

            DefaultAnimation    = reader.ReadUInt32();
            DefaultScript       = reader.ReadUInt32();
            DefaultMotionTable  = reader.ReadUInt32();
            DefaultSoundTable   = reader.ReadUInt32();
            DefaultScriptTable  = reader.ReadUInt32();
        }

19 Source : Polygon.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void BuildPolygon(ModelPolygon _poly, Vector3 position, Quaternion orientation, float scalar = 1.0f)
        {
            Vertices = new List<Vector3>();

            // build the matrix transform
            var transform = Matrix4x4.CreateScale(scalar) * Matrix4x4.CreateFromQuaternion(orientation) * Matrix4x4.CreateTranslation(position);

            // transform the vertices
            // from local object to world space
            foreach (var vertex in _poly.Vertices)
            {
                Vertices.Add(Vector3.Transform(vertex.Origin, transform));
            }
        }

19 Source : BoundingBox.cs
with GNU General Public License v3.0
from ACEmulator

public void BuildVerts()
        {
            Verts = new List<Vector3>();
            /*Verts.Add(new Vector3(Mins.X, Mins.Y, Maxs.Z));   // Front NW
            Verts.Add(new Vector3(Maxs.X, Mins.Y, Maxs.Z));   // Front NE
            Verts.Add(new Vector3(Maxs.X, Mins.Y, Mins.Z));   // Front SE
            Verts.Add(new Vector3(Mins.X, Mins.Y, Mins.Z));   // Front SW
            Verts.Add(new Vector3(Maxs.X, Maxs.Y, Maxs.Z));   // Back NE
            Verts.Add(new Vector3(Mins.X, Maxs.Y, Maxs.Z));   // Back NW
            Verts.Add(new Vector3(Mins.X, Maxs.Y, Mins.Z));   // Back SW
            Verts.Add(new Vector3(Maxs.X, Maxs.Y, Mins.Z));   // Back SE*/

            Verts.Add(new Vector3(Maxs.X, Maxs.Y, Maxs.Z));   // Front NW
            Verts.Add(new Vector3(Mins.X, Maxs.Y, Maxs.Z));   // Front NE
            Verts.Add(new Vector3(Mins.X, Maxs.Y, Mins.Z));   // Front SE
            Verts.Add(new Vector3(Maxs.X, Maxs.Y, Mins.Z));   // Front SW
            Verts.Add(new Vector3(Mins.X, Mins.Y, Maxs.Z));   // Back NE
            Verts.Add(new Vector3(Maxs.X, Mins.Y, Maxs.Z));   // Back NW
            Verts.Add(new Vector3(Maxs.X, Mins.Y, Mins.Z));   // Back SW
            Verts.Add(new Vector3(Mins.X, Mins.Y, Mins.Z));   // Back SE
        }

19 Source : Setup.cs
with GNU General Public License v3.0
from ACEmulator

public List<Vector3> GetVertices()
        {
            var verts = new List<Vector3>();

            for (var i = 0; i < Parts.Count; i++)
            {
                if (Parts[i]._gfxObj.Id == 0x010001EC)
                    continue;

                var part = Parts[i];
                var placementFrame = PlacementFrames[i];

                var partVerts = part.VertexArray.Select(v => v.Position).ToList();

                foreach (var partVert in partVerts)
                    verts.Add(Vector3.Transform(partVert, placementFrame));
            }
            return verts;
        }

19 Source : BuiltinDebugViewsComponent.cs
with MIT License
from AdultLink

public void BuildMesh(int columns, int rows)
            {
                // Base shape
                var arrow = new Vector3[6]
                {
                    new Vector3(0f, 0f, 0f),
                    new Vector3(0f, 1f, 0f),
                    new Vector3(0f, 1f, 0f),
                    new Vector3(-1f, 1f, 0f),
                    new Vector3(0f, 1f, 0f),
                    new Vector3(1f, 1f, 0f)
                };

                // make the vertex array
                int vcount = 6 * columns * rows;
                var vertices = new List<Vector3>(vcount);
                var uvs = new List<Vector2>(vcount);

                for (int iy = 0; iy < rows; iy++)
                {
                    for (int ix = 0; ix < columns; ix++)
                    {
                        var uv = new Vector2(
                                (0.5f + ix) / columns,
                                (0.5f + iy) / rows
                                );

                        for (int i = 0; i < 6; i++)
                        {
                            vertices.Add(arrow[i]);
                            uvs.Add(uv);
                        }
                    }
                }

                // make the index array
                var indices = new int[vcount];

                for (int i = 0; i < vcount; i++)
                    indices[i] = i;

                // initialize the mesh object
                mesh = new Mesh { hideFlags = HideFlags.DontSave };
                mesh.SetVertices(vertices);
                mesh.SetUVs(0, uvs);
                mesh.SetIndices(indices, MeshTopology.Lines, 0);
                mesh.UploadMeshData(true);

                // update the properties
                columnCount = columns;
                rowCount = rows;
            }

19 Source : ObjLoader.cs
with The Unlicense
from aeroson

Mesh Parse(Resource resource, GameObject appendToGameObject)
        {
            using (StreamReader textReader = new StreamReader(resource))
            {

                int i1, i2, i3, i4;

                string line;
                while ((line = textReader.ReadLine()) != null)
                {
                    line = line.Trim(trimCharacters);
                    line = line.Replace("  ", " ");

                    string[] parameters = line.Split(splitCharacters);

                    switch (parameters[0])
                    {
                        case "p": // Point
                            break;

                        case "v": // Vertex
                            var v = Vector3.Zero;
                            Parse(ref parameters[1], ref v.X);
                            Parse(ref parameters[2], ref v.Y);
                            Parse(ref parameters[3], ref v.Z);
                            verticesObj.Add(v);
                            break;

                        case "vt": // TexCoord
                            gotUvs = true;
                            var vt = Vector2.Zero;
                            Parse(ref parameters[1], ref vt.X);
                            Parse(ref parameters[2], ref vt.Y);
                            uvsObj.Add(vt);
                            break;

                        case "vn": // Normal
                            gotNormal = true;
                            var vn = Vector3.Zero;
                            Parse(ref parameters[1], ref vn.X);
                            Parse(ref parameters[2], ref vn.Y);
                            Parse(ref parameters[3], ref vn.Z);
                            normalsObj.Add(vn);
                            break;

                        case "f":
                            switch (parameters.Length)
                            {
                                case 4:
                                    i1 = ParseFaceParameter(parameters[1]);
                                    i2 = ParseFaceParameter(parameters[2]);
                                    i3 = ParseFaceParameter(parameters[3]);
                                    triangleIndiciesMesh.Add(i1);
                                    triangleIndiciesMesh.Add(i2);
                                    triangleIndiciesMesh.Add(i3);
                                    break;

                                case 5:
                                    i1 = ParseFaceParameter(parameters[1]);
                                    i2 = ParseFaceParameter(parameters[2]);
                                    i3 = ParseFaceParameter(parameters[3]);
                                    i4 = ParseFaceParameter(parameters[4]);
                                    triangleIndiciesMesh.Add(i1);
                                    triangleIndiciesMesh.Add(i2);
                                    triangleIndiciesMesh.Add(i3);
                                    triangleIndiciesMesh.Add(i1);
                                    triangleIndiciesMesh.Add(i3);
                                    triangleIndiciesMesh.Add(i4);
                                    break;
                            }
                            break;
                        case "mtllib":
                            if (Resource.ResourceInFolderExists(resource, parameters[1]))
                            {
                                materialLibrary = new MaterialLibrary(Resource.GetResourceInFolder(resource, parameters[1]));
                            }
                            break;
                        case "usemtl":
                            if (materialLibrary!=null) lastMaterial = materialLibrary.GetMat(parameters[1]);
                            break;
                    }
                }

                textReader.Close();
            }


            if(appendToGameObject!=null) return EndObjPart(appendToGameObject);

            Debug.Info("Loaded " + resource.originalPath + " vertices:" + verticesMesh.Count + " faces:" + triangleIndiciesMesh.Count / 3);

            return EndMesh();
    
        }

19 Source : ObjLoader.cs
with The Unlicense
from aeroson

int FindOrAddObjVertex(ref string faceParamater, ref Vector3 vertex, ref Vector2 texCoord, ref Vector3 normal)
        {
            int index;
            if (objFaceToMeshIndicie.TryGetValue(faceParamater, out index)) {
                return index;
            } else {

                verticesMesh.Add(vertex);
                uvsMesh.Add(texCoord);
                normalsMesh.Add(normal);

                index = verticesMesh.Count - 1;
                objFaceToMeshIndicie[faceParamater]=index;

                return index;
            }
        }

19 Source : LegoPiece.cs
with The Unlicense
from aeroson

public override void Start()
        {

            var m = GetComponent<MeshRenderer>();
            if (m)
            {
                var b=m.mesh.bounds;                

                const float halfSize = 1.139775f;

                int xCount = (int)Math.Round( b.extents.X / halfSize );
                int zCount = (int)Math.Round( b.extents.Z / halfSize );

                for (int x = 0; x < xCount; x++)
                {
                    for (int z = 0; z < zCount; z++)
                    {
                        var slot = b.min + new Vector3(halfSize + x * halfSize * 2, 0, halfSize + z * halfSize * 2);
                        slots.Add(slot);                        

                        var point = slot;
                        point.Y = b.max.Y;
                        point.Y -= 0.45f;
                        points.Add(point);

                        //VisualizePosition.Create(gameObject, point); VisualizePosition.Create(gameObject, slot);
                    }
                }

            }
            
            
        }

19 Source : RoadGenerator.cs
with Apache License 2.0
from Aggrathon

public void Generate(float[,] heights, Vector3 terrainSize, Vector3 terrainPosition, float waterRelativeHeight)
	{
		int heightWidth = heights.GetLength(0);
		System.Random rnd = new System.Random();
		int pathFindingGraphSize = heightWidth / pathFindingSpacing - 2 * pathFindingGraphMargin;

		Pathfinding.PathFindNode[,] nodes = new Pathfinding.PathFindNode[pathFindingGraphSize, pathFindingGraphSize];
		for (int i = 1; i < pathFindingGraphSize - 1; i++)
		{
			for (int j = 1; j < pathFindingGraphSize - 1; j++)
			{
				float nodeHeight = heights[(i + pathFindingGraphMargin) * pathFindingSpacing, (j + pathFindingGraphMargin) * pathFindingSpacing];
				if (nodeHeight > waterRelativeHeight + 0.03f)
					nodes[i, j] = new Pathfinding.PathFindNode(i, j, nodeHeight);
			}
		}
		Pathfinding pf = new Pathfinding(nodes, heightPenalty);
		List<Pathfinding.PathFindNode> path = pf.GetRoad(numCheckpoints, rnd);
		road.Clear();
		for (int i = 0; i < path.Count; i++)
		{
			Vector3 pos = Vector3.Scale(terrainSize, path[i].GetLocalPosition(pathFindingGraphSize, pathFindingGraphSize, pathFindingGraphMargin)) + terrainPosition;
			if (road.Count < 1 || Vector3.SqrMagnitude(pos - road[road.Count - 1]) > 1)
				road.Add(pos);
		}
	}

19 Source : RoadGenerator.cs
with Apache License 2.0
from Aggrathon

public void AddNode(Vector3 node, float strength)
		{
			if(roadNodes == null)
			{
				roadNodes = new List<Vector3>();
				roadNodes.Add(node);
				strengths = new List<float>();
				strengths.Add(strength);
			}
			else
			{
				for (int i = 0; i < roadNodes.Count; i++)
				{
					if(roadNodes[i] == node)
					{
						if (strengths[i] < strength)
							strengths[i] = strength;
						return;
					}
				}
				roadNodes.Add(node);
				strengths.Add(strength);
			}
		}

19 Source : TraverserCharacterController.Private.cs
with MIT License
from AitorSimona

private void CheckGroundCollision()
        {
            int colliderIndex = CastGroundProbe();

            if (colliderIndex != -1)
            {   
                // --- Set the closest collider as our ground ---  
                current.ground = hitColliders[colliderIndex];
                current.isGrounded = true;
            }      

            // --- Add cast position to debug draw lists ---
            if (debugDraw)
            {
                if (probePositions.Count == simulationCounter)
                    probePositions.Add(position);
                else
                    probePositions[simulationCounter] = position;

                if (planePositions.Count == simulationCounter)
                    planePositions.Add(characterController.bounds.min + Vector3.forward * characterController.radius + Vector3.right * characterController.radius + Vector3.up * groundProbeRadius);
                else
                    planePositions[simulationCounter] = characterController.bounds.min + Vector3.forward * characterController.radius + Vector3.right * characterController.radius + Vector3.up * groundProbeRadius;
            }

            // --- Prevent drop/fall, snap to ground ---

            if (currentGroundSnap)
            {
                groundRay.origin = characterController.transform.position;
                groundRay.direction = -Vector3.up;

                if (state.previousCollision.ground != null 
                    && !Physics.Raycast(groundRay.origin, groundRay.direction, groundSnapRayDistance, characterCollisionMask, QueryTriggerInteraction.Ignore))
                {
                    // --- We want to slide along the edge of the collider, not get trapped on it, so we need to properly adjust the trajectory ---

                    // --- Obtain collider's closest point and compute a new velocity vector ---
                    Vector3 correctedPosition = state.previousCollision.position;
                    Vector3 closestColliderPosition = state.previousCollision.ground.ClosestPoint(state.currentCollision.position);
                    Vector3 correctedVelocityVector = closestColliderPosition - state.previousCollision.position;

                    // --- Project our current velocity on the newly computed velocity vector ---                   
                    Vector3 desiredVelocity = Vector3.Project(state.currentCollision.velocity, correctedVelocityVector);
                    correctedPosition += desiredVelocity * Time.deltaTime;
                    state.currentCollision.velocity = desiredVelocity / stepping;

                    // --- Manually correct controller's position ---
                    characterController.enabled = false;
                    transform.position = correctedPosition;
                    characterController.enabled = true;
                    state.currentCollision.position = transform.position;                   
                }

                // --- Draw casted ray ---
                if (debugDraw)
                    Debug.DrawRay(groundRay.origin, groundRay.direction * groundSnapRayDistance);
            }
        }

19 Source : MeshUtility.cs
with Apache License 2.0
from aivclab

static int GetMiddlePoint(int p1,
                              int p2,
                              ref List<Vector3> vertices,
                              ref Dictionary<long, int> cache,
                              float radius) {
      // first check if we have it already
      var first_is_smaller = p1 < p2;
      long smaller_index = first_is_smaller ? p1 : p2;
      long greater_index = first_is_smaller ? p2 : p1;
      var key = (smaller_index << 32) + greater_index;

      if (cache.TryGetValue(key : key, value : out var ret)) {
        return ret;
      }

      // not in cache, calculate it
      var point1 = vertices[index : p1];
      var point2 = vertices[index : p2];
      var middle = new Vector3(x : (point1.x + point2.x) / 2f,
                               y : (point1.y + point2.y) / 2f,
                               z : (point1.z + point2.z) / 2f);

      // add vertex makes sure point is on unit sphere
      var i = vertices.Count;
      vertices.Add(item : middle.normalized * radius);

      // store it, return index
      cache.Add(key : key, value : i);

      return i;
    }

19 Source : MeshUtility.cs
with Apache License 2.0
from aivclab

public static Mesh CreateIcoSphere(int recursion_level, float radius) {
      var mesh = new Mesh();

      var vert_list = new List<Vector3>();
      var middle_point_index_cache = new Dictionary<long, int>();

      // create 12 vertices of a icosahedron
      var t = (1f + Mathf.Sqrt(5f)) / 2f;

      vert_list.Add(item : new Vector3(-1f, y : t, 0f).normalized * radius);
      vert_list.Add(item : new Vector3(1f, y : t, 0f).normalized * radius);
      vert_list.Add(item : new Vector3(-1f, y : -t, 0f).normalized * radius);
      vert_list.Add(item : new Vector3(1f, y : -t, 0f).normalized * radius);

      vert_list.Add(item : new Vector3(0f, -1f, z : t).normalized * radius);
      vert_list.Add(item : new Vector3(0f, 1f, z : t).normalized * radius);
      vert_list.Add(item : new Vector3(0f, -1f, z : -t).normalized * radius);
      vert_list.Add(item : new Vector3(0f, 1f, z : -t).normalized * radius);

      vert_list.Add(item : new Vector3(x : t, 0f, -1f).normalized * radius);
      vert_list.Add(item : new Vector3(x : t, 0f, 1f).normalized * radius);
      vert_list.Add(item : new Vector3(x : -t, 0f, -1f).normalized * radius);
      vert_list.Add(item : new Vector3(x : -t, 0f, 1f).normalized * radius);

      // create 20 triangles of the icosahedron
      var faces = new List<TriangleIndices> {
                                                // 5 faces around point 0
                                                new TriangleIndices(0, 11, 5),
                                                new TriangleIndices(0, 5, 1),
                                                new TriangleIndices(0, 1, 7),
                                                new TriangleIndices(0, 7, 10),
                                                new TriangleIndices(0, 10, 11),
                                                // 5 adjacent faces
                                                new TriangleIndices(1, 5, 9),
                                                new TriangleIndices(5, 11, 4),
                                                new TriangleIndices(11, 10, 2),
                                                new TriangleIndices(10, 7, 6),
                                                new TriangleIndices(7, 1, 8),
                                                // 5 faces around point 3
                                                new TriangleIndices(3, 9, 4),
                                                new TriangleIndices(3, 4, 2),
                                                new TriangleIndices(3, 2, 6),
                                                new TriangleIndices(3, 6, 8),
                                                new TriangleIndices(3, 8, 9),
                                                // 5 adjacent faces
                                                new TriangleIndices(4, 9, 5),
                                                new TriangleIndices(2, 4, 11),
                                                new TriangleIndices(6, 2, 10),
                                                new TriangleIndices(8, 6, 7),
                                                new TriangleIndices(9, 8, 1)
                                            };

      // refine triangles
      for (var i = 0; i < recursion_level; i++) {
        var faces2 = new List<TriangleIndices>();
        for (var index = 0; index < faces.Count; index++) {
          var tri = faces[index : index];
// replace triangle by 4 triangles
          var a = GetMiddlePoint(p1 : tri._V1,
                                 p2 : tri._V2,
                                 vertices : ref vert_list,
                                 cache : ref middle_point_index_cache,
                                 radius : radius);
          var b = GetMiddlePoint(p1 : tri._V2,
                                 p2 : tri._V3,
                                 vertices : ref vert_list,
                                 cache : ref middle_point_index_cache,
                                 radius : radius);
          var c = GetMiddlePoint(p1 : tri._V3,
                                 p2 : tri._V1,
                                 vertices : ref vert_list,
                                 cache : ref middle_point_index_cache,
                                 radius : radius);

          faces2.Add(item : new TriangleIndices(v1 : tri._V1, v2 : a, v3 : c));
          faces2.Add(item : new TriangleIndices(v1 : tri._V2, v2 : b, v3 : a));
          faces2.Add(item : new TriangleIndices(v1 : tri._V3, v2 : c, v3 : b));
          faces2.Add(item : new TriangleIndices(v1 : a, v2 : b, v3 : c));
        }

        faces = faces2;
      }

      mesh.vertices = vert_list.ToArray();

      var tri_list = new List<int>();
      for (var i = 0; i < faces.Count; i++) {
        tri_list.Add(item : faces[index : i]._V1);
        tri_list.Add(item : faces[index : i]._V2);
        tri_list.Add(item : faces[index : i]._V3);
      }

      mesh.triangles = tri_list.ToArray();
      mesh.uv = new Vector2[vert_list.Count];

      var normals = new Vector3[vert_list.Count];
      for (var i = 0; i < normals.Length; i++) {
        normals[i] = vert_list[index : i].normalized;
      }

      mesh.normals = normals;

      mesh.RecalculateBounds();

      return mesh;
    }

19 Source : MeshUtility.cs
with Apache License 2.0
from aivclab

public static Mesh GenerateSpotlightCircleMesh(Camera main) {
      if (!main) {
        return null;
      }

      const int circle_segment_count = 64;
      const int circle_vertex_count = circle_segment_count + 2;
      const int circle_index_count = circle_segment_count * 3;
      const Single segment_width = Mathf.PI * 2f / circle_segment_count;

      var circle = new Mesh();
      var vertices = new List<Vector3>(capacity : circle_vertex_count);
      var indices = new int[circle_index_count];

      var angle = 0f;
      vertices.Add(item : Vector3.zero);
      for (var i = 1; i < circle_vertex_count; ++i) {
        vertices.Add(item : new Vector3(x : Mathf.Cos(f : angle), y : Mathf.Sin(f : angle), 0f));
        angle -= segment_width;
        if (i > 1) {
          var j = (i - 2) * 3;
          indices[j + 0] = 0;
          indices[j + 1] = i - 1;
          indices[j + 2] = i;
        }
      }

      circle.SetVertices(inVertices : vertices);
      circle.SetIndices(indices : indices, topology : MeshTopology.Triangles, 0);


      //var x1 = Mathf.Tan(main.fieldOfView * 0.5f * Mathf.Deg2Rad) * main.aspect * main.nearClipPlane;
      //var y1 = Mathf.Tan(main.fieldOfView * 0.5f * Mathf.Deg2Rad) * main.nearClipPlane;
      //var z1 = main.nearClipPlane;

      //normals
      var normals_list = new List<Vector3>();
      for (var i = 0; i < vertices.Count; i++) {
        normals_list.Add(item : Vector3.forward);
      }

      circle.SetNormals(inNormals : normals_list);
      //circle.RecalculateNormals();
      circle.RecalculateBounds();
      //circle.Optimize();
      return circle;
    }

19 Source : MeshUtility.cs
with Apache License 2.0
from aivclab

public static Mesh GenerateSpotlightCircleMesh(Camera main) {
      if (!main) {
        return null;
      }

      const int circle_segment_count = 64;
      const int circle_vertex_count = circle_segment_count + 2;
      const int circle_index_count = circle_segment_count * 3;
      const Single segment_width = Mathf.PI * 2f / circle_segment_count;

      var circle = new Mesh();
      var vertices = new List<Vector3>(capacity : circle_vertex_count);
      var indices = new int[circle_index_count];

      var angle = 0f;
      vertices.Add(item : Vector3.zero);
      for (var i = 1; i < circle_vertex_count; ++i) {
        vertices.Add(item : new Vector3(x : Mathf.Cos(f : angle), y : Mathf.Sin(f : angle), 0f));
        angle -= segment_width;
        if (i > 1) {
          var j = (i - 2) * 3;
          indices[j + 0] = 0;
          indices[j + 1] = i - 1;
          indices[j + 2] = i;
        }
      }

      circle.SetVertices(inVertices : vertices);
      circle.SetIndices(indices : indices, topology : MeshTopology.Triangles, 0);


      //var x1 = Mathf.Tan(main.fieldOfView * 0.5f * Mathf.Deg2Rad) * main.aspect * main.nearClipPlane;
      //var y1 = Mathf.Tan(main.fieldOfView * 0.5f * Mathf.Deg2Rad) * main.nearClipPlane;
      //var z1 = main.nearClipPlane;

      //normals
      var normals_list = new List<Vector3>();
      for (var i = 0; i < vertices.Count; i++) {
        normals_list.Add(item : Vector3.forward);
      }

      circle.SetNormals(inNormals : normals_list);
      //circle.RecalculateNormals();
      circle.RecalculateBounds();
      //circle.Optimize();
      return circle;
    }

19 Source : MeshUtility.cs
with Apache License 2.0
from aivclab

public static Mesh GenerateSpotlightCircleMesh2( Camera main, float radius = 1f, int n = 60) {
      if (!main) {
        return null;
      }
      var mesh = new Mesh();

      var vertices_list = new List<Vector3> { };
      float x;
      float y;
      for (var i = 0; i < n; i++) {
        x = radius * Mathf.Sin(f : (2 * Mathf.PI * i) / n);
        y = radius * Mathf.Cos(f : (2 * Mathf.PI * i) / n);
        vertices_list.Add(item : new Vector3(x : x, y : y, 0f));
      }

      var vertices = vertices_list.ToArray();

      //triangles
      var triangles_list = new List<int> { };
      for (var i = 0; i < (n - 2); i++) {
        triangles_list.Add(0);
        triangles_list.Add(item : i + 1);
        triangles_list.Add(item : i + 2);
      }

      var triangles = triangles_list.ToArray();

      var x1 = Mathf.Tan(f : main.fieldOfView * 0.5f * Mathf.Deg2Rad) * main.aspect * main.nearClipPlane;
      var y1 = Mathf.Tan(f : main.fieldOfView * 0.5f * Mathf.Deg2Rad) * main.nearClipPlane;
      var z1 = main.nearClipPlane;

      //normals
      var normals_list = new List<Vector3> { };
      for (var i = 0; i < vertices.Length; i++) {
        normals_list.Add(item : Vector3.forward);
      }

      var normals = normals_list.ToArray();

      //initialise
      mesh.vertices = vertices;
      mesh.triangles = triangles;
      mesh.normals = normals;

      return mesh;
    }

19 Source : MeshUtility.cs
with Apache License 2.0
from aivclab

public static Mesh GenerateSpotlightCircleMesh2( Camera main, float radius = 1f, int n = 60) {
      if (!main) {
        return null;
      }
      var mesh = new Mesh();

      var vertices_list = new List<Vector3> { };
      float x;
      float y;
      for (var i = 0; i < n; i++) {
        x = radius * Mathf.Sin(f : (2 * Mathf.PI * i) / n);
        y = radius * Mathf.Cos(f : (2 * Mathf.PI * i) / n);
        vertices_list.Add(item : new Vector3(x : x, y : y, 0f));
      }

      var vertices = vertices_list.ToArray();

      //triangles
      var triangles_list = new List<int> { };
      for (var i = 0; i < (n - 2); i++) {
        triangles_list.Add(0);
        triangles_list.Add(item : i + 1);
        triangles_list.Add(item : i + 2);
      }

      var triangles = triangles_list.ToArray();

      var x1 = Mathf.Tan(f : main.fieldOfView * 0.5f * Mathf.Deg2Rad) * main.aspect * main.nearClipPlane;
      var y1 = Mathf.Tan(f : main.fieldOfView * 0.5f * Mathf.Deg2Rad) * main.nearClipPlane;
      var z1 = main.nearClipPlane;

      //normals
      var normals_list = new List<Vector3> { };
      for (var i = 0; i < vertices.Length; i++) {
        normals_list.Add(item : Vector3.forward);
      }

      var normals = normals_list.ToArray();

      //initialise
      mesh.vertices = vertices;
      mesh.triangles = triangles;
      mesh.normals = normals;

      return mesh;
    }

19 Source : ComplexThrowable.cs
with MIT License
from ajayyy

private void PhysicsAttach( Hand hand )
		{
			PhysicsDetach( hand );

			Rigidbody holdingBody = null;
			Vector3 holdingPoint = Vector3.zero;

			// The hand should grab onto the nearest rigid body
			float closestDistance = float.MaxValue;
			for ( int i = 0; i < rigidBodies.Count; i++ )
			{
				float distance = Vector3.Distance( rigidBodies[i].worldCenterOfMreplaced, hand.transform.position );
				if ( distance < closestDistance )
				{
					holdingBody = rigidBodies[i];
					closestDistance = distance;
				}
			}

			// Couldn't grab onto a body
			if ( holdingBody == null )
				return;

			// Create a fixed joint from the hand to the holding body
			if ( attachMode == AttachMode.FixedJoint )
			{
				Rigidbody handRigidbody = Util.FindOrAddComponent<Rigidbody>( hand.gameObject );
				handRigidbody.isKinematic = true;

				FixedJoint handJoint = hand.gameObject.AddComponent<FixedJoint>();
				handJoint.connectedBody = holdingBody;
			}

			// Don't let the hand interact with other things while it's holding us
			hand.HoverLock( null );

			// Affix this point
			Vector3 offset = hand.transform.position - holdingBody.worldCenterOfMreplaced;
			offset = Mathf.Min( offset.magnitude, 1.0f ) * offset.normalized;
			holdingPoint = holdingBody.transform.InverseTransformPoint( holdingBody.worldCenterOfMreplaced + offset );

			hand.AttachObject( this.gameObject, attachmentFlags );

			// Update holding list
			holdingHands.Add( hand );
			holdingBodies.Add( holdingBody );
			holdingPoints.Add( holdingPoint );
		}

19 Source : Path.cs
with MIT License
from Alan-FGR

public List<Vector3> SubdivideEvenly(int divisions)
        {
            List<Vector3> verts = new List<Vector3>();

            float length = GetLength();

            float deltaLength = length / divisions + 0.001f;
            float t = 0.000f;

            // we always start at the first control point
            Vector2 start = ControlPoints[0];
            Vector2 end = GetPosition(t);

            // increment t until we are at half the distance
            while (deltaLength * 0.5f >= Vector2.Distance(start, end))
            {
                end = GetPosition(t);
                t += 0.0001f;

                if (t >= 1f)
                    break;
            }

            start = end;

            // for each box
            for (int i = 1; i < divisions; i++)
            {
                Vector2 normal = GetPositionNormal(t);
                float angle = (float)Math.Atan2(normal.Y, normal.X);

                verts.Add(new Vector3(end, angle));

                // until we reach the correct distance down the curve
                while (deltaLength >= Vector2.Distance(start, end))
                {
                    end = GetPosition(t);
                    t += 0.00001f;

                    if (t >= 1f)
                        break;
                }
                if (t >= 1f)
                    break;

                start = end;
            }
            return verts;
        }

19 Source : AstronautDirections.cs
with MIT License
from alen-smajic

void HandleDirectionsResponse(DirectionsResponse response)
		{
			if (null == response.Routes || response.Routes.Count < 1)
			{
				return;
			}

			var dat = new List<Vector3>();
			foreach (var point in response.Routes[0].Geometry)
			{
				dat.Add(Conversions.GeoToWorldPosition(point.x, point.y, _map.CenterMercator, _map.WorldRelativeScale).ToVector3xz());
			}

			callback(dat);
		}

19 Source : LowPolyTerrainStrategy.cs
with MIT License
from alen-smajic

private void CreateBaseMesh(UnityTile tile)
		{
			//TODO use arrays instead of lists
			_newVertexList.Clear();
			_newNormalList.Clear();
			_newUvList.Clear();
			_newTriangleList.Clear();

			var cap = (_elevationOptions.modificationOptions.sampleCount - 1);
			for (float y = 0; y < cap; y++)
			{
				for (float x = 0; x < cap; x++)
				{
					var x1 = tile.TileScale * (float)(Mathd.Lerp(tile.Rect.Min.x, tile.Rect.Max.x, x / cap) - tile.Rect.Center.x);
					var y1 = tile.TileScale * (float)(Mathd.Lerp(tile.Rect.Min.y, tile.Rect.Max.y, y / cap) - tile.Rect.Center.y);
					var x2 = tile.TileScale * (float)(Mathd.Lerp(tile.Rect.Min.x, tile.Rect.Max.x, (x + 1) / cap) - tile.Rect.Center.x);
					var y2 = tile.TileScale * (float)(Mathd.Lerp(tile.Rect.Min.y, tile.Rect.Max.y, (y + 1) / cap) - tile.Rect.Center.y);

					var triStart = _newVertexList.Count;
					_newVertexList.Add(new Vector3(x1, 0, y1));
					_newVertexList.Add(new Vector3(x2, 0, y1));
					_newVertexList.Add(new Vector3(x1, 0, y2));
					//--
					_newVertexList.Add(new Vector3(x2, 0, y1));
					_newVertexList.Add(new Vector3(x2, 0, y2));
					_newVertexList.Add(new Vector3(x1, 0, y2));

					_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
					_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
					_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
					//--
					_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
					_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
					_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);


					_newUvList.Add(new Vector2(x / cap, 1 - y / cap));
					_newUvList.Add(new Vector2((x + 1) / cap, 1 - y / cap));
					_newUvList.Add(new Vector2(x / cap, 1 - (y + 1) / cap));
					//--
					_newUvList.Add(new Vector2((x + 1) / cap, 1 - y / cap));
					_newUvList.Add(new Vector2((x + 1) / cap, 1 - (y + 1) / cap));
					_newUvList.Add(new Vector2(x / cap, 1 - (y + 1) / cap));

					_newTriangleList.Add(triStart);
					_newTriangleList.Add(triStart + 1);
					_newTriangleList.Add(triStart + 2);
					//--
					_newTriangleList.Add(triStart + 3);
					_newTriangleList.Add(triStart + 4);
					_newTriangleList.Add(triStart + 5);
				}
			}


			var mesh = tile.MeshFilter.sharedMesh;
			mesh.indexFormat = IndexFormat.UInt32;
			mesh.SetVertices(_newVertexList);
			mesh.SetNormals(_newNormalList);
			mesh.SetUVs(0, _newUvList);
			mesh.SetTriangles(_newTriangleList, 0);
			mesh.RecalculateBounds();
		}

19 Source : LoftModifier.cs
with MIT License
from alen-smajic

public override void Run(VectorFeatureUnity feature, MeshData md, UnityTile tile = null)
		{
			if (feature.Points.Count < 1)
				return;

			foreach (var roadSegment in feature.Points)
			{
				_counter = roadSegment.Count;
				if (_counter <= 1)
					continue;

				var vl = new List<Vector3>(_sliceCount * _counter);
				var edges = new List<Vector3>(_counter);
				int co = 0;

				for (int j = 0; j < _counter; j++)
				{
					var current = Constants.Math.Vector3Zero;

					current = roadSegment[j];
					Vector3 dirCurrent, dir1, dir2;
					if (j > 0 && j < (_counter - 1))
					{
						dir1 = (roadSegment[j] - roadSegment[j - 1]).normalized;
						dir2 = (roadSegment[j + 1] - roadSegment[j]).normalized;
						dirCurrent = (dir2 + dir1).normalized;
					}
					else if (j == 0) //first
					{
						dirCurrent = (roadSegment[j + 1] - roadSegment[j]).normalized;
					}
					else //last
					{
						dirCurrent = (roadSegment[j] - roadSegment[j - 1]).normalized;
					}
					var q = Quaternion.LookRotation(dirCurrent);

					co = _slice.Count;
					for (int i = 0; i < co; i++)
					{
						var p = q * _slice[i];
						vl.Add(p + current);
						if (i == co - 1) //last item capped
						{
							edges.Add(p + current);
						}
					}
				}

				if (md.Triangles.Count == 0)
				{
					md.Triangles.Add(new List<int>());
				}
				md.Vertices.Capacity = md.Vertices.Count + (vl.Count - _sliceCount) * 4;
				md.Normals.Capacity = md.Normals.Count + (vl.Count - _sliceCount) * 4;
				md.Triangles.Capacity = md.Triangles.Count + (vl.Count - _sliceCount) * 6;
				
				var uvDist = 0f;
				float edMag = 0f, h = 0f;
				co = 0;
				Vector3 norm;

				for (int i = 0; i < _counter - 1; i++)
				{
					for (int j = 0; j < _sliceCount - 1; j++)
					{
						var ind = i * _sliceCount + j;
						var ed = vl[ind + _sliceCount] - vl[ind];
						edMag = ed.magnitude;
						co = md.Vertices.Count;
						norm = Vector3.Cross(vl[ind] - vl[ind + 1], vl[ind + _sliceCount] - vl[ind]).normalized;
						md.Vertices.Add(vl[ind]);
						md.Vertices.Add(vl[ind + 1]);
						md.Vertices.Add(vl[ind + _sliceCount]);
						md.Vertices.Add(vl[ind + _sliceCount + 1]);

						h = (float)j / _sliceCount;

						md.UV[0].Add(new Vector2(uvDist, ((float)j - 1) / _sliceCount));
						md.UV[0].Add(new Vector2(uvDist, h));
						md.UV[0].Add(new Vector2(uvDist + edMag, ((float)j - 1) / _sliceCount));
						md.UV[0].Add(new Vector2(uvDist + edMag, h));

						md.Tangents.Add(new Vector4(ed.normalized.x, ed.normalized.y, ed.normalized.z, 1));
						md.Tangents.Add(new Vector4(ed.normalized.x, ed.normalized.y, ed.normalized.z, 1));
						md.Tangents.Add(new Vector4(ed.normalized.x, ed.normalized.y, ed.normalized.z, 1));
						md.Tangents.Add(new Vector4(ed.normalized.x, ed.normalized.y, ed.normalized.z, 1));

						md.Normals.Add(norm);
						md.Normals.Add(norm);
						md.Normals.Add(norm);
						md.Normals.Add(norm);

						md.Triangles[0].Add(co);
						md.Triangles[0].Add(co + 2);
						md.Triangles[0].Add(co + 1);

						md.Triangles[0].Add(co + 1);
						md.Triangles[0].Add(co + 2);
						md.Triangles[0].Add(co + 3);
					}
					uvDist += edMag;
				}

				if (_closeEdges && edges.Count > 2)
				{
					if (md.Triangles.Count < 2)
					{
						md.Triangles.Add(new List<int>());
					}

					var flatData = EarcutLibrary.Flatten(new List<List<Vector3>>() { edges });
					var result = EarcutLibrary.Earcut(flatData.Vertices, flatData.Holes, flatData.Dim);

					md.Triangles[1].AddRange(result.Select(x => md.Vertices.Count + x).ToList());
					for (int i = 0; i < edges.Count; i++)
					{
						md.Vertices.Add(edges[i]);
						md.Normals.Add(Constants.Math.Vector3Up);
						md.UV[0].Add(new Vector2(edges[i].x, edges[i].z));
						md.Tangents.Add(new Vector4(1,0,0,1));
					}
				}
			}
		}

19 Source : MapBuilder.cs
with MIT License
from alen-smajic

IEnumerator WayBuilder()
    {
        float TargetCount = MapReader.ways.Count;
        Text PercentageDisplayer = InGameLoadingScreen.GetComponent<Text>();

        InGameLoadingWindow.SetActive(true);

        foreach (KeyValuePair<ulong, OsmWay> w in MapReader.ways)
        {
            // A simple loading progress logic, which returns the amount
            // of processed items divided by the total number of items.
            processed_items += 1;
            float loadingPercentage = processed_items / TargetCount * 100;

            if(loadingPercentage < 99) 
            {
                if(loadingPercentage > percentageAmount)
                {
                    percentageAmount += 1;
                    PercentageDisplayer.text = percentageAmount.ToString() + "%";
                }
            }
            else
            {
                InGameLoadingScreen.SetActive(false);
                InGameLoadingMessage.SetActive(false);
                InGameLoadingWindow.SetActive(false);
            }

            // Here we start the process of road/rail road instantiation.
            if (w.Value.PublicTransportStreet)
            {
                if (UserPreferences.PublicTransportStreets)
                {
                    inUse = bus_streets;
                }
                else
                {
                    inUse = null;
                    continue;
                }
            }
            else if (w.Value.PublicTransportRailway)
            {
                if (UserPreferences.PublicTransportRailways)
                {
                    if(!UserPreferences.Subways && !UserPreferences.Trams && !UserPreferences.Trains && !UserPreferences.Railways && !UserPreferences.LightRails)
                    {
                        inUse = public_transport_railways;
                    }
                    else if (w.Value.TransportTypes.Contains("subway"))
                    {
                        if (UserPreferences.Subways)
                        {
                            inUse = subways;
                        }
                        else
                        {
                            inUse = null;
                            continue;
                        }
                    }
                    else if (w.Value.TransportTypes.Contains("tram"))
                    {
                        if (UserPreferences.Trams)
                        {
                            inUse = trams;
                        }
                        else
                        {
                            inUse = null;
                            continue;
                        }
                    }
                    else if (w.Value.TransportTypes.Contains("train"))
                    {
                        if (UserPreferences.Trains)
                        {
                            inUse = trains;
                        }
                        else
                        {
                            inUse = null;
                            continue;
                        }
                    }
                    else if (w.Value.TransportTypes.Contains("railway"))
                    {
                        if (UserPreferences.Railways)
                        {
                            inUse = railway;
                        }
                        else
                        {
                            inUse = null;
                            continue;
                        }
                    }
                    else if (w.Value.TransportTypes.Contains("light_rail"))
                    {
                        if (UserPreferences.LightRails)
                        {
                            inUse = light_rails;
                        }
                        else
                        {
                            inUse = null;
                            continue;
                        }
                    }
                    else
                    {
                        inUse = null;
                        continue;
                    }
                    
                }
            }
            else
            {
                inUse = null;
                continue;
            }
                                             
            GameObject go = new GameObject();
            var waytext = go.AddComponent<Text>();
            foreach (string tramline in w.Value.TransportLines)
            {
                waytext.text += tramline + ", ";
            }
            Vector3 localOrigin = GetCentre(w.Value);
            go.transform.position = localOrigin - MapReader.bounds.Centre;

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

            mr.material = inUse;

            // Here we store the vectors, normales and indexes.
            List<Vector3> vectors = new List<Vector3>();  
            List<Vector3> normals = new List<Vector3>();
            List<int> indicies = new List<int>();

            for (int i = 1; i < w.Value.NodeIDs.Count; i++)
            {
                OsmNode p1 = MapReader.nodes[w.Value.NodeIDs[i - 1]];
                OsmNode p2 = MapReader.nodes[w.Value.NodeIDs[i]];

                Vector3 s1 = p1 - localOrigin;  
                Vector3 s2 = p2 - localOrigin;

                Vector3 diff = (s2 - s1).normalized;

                // The width of road and railroads is set to 1 meter.
                var cross = Vector3.Cross(diff, Vector3.up) * 1.0f; 

                Vector3 v1 = s1 + cross;
                Vector3 v2 = s1 - cross;
                Vector3 v3 = s2 + cross;
                Vector3 v4 = s2 - cross;

                vectors.Add(v1);  
                vectors.Add(v2);
                vectors.Add(v3);
                vectors.Add(v4);

                normals.Add(Vector3.up);  
                normals.Add(Vector3.up);
                normals.Add(Vector3.up);
                normals.Add(Vector3.up);

                int idx1, idx2, idx3, idx4;
                idx4 = vectors.Count - 1;
                idx3 = vectors.Count - 2;
                idx2 = vectors.Count - 3;
                idx1 = vectors.Count - 4;

                indicies.Add(idx1);
                indicies.Add(idx3);
                indicies.Add(idx2);

                indicies.Add(idx3);
                indicies.Add(idx4);
                indicies.Add(idx2);
            }
            go.name += w.Value.ID;
            mf.mesh.vertices = vectors.ToArray();
            mf.mesh.normals = normals.ToArray();
            mf.mesh.triangles = indicies.ToArray();

            yield return null;

            // Lastly we store the Unity coordinates of every generated way. This is then used later on
            // when we want to move the transport vehicles across the ways.
            for(int i = 0; i < w.Value.NodeIDs.Count; i++)
            {
                OsmNode p1 = MapReader.nodes[w.Value.NodeIDs[i]];
                w.Value.UnityCoordinates.Add(p1 - MapReader.bounds.Centre);
            }
        }
    }

19 Source : ElevatedTerrainWithSidesStrategy.cs
with MIT License
from alen-smajic

private void CreateBaseMesh(UnityTile tile)
		{
			//TODO use arrays instead of lists
			_newVertexList.Clear();
			_newNormalList.Clear();
			_newUvList.Clear();
			_newTriangleList.Clear();

			var _sampleCount = _elevationOptions.modificationOptions.sampleCount;
			for (float y = 0; y < _sampleCount; y++)
			{
				var yrat = y / (_sampleCount - 1);
				for (float x = 0; x < _sampleCount; x++)
				{
					var xrat = x / (_sampleCount - 1);

					var xx = Mathd.Lerp(tile.Rect.Min.x, tile.Rect.Max.x, xrat);
					var yy = Mathd.Lerp(tile.Rect.Min.y, tile.Rect.Max.y, yrat);

					_newVertexList.Add(new Vector3(
						(float)(xx - tile.Rect.Center.x) * tile.TileScale,
						0,
						(float)(yy - tile.Rect.Center.y) * tile.TileScale));
					_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
					_newUvList.Add(new Vector2(x * 1f / (_sampleCount - 1), 1 - (y * 1f / (_sampleCount - 1))));
				}
			}

			int vertA, vertB, vertC;
			for (int y = 0; y < _sampleCount - 1; y++)
			{
				for (int x = 0; x < _sampleCount - 1; x++)
				{
					vertA = (y * _sampleCount) + x;
					vertB = (y * _sampleCount) + x + _sampleCount + 1;
					vertC = (y * _sampleCount) + x + _sampleCount;
					_newTriangleList.Add(vertA);
					_newTriangleList.Add(vertB);
					_newTriangleList.Add(vertC);

					vertA = (y * _sampleCount) + x;
					vertB = (y * _sampleCount) + x + 1;
					vertC = (y * _sampleCount) + x + _sampleCount + 1;
					_newTriangleList.Add(vertA);
					_newTriangleList.Add(vertB);
					_newTriangleList.Add(vertC);
				}
			}

			var sideVertBase = _newVertexList.Count;

			var lastRow = (_sampleCount - 1) * _sampleCount;
			var baseTriList = new List<int>();
			for (int x = 0; x < _sampleCount; x++)
			{
				//side wall
				//024
				//135
				_newVertexList.Add(_newVertexList[x]);
				_newVertexList.Add(new Vector3(
					_newVertexList[x].x,
					-_elevationOptions.sideWallOptions.wallHeight,
					_newVertexList[x].z));
				_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Forward);
				_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Forward);
				_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 1));
				_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 0));

				//---

				_newVertexList.Add(_newVertexList[x * _sampleCount]);
				_newVertexList.Add(new Vector3(
						_newVertexList[x * _sampleCount].x,
					-_elevationOptions.sideWallOptions.wallHeight,
						_newVertexList[x * _sampleCount].z));
				_newNormalList.Add(Vector3.left);
				_newNormalList.Add(Vector3.left);
				_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 1));
				_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 0));

				//---

				_newVertexList.Add(_newVertexList[(x + 1) * _sampleCount - 1]);
				_newVertexList.Add(new Vector3(
						_newVertexList[(x + 1) * _sampleCount - 1].x,
					-_elevationOptions.sideWallOptions.wallHeight,
						_newVertexList[(x + 1) * _sampleCount - 1].z));
				_newNormalList.Add(Vector3.right);
				_newNormalList.Add(Vector3.right);
				_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 1));
				_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 0));

				//---

				_newVertexList.Add(_newVertexList[lastRow + x]);
				_newVertexList.Add(new Vector3(
					_newVertexList[lastRow + x].x,
					-_elevationOptions.sideWallOptions.wallHeight,
					_newVertexList[lastRow + x].z));
				_newNormalList.Add(Vector3.back);
				_newNormalList.Add(Vector3.back);
				_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 1));
				_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 0));

				if (x > 0)
				{
					baseTriList.Add(sideVertBase + 8 * x);
					baseTriList.Add(sideVertBase + 8 * x - 8);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 1);

					baseTriList.Add(sideVertBase + 8 * x);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 1);
					baseTriList.Add(sideVertBase + 8 * x + 1);

					//---

					baseTriList.Add(sideVertBase + 8 * x + 2);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 1 + 2);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 2);

					baseTriList.Add(sideVertBase + 8 * x + 2);
					baseTriList.Add(sideVertBase + 8 * x + 1 + 2);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 1 + 2);

					//---

					baseTriList.Add(sideVertBase + 8 * x + 4);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 4);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 1 + 4);

					baseTriList.Add(sideVertBase + 8 * x + 4);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 1 + 4);
					baseTriList.Add(sideVertBase + 8 * x + 1 + 4);

					//---

					baseTriList.Add(sideVertBase + 8 * x + 6);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 1 + 6);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 6);

					baseTriList.Add(sideVertBase + 8 * x + 6);
					baseTriList.Add(sideVertBase + 8 * x + 1 + 6);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 1 + 6);
				}
			}


			var mesh = tile.MeshFilter.mesh;
			mesh.SetVertices(_newVertexList);
			mesh.SetNormals(_newNormalList);
			mesh.SetUVs(0, _newUvList);
			mesh.subMeshCount = 2;
			mesh.SetTriangles(_newTriangleList, 0);
			mesh.SetTriangles(baseTriList, 1);
		}

19 Source : ElevatedTerrainWithSidesStrategy.cs
with MIT License
from alen-smajic

private void CreateBaseMesh(UnityTile tile)
		{
			//TODO use arrays instead of lists
			_newVertexList.Clear();
			_newNormalList.Clear();
			_newUvList.Clear();
			_newTriangleList.Clear();

			var _sampleCount = _elevationOptions.modificationOptions.sampleCount;
			for (float y = 0; y < _sampleCount; y++)
			{
				var yrat = y / (_sampleCount - 1);
				for (float x = 0; x < _sampleCount; x++)
				{
					var xrat = x / (_sampleCount - 1);

					var xx = Mathd.Lerp(tile.Rect.Min.x, tile.Rect.Max.x, xrat);
					var yy = Mathd.Lerp(tile.Rect.Min.y, tile.Rect.Max.y, yrat);

					_newVertexList.Add(new Vector3(
						(float)(xx - tile.Rect.Center.x) * tile.TileScale,
						0,
						(float)(yy - tile.Rect.Center.y) * tile.TileScale));
					_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
					_newUvList.Add(new Vector2(x * 1f / (_sampleCount - 1), 1 - (y * 1f / (_sampleCount - 1))));
				}
			}

			int vertA, vertB, vertC;
			for (int y = 0; y < _sampleCount - 1; y++)
			{
				for (int x = 0; x < _sampleCount - 1; x++)
				{
					vertA = (y * _sampleCount) + x;
					vertB = (y * _sampleCount) + x + _sampleCount + 1;
					vertC = (y * _sampleCount) + x + _sampleCount;
					_newTriangleList.Add(vertA);
					_newTriangleList.Add(vertB);
					_newTriangleList.Add(vertC);

					vertA = (y * _sampleCount) + x;
					vertB = (y * _sampleCount) + x + 1;
					vertC = (y * _sampleCount) + x + _sampleCount + 1;
					_newTriangleList.Add(vertA);
					_newTriangleList.Add(vertB);
					_newTriangleList.Add(vertC);
				}
			}

			var sideVertBase = _newVertexList.Count;

			var lastRow = (_sampleCount - 1) * _sampleCount;
			var baseTriList = new List<int>();
			for (int x = 0; x < _sampleCount; x++)
			{
				//side wall
				//024
				//135
				_newVertexList.Add(_newVertexList[x]);
				_newVertexList.Add(new Vector3(
					_newVertexList[x].x,
					-_elevationOptions.sideWallOptions.wallHeight,
					_newVertexList[x].z));
				_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Forward);
				_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Forward);
				_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 1));
				_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 0));

				//---

				_newVertexList.Add(_newVertexList[x * _sampleCount]);
				_newVertexList.Add(new Vector3(
						_newVertexList[x * _sampleCount].x,
					-_elevationOptions.sideWallOptions.wallHeight,
						_newVertexList[x * _sampleCount].z));
				_newNormalList.Add(Vector3.left);
				_newNormalList.Add(Vector3.left);
				_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 1));
				_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 0));

				//---

				_newVertexList.Add(_newVertexList[(x + 1) * _sampleCount - 1]);
				_newVertexList.Add(new Vector3(
						_newVertexList[(x + 1) * _sampleCount - 1].x,
					-_elevationOptions.sideWallOptions.wallHeight,
						_newVertexList[(x + 1) * _sampleCount - 1].z));
				_newNormalList.Add(Vector3.right);
				_newNormalList.Add(Vector3.right);
				_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 1));
				_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 0));

				//---

				_newVertexList.Add(_newVertexList[lastRow + x]);
				_newVertexList.Add(new Vector3(
					_newVertexList[lastRow + x].x,
					-_elevationOptions.sideWallOptions.wallHeight,
					_newVertexList[lastRow + x].z));
				_newNormalList.Add(Vector3.back);
				_newNormalList.Add(Vector3.back);
				_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 1));
				_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 0));

				if (x > 0)
				{
					baseTriList.Add(sideVertBase + 8 * x);
					baseTriList.Add(sideVertBase + 8 * x - 8);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 1);

					baseTriList.Add(sideVertBase + 8 * x);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 1);
					baseTriList.Add(sideVertBase + 8 * x + 1);

					//---

					baseTriList.Add(sideVertBase + 8 * x + 2);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 1 + 2);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 2);

					baseTriList.Add(sideVertBase + 8 * x + 2);
					baseTriList.Add(sideVertBase + 8 * x + 1 + 2);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 1 + 2);

					//---

					baseTriList.Add(sideVertBase + 8 * x + 4);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 4);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 1 + 4);

					baseTriList.Add(sideVertBase + 8 * x + 4);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 1 + 4);
					baseTriList.Add(sideVertBase + 8 * x + 1 + 4);

					//---

					baseTriList.Add(sideVertBase + 8 * x + 6);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 1 + 6);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 6);

					baseTriList.Add(sideVertBase + 8 * x + 6);
					baseTriList.Add(sideVertBase + 8 * x + 1 + 6);
					baseTriList.Add(sideVertBase + 8 * x - 8 + 1 + 6);
				}
			}


			var mesh = tile.MeshFilter.mesh;
			mesh.SetVertices(_newVertexList);
			mesh.SetNormals(_newNormalList);
			mesh.SetUVs(0, _newUvList);
			mesh.subMeshCount = 2;
			mesh.SetTriangles(_newTriangleList, 0);
			mesh.SetTriangles(baseTriList, 1);
		}

19 Source : LowPolyTerrainStrategy.cs
with MIT License
from alen-smajic

private void CreateBaseMesh(UnityTile tile)
		{
			//TODO use arrays instead of lists
			_newVertexList.Clear();
			_newNormalList.Clear();
			_newUvList.Clear();
			_newTriangleList.Clear();

			var cap = (_elevationOptions.modificationOptions.sampleCount - 1);
			for (float y = 0; y < cap; y++)
			{
				for (float x = 0; x < cap; x++)
				{
					var x1 = tile.TileScale * (float)(Mathd.Lerp(tile.Rect.Min.x, tile.Rect.Max.x, x / cap) - tile.Rect.Center.x);
					var y1 = tile.TileScale * (float)(Mathd.Lerp(tile.Rect.Min.y, tile.Rect.Max.y, y / cap) - tile.Rect.Center.y);
					var x2 = tile.TileScale * (float)(Mathd.Lerp(tile.Rect.Min.x, tile.Rect.Max.x, (x + 1) / cap) - tile.Rect.Center.x);
					var y2 = tile.TileScale * (float)(Mathd.Lerp(tile.Rect.Min.y, tile.Rect.Max.y, (y + 1) / cap) - tile.Rect.Center.y);

					var triStart = _newVertexList.Count;
					_newVertexList.Add(new Vector3(x1, 0, y1));
					_newVertexList.Add(new Vector3(x2, 0, y1));
					_newVertexList.Add(new Vector3(x1, 0, y2));
					//--
					_newVertexList.Add(new Vector3(x2, 0, y1));
					_newVertexList.Add(new Vector3(x2, 0, y2));
					_newVertexList.Add(new Vector3(x1, 0, y2));

					_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
					_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
					_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
					//--
					_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
					_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
					_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);


					_newUvList.Add(new Vector2(x / cap, 1 - y / cap));
					_newUvList.Add(new Vector2((x + 1) / cap, 1 - y / cap));
					_newUvList.Add(new Vector2(x / cap, 1 - (y + 1) / cap));
					//--
					_newUvList.Add(new Vector2((x + 1) / cap, 1 - y / cap));
					_newUvList.Add(new Vector2((x + 1) / cap, 1 - (y + 1) / cap));
					_newUvList.Add(new Vector2(x / cap, 1 - (y + 1) / cap));

					_newTriangleList.Add(triStart);
					_newTriangleList.Add(triStart + 1);
					_newTriangleList.Add(triStart + 2);
					//--
					_newTriangleList.Add(triStart + 3);
					_newTriangleList.Add(triStart + 4);
					_newTriangleList.Add(triStart + 5);
				}
			}


			var mesh = tile.MeshFilter.sharedMesh;
			mesh.indexFormat = IndexFormat.UInt32;
			mesh.SetVertices(_newVertexList);
			mesh.SetNormals(_newNormalList);
			mesh.SetUVs(0, _newUvList);
			mesh.SetTriangles(_newTriangleList, 0);
			mesh.RecalculateBounds();
		}

19 Source : LineMeshModifier.cs
with MIT License
from alen-smajic

private void AddCurrentVertex(Vector3 vertexPosition, float dist, Vector3 normal, MeshData md, float endLeft = 0, float endRight = 0)
		{
			var triIndexStart = md.Vertices.Count;
			var extrude = normal;
			if (endLeft != 0)
			{
				extrude -= (normal.Perpendicular() * endLeft);
			}

			var vert = vertexPosition + extrude * _scaledWidth;
			_vertexList.Add(vert);
			_normalList.Add(Constants.Math.Vector3Up);
			_uvList.Add(new Vector2(1, dist));
			_tangentList.Add(normal.Perpendicular() * -1);

			_index3 = triIndexStart + _vertexList.Count - 1;
			if (_index1 >= triIndexStart && _index2 >= triIndexStart)
			{
				_triangleList.Add(_index1);
				_triangleList.Add(_index3);
				_triangleList.Add(_index2);
				md.Edges.Add(triIndexStart + _vertexList.Count - 1);
				md.Edges.Add(triIndexStart + _vertexList.Count - 3);
			}

			_index1 = _index2;
			_index2 = _index3;


			extrude = normal * -1;
			if (endRight != 0)
			{
				extrude -= normal.Perpendicular() * endRight;
			}

			_vertexList.Add(vertexPosition + extrude * _scaledWidth);
			_normalList.Add(Constants.Math.Vector3Up);
			_uvList.Add(new Vector2(0, dist));
			_tangentList.Add(normal.Perpendicular() * -1);

			_index3 = triIndexStart + _vertexList.Count - 1;
			if (_index1 >= triIndexStart && _index2 >= triIndexStart)
			{
				_triangleList.Add(_index1);
				_triangleList.Add(_index2);
				_triangleList.Add(_index3);
				md.Edges.Add(triIndexStart + _vertexList.Count - 3);
				md.Edges.Add(triIndexStart + _vertexList.Count - 1);
			}

			_index1 = _index2;
			_index2 = _index3;
		}

19 Source : SmoothLineModifier.cs
with MIT License
from alen-smajic

public override void Run(VectorFeatureUnity feature, MeshData md, UnityTile tile = null)
        {
			_counter = feature.Points.Count;

			for (int i = 0; i < _counter; i++)
            {
                var nl = new List<Vector3>();
				_counter2 = feature.Points[i].Count;
				for (int j = 1; j < _counter2; j++)
                {
                    nl.Add(feature.Points[i][j - 1]);
                    var dist = Vector3.Distance(feature.Points[i][j - 1], feature.Points[i][j]);
                    var step = Math.Min(_maxEdgeSectionCount, dist / _preferredEdgeSectionLength);
                    if (step > 1)
                    {
                        var counter = 1;
                        while (counter < step)
                        {
                            var nv = Vector3.Lerp(feature.Points[i][j - 1], feature.Points[i][j], Mathf.Min(1, counter / step));
                            nl.Add(nv);
                            counter++;
                        }
                    }
                    nl.Add(feature.Points[i][j]);
                }
                feature.Points[i] = nl;
            }
        }

19 Source : SortWay.cs
with MIT License
from alen-smajic

private void Start()
    {
        allWayCoordinates = new List<List<Vector3>>();
        SortedPathAndWays = new List<List<List<Vector3>>>();
        SplittedinPaths = new List<List<Vector3>>();
        PathsInRightOrder = new List<List<Vector3>>();

        MoveToTarget = new List<Vector3>();
        PathLastNode = new List<Vector3>();

        List<GameObject> allObjects = new List<GameObject>();
        Scene scene = SceneManager.GetActiveScene();
        scene.GetRootGameObjects(allObjects);

        // This for loop returns a list "allWayCoordinates" which contains more lists. Every list of these are way objects
        // which contain the node coordinates
        for (int i = 0; i < TranSportWayMarker.SelectedWays.Count; i++)
        {
            string ObjectName = allObjects[TranSportWayMarker.SelectedWays[i]].name;
            string ObjectID = ObjectName.Substring(15); // The ID of the way is being determined in order to search for it in the MapReader clreplaced.

            List<Vector3> WayNodes = new List<Vector3>();
            for (int j = 0; j < MapReader.ways[Convert.ToUInt64(ObjectID)].UnityCoordinates.Count; j++)
            {
                WayNodes.Add(MapReader.ways[Convert.ToUInt64(ObjectID)].UnityCoordinates[j]);
            }
            allWayCoordinates.Add(WayNodes); 
            // allWayCoordinates contains lists which represent the way objects. Every single one of these lists contains the node coordinates as values.
        }

        // Next we create a new list (SortedPathAndWays). This list merges the ways that belong to a common path.
        // E.g. if a bus line ends on one edge of the map and continues at another edge of the map, the corresponding ways will be stored in different lists.
        List<List<Vector3>> localList = new List<List<Vector3>>();
        localList.Add(allWayCoordinates[0]);
        SortedPathAndWays.Add(localList);
        allWayCoordinates.RemoveAt(0);

        // Is being called to sort the SortedPathAndWays with  respect to allWayCoordinates.
        SortList(allWayCoordinates, 0);

        // Here we transform the three-dimensional SortedPathAndWays list into a two-dimensional list. We do this by concatenating the inner lists
        // because these are already sorted.
        List<Vector3> temporaryList = new List<Vector3>();
        for(int i = 0; i < SortedPathAndWays.Count; i++) 
        {
            temporaryList = SortedPathAndWays[i].SelectMany(x => x).ToList();
            SplittedinPaths.Add(temporaryList);
        }

        for(int i = 0; i < TranSportWayMarker.StationOrder.Count; i++)
        {
            for(int j = 0; j < SplittedinPaths.Count; j++)
            {
                for(int k = 0; k < SplittedinPaths[j].Count; k++)
                {
                    if(TranSportWayMarker.StationOrder[i] == SplittedinPaths[j][k])
                    {
                        if (PathsInRightOrder.Contains(SplittedinPaths[j]))
                        {
                            break;
                        }
                        else
                        {
                            PathsInRightOrder.Add(SplittedinPaths[j]);
                        }
                    }
                }
            }
        }

        // Append paths which dont contain any station at the end.
        for(int i = 0; i < SplittedinPaths.Count; i++)
        {
            if (!PathsInRightOrder.Contains(SplittedinPaths[i]))
            {
                PathsInRightOrder.Add(SplittedinPaths[i]);
            }
        }

        // Switch the direction of the values within the paths using the stations.
        int firstIndex = -1;
        int secondIndex = -1;
        for(int i = 0; i < TranSportWayMarker.StationOrder.Count; i++)
        {
            for(int k = 0; k < PathsInRightOrder.Count; k++)
            {
                for(int j = 0; j < PathsInRightOrder[k].Count; j++)
                {
                    if(TranSportWayMarker.StationOrder[i] == PathsInRightOrder[k][j])
                    {
                        if(firstIndex == -1)
                        {
                            firstIndex = j;
                            break;
                        }
                        else
                        {
                            secondIndex = j;
                            break;
                        }
                    }
                }
                if(firstIndex != -1 && secondIndex != -1)
                {
                    if(firstIndex > secondIndex)
                    {
                        PathsInRightOrder[k].Reverse();
                        break;
                    }
                }
            }
        }

        for(int i = 0; i < PathsInRightOrder.Count; i++)
        {
            for(int j = 0; j < SortWay.PathsInRightOrder[i].Count; j++)
            {
                MoveToTarget.Add(SortWay.PathsInRightOrder[i][j]);
            }
        }

        if(SortWay.PathsInRightOrder.Count > 1)
        {
            for(int i = 0; i < PathsInRightOrder.Count; i++)
            {
                PathLastNode.Add(PathsInRightOrder[i][PathsInRightOrder[i].Count - 1]);
            }
        }

        IdentifyVehicle();
    }

19 Source : SortWay.cs
with MIT License
from alen-smajic

private void Start()
    {
        allWayCoordinates = new List<List<Vector3>>();
        SortedPathAndWays = new List<List<List<Vector3>>>();
        SplittedinPaths = new List<List<Vector3>>();
        PathsInRightOrder = new List<List<Vector3>>();

        MoveToTarget = new List<Vector3>();
        PathLastNode = new List<Vector3>();

        List<GameObject> allObjects = new List<GameObject>();
        Scene scene = SceneManager.GetActiveScene();
        scene.GetRootGameObjects(allObjects);

        // This for loop returns a list "allWayCoordinates" which contains more lists. Every list of these are way objects
        // which contain the node coordinates
        for (int i = 0; i < TranSportWayMarker.SelectedWays.Count; i++)
        {
            string ObjectName = allObjects[TranSportWayMarker.SelectedWays[i]].name;
            string ObjectID = ObjectName.Substring(15); // The ID of the way is being determined in order to search for it in the MapReader clreplaced.

            List<Vector3> WayNodes = new List<Vector3>();
            for (int j = 0; j < MapReader.ways[Convert.ToUInt64(ObjectID)].UnityCoordinates.Count; j++)
            {
                WayNodes.Add(MapReader.ways[Convert.ToUInt64(ObjectID)].UnityCoordinates[j]);
            }
            allWayCoordinates.Add(WayNodes); 
            // allWayCoordinates contains lists which represent the way objects. Every single one of these lists contains the node coordinates as values.
        }

        // Next we create a new list (SortedPathAndWays). This list merges the ways that belong to a common path.
        // E.g. if a bus line ends on one edge of the map and continues at another edge of the map, the corresponding ways will be stored in different lists.
        List<List<Vector3>> localList = new List<List<Vector3>>();
        localList.Add(allWayCoordinates[0]);
        SortedPathAndWays.Add(localList);
        allWayCoordinates.RemoveAt(0);

        // Is being called to sort the SortedPathAndWays with  respect to allWayCoordinates.
        SortList(allWayCoordinates, 0);

        // Here we transform the three-dimensional SortedPathAndWays list into a two-dimensional list. We do this by concatenating the inner lists
        // because these are already sorted.
        List<Vector3> temporaryList = new List<Vector3>();
        for(int i = 0; i < SortedPathAndWays.Count; i++) 
        {
            temporaryList = SortedPathAndWays[i].SelectMany(x => x).ToList();
            SplittedinPaths.Add(temporaryList);
        }

        for(int i = 0; i < TranSportWayMarker.StationOrder.Count; i++)
        {
            for(int j = 0; j < SplittedinPaths.Count; j++)
            {
                for(int k = 0; k < SplittedinPaths[j].Count; k++)
                {
                    if(TranSportWayMarker.StationOrder[i] == SplittedinPaths[j][k])
                    {
                        if (PathsInRightOrder.Contains(SplittedinPaths[j]))
                        {
                            break;
                        }
                        else
                        {
                            PathsInRightOrder.Add(SplittedinPaths[j]);
                        }
                    }
                }
            }
        }

        // Append paths which dont contain any station at the end.
        for(int i = 0; i < SplittedinPaths.Count; i++)
        {
            if (!PathsInRightOrder.Contains(SplittedinPaths[i]))
            {
                PathsInRightOrder.Add(SplittedinPaths[i]);
            }
        }

        // Switch the direction of the values within the paths using the stations.
        int firstIndex = -1;
        int secondIndex = -1;
        for(int i = 0; i < TranSportWayMarker.StationOrder.Count; i++)
        {
            for(int k = 0; k < PathsInRightOrder.Count; k++)
            {
                for(int j = 0; j < PathsInRightOrder[k].Count; j++)
                {
                    if(TranSportWayMarker.StationOrder[i] == PathsInRightOrder[k][j])
                    {
                        if(firstIndex == -1)
                        {
                            firstIndex = j;
                            break;
                        }
                        else
                        {
                            secondIndex = j;
                            break;
                        }
                    }
                }
                if(firstIndex != -1 && secondIndex != -1)
                {
                    if(firstIndex > secondIndex)
                    {
                        PathsInRightOrder[k].Reverse();
                        break;
                    }
                }
            }
        }

        for(int i = 0; i < PathsInRightOrder.Count; i++)
        {
            for(int j = 0; j < SortWay.PathsInRightOrder[i].Count; j++)
            {
                MoveToTarget.Add(SortWay.PathsInRightOrder[i][j]);
            }
        }

        if(SortWay.PathsInRightOrder.Count > 1)
        {
            for(int i = 0; i < PathsInRightOrder.Count; i++)
            {
                PathLastNode.Add(PathsInRightOrder[i][PathsInRightOrder[i].Count - 1]);
            }
        }

        IdentifyVehicle();
    }

See More Examples