Example #1
0
    void ParseGcode()
    {
        killExtrusions();
        // extrusionlines = null;
        // Array.Resize(ref extrusionlines, 1000); // 1000 should Unity anyway crashes long before because it is crap.

        for (int i = 0; i < actualSelectedGcode.Length; i++)
        {
            // misc stuff
            if (actualSelectedGcode[i].StartsWith(";"))
            {
                if (actualSelectedGcode[i].StartsWith(";Sliced"))
                {
                    string[] slicerVersion = actualSelectedGcode[i].Split(' ');
                    if (debugPrints)
                    {
                        Debug.Log("SLICER: " + slicerVersion[2] + " " + slicerVersion[3]);
                    }

                    slicerGcode = 1;
                }
                if (actualSelectedGcode[i].StartsWith(";Dimension"))
                {
                    string[] dimensions = actualSelectedGcode[i].Split(' ');
                    bedX           = float.Parse(dimensions[1].Replace('.', ','));
                    bedY           = float.Parse(dimensions[2].Replace('.', ','));
                    bedZ           = float.Parse(dimensions[3].Replace('.', ','));
                    nozzleDiameter = float.Parse(dimensions[4].Replace('.', ','));

                    SetBuildplate(bedX, bedY);
                    if (debugPrints)
                    {
                        Debug.Log(actualSelectedGcode[i]);
                    }
                }
                // actual tool position height
                if (actualSelectedGcode[i].StartsWith(";Z:"))
                {
                    string[] temp = actualSelectedGcode[i].Split(':');
                    actualZheight = float.Parse(temp[1].Replace('.', ','));
                    if (debugPrints)
                    {
                        Debug.Log("GECODE Z HEIGT ACTUAL " + actualZheight);
                    }
                }
                // layer Height
                if (actualSelectedGcode[i].StartsWith(";HEIGHT"))
                {
                    string[] temp = actualSelectedGcode[i].Split(':');
                    actualLayerHeight = float.Parse(temp[1].Replace('.', ','));
                }
                if (actualSelectedGcode[i].StartsWith(";LAYER:0"))
                {
                    isPrinting = true;
                }
                if (actualSelectedGcode[i].StartsWith(";End"))
                {
                    isPrinting = false;
                }
                if (debugPrints)
                {
                    if (actualSelectedGcode[i].StartsWith(";TYPE")) // write all feature in file
                    {
                        adebugtext += actualSelectedGcode[i] + "\n";
                        System.IO.File.WriteAllText("clean.txt", adebugtext);
                    }
                }
            }


            // Soported feature types
            // ; TYPE: WALL - INNER
            // ; TYPE: WALL - OUTER
            // ; TYPE: SOLID - FILL
            // ; TYPE: SKIRT
            // ; TYPE: FILL
            if (actualSelectedGcode[i].StartsWith(";TYPE:SKIRT"))
            {
                GameObject meshtest = new GameObject();
                meshtest.tag  = "extrusion";
                meshtest.name = actualSelectedGcode[i];

                meshtest.AddComponent <Spline>();
                meshtest.AddComponent <SplineMeshTiling>();



                Spline spline = meshtest.GetComponent <Spline>();
                spline.tag = "extrusion";
                SplineMeshTiling smt = meshtest.GetComponent <SplineMeshTiling>();
                smt.tag = "extrusion";

                smt.updateInPlayMode = true;

                go      = GameObject.CreatePrimitive(PrimitiveType.Cube);
                go.name = "Filament: " + actualSelectedGcode[i];
                go.tag  = "extrusion";

                Mesh mesh = go.GetComponent <MeshFilter>().sharedMesh;
                smt.mesh = mesh; // test
                // Debug.Log(Skirt + "     - materials");
                // Debug.Log(smt.material + " -- -- --");
                smt.material = Skirt;
                // Debug.Log(smt.material + " -- -- --");
                smt.rotation = new Vector3(0.0f, 0.0f, 0.0f);
                smt.scale    = new Vector3(0.2f * scale, 0.2f * scale, 0.45f * scale);

                if (visibleLayers.value >= (actualZheight * scale))
                {
                    meshtest.SetActive(true);
                    go.SetActive(true);
                }
                else
                {
                    meshtest.SetActive(false);
                    go.SetActive(false);
                }


                string[] before = actualSelectedGcode[(i - 2)].Split(' ');
                float    xx;
                float    yy;
                xx = float.Parse(before[2].Replace('.', ',').Substring(1));
                yy = float.Parse(before[3].Replace('.', ',').Substring(1));

                if (debugPrints)
                {
                    Debug.Log("X :" + xx + "   Y: " + yy);
                }

                spline.AddNode(new SplineNode(new Vector3(xx * scale, (actualZheight - (actualLayerHeight / 2)) * scale, yy * scale), new Vector3(xx * scale - 0.000001f, (actualZheight - (actualLayerHeight / 2)) * scale, yy * scale - 0.000001f)));
                // spline.AddNode(new SplineNode(new Vector3(x * scale, (actualZheight - (actualLayerHeight / 2)) * scale, y * scale), new Vector3(x * scale - 0.000001f, (actualZheight - (actualLayerHeight / 2)) * scale, y * scale - 0.000001f)));

                if (debugPrints)
                {
                    Debug.Log("Aktuelle Zeile : " + actualSelectedGcode[i] + "  " + i);
                }

                int n = 1;
                while ((i + n) < actualSelectedGcode.Length)
                {
                    if (actualSelectedGcode[i + n].StartsWith(";LAYER"))
                    {
                        break;
                    }
                    if (actualSelectedGcode[i + n].StartsWith(";End GCode"))
                    {
                        break;
                    }
                    if (actualSelectedGcode[i + n].StartsWith(";TYPE"))
                    {
                        if (debugPrints)
                        {
                            Debug.Log("I: " + i + " n: " + n + "Aktuelle Zeile : " + i + "   " + actualSelectedGcode[i]);
                        }

                        break;
                    }
                    if (actualSelectedGcode[i + n].StartsWith("G1")) // extrusion moves
                    {
                        if (debugPrints)
                        {
                            Debug.Log("G1 ------------------------- ");
                        }


                        float posX;
                        float posY;

                        string[] cords = actualSelectedGcode[i + n].Split(' ');


                        if (cords[1].StartsWith("F"))
                        {
                            posX = float.Parse(cords[2].Replace('.', ',').Substring(1));
                            posY = float.Parse(cords[3].Replace('.', ',').Substring(1));
                        }
                        else
                        {
                            posX = float.Parse(cords[1].Replace('.', ',').Substring(1));
                            posY = float.Parse(cords[2].Replace('.', ',').Substring(1));
                        }
                        spline.AddNode(new SplineNode(new Vector3(posX * scale, (actualZheight - (actualLayerHeight / 2)) * scale, posY * scale), new Vector3(posX * scale - 0.000001f, (actualZheight - (actualLayerHeight / 2)) * scale, posY * scale - 0.000001f)));
                    }
                    n++;
                }
            }

            // --------------------------------------------------------------------------------------

            if (actualSelectedGcode[i].StartsWith(";TYPE:WALL-OUTER"))
            {
                GameObject meshtest = new GameObject();
                meshtest.tag  = "extrusion";
                meshtest.name = actualSelectedGcode[i];

                meshtest.AddComponent <Spline>();
                meshtest.AddComponent <SplineMeshTiling>();


                Spline           spline = meshtest.GetComponent <Spline>();
                SplineMeshTiling smt    = meshtest.GetComponent <SplineMeshTiling>();

                spline.tag = "extrusion";
                smt.tag    = "extrusion";

                smt.updateInPlayMode = true;

                go      = GameObject.CreatePrimitive(PrimitiveType.Cube);
                go.name = "Filament: " + actualSelectedGcode[i];
                go.tag  = "extrusion";

                Mesh mesh = go.GetComponent <MeshFilter>().sharedMesh;
                smt.mesh = mesh; // test
                // Debug.Log(Skirt + "     - materials");
                // Debug.Log(smt.material + " -- -- --");
                smt.material = OuterShell;
                // Debug.Log(smt.material + " -- -- --");
                smt.rotation = new Vector3(0.0f, 0.0f, 0.0f);
                smt.scale    = new Vector3(0.19f * scale, 0.2f * scale, 0.4f * scale);

                if (visibleLayers.value >= (actualZheight * scale))
                {
                    meshtest.SetActive(true);
                    go.SetActive(true);
                }
                else
                {
                    meshtest.SetActive(false);
                    go.SetActive(false);
                }

                string[] before = actualSelectedGcode[(i - 1)].Split(' ');
                float    xx;
                float    yy;
                if (before[1].StartsWith("F"))
                {
                    xx = float.Parse(before[2].Replace('.', ',').Substring(1));
                    yy = float.Parse(before[3].Replace('.', ',').Substring(1));
                }
                else
                {
                    xx = float.Parse(before[1].Replace('.', ',').Substring(1));
                    yy = float.Parse(before[2].Replace('.', ',').Substring(1));
                }

                if (debugPrints)
                {
                    Debug.Log("X :" + xx + "   Y: " + yy);
                }

                spline.AddNode(new SplineNode(new Vector3(xx * scale, (actualZheight - (actualLayerHeight / 2)) * scale, yy * scale), new Vector3(xx * scale - 0.000001f, (actualZheight - (actualLayerHeight / 2)) * scale, yy * scale - 0.000001f)));
                // spline.AddNode(new SplineNode(new Vector3(x * scale, (actualZheight - (actualLayerHeight / 2)) * scale, y * scale), new Vector3(x * scale - 0.000001f, (actualZheight - (actualLayerHeight / 2)) * scale, y * scale - 0.000001f)));

                if (debugPrints)
                {
                    Debug.Log("Aktuelle Zeile : " + actualSelectedGcode[i] + "  " + i);
                }

                int n = 1;
                while ((i + n) < actualSelectedGcode.Length)
                {
                    if (actualSelectedGcode[i + n].StartsWith(";LAYER"))
                    {
                        break;
                    }
                    if (actualSelectedGcode[i + n].StartsWith(";End GCode"))
                    {
                        break;
                    }
                    if (actualSelectedGcode[i + n].StartsWith(";TYPE"))
                    {
                        if (debugPrints)
                        {
                            Debug.Log("I: " + i + " n: " + n + "Aktuelle Zeile : " + i + "   " + actualSelectedGcode[i]);
                        }

                        break;
                    }
                    if (actualSelectedGcode[i + n].StartsWith("G1")) // extrusion moves
                    {
                        if (debugPrints)
                        {
                            Debug.Log("G1 ------------------------- ");
                        }


                        float posX;
                        float posY;

                        string[] cords = actualSelectedGcode[i + n].Split(' ');


                        if (cords[1].StartsWith("F"))
                        {
                            posX = float.Parse(cords[2].Replace('.', ',').Substring(1));
                            posY = float.Parse(cords[3].Replace('.', ',').Substring(1));
                        }
                        else
                        {
                            posX = float.Parse(cords[1].Replace('.', ',').Substring(1));
                            posY = float.Parse(cords[2].Replace('.', ',').Substring(1));
                        }
                        spline.AddNode(new SplineNode(new Vector3(posX * scale, (actualZheight - (actualLayerHeight / 2)) * scale, posY * scale), new Vector3(posX * scale - 0.000001f, (actualZheight - (actualLayerHeight / 2)) * scale, posY * scale - 0.000001f)));
                    }
                    n++;
                }
            }

            // -----------------------------------------------

            if (actualSelectedGcode[i].StartsWith(";TYPE:WALL-INNER"))
            {
                GameObject meshtest = new GameObject();
                meshtest.tag  = "extrusion";
                meshtest.name = actualSelectedGcode[i];

                meshtest.AddComponent <Spline>();
                meshtest.AddComponent <SplineMeshTiling>();


                Spline           spline = meshtest.GetComponent <Spline>();
                SplineMeshTiling smt    = meshtest.GetComponent <SplineMeshTiling>();

                spline.tag = "extrusion";
                smt.tag    = "extrusion";

                smt.updateInPlayMode = true;

                go      = GameObject.CreatePrimitive(PrimitiveType.Cube);
                go.name = "Filament: " + actualSelectedGcode[i];
                go.tag  = "extrusion";

                Mesh mesh = go.GetComponent <MeshFilter>().sharedMesh;
                smt.mesh = mesh; // test
                // Debug.Log(Skirt + "     - materials");
                // Debug.Log(smt.material + " -- -- --");
                smt.material = InnerShell;
                // Debug.Log(smt.material + " -- -- --");
                smt.rotation = new Vector3(0.0f, 0.0f, 0.0f);
                smt.scale    = new Vector3(0.19f * scale, 0.2f * scale, 0.4f * scale);

                if (visibleLayers.value >= (actualZheight * scale))
                {
                    meshtest.SetActive(true);
                    go.SetActive(true);
                }
                else
                {
                    meshtest.SetActive(false);
                    go.SetActive(false);
                }

                string[] before = actualSelectedGcode[(i - 1)].Split(' ');
                float    xx;
                float    yy;
                if (before[1].StartsWith("F"))
                {
                    xx = float.Parse(before[2].Replace('.', ',').Substring(1));
                    yy = float.Parse(before[3].Replace('.', ',').Substring(1));
                }
                else
                {
                    xx = float.Parse(before[1].Replace('.', ',').Substring(1));
                    yy = float.Parse(before[2].Replace('.', ',').Substring(1));
                }

                if (debugPrints)
                {
                    Debug.Log("X :" + xx + "   Y: " + yy);
                }

                spline.AddNode(new SplineNode(new Vector3(xx * scale, (actualZheight - (actualLayerHeight / 2)) * scale, yy * scale), new Vector3(xx * scale - 0.000001f, (actualZheight - (actualLayerHeight / 2)) * scale, yy * scale - 0.000001f)));
                // spline.AddNode(new SplineNode(new Vector3(x * scale, (actualZheight - (actualLayerHeight / 2)) * scale, y * scale), new Vector3(x * scale - 0.000001f, (actualZheight - (actualLayerHeight / 2)) * scale, y * scale - 0.000001f)));

                if (debugPrints)
                {
                    Debug.Log("Aktuelle Zeile : " + actualSelectedGcode[i] + "  " + i);
                }

                int n = 1;
                while ((i + n) < actualSelectedGcode.Length)
                {
                    if (actualSelectedGcode[i + n].StartsWith(";LAYER"))
                    {
                        break;
                    }
                    if (actualSelectedGcode[i + n].StartsWith(";End GCode"))
                    {
                        break;
                    }
                    if (actualSelectedGcode[i + n].StartsWith(";TYPE"))
                    {
                        if (debugPrints)
                        {
                            Debug.Log("I: " + i + " n: " + n + "Aktuelle Zeile : " + i + "   " + actualSelectedGcode[i]);
                        }

                        break;
                    }
                    if (actualSelectedGcode[i + n].StartsWith("G1")) // extrusion moves
                    {
                        if (debugPrints)
                        {
                            Debug.Log("G1 ------------------------- ");
                        }


                        float posX;
                        float posY;

                        string[] cords = actualSelectedGcode[i + n].Split(' ');


                        if (cords[1].StartsWith("F"))
                        {
                            posX = float.Parse(cords[2].Replace('.', ',').Substring(1));
                            posY = float.Parse(cords[3].Replace('.', ',').Substring(1));
                        }
                        else
                        {
                            posX = float.Parse(cords[1].Replace('.', ',').Substring(1));
                            posY = float.Parse(cords[2].Replace('.', ',').Substring(1));
                        }
                        spline.AddNode(new SplineNode(new Vector3(posX * scale, (actualZheight - (actualLayerHeight / 2)) * scale, posY * scale), new Vector3(posX * scale - 0.000001f, (actualZheight - (actualLayerHeight / 2)) * scale, posY * scale - 0.000001f)));
                    }
                    n++;
                }
            }

            // -----------------------------------------------

            if (actualSelectedGcode[i].StartsWith(";TYPE:SOLID-FILL"))
            {
                GameObject meshtest = new GameObject();
                meshtest.tag  = "extrusion";
                meshtest.name = actualSelectedGcode[i];

                meshtest.AddComponent <Spline>();
                meshtest.AddComponent <SplineMeshTiling>();


                Spline           spline = meshtest.GetComponent <Spline>();
                SplineMeshTiling smt    = meshtest.GetComponent <SplineMeshTiling>();

                spline.tag = "extrusion";
                smt.tag    = "extrusion";

                smt.updateInPlayMode = true;
                smt.curveSpace       = true;

                go      = GameObject.CreatePrimitive(PrimitiveType.Cube);
                go.name = "Filament: " + actualSelectedGcode[i];
                go.tag  = "extrusion";

                Mesh mesh = go.GetComponent <MeshFilter>().sharedMesh;
                smt.mesh = mesh; // test
                // Debug.Log(Skirt + "     - materials");
                // Debug.Log(smt.material + " -- -- --");
                smt.material = SolidInfill;
                // Debug.Log(smt.material + " -- -- --");
                smt.rotation = new Vector3(0.0f, 0.0f, 0.0f);
                smt.scale    = new Vector3(0.19f * scale, 0.2f * scale, 0.4f * scale);

                if (visibleLayers.value >= (actualZheight * scale))
                {
                    meshtest.SetActive(true);
                    go.SetActive(true);
                }
                else
                {
                    meshtest.SetActive(false);
                    go.SetActive(false);
                }

                string[] before = actualSelectedGcode[(i - 1)].Split(' ');
                float    xx;
                float    yy;
                if (before[1].StartsWith("F"))
                {
                    xx = float.Parse(before[2].Replace('.', ',').Substring(1));
                    yy = float.Parse(before[3].Replace('.', ',').Substring(1));
                }
                else
                {
                    xx = float.Parse(before[1].Replace('.', ',').Substring(1));
                    yy = float.Parse(before[2].Replace('.', ',').Substring(1));
                }

                if (debugPrints)
                {
                    Debug.Log("X :" + xx + "   Y: " + yy);
                }

                spline.AddNode(new SplineNode(new Vector3(xx * scale, (actualZheight - (actualLayerHeight / 2)) * scale, yy * scale), new Vector3(xx * scale - 0.000001f, (actualZheight - (actualLayerHeight / 2)) * scale, yy * scale - 0.000001f)));
                // spline.AddNode(new SplineNode(new Vector3(x * scale, (actualZheight - (actualLayerHeight / 2)) * scale, y * scale), new Vector3(x * scale - 0.000001f, (actualZheight - (actualLayerHeight / 2)) * scale, y * scale - 0.000001f)));

                if (debugPrints)
                {
                    Debug.Log("Aktuelle Zeile : " + actualSelectedGcode[i] + "  " + i);
                }

                int n = 1;
                while ((i + n) < actualSelectedGcode.Length)
                {
                    if (actualSelectedGcode[i + n].StartsWith(";LAYER"))
                    {
                        break;
                    }
                    if (actualSelectedGcode[i + n].StartsWith(";End GCode"))
                    {
                        break;
                    }
                    if (actualSelectedGcode[i + n].StartsWith(";TYPE"))
                    {
                        if (debugPrints)
                        {
                            Debug.Log("I: " + i + " n: " + n + "Aktuelle Zeile : " + i + "   " + actualSelectedGcode[i]);
                        }

                        break;
                    }
                    if (actualSelectedGcode[i + n].StartsWith("G1")) // extrusion moves
                    {
                        if (debugPrints)
                        {
                            Debug.Log("G1 ------------------------- ");
                        }


                        float posX;
                        float posY;

                        string[] cords = actualSelectedGcode[i + n].Split(' ');


                        if (cords[1].StartsWith("F"))
                        {
                            posX = float.Parse(cords[2].Replace('.', ',').Substring(1));
                            posY = float.Parse(cords[3].Replace('.', ',').Substring(1));
                        }
                        else
                        {
                            posX = float.Parse(cords[1].Replace('.', ',').Substring(1));
                            posY = float.Parse(cords[2].Replace('.', ',').Substring(1));
                        }
                        spline.AddNode(new SplineNode(new Vector3(posX * scale, (actualZheight - (actualLayerHeight / 2)) * scale, posY * scale), new Vector3(posX * scale - 0.000001f, (actualZheight - (actualLayerHeight / 2)) * scale, posY * scale - 0.000001f)));
                    }
                    n++;
                }
            }



            // -----------------------------------------------

            if (actualSelectedGcode[i].StartsWith(";TYPE:FILL"))
            {
                GameObject meshtest = new GameObject();
                meshtest.tag  = "extrusion";
                meshtest.name = actualSelectedGcode[i];

                meshtest.AddComponent <Spline>();
                meshtest.AddComponent <SplineMeshTiling>();


                Spline           spline = meshtest.GetComponent <Spline>();
                SplineMeshTiling smt    = meshtest.GetComponent <SplineMeshTiling>();

                spline.tag = "extrusion";
                smt.tag    = "extrusion";

                smt.updateInPlayMode = true;
                smt.curveSpace       = true;

                go      = GameObject.CreatePrimitive(PrimitiveType.Cube);
                go.name = "Filament: " + actualSelectedGcode[i];
                go.tag  = "extrusion";

                Mesh mesh = go.GetComponent <MeshFilter>().sharedMesh;
                smt.mesh = mesh; // test
                // Debug.Log(Skirt + "     - materials");
                // Debug.Log(smt.material + " -- -- --");
                smt.material = Infill;
                // Debug.Log(smt.material + " -- -- --");
                smt.rotation = new Vector3(0.0f, 0.0f, 0.0f);
                smt.scale    = new Vector3(0.19f * scale, 0.2f * scale, 0.4f * scale);

                if (visibleLayers.value >= (actualZheight * scale))
                {
                    meshtest.SetActive(true);
                    go.SetActive(true);
                }
                else
                {
                    meshtest.SetActive(false);
                    go.SetActive(false);
                }

                string[] before = actualSelectedGcode[(i - 1)].Split(' ');
                float    xx;
                float    yy;
                if (before[1].StartsWith("F"))
                {
                    xx = float.Parse(before[2].Replace('.', ',').Substring(1));
                    yy = float.Parse(before[3].Replace('.', ',').Substring(1));
                }
                else
                {
                    xx = float.Parse(before[1].Replace('.', ',').Substring(1));
                    yy = float.Parse(before[2].Replace('.', ',').Substring(1));
                }

                if (debugPrints)
                {
                    Debug.Log("X :" + xx + "   Y: " + yy);
                }

                spline.AddNode(new SplineNode(new Vector3(xx * scale, (actualZheight - (actualLayerHeight / 2)) * scale, yy * scale), new Vector3(xx * scale - 0.000001f, (actualZheight - (actualLayerHeight / 2)) * scale, yy * scale - 0.000001f)));
                // spline.AddNode(new SplineNode(new Vector3(x * scale, (actualZheight - (actualLayerHeight / 2)) * scale, y * scale), new Vector3(x * scale - 0.000001f, (actualZheight - (actualLayerHeight / 2)) * scale, y * scale - 0.000001f)));

                if (debugPrints)
                {
                    Debug.Log("Aktuelle Zeile : " + actualSelectedGcode[i] + "  " + i);
                }

                int n = 1;
                while ((i + n) < actualSelectedGcode.Length)
                {
                    if (actualSelectedGcode[i + n].StartsWith(";LAYER"))
                    {
                        break;
                    }
                    if (actualSelectedGcode[i + n].StartsWith(";End GCode"))
                    {
                        break;
                    }
                    if (actualSelectedGcode[i + n].StartsWith(";TYPE"))
                    {
                        if (debugPrints)
                        {
                            Debug.Log("I: " + i + " n: " + n + "Aktuelle Zeile : " + i + "   " + actualSelectedGcode[i]);
                        }

                        break;
                    }
                    if (actualSelectedGcode[i + n].StartsWith("G1")) // extrusion moves
                    {
                        if (debugPrints)
                        {
                            Debug.Log("G1 ------------------------- ");
                        }

                        if (actualSelectedGcode[i + n - 1].StartsWith(";"))
                        {
                            Debug.Log("G1 -------first in infill ------------------ ");
                        }
                        else
                        {
                            string[] BeforeCords = actualSelectedGcode[i + n - 1].Split(' ');
                            float    beforeX;
                            float    beforeY;

                            float posX;
                            float posY;

                            string[] cords = actualSelectedGcode[i + n].Split(' ');



                            if (BeforeCords[1].StartsWith("F"))
                            {
                                beforeX = float.Parse(BeforeCords[2].Replace('.', ',').Substring(1));
                                beforeY = float.Parse(BeforeCords[3].Replace('.', ',').Substring(1));
                            }
                            else
                            {
                                beforeX = float.Parse(BeforeCords[1].Replace('.', ',').Substring(1));
                                beforeY = float.Parse(BeforeCords[2].Replace('.', ',').Substring(1));
                            }


                            if (cords[1].StartsWith("F"))
                            {
                                posX = float.Parse(cords[2].Replace('.', ',').Substring(1));
                                posY = float.Parse(cords[3].Replace('.', ',').Substring(1));
                            }
                            else
                            {
                                posX = float.Parse(cords[1].Replace('.', ',').Substring(1));
                                posY = float.Parse(cords[2].Replace('.', ',').Substring(1));
                            }
                            spline.AddNode(new SplineNode(new Vector3(beforeX * scale, (actualZheight - (actualLayerHeight / 2)) * scale, beforeY * scale), new Vector3(beforeX * scale - 0.000001f, (actualZheight - (actualLayerHeight / 2)) * scale, beforeY * scale - 0.000001f)));
                            spline.AddNode(new SplineNode(new Vector3(posX * scale, (actualZheight - (actualLayerHeight / 2)) * scale, posY * scale), new Vector3(posX * scale - 0.000001f, (actualZheight - (actualLayerHeight / 2)) * scale, posY * scale - 0.000001f)));
                        }
                    }
                    n++;
                }
            }
        }
        visibleLayers.maxValue = (actualZheight * scale);
    }
Example #2
0
    public static void CreateStreetNetwork()
    {
        polygons = new List <Vector3[]>();

        bool linearOption = true;

        int laneCounter        = 0;
        int streetLightCounter = 0;
        int buildingCounter    = 0;

        GameObject[] buildingsToPlace = Resources.LoadAll <GameObject>("Models/Buildings");

        MonoBehaviour.print("Inserting 3d Streets");

        foreach (NetFileEdge e in edges.Values)
        {
            foreach (NetFileLane l in e.getLanes())
            {
                int        lineCounter = 0;
                GameObject spline      = new GameObject("LaneSegment_" + l.id);
                spline.AddComponent <Path>();
                spline.transform.SetParent(network.transform);

                Spline           splineObject     = spline.AddComponent <Spline>();
                SplineMeshTiling splineMeshTiling = spline.AddComponent <SplineMeshTiling>();

                Vector3 nextDirection = new Vector3((float)l.shape[0][0] - xmin, 0, (float)l.shape[0][1] - ymin) - new Vector3((float)l.shape[1][0] - xmin, 0, (float)l.shape[1][1] - ymin);
                Vector3 lastPosition  = new Vector3((float)l.shape[0][0] - xmin, 0, (float)l.shape[0][1] - ymin);
                splineObject.AddNode(new SplineNode(lastPosition, lastPosition - nextDirection.normalized));
                bool isFirst = true;
                foreach (double[] coordPair in l.shape)
                {
                    if (isFirst)
                    {
                        isFirst = false;
                        continue;
                    }
                    nextDirection = lastPosition - new Vector3((float)coordPair[0] - xmin, 0, (float)coordPair[1] - ymin);
                    splineObject.AddNode(new SplineNode(new Vector3((float)coordPair[0] - xmin, 0, (float)coordPair[1] - ymin), new Vector3((float)coordPair[0] - xmin, 0, (float)coordPair[1] - ymin) - nextDirection.normalized));
                    lastPosition = new Vector3((float)coordPair[0] - xmin, 0, (float)coordPair[1] - ymin);
                }

                int nodeCounter = 0;
                foreach (SplineNode splineNode in splineObject.nodes)
                {
                    GameObject node = new GameObject("Node_" + nodeCounter);
                    node.transform.SetParent(spline.transform);
                    node.transform.position = splineNode.Position;
                    nodeCounter++;
                }

                // Add meshes
                Material     material  = Resources.Load <Material>("Materials/planeMaterial");
                MeshRenderer mRenderer = mRenderer = spline.GetComponent <MeshRenderer>();
                if (mRenderer == null)
                {
                    mRenderer = spline.AddComponent <MeshRenderer>();
                }
                mRenderer.material = material;

                GameObject plane = GameObject.CreatePrimitive(PrimitiveType.Plane);

                splineMeshTiling.material         = Resources.Load <Material>("Materials/planeMaterial");
                splineMeshTiling.mesh             = plane.GetComponent <MeshFilter>().mesh;
                splineMeshTiling.updateInPlayMode = true;
                splineMeshTiling.scale            = new Vector3(0.3f, 1, 0.3f);
                GameObject.Destroy(plane);

                // (1.1) Add Lanes to polygon list for tree placement check
                for (int i = 0; i < l.shape.Count - 1; i++)
                {
                    double length = Math.Sqrt(Math.Pow(l.shape[i][0] - xmin - (l.shape[i + 1][0] - xmin), 2) + Math.Pow(l.shape[i][1] - ymin - (l.shape[i + 1][1] - ymin), 2));
                    // Calc the position (in line with the lane)
                    float  x1 = (float)l.shape[i][0] - xmin;
                    float  y1 = (float)l.shape[i][1] - ymin;
                    float  x2 = (float)l.shape[i + 1][0] - xmin;
                    float  y2 = (float)l.shape[i + 1][1] - ymin;
                    double Dx = x2 - x1;
                    double Dy = y2 - y1;
                    double D  = Math.Sqrt(Dx * Dx + Dy * Dy);
                    double W  = 10;
                    Dx = 0.5 * W * Dx / D;
                    Dy = 0.5 * W * Dy / D;
                    Vector3[] polygon = new Vector3[] { new Vector3((float)(x1 - Dy), 0, (float)(y1 + Dx)),
                                                        new Vector3((float)(x1 + Dy), 0, (float)(y1 - Dx)),
                                                        new Vector3((float)(x2 + Dy), 0, (float)(y2 - Dx)),
                                                        new Vector3((float)(x2 - Dy), 0, (float)(y2 + Dx)) };
                    polygons.Add(polygon);


                    // (2) Add Street Lamps (only if long enough)
                    if (length >= minLengthForStreetLamp && e.getLanes().Count == 1)
                    {
                        float angle = Mathf.Atan2(y2 - y1, x2 - x1) * 180 / Mathf.PI;

                        // Allway located at the middle of a street
                        double ratioRotPoint = 0.5;
                        double ratio         = 0.5 + streeLampDistance / length;

                        float xDest = (float)((1 - ratio) * x1 + ratio * x2);
                        float yDest = (float)((1 - ratio) * y1 + ratio * y2);

                        float xRotDest = (float)((1 - ratioRotPoint) * x1 + ratioRotPoint * x2);
                        float yRotDest = (float)((1 - ratioRotPoint) * y1 + ratioRotPoint * y2);

                        GameObject streetLampPrefab = Resources.Load <GameObject>("Models/streetlight");
                        GameObject streetLamp       = GameObject.Instantiate(streetLampPrefab, new Vector3(xDest, 0, yDest), Quaternion.Euler(new Vector3(0, 0, 0)));
                        streetLamp.name = "StreetLight_" + streetLightCounter++;
                        streetLamp.transform.SetParent(network.transform);
                        streetLamp.transform.RotateAround(new Vector3(xRotDest, 0, yRotDest), Vector3.up, -90.0f);
                        streetLamp.transform.Rotate(Vector3.up, -angle);
                    }

                    if (buildingsToPlace.Length > 0 && length >= lengthFromBuildingToBuildingAlongRoad && e.getLanes().Count <= maxLanesForBuildings)
                    {
                        // Get the angle perpendicular to the road, the number of buildings along the road and the exact length between them.
                        float  angle                  = Mathf.Atan2(y2 - y1, x2 - x1) * 180 / Mathf.PI;
                        int    amountOfBuildings      = (int)(length / lengthFromBuildingToBuildingAlongRoad);
                        double lengthBetweenBuildings = length / (amountOfBuildings + 1);

                        for (int buildingNum = 0; buildingNum < amountOfBuildings; buildingNum++)
                        {
                            GameObject building = buildingsToPlace[UnityEngine.Random.Range(0, buildingsToPlace.Length)];

                            // Find the ratio along the road e.g. the building is halfway down the road and then work out the x and y coords for that point on the road.
                            double ratio = (lengthBetweenBuildings * (buildingNum + 1)) / length;
                            float  xDest = (float)((1 - ratio) * x1 + ratio * x2);
                            float  yDest = (float)((1 - ratio) * y1 + ratio * y2);

                            GameObject buildingCreated = GameObject.Instantiate(building, new Vector3(xDest, 0, yDest), Quaternion.Euler(new Vector3(0, 0, 0)));
                            buildingCreated.transform.SetParent(network.transform);
                            // Rotate and place building on road then move forward away from the road by a constant.
                            buildingCreated.transform.Rotate(Vector3.up, -angle);
                            buildingCreated.transform.position = buildingCreated.transform.position + buildingCreated.transform.forward * lengthFromRoadToBuilding;
                            Physics.SyncTransforms();
                            Collider[] otherCollisions   = Physics.OverlapBox(buildingCreated.gameObject.GetComponentInChildren <BoxCollider>().bounds.center, buildingCreated.gameObject.GetComponentInChildren <BoxCollider>().bounds.extents, buildingCreated.transform.rotation);
                            bool       isBuildingAlready = false;
                            foreach (Collider collider in otherCollisions)
                            {
                                if (collider.transform.IsChildOf(buildingCreated.transform))
                                {
                                    continue;
                                }
                                foreach (GameObject otherBuilding in buildings)
                                {
                                    if (collider.transform.IsChildOf(otherBuilding.transform))
                                    {
                                        isBuildingAlready = true;
                                        break;
                                    }
                                }
                            }
                            if (!isBuildingAlready)
                            {
                                buildingCreated.name = "Building_" + buildingCounter++;
                                buildings.Add(buildingCreated);
                            }
                            else
                            {
                                GameObject.Destroy(buildingCreated);
                            }
                        }
                    }
                }
            }
        }

        // (3) Draw all Junction areas ------------------------------------
        MonoBehaviour.print("Inserting 3d Junctions");

        int junctionCounter = 0;

        foreach (NetFileJunction j in junctions.Values)
        {
            List <int> indices = new List <int>();

            Vector2[] vertices2D = new Vector2[j.shape.Count];
            for (int i = 0; i < j.shape.Count; i++)
            {
                vertices2D[i] = new Vector3((float)(j.shape[i])[0] - xmin, (float)(j.shape[i])[1] - ymin);
            }

            // Use the triangulator to get indices for creating triangles
            Triangulator tr            = new Triangulator(vertices2D);
            List <int>   bottomIndices = new List <int>(tr.Triangulate());
            indices.AddRange(bottomIndices);


            // Create the Vector3 vertices
            Vector3[] vertices = new Vector3[vertices2D.Length];
            for (int i = 0; i < vertices.Length; i++)
            {
                vertices[i] = new Vector3(vertices2D[i].x, 0, vertices2D[i].y);
            }

            Mesh mesh = new Mesh();
            mesh.Clear();
            mesh.vertices  = vertices;
            mesh.triangles = indices.ToArray();
            mesh.RecalculateNormals();
            mesh.RecalculateBounds();

            Bounds    bounds = mesh.bounds;
            Vector2[] uvs    = new Vector2[vertices.Length];
            for (int i = 0; i < vertices.Length; i++)
            {
                uvs[i] = new Vector2(vertices[i].x / bounds.size.x, vertices[i].z / bounds.size.z);
            }
            mesh.uv = uvs;
            mesh.RecalculateNormals();
            mesh.RecalculateBounds();

            // Set up game object with mesh;
            GameObject   junction3D  = new GameObject("junction_" + junctionCounter++);
            MeshRenderer r           = (MeshRenderer)junction3D.AddComponent(typeof(MeshRenderer));
            tlLogicType  tlLogicType = trafficLightPrograms.ToList().Find(e => e.Key.Equals(j.id) && e.Value.Items.Length > 0).Value;
            if (tlLogicType != null)
            {
                Junction junction = junction3D.AddComponent <Junction>();
                junction.junctionId = j.id;
                // Create Camera object for the junction.
                GameObject cameraGameObject = new GameObject("junction_camera_" + j.id);
                cameraGameObject.transform.SetParent(junction3D.transform);
                // Get the center position of the Junction.
                cameraGameObject.transform.position = mesh.bounds.center;
                // Move the camera back for "cameraDistance" and up for "cameraHeight".
                cameraGameObject.transform.position = cameraGameObject.transform.position + (cameraGameObject.transform.TransformDirection(Vector3.back) * cameraDistance) + (cameraGameObject.transform.TransformDirection(Vector3.up) * cameraHeight);
                // Look the camera down by "cameraTiltDown".
                cameraGameObject.transform.Rotate(new Vector3(cameraTiltDown, 0, 0));
                // Add the Camera component to the object, assign it to the junction and add the CameraManager component.
                Camera camera = cameraGameObject.AddComponent <Camera>();
                junction.junctionCamera = camera;
                cameraGameObject.AddComponent <CameraManager>();
            }
            Material material = Resources.Load <Material>("Materials/sidewalk");
            r.material = material;
            MeshFilter filter = junction3D.AddComponent(typeof(MeshFilter)) as MeshFilter;
            filter.mesh = mesh;
            junction3D.transform.SetParent(network.transform);

            // (3.1) Add junctions to polygon list for tree placement check
            polygons.Add(vertices);
        }

        // (4) Draw Traffic Lights
        MonoBehaviour.print("Inserting 3d Traffic Lights");

        foreach (NetFileJunction j in junctions.Values)
        {
            if (j.type == junctionTypeType.traffic_light)
            {
                int index = 0;
                foreach (NetFileLane l in j.incLanes)
                {
                    // Calc the position (in line with the lane)
                    float x1     = (float)l.shape[0][0] - xmin;
                    float y1     = (float)l.shape[0][1] - ymin;
                    float x2     = (float)l.shape[1][0] - xmin;
                    float y2     = (float)l.shape[1][1] - ymin;
                    float length = (float)Math.Sqrt(Math.Pow(y2 - y1, 2) + Math.Pow(x2 - x1, 2));
                    float angle  = Mathf.Atan2(y2 - y1, x2 - x1) * 180 / Mathf.PI;

                    double ratio = (length - trafficLightDistance) / length;

                    float xDest = (float)((1 - ratio) * x1 + ratio * x2);
                    float yDest = (float)((1 - ratio) * y1 + ratio * y2);

                    string trafficLightId = l.id;
                    // Insert the 3d object, rotate from lane 90° to the right side and then orientate the traffic light towards the vehicles
                    GameObject trafficLightPrefab = Resources.Load <GameObject>("Models/TrafficLight");
                    GameObject trafficLight       = GameObject.Instantiate(trafficLightPrefab, new Vector3(xDest, 0, yDest), Quaternion.Euler(new Vector3(0, 0, 0)));
                    trafficLight.name = "TrafficLight_" + trafficLightId;
                    trafficLight.GetComponentInChildren <TrafficLight>().trafficLightId = trafficLightId;
                    trafficLight.transform.SetParent(network.transform);
                    trafficLight.transform.RotateAround(new Vector3(x2, 0, y2), Vector3.up, -90.0f);
                    trafficLight.transform.Rotate(Vector3.up, -angle);

                    // Insert traffic light index as empty GameObject into traffic light
                    GameObject TLindex    = new GameObject("index");
                    GameObject TLindexVal = new GameObject(Convert.ToString(index));
                    TLindexVal.transform.SetParent(TLindex.transform);
                    TLindex.transform.SetParent(trafficLight.transform);
                    index++;
                }
            }
        }
    }
Example #3
0
 // Start is called before the first frame update
 void Start()
 {
     _spline           = GetComponent <Spline>();
     _splineMeshTiling = GetComponent <SplineMeshTiling>();
 }