Example #1
0
    public void Init()
    {
        isEnable = shapes.Count > 0;
        if (!isEnable)
        {
            return;
        }

        var args = GetArgBufferData(shapes.Count);

        argsBuffer = new ComputeBuffer(1, args.Length * sizeof(uint), ComputeBufferType.IndirectArguments);
        argsBuffer.SetData(args);

        // Initialize buffer with the given population.
        var properties = new MeshProperties[shapes.Count];

        for (int i = 0; i < shapes.Count; i++)
        {
            var props = new MeshProperties();
            props.mat     = shapes[i].transform;
            props.color   = shapes[i].color;
            properties[i] = props;
        }

        meshPropertiesBuffer = new ComputeBuffer(shapes.Count, MeshProperties.Size());
        meshPropertiesBuffer.SetData(properties);
        material.SetBuffer("_Properties", meshPropertiesBuffer);
    }
Example #2
0
    void ObjLoaded(string name, GameObject target)
    {
        // update material for object here
        MeshProperties prop = g_meshProperties[name];

        foreach (MeshRenderer mr in target.GetComponentsInChildren <MeshRenderer>())
        {
            mr.material.color = prop.baseColour;
            // disable unused features
            mr.lightProbeUsage      = LightProbeUsage.Off;
            mr.reflectionProbeUsage = ReflectionProbeUsage.Off;
            mr.shadowCastingMode    = ShadowCastingMode.Off;
            mr.receiveShadows       = false;
            mr.enabled = false;
        }

        // create mesh collisder
        foreach (Transform child in target.transform)
        {
            GameObject go = child.gameObject;
            Mesh       m  = (go.GetComponent(typeof(MeshFilter)) as MeshFilter).mesh;
            if (m)
            {
                MeshCollider mc = go.AddComponent <MeshCollider>() as MeshCollider;
                mc.sharedMesh = m;
                mc.enabled    = false;
            }
        }
    }
Example #3
0
        private void InitializeBuffers()
        {
            int kernel = compute.FindKernel("CSMain");

            // Argument buffer used by DrawMeshInstancedIndirect.
            uint[] args = new uint[5] { 0, 0, 0, 0, 0 };
            // Arguments for drawing mesh.
            // 0 == number of triangle indices, 1 == population, others are only relevant if drawing submeshes.
            args[0] = (uint)mesh.GetIndexCount(0);
            args[1] = (uint)population;
            args[2] = (uint)mesh.GetIndexStart(0);
            args[3] = (uint)mesh.GetBaseVertex(0);
            argsBuffer = new ComputeBuffer(1, args.Length * sizeof(uint), ComputeBufferType.IndirectArguments);
            argsBuffer.SetData(args);

            // Initialize buffer with the given population.
            MeshProperties[] properties = new MeshProperties[population];
            for (int i = 0; i < population; i++)
            {
                MeshProperties props = new MeshProperties();
                Vector3 position = new Vector3(Random.Range(-range, range), Random.Range(-range, range), Random.Range(-range, range));
                Quaternion rotation = Quaternion.Euler(Random.Range(-180, 180), Random.Range(-180, 180), Random.Range(-180, 180));
                Vector3 scale = Vector3.one;

                props.mat = Matrix4x4.TRS(position, rotation, scale);
                props.color = Color.Lerp(Color.red, Color.blue, Random.value);

                properties[i] = props;
            }

            meshPropertiesBuffer = new ComputeBuffer(population, MeshProperties.Size());
            meshPropertiesBuffer.SetData(properties);
            compute.SetBuffer(kernel, "_Properties", meshPropertiesBuffer);
            material.SetBuffer("_Properties", meshPropertiesBuffer);
        }
Example #4
0
        private void Do()
        {
            GmshMeshGenerator meshGenerator  = new GmshMeshGenerator(configuration.GmshPath);
            MeshProperties    meshProperties = new MeshProperties
            {
                Size = Convert.ToDouble(tbDimensionFE.Text, CultureInfo.InvariantCulture),
                Type = (MeshType)cbTypeOfFE.SelectedItem,
            };
            List <string> files = ChooseFiles();

            foreach (string file in files.Where(File.Exists))
            {
                FileInfo     fileInfo  = new FileInfo(file);
                DxfDocument  doc       = DxfDocument.Load(file);
                DxfModel     model     = DxfManager.GetDxfModel(doc, tbFrameLayer.Text, tbShellLayer.Text);
                Model        meshModel = Solver.GetMeshModel(model);
                Mesh         mesh      = meshGenerator.GenerateMesh(meshModel, meshProperties);
                List <int[]> elements  = mesh.Connectivities
                                         .Select(con =>
                {
                    int[] ints = new int[con.Points.Length];
                    for (int index = 0; index < ints.Length; index++)
                    {
                        ints[index] = con.Points[index];
                    }
                    return(ints);
                })
                                         .ToList();
                Dictionary <int, double[]> points = mesh.Points
                                                    .ToDictionary(kvp => kvp.Key,
                                                                  kvp =>
                {
                    double[] point = new double[kvp.Value.Count];
                    for (var index = 0; index < point.Length; index++)
                    {
                        point[index] = kvp.Value[index];
                    }
                    return(point);
                });

                if (cbGenerateDXF.Checked)
                {
                    if (fileInfo.DirectoryName != null)
                    {
                        string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
                        string destinationPath          = Path.Combine(fileInfo.DirectoryName,
                                                                       path2: $"{fileNameWithoutExtension}_IMPORT_TO_SAP.dxf");
                        DxfManager.CreateDxfFile(destinationPath, elements, points);
                    }
                }
                if (cbImportSAP2000.Checked)
                {
                }
                //SAPmodelGenerator.ImportModel(elements, points);
            }
        }
Example #5
0
    void UpdateBuffers()
    {
        // Ensure submesh index is in range
        if (instanceMesh != null)
        {
            subMeshIndex = Mathf.Clamp(subMeshIndex, 0, instanceMesh.subMeshCount - 1);
        }

        // Positions
        if (meshPropertiesBuffer != null)
        {
            meshPropertiesBuffer.Release();
        }
        meshPropertiesBuffer = new ComputeBuffer(instanceCount, MeshProperties.Size());
        MeshProperties[] properties = new MeshProperties[instanceCount];
        for (int i = 0; i < instanceCount; i++)
        {
            float          angle    = Random.Range(0.0f, Mathf.PI * 2.0f);
            float          distance = Random.Range(20.0f, 100.0f);
            float          height   = Random.Range(-2.0f, 2.0f);
            float          size     = Random.Range(0.05f, 0.25f);
            MeshProperties props    = new MeshProperties();
            Vector3        position = new Vector3(Random.Range(-range, range), Random.Range(-range, range), Random.Range(-range, range));
            Quaternion     rotation = Quaternion.Euler(Random.Range(-180, 180), Random.Range(-180, 180), Random.Range(-180, 180));
            Vector3        scale    = Vector3.one * 5;

            props.mat = Matrix4x4.TRS(position, rotation, scale);
            // props.color = Color.Lerp(Color.red, Color.blue, Random.value);
            properties[i] = props;
        }
        meshPropertiesBuffer.SetData(properties);
        instanceMaterial.SetBuffer("_Properties", meshPropertiesBuffer);
        //instanceMaterial.SetTexture("_MainTex", t);

        // Indirect args
        if (instanceMesh != null)
        {
            args[0] = (uint)instanceMesh.GetIndexCount(subMeshIndex);
            args[1] = (uint)instanceCount;
            args[2] = (uint)instanceMesh.GetIndexStart(subMeshIndex);
            args[3] = (uint)instanceMesh.GetBaseVertex(subMeshIndex);
        }
        else
        {
            args[0] = args[1] = args[2] = args[3] = 0;
        }
        argsBuffer.SetData(args);

        cachedInstanceCount = instanceCount;
        cachedSubMeshIndex  = subMeshIndex;
    }
        public DotShaderData(Mesh dotMesh, int numDots)
        {
            MeshProps            = new MeshProperties[numDots];
            MeshPropertiesBuffer = new ComputeBuffer(numDots, MeshProperties.Size());

            var args = new uint[5]
            {
                dotMesh.GetIndexCount(0),
                (uint)numDots,
                dotMesh.GetIndexStart(0),
                dotMesh.GetBaseVertex(0),
                0
            };

            ArgsBuffer = new ComputeBuffer(1, args.Length * sizeof(uint), ComputeBufferType.IndirectArguments);
            ArgsBuffer.SetData(args);
        }
Example #7
0
    public GameObject GenerateMesh(string meshFile, string meshName, Vector3 scale)
    {
        MeshDataset dataset = new MeshDataset(meshFile);

        Vector3 max = new Vector3(int.MinValue, int.MinValue, int.MinValue);
        Vector3 min = new Vector3(int.MaxValue, int.MaxValue, int.MaxValue);

        // Creates root object to hold all the instantiated quads
        GameObject rootObject = new GameObject();

        rootObject.name = meshName;

        for (int faceIdx = 0; faceIdx < dataset.numFaces; faceIdx++)
        {
            Vector4    face = dataset.faces[faceIdx];
            GameObject quad = GameObject.Instantiate(quadToInstantiate, rootObject.transform, true) as GameObject;
            quad.transform.parent = rootObject.transform;

            Vector3 normal = CalculateQuadNormal(dataset, quad, face);
            quad.transform.position      = CalculateQuadPosition(dataset, quad, face);
            quad.transform.localRotation = CalculateQuadRotation(normal);
            ApplyMaterial(dataset, quad, face, normal);

            min = Vector3.Min(min, quad.transform.position);
            max = Vector3.Max(max, quad.transform.position);
        }

        rootObject.transform.localScale = scale;
        MeshProperties mp = rootObject.AddComponent <MeshProperties>();

        mp.min = Vector3.Scale(min, scale);
        mp.max = Vector3.Scale(max, scale);

        rootObject.tag = "LevelRoot";
        BoxCollider nextLevelTrigger = rootObject.AddComponent <BoxCollider>();

        nextLevelTrigger.size      = new Vector3(10, 2, 10);
        nextLevelTrigger.isTrigger = true;

        return(rootObject);
    }
Example #8
0
    public static MeshProperties GenerateTerrainMesh(float[,] noiseMap, float heightMultiplier, float levelArea, float levelOfDetail)
    {
        int   width    = noiseMap.GetLength(0);
        int   height   = noiseMap.GetLength(1);
        float topLeftX = (width - 1) / -2f; //allows centering of mesh
        float topLeftZ = (height - 1) / 2f; //allows centering of mesh

        if (levelOfDetail == 0)
        {
            levelOfDetail = 0.5f;
        }
        float increment = levelOfDetail * 2;

        int verticiesPerLine = (int)((width - 1) / increment) + 1;

        MeshProperties meshProp    = new MeshProperties(verticiesPerLine, verticiesPerLine);
        int            vertexIndex = 0;

        for (int y = 0; y < height; y += (int)increment) //Loop through map
        {
            for (int x = 0; x < width; x += (int)increment)
            {
                if (noiseMap[x, y] < levelArea)
                {
                    noiseMap[x, y] = levelArea;
                }
                meshProp.vertices[vertexIndex] = new Vector3(topLeftX + x, noiseMap[x, y] * heightMultiplier, topLeftZ - y);
                meshProp.uvs[vertexIndex]      = new Vector2(x / (float)width, y / (float)height);
                if (x < width - 1 && y < height - 1)                                                                       //Skip vertices on edge and bottom of map
                {
                    meshProp.AddTriangle(vertexIndex, vertexIndex + verticiesPerLine + 1, vertexIndex + verticiesPerLine); //triangle 1 (Has to draw them in clockwise for Unity)
                    meshProp.AddTriangle(vertexIndex + verticiesPerLine + 1, vertexIndex, vertexIndex + 1);                //triangle 2 to make a square
                }
                vertexIndex++;
            }
        }
        return(meshProp); //Sending properties rather than the mesh for threading
    }
Example #9
0
        public static MeshProperties GetMeshProperties(this Mesh mesh, double offsetDist, double jointWidth, double rotation, int[] maleFemale, double maxLength)
        {
            //Base structure to hold mesh and its properties
            MeshProperties mp = new MeshProperties();


            //Mesh
            mp.mesh = mesh; //NGonsCore.PolylineUtil.Loft(polylines.ToArray());

            //Vertices
            mp.nGonTV       = mp.mesh.GetNGonsTopoBoundaries(); //1.Get all edges
            mp.faceVertices = mp.mesh.GetNGonsBoundariesPoint3d(mp.mesh.GetNGonsBoundaries());
            mp.allV         = mp.mesh.GetAllNGonsTopoVertices();
            mp.vertexNGons  = mp.mesh.GetNGonsConnectedToNGonTopologyVertices(mp.allV, false);


            //Edges
            mp.allE     = mp.mesh.GetAllNGonEdges(mp.nGonTV);
            mp.allEDict = GrasshopperUtil.DictFromHash(mp.allE);
            mp.edgeV    = mp.mesh.GetAllNGonEdges_TopoVertices(mp.nGonTV, mp.allE);

            //Faces
            mp.ngonEdges = mp.mesh.GetNGonFacesEdges(mp.nGonTV);           //2.Get all edges in ngon faces
            mp.eNgons    = mp.mesh.GetNgonsConnectedToNGonsEdges(mp.allE); //3.Get ngons connected to edges

            //Planes
            Plane[] planes = mp.mesh.GetNgonPlanes();
            mp.planesO = planes;


            mp.planesOffset  = mp.planesO.MovePlaneArrayByAxis(offsetDist, -1, 2, false);
            mp.planesOffset2 = mp.planesO.MovePlaneArrayByAxis(offsetDist * 2, -1, 2, false);


            //Lines
            mp.innerLines  = mp.mesh.GetAllNGonEdgesLines(mp.allE); //Plane origin points will be on those lines
            mp.allVPoint3d = new Point3d[mp.allV.Count];            //id = allV
            Dictionary <int, Point3d> allVMoved = new Dictionary <int, Point3d>(mp.allV.Count);

            int n = 0;

            foreach (int id in mp.allV)
            {
                int[] nn = mp.vertexNGons[n];
                Rhino.Geometry.Intersect.Intersection.PlanePlanePlane(mp.planesOffset[nn[0]], mp.planesOffset[nn[1]],
                                                                      mp.planesOffset[nn[2]], out mp.allVPoint3d[n]);
                allVMoved.Add(id, mp.allVPoint3d[n]);
                n++;
            }

            for (int i = 0; i < mp.edgeV.Length; i++)
            {
                mp.innerLines[i] = new Line(allVMoved[mp.edgeV[i][0]], allVMoved[mp.edgeV[i][1]]);
            }

            //JointTypes
            //ToDo: Automate faces: start from bisectors that are 1-1, then full faces

            //Joints for 2 valence edges
            mp.jointTypes = new int[mp.allE.Count][];


            //Joint types automation which one is male, female or incase of bisecto none
            //1 - None 2 - Female, 3 - Male
            Dictionary <int, Plane> bisectors = new Dictionary <int, Plane>();

            double minAngle            = 3.14159 / 18 * 3;
            double maxAngle            = 3.14159 / 18 * 15;
            Dictionary <int, int> swap = new Dictionary <int, int>()
            {
                { 3, 2 }, { 2, 3 }
            };

            for (int i = 0; i < mp.allE.Count; i++)
            {
                int[] ngons = mp.eNgons[i];

                switch (ngons.Length)
                {
                //For naked Edges
                case (1):
                    mp.jointTypes[i] = new int[1] {
                        0
                    };
                    break;

                //For 2 valence edge
                case (2):
                    double angle = Vector3d.VectorAngle(planes[ngons[0]].ZAxis, planes[ngons[1]].ZAxis);
                    if (angle < minAngle || angle > maxAngle)
                    {
                        Plane bisector = NGonsCore.PlaneUtil.BisectorPlane(planes[ngons[0]], planes[ngons[1]]);
                        bisectors.Add(i, bisector);
                        mp.jointTypes[i] = new int[2] {
                            1, 1
                        };
                    }
                    else
                    {
                        int a = maleFemale[ngons[0]];
                        int b = maleFemale[ngons[1]];

                        if (a == 1 || b == 1)
                        {
                            mp.jointTypes[i] = new int[2] {
                                1, 1
                            }
                        }
                        ;
                        //else if (a == -1 || b == -1)
                        //mp.jointTypes[i] = new int[2] { -1, -1 };
                        else if (Math.Abs(a) != Math.Abs(b))
                        {
                            mp.jointTypes[i] = new int[2] {
                                Math.Abs(a), Math.Abs(b)
                            }
                        }
                        ;
                        else if (a == b)
                        {
                            mp.jointTypes[i] = new[] { 3, 2 }
                        }
                        ;
                        else if (a > b)
                        {
                            mp.jointTypes[i] = new[] { a, swap[Math.Abs(b)] }
                        }
                        ;
                        else
                        {
                            mp.jointTypes[i] = new[] { swap[Math.Abs(a)], b }
                        };
                    }
                    break;

                //ToDo: For n valence edges not implemented
                default:
                    mp.jointTypes[i] = Enumerable.Range(9, ngons.Length).ToArray();
                    break;
                } //Switch
            }     //For

            //Values
            mp.offsetDist = offsetDist;

            mp.maxLength = maxLength;

            mp.edgePlanes = EPlanes(mp.mesh, mp.allE, mp.allEDict, mp.planesO, mp.planesOffset, mp.eNgons, jointWidth, rotation, mp.innerLines, mp.ngonEdges, mp.jointTypes, mp.vertexNGons, mp.allV.ToArray(), mp.maxLength);


            //Output
            return(mp);
        }
Example #10
0
    private void Init()
    {
        population = faceWidth * faceWidth * 6;
        bounds     = new Bounds(transform.position, Vector3.one * faceWidth * 2);
        uint[] args = new uint[5] {
            0, 0, 0, 0, 0
        };
        // Arguments for drawing mesh.
        // 0 == number of triangle indices, 1 == population, others are only relevant if drawing submeshes.
        args[0]    = (uint)mesh.GetIndexCount(0);
        args[1]    = (uint)population;
        args[2]    = (uint)mesh.GetIndexStart(0);
        args[3]    = (uint)mesh.GetBaseVertex(0);
        argsBuffer = new ComputeBuffer(1, args.Length * sizeof(uint), ComputeBufferType.IndirectArguments);
        argsBuffer.SetData(args);

        //Job to calculate the positions of the pillars
        //CalculatePositionsJob calculatePositionsJob = new CalculatePositionsJob
        //{
        //    population = population,
        //    faceWidth = this.faceWidth,
        //    planetScale = this.planetScale,

        //    positions = new NativeArray<Vector3>(population, Allocator.TempJob)
        //};
        //JobHandle jobHandle = calculatePositionsJob.Schedule();
        //jobHandle.Complete();

        // Initialize buffer with the given population.
        MeshProperties[] properties = new MeshProperties[population];
        if (computePosAndRot)
        {
            for (int i = 0; i < population; i++)
            {
                MeshProperties props = new MeshProperties();
                //Vector3 position = calculatePositionsJob.positions[i];
                //Vector3 position = Vector3.zero;//Vector3.zero; // GetPillarPosition(i);
                //Quaternion rotation = Quaternion.identity;// Quaternion.identity; // GetPillarRotation(position);
                //Vector3 scale = Vector3.one / 100;

                //props.mat = Matrix4x4.TRS(position, rotation, scale);
                props.mat   = new Matrix4x4();
                props.color = new Color(Random.value, Random.value, Random.value);

                properties[i] = props;
            }
            //calculatePositionsJob.positions.Dispose();

            meshPropertiesBuffer = new ComputeBuffer(population, MeshProperties.Size());
            meshPropertiesBuffer.SetData(properties);

            int kernel = compute.FindKernel("CSMain");
            compute.SetBuffer(kernel, "_Properties", meshPropertiesBuffer);

            compute.SetVector("_CenterPosition", transform.position);
            compute.SetFloat("_PlanetScale", planetScale);
            compute.SetInt("_FaceWidth", faceWidth);
            Quaternion tempRot = Quaternion.Euler(0, 45, 0);
            compute.SetFloats("_DebugQuaternion", tempRot.x, tempRot.y, tempRot.z, tempRot.w);
            compute.Dispatch(kernel, Mathf.CeilToInt(population / 64f), 1, 1);
        }
        else
        {
            for (int i = 0; i < population; i++)
            {
                MeshProperties props = new MeshProperties();
                //Vector3 position = calculatePositionsJob.positions[i];
                Vector3    position = GetPillarPosition(i);        //Vector3.zero; // GetPillarPosition(i);
                Quaternion rotation = GetPillarRotation(position); // Quaternion.identity; // GetPillarRotation(position);
                Vector3    scale    = Vector3.one / 100;

                props.mat   = Matrix4x4.TRS(position, rotation, scale);
                props.color = Color.Lerp(Color.red, Color.blue, Random.value);

                properties[i] = props;
            }
            //calculatePositionsJob.positions.Dispose();

            meshPropertiesBuffer = new ComputeBuffer(population, MeshProperties.Size());
            meshPropertiesBuffer.SetData(properties);
        }
        //meshPropertiesBuffer.GetData(properties);
        //for (int i = 0; i < population; i++)
        //{
        //    UnityEngine.Debug.Log(new Vector3(properties[i].mat[0, 3], properties[i].mat[1, 3], properties[i].mat[2, 3]));
        //}
        material.SetBuffer("_Properties", meshPropertiesBuffer);
    }
Example #11
0
 public void DrawMesh(MeshProperties meshProp)
 {
     meshFilter.sharedMesh = meshProp.CreateMesh();
     //meshRenderer.sharedMaterial.mainTexture = newTexture;
     meshCollider.sharedMesh = meshProp.CreateMesh();
 }
    private void InitializeBuffers()
    {
        kernel = computeShader.FindKernel("CSMain");

        // Argument buffer used by DrawMeshInstancedIndirect.
        uint[] args = new uint[5] {
            0, 0, 0, 0, 0
        };
        // Arguments for drawing mesh.
        // 0 == number of triangle indices, 1 == population, others are only relevant if drawing submeshes.
        args[0]    = (uint)mesh.GetIndexCount(0);
        args[1]    = (uint)population;
        args[2]    = (uint)mesh.GetIndexStart(0);
        args[3]    = (uint)mesh.GetBaseVertex(0);
        argsBuffer = new ComputeBuffer(1, args.Length * sizeof(uint), ComputeBufferType.IndirectArguments);
        argsBuffer.SetData(args);
        //saturationArray ={0,9,0,6,0,8,0.8,0.9}
        // Initialize buffer with the given population.
        properties = new MeshProperties[population];
        // float satArray[] = [0.]
        for (int i = 0; i < population; i++)
        {
            if (i < 50)
            {
                MeshProperties props    = new MeshProperties();
                Vector3        position = new Vector3(Random.Range(-range / 2.0f, range / 2.0f), Random.Range(-range / 2.0f, range / 2.0f), Random.Range(-range / 2.0f, range / 2.0f));
                Quaternion     rotation = Quaternion.Euler(Random.Range(-180, 180), Random.Range(-180, 180), Random.Range(-180, 180));
                Vector3        scale    = new Vector3(5.0f, 5.0f, 5.0f);
                props.mat   = Matrix4x4.TRS(position, rotation, scale);
                props.color = Color.HSVToRGB(i * 0.02f, 1.0f, 1.0f);

                props.velocity = new Vector3(Random.Range(-0.2f, 0.2f), Random.Range(-0.2f, 0.2f), Random.Range(-0.2f, 0.2f));

                properties[i] = props;
            }
            else
            {
                MeshProperties props    = new MeshProperties();
                Vector3        position = new Vector3(Random.Range(-range / 2.0f, range / 2.0f), Random.Range(-range / 2.0f, range / 2.0f), Random.Range(-range / 2.0f, range / 2.0f));
                Quaternion     rotation = Quaternion.Euler(Random.Range(-180, 180), Random.Range(-180, 180), Random.Range(-180, 180));
                Vector3        scale    = new Vector3(0.5f, 0.5f, 0.5f);

                props.mat   = Matrix4x4.TRS(position, rotation, scale);
                props.color = Color.HSVToRGB(Random.Range(0.65f, 0.8f), Random.Range(0.4f, 0.6f), 1);

                props.velocity = new Vector3(Random.Range(-0.2f, 0.2f), Random.Range(-0.2f, 0.2f), Random.Range(-0.2f, 0.2f));

                properties[i] = props;
            }
        }

        meshPropertiesBuffer = new ComputeBuffer(population, MeshProperties.Size());
        meshPropertiesBuffer.SetData(properties);
        computeShader.SetBuffer(kernel, "_Properties", meshPropertiesBuffer); // for compute shader.
        material.SetBuffer("_Properties", meshPropertiesBuffer);              // for regular shader.

        currentVelocityArray  = new Vector3[population];
        currentVelocityBuffer = new ComputeBuffer(population, 12);
        currentVelocityBuffer.SetData(currentVelocityArray);
        computeShader.SetBuffer(kernel, "_currentVelocityBuffer", currentVelocityBuffer);

        cohVelocityArray  = new Vector3[population];
        cohVelocityBuffer = new ComputeBuffer(population, 12);
        cohVelocityBuffer.SetData(cohVelocityArray);
        computeShader.SetBuffer(kernel, "_cohVelocityBuffer", cohVelocityBuffer);

        alignVelocityArray  = new Vector3[population];
        alignVelocityBuffer = new ComputeBuffer(population, 12);
        alignVelocityBuffer.SetData(alignVelocityArray);
        computeShader.SetBuffer(kernel, "_alignVelocityBuffer", alignVelocityBuffer);

        avoidVelocityArray  = new Vector3[population];
        avoidVelocityBuffer = new ComputeBuffer(population, 12);
        avoidVelocityBuffer.SetData(avoidVelocityArray);
        computeShader.SetBuffer(kernel, "_avoidVelocityBuffer", avoidVelocityBuffer);
    }
Example #13
0
    public static MeshProperties[] CreateMesh(List <BoundaryPoint> genPoly, Transform objTrans, float spriteSquareSize)
    {
        const int   _FRONTOFFSET     = 3;
        const float _BACKFACE_OFFSET = 0.5f;
        const float _SCALE_FACTOR    = 1.1f;

        MeshProperties _generatedMesh;
        MeshProperties _frontFaceMesh;

        Vector2[] _genPolyArrFront = new Vector2[genPoly.Count];

        List <VertexProperties> _verts = new List <VertexProperties>();
        List <VertexProperties> _frontFaceVerticies = new List <VertexProperties>();

        List <int> _indicies          = new List <int>();
        List <int> _frontFaceIndicies = new List <int>();

        //ConvertingToArray
        for (int i = 0; i < genPoly.Count; i++)
        {
            _genPolyArrFront[i] = objTrans.TransformPoint(genPoly[i].Pos);
        }

        Vector3 vecSum = Vector3.zero;

        //VerticiesFront
        for (int i = 0; i < genPoly.Count; i++)
        {
            Vector3 _position = new Vector3(_genPolyArrFront[i].x, _genPolyArrFront[i].y, 0.0f);

            vecSum += _position;

            _verts.Add(new VertexProperties {
                position = _position
            });
            _verts.Add(new VertexProperties {
                position = _position
            });
            _verts.Add(new VertexProperties {
                position = _position
            });

            _frontFaceVerticies.Add(new VertexProperties {
                position = _position
            });
        }

        //Calculating the center of the unscaled polygon
        Vector3 polygonCenter = vecSum / genPoly.Count;

        polygonCenter.z = objTrans.position.z;

        Matrix4x4 scaleMatrix = BlastProof.Mathematics.ScaleMatrix(_SCALE_FACTOR);

        Vector3 vecSum2 = Vector3.zero;

        //VerticiesBack
        for (int i = 0; i < genPoly.Count; i++)
        {
            Vector3 _position = scaleMatrix.MultiplyPoint(new Vector3(_genPolyArrFront[i].x, _genPolyArrFront[i].y, _BACKFACE_OFFSET));
            vecSum2 += _position;

            _verts.Add(new VertexProperties {
                position = _position
            });
            _verts.Add(new VertexProperties {
                position = _position
            });
            _verts.Add(new VertexProperties {
                position = _position
            });
        }

        Vector3 scaledPolyCenter = vecSum2 / genPoly.Count;

        scaledPolyCenter.z = objTrans.position.z;

        //Caching how much should the polygon move on axis so it matches the original scale polygon
        Vector3 translVec = polygonCenter - scaledPolyCenter;

        Matrix4x4 transMatrix = BlastProof.Mathematics.TranslateMatrix(translVec);

        //Multiplying each backface polygon position with the translation matrix so the center of backface polygon and frontface polygon matches
        for (int i = _verts.Count / 2; i < _verts.Count; i++)
        {
            _verts[i].position = transMatrix.MultiplyPoint(_verts[i].position);
        }

        var newGenPolyArrFront = new List <Poly2Tri.PolygonPoint>();

        for (int i = 0; i < _genPolyArrFront.Length; i++)
        {
            var point = new Poly2Tri.PolygonPoint(_genPolyArrFront[i].x, _genPolyArrFront[i].y);
            point.index = i;
            newGenPolyArrFront.Add(point);
        }

        Poly2Tri.Polygon poly = new Poly2Tri.Polygon(newGenPolyArrFront);

        DTSweepContext tcx = new DTSweepContext();

        tcx.PrepareTriangulation(poly);
        DTSweep.Triangulate(tcx);

        List <int> indiciesFromTriangulator = new List <int>();

        foreach (var triangle in poly.Triangles)
        {
            foreach (var point in triangle.Points)
            {
                indiciesFromTriangulator.Add(point.index);
            }
        }

        indiciesFromTriangulator.Reverse();

        Triangulator tri = new Triangulator(_genPolyArrFront);

        int[] triangledPoly = indiciesFromTriangulator.ToArray();

        //FrontFaceIndicies
        for (int i = 0; i < triangledPoly.Length; i++)
        {
            _indicies.Add(triangledPoly[i] * _FRONTOFFSET);
            _frontFaceIndicies.Add(triangledPoly[i]);
        }

        //BackFaceIndicies
        for (int i = triangledPoly.Length - 1; i >= 0; i--)
        {
            _indicies.Add(triangledPoly[i] * _FRONTOFFSET + (_verts.Count / 2));
        }

        //Front-Back Faces normals
        for (int i = 0; i < _indicies.Count / 2; i += 3)
        {
            int[] v1 = { _indicies[i], _indicies[(i + 1) % (_indicies.Count / 2)], _indicies[(i + 2) % (_indicies.Count / 2)] };
            int[] v2 = { _indicies[i + (_indicies.Count / 2)], _indicies[(i + 1) % (_indicies.Count / 2) + (_indicies.Count / 2)], _indicies[(i + 2) % (_indicies.Count / 2) + (_indicies.Count / 2)] };

            GetNormalsForVerts(_verts, v1);
            GetNormalsForVerts(_verts, v2);
            GetUVsWithSize(_verts, v1, Faces.forward, spriteSquareSize);
            GetUVsWithSize(_verts, v2, Faces.forward, spriteSquareSize);
        }

        //Generating Side Triangles
        for (int i = 1; i < _verts.Count / 2; i += 6)
        {
            int[] frontFaceVerts = { i, (i + 3) % (_verts.Count / 2) };
            int[] backFaceVerts  = { (i + (_verts.Count / 2)), (i + 3) % (_verts.Count / 2) + (_verts.Count / 2) };

            //verts pos are used as uvs
            int[] uvCoord = { i, (i + 3) % (_verts.Count / 2), (i + (_verts.Count / 2)), (i + 3) % (_verts.Count / 2) + (_verts.Count / 2) };

            GetQuadIndicies(frontFaceVerts, backFaceVerts, _indicies, _verts);

            GetUVsWithSize(_verts, uvCoord, Faces.left, spriteSquareSize);
        }

        //Generate Up-Down Verts
        for (int i = 5; i < _verts.Count / 2; i += 6)
        {
            int[] frontFaceVerts = { i % (_verts.Count / 2), (i + 3) % (_verts.Count / 2) };
            int[] backFaceVerts  = { (i % (_verts.Count / 2) + (_verts.Count / 2)),
                                     (i + 3) % (_verts.Count / 2) + (_verts.Count / 2) };

            //verts pos are used as uvs
            int[] uvCoord = { i % (_verts.Count / 2), (i + 3) % (_verts.Count / 2), (i % (_verts.Count / 2) + (_verts.Count / 2)), (i + 3) % (_verts.Count / 2) + (_verts.Count / 2) };

            GetQuadIndicies(frontFaceVerts, backFaceVerts, _indicies, _verts);
            GetUVsWithSize(_verts, uvCoord, Faces.up, spriteSquareSize);
        }

        _generatedMesh             = new MeshProperties(_verts);
        _generatedMesh.mesh_center = polygonCenter;
        _generatedMesh.SetIndicies(_indicies.ToArray());

        _frontFaceMesh             = new MeshProperties(_frontFaceVerticies);
        _frontFaceMesh.mesh_center = polygonCenter;
        _frontFaceMesh.SetIndicies(_frontFaceIndicies.ToArray());

        return(new MeshProperties[] { _generatedMesh, _frontFaceMesh });
    }