Example #1
0
        private Extent CalculateExtents()
        {
            corners    = new UnityEngine.Vector3[4];
            corners[0] = transform.position + topLeft;
            corners[1] = transform.position + topRight;
            corners[2] = transform.position + bottomRight;
            corners[3] = transform.position + bottomLeft;

            // Determine the min and max X- en Z-value of the visible coordinates
            var unityMax = new UnityEngine.Vector3(-9999999, -9999999, -99999999);
            var unityMin = new UnityEngine.Vector3(9999999, 9999999, 9999999);

            for (int i = 0; i < 4; i++)
            {
                unityMin.x = Mathf.Min(unityMin.x, corners[i].x);
                unityMin.z = Mathf.Min(unityMin.z, corners[i].z);
                unityMax.x = Mathf.Max(unityMax.x, corners[i].x);
                unityMax.z = Mathf.Max(unityMax.z, corners[i].z);
            }

            // Convert min and max to WGS84 coordinates
            var wGSMin = CoordConvert.UnitytoWGS84(unityMin);
            var wGSMax = CoordConvert.UnitytoWGS84(unityMax);

            // Area that should be loaded
            var extent = new Extent(wGSMin.lon, wGSMin.lat, wGSMax.lon, wGSMax.lat);

            return(extent);
        }
        private Extent CameraExtent()
        {
            // Determine what world coordinates are in the corners of our view
            corners    = new Vector3[4];
            corners[0] = GetCornerPoint(Corners.TOP_LEFT);
            corners[1] = GetCornerPoint(Corners.TOP_RIGHT);
            corners[2] = GetCornerPoint(Corners.BOTTOM_RIGHT);
            corners[3] = GetCornerPoint(Corners.BOTTOM_LEFT);

            // Determine the min and max X- en Z-value of the visible coordinates
            var unityMax = new Vector3(-9999999, -9999999, -99999999);
            var unityMin = new Vector3(9999999, 9999999, 9999999);

            for (int i = 0; i < 4; i++)
            {
                unityMin.x = Mathf.Min(unityMin.x, corners[i].x);
                unityMin.z = Mathf.Min(unityMin.z, corners[i].z);
                unityMax.x = Mathf.Max(unityMax.x, corners[i].x);
                unityMax.z = Mathf.Max(unityMax.z, corners[i].z);
            }

            // Convert min and max to WGS84 coordinates
            var wGSMin = CoordConvert.UnitytoWGS84(unityMin);
            var wGSMax = CoordConvert.UnitytoWGS84(unityMax);

            // Area that should be loaded
            var extent = new Extent(wGSMin.lon, wGSMin.lat, wGSMax.lon, wGSMax.lat);

            return(extent);
        }
Example #3
0
        void ImportSingle(double originX, double originY)
        {
            string jsonfilename = $" panden_{originX}.0_{originY}.0.json";

            float  tileSize = 1000;
            string filepath = Path.Combine(basefilepath, jsonfilename);

            if (File.Exists(filepath))
            {
                CityModel cm = new CityModel(filepath, jsonfilename);

                var buildings = cm.LoadBuildings(1);

                //type voetpad
                Mesh buildingMesh = CreateCityObjectMesh(cm, "Building", originX, originY, tileSize, null, null, true);


                buildingMesh.uv2 = RDuv2(buildingMesh.vertices, CoordConvert.RDtoUnity(new Vector3RD(originX, originY, 0)), tileSize);
                //  Physics.BakeMesh(buildingMesh.GetInstanceID(), false);

                var lod1name = $"{filePrefix}_{originX}-{originY}-lod1.mesh";

                AssetDatabase.CreateAsset(buildingMesh, Path.Combine(destinationPath, lod1name));
                Debug.Log(lod1name);
            }
        }
        /// <summary>
        /// Parse a tree from a string line to a new List item containing the following ; seperated fields:
        /// OBJECTNUMMER;Soortnaam_NL;Boomnummer;Soortnaam_WTS;Boomtype;Boomhoogte;Plantjaar;Eigenaar;Beheerder;Categorie;SOORT_KORT;SDVIEW;RADIUS;WKT_LNG_LAT;WKT_LAT_LNG;LNG;LAT;
        /// </summary>
        /// <param name="line">Text line matching the same fields as the header</param>
        private void ParseTree(string line)
        {
            string[] cell = line.Split(';');

            Tree newTree = new Tree()
            {
                OBJECTNUMMER  = cell[0],
                Soortnaam_NL  = cell[1],
                Boomnummer    = cell[2],
                Soortnaam_WTS = cell[3],
                Boomtype      = cell[4],
                Boomhoogte    = cell[5],
                Plantjaar     = int.Parse(cell[6]),
                Eigenaar      = cell[7],
                Beheerder     = cell[8],
                Categorie     = cell[9],
                SOORT_KORT    = cell[10],
                SDVIEW        = cell[11],
                RADIUS        = cell[12],
                WKT_LNG_LAT   = cell[13],
                WKT_LAT_LNG   = cell[14],
                LNG           = double.Parse(cell[15]),
                LAT           = double.Parse(cell[16])
            };

            //Extra generated tree data
            newTree.RD                = CoordConvert.WGS84toRD(newTree.LNG, newTree.LAT);
            newTree.position          = CoordConvert.WGS84toUnity(newTree.LNG, newTree.LAT);
            newTree.averageTreeHeight = EstimateTreeHeight(newTree.Boomhoogte);
            newTree.prefab            = FindClosestPrefabTypeByName(newTree.Soortnaam_NL);

            trees.Add(newTree);
        }
Example #5
0
        private IEnumerator SpawnManholeObjects()
        {
            SewerManholes.Feature sewerManholeFeature;
            for (int i = 0; i < sewerManholes.features.Length; i++)
            {
                //Speedy way to check if the string is not a 'Knikpunt'
                if (sewerManholes.features[i].properties.objectsoort.Length == 8)
                {
                    continue;
                }

                if ((i % maxSpawnsPerFrame) == 0)
                {
                    yield return(new WaitForEndOfFrame());
                }

                sewerManholeFeature = sewerManholes.features[i];
                sewerManholeSpawner.CreateManhole(
                    CoordConvert.WGS84toUnity(new Vector3WGS(
                                                  sewerManholeFeature.geometry.coordinates[0],
                                                  sewerManholeFeature.geometry.coordinates[1],
                                                  (float.Parse(sewerManholeFeature.properties.putdekselhoogte, CultureInfo.InvariantCulture) + napOffset)
                                                  )
                                              )
                    );
            }
            CombineSewerage();
            yield return(null);
        }
Example #6
0
        /// <summary>
        /// Moves child buildings whose centerpoint is within the bounds into the tile.
        /// </summary>
        /// <param name="rd">The tile RD coordinates (bottomleft)</param>
        /// <param name="targetParentTile">Tile gameobject to move buildings into</param>
        /// <param name="removeOutside">Clear up the buildings that are outside</param>
        /// <returns></returns>
        private int MoveChildrenIntoTile(Vector2Int rd, GameObject targetParentTile, bool removeOutside = false)
        {
            //Lets use meshrenderer bounds to get the buildings centre for now, and put them in the right tile
            Vector3RD  childRDCenter;
            Vector2Int childGroupedTile;
            int        buildingsAdded = 0;

            MeshRenderer[] renderers = GetComponentsInChildren <MeshRenderer>(true);
            for (int i = renderers.Length - 1; i >= 0; i--)
            {
                var building = renderers[i];
                childRDCenter    = CoordConvert.UnitytoRD(building.bounds.center);
                childGroupedTile = new Vector2Int(
                    Mathf.FloorToInt((float)childRDCenter.x / tileSize) * tileSize,
                    Mathf.FloorToInt((float)childRDCenter.y / tileSize) * tileSize
                    );

                //If we have a tile for this object, put it in.
                if (childGroupedTile == rd)
                {
                    buildingsAdded++;
                    building.transform.SetParent(targetParentTile.transform, true);
                }
                else if (removeOutside && !overrideChildObjects.Contains(building.gameObject))
                {
                    //This child is not in our tile. destroy it. Leave it there if it is an override object
                    Destroy(building.GetComponent <MeshFilter>().sharedMesh);
                    Destroy(building.gameObject);
                }
            }
            return(buildingsAdded);
        }
    private void SetGPSCoordinates()
    {
        //Get the GPS coordinates for our world centre
        var coordinates = CoordConvert.UnitytoWGS84(Vector3.zero);

        longitude = coordinates.lon;
        latitude  = coordinates.lat;
    }
Example #8
0
 private void ReadVertices()
 {
     Vector3[] verts = mesh.vertices;
     rdVertices = new Vector3RD[verts.Length];
     for (int i = 0; i < verts.Length; i++)
     {
         rdVertices[i] = CoordConvert.UnitytoRD((verts[i] + tileOrigin));
     }
 }
        /// <summary>
        /// Load all the large ground tiles from AssetBundles, spawn it in our world, and start filling it with the trees that match the tile
        /// its RD coordinate rectangle. The tiles are named after the RD coordinates in origin at the bottomleft of the tile.
        /// </summary>
        private IEnumerator TraverseTileFiles()
        {
            var info     = new DirectoryInfo(sourceGroundTilesFolder);
            var fileInfo = info.GetFiles();

            var currentFile = 0;

            while (currentFile < fileInfo.Length)
            {
                FileInfo file = fileInfo[currentFile];
                if (!file.Name.Contains(".manifest") && file.Name.Contains("_"))
                {
                    Debug.Log($"Filling tile {currentFile}/{fileInfo.Length} {file.Name}");
                    yield return(new WaitForEndOfFrame());


                    string[] splitted    = file.Name.Split('_');
                    string[] coordinates = splitted[1].Split('-');

                    Vector3RD tileRDCoordinatesBottomLeft = new Vector3RD(double.Parse(coordinates[0]), double.Parse(coordinates[1]), 0);

                    var assetBundleTile = AssetBundle.LoadFromFile(file.FullName);

                    var mesh = assetBundleTile.LoadAllAssets <Mesh>().First();

                    if (mesh.bounds.size == Vector3.zero)
                    {
                        Debug.Log($"mesh bound is zero {file.Name}");
                        currentFile++;
                        continue;
                    }

                    GameObject newTile = new GameObject();
                    newTile.isStatic = true;
                    newTile.name     = file.Name;
                    newTile.AddComponent <MeshFilter>().sharedMesh   = mesh;
                    newTile.AddComponent <MeshCollider>().sharedMesh = mesh;
                    newTile.AddComponent <MeshRenderer>().material   = previewMaterial;
                    newTile.GetComponent <MeshRenderer>().materials  = _terrainMaterials.ToArray();

                    newTile.transform.position = CoordConvert.RDtoUnity(tileRDCoordinatesBottomLeft);

                    GameObject treeRoot = new GameObject();
                    treeRoot.name = file.Name.Replace("terrain", "trees");
                    treeRoot.transform.position = newTile.transform.position;

                    yield return(new WaitForEndOfFrame());                    //Make sure collider is processed

                    // yield return new WaitForSeconds(0.3f);


                    SpawnTreesInTile(treeRoot, tileRDCoordinatesBottomLeft);
                }
                currentFile++;
            }
        }
        private Vector3Int GetCameraPosition(ICameraExtents cameraExtents)
        {
            var        cameraPositionRD = CoordConvert.UnitytoRD(cameraExtents.GetPosition());
            Vector3Int cameraPosition   = new Vector3Int();

            cameraPosition.x = (int)cameraPositionRD.x;
            cameraPosition.y = (int)cameraPositionRD.y;
            cameraPosition.z = (int)cameraPositionRD.z;
            return(cameraPosition);
        }
Example #11
0
        /// <summary>
        /// Used from Javascript to move the camera to a specific WGS84 (gps) location based on the hash # in the url
        /// </summary>
        /// <param name="latitudeLongitude">Comma seperated lat,long string</param>
        public void ChangedPointFromUrl(string latitudeLongitude)
        {
            string[] coordinates = latitudeLongitude.Split(',');
            var      latitude    = double.Parse(coordinates[0]);
            var      longitude   = double.Parse(coordinates[1]);

            var convertedCoordinate = CoordConvert.WGS84toUnity(longitude, latitude);

            currentCamera.transform.position = new Vector3(convertedCoordinate.x, this.transform.position.y, convertedCoordinate.z);
        }
 public Vector3 GetUnityPoint(double x, double y, double z)
 {
     if (Config.activeConfiguration.sewerageApiType == SewerageApiType.Amsterdam)
     {
         return(CoordConvert.WGS84toUnity(new Vector3WGS(x, y, z + Config.activeConfiguration.zeroGroundLevelY)));
     }
     else
     {
         return(CoordConvert.RDtoUnity(new Vector3RD(x, y, z + Config.activeConfiguration.zeroGroundLevelY)));
     }
 }
Example #13
0
    //private void HandleInsideTile(TerrainTile terrainTile, int X, int Y)
    // {
    //     if (terrainTile == null)
    //     {
    //         activeTiles--;
    //         return;
    //     }
    //     Debug.Log(X + "-" + Y + " :insideTile");
    //     Vector3WGS centerWGS = TerrainTileCenterWGS(X, Y);
    //     Vector3 centerUnity = CoordConvert.WGS84toUnity(extentWGS.x, extentWGS.y);
    //     centerUnity.y = 0;
    //     Vector3RD[] verticesRD = getVerticesRD(terrainTile, X, Y, centerWGS);
    //     Vector3[] verticesUnity = VerticesRDtoUnity(verticesRD, centerUnity);
    //     int[] triangles = getTriangles(terrainTile);
    //     Mesh newSubMesh = new Mesh();
    //     newSubMesh.vertices = verticesUnity;
    //     newSubMesh.triangles = triangles;
    //     newSubMesh.uv = getUVs(verticesRD);
    //     newSubMesh.RecalculateNormals();
    //    submeshes.Add(newSubMesh);
    //     activeTiles--;
    // }
    private Vector3[] VerticesRDtoUnity(Vector3RD[] verticesRD, Vector3 unityOrigin)
    {
        int vertexcount = verticesRD.Length;

        Vector3[] verticesUnity = new Vector3[vertexcount];
        for (int i = 0; i < vertexcount; i++)
        {
            verticesUnity[i] = CoordConvert.RDtoUnity(verticesRD[i]) - unityOrigin;
        }
        return(verticesUnity);
    }
 private void OnDrawGizmos()
 {
     Gizmos.color = Color.white;
     foreach (var tileList in tileDistances)
     {
         foreach (var tile in tileList)
         {
             Gizmos.DrawWireCube(CoordConvert.RDtoUnity(new Vector3(tile.x + 500, tile.y + 500, 0)), new Vector3(1000, 100, 1000));
         }
     }
 }
        /// <summary>
        /// Load all the large ground tiles from AssetBundles, spawn it in our world, and start filling it with the trees that match the tile
        /// its RD coordinate rectangle. The tiles are named after the RD coordinates in origin at the bottomleft of the tile.
        /// </summary>
        private IEnumerator TraverseTileFiles()
        {
            var info     = new DirectoryInfo(sourceGroundTilesFolder);
            var fileInfo = info.GetFiles();

            var currentFile = 0;

            while (currentFile < fileInfo.Length)
            {
                FileInfo file = fileInfo[currentFile];
                if (!file.Name.Contains(".manifest") && file.Name.Contains("_"))
                {
                    Debug.Log("Filling tile " + currentFile + "/" + fileInfo.Length);
                    yield return(new WaitForEndOfFrame());

                    string filename = file.Name;
                    filename = filename.Replace("terrain_", "");
                    string[] coordinates = filename.Split('-');

                    Vector3RD tileRDCoordinatesBottomLeft = new Vector3RD(double.Parse(coordinates[0], System.Globalization.CultureInfo.InvariantCulture), double.Parse(coordinates[1], System.Globalization.CultureInfo.InvariantCulture), 0);
                    Vector3RD tileCenter          = new Vector3RD(tileRDCoordinatesBottomLeft.x + 500, tileRDCoordinatesBottomLeft.y + 500, tileRDCoordinatesBottomLeft.z);
                    var       assetBundleTile     = AssetBundle.LoadFromFile(file.FullName);
                    Mesh[]    meshesInAssetbundle = new Mesh[0];
                    try
                    {
                        meshesInAssetbundle = assetBundleTile.LoadAllAssets <Mesh>();
                    }
                    catch (Exception)
                    {
                        Debug.Log("Could not find a mesh in this assetbundle.");
                        assetBundleTile.Unload(true);
                    }

                    GameObject newTile = new GameObject();
                    newTile.isStatic = true;
                    newTile.name     = file.Name;
                    newTile.AddComponent <MeshFilter>().sharedMesh   = meshesInAssetbundle[0];
                    newTile.AddComponent <MeshCollider>().sharedMesh = meshesInAssetbundle[0];

                    newTile.AddComponent <MeshRenderer>().material = previewMaterial;
                    newTile.transform.position = CoordConvert.RDtoUnity(tileCenter);

                    GameObject treeRoot = new GameObject();
                    treeRoot.name = file.Name.Replace("terrain", "trees");
                    treeRoot.transform.position = newTile.transform.position;

                    yield return(new WaitForEndOfFrame());                    //Make sure collider is processed

                    SpawnTreesInTile(treeRoot, tileRDCoordinatesBottomLeft);
                }
                currentFile++;
            }
        }
        private GameObject CreateNewGameObject(AssetBundle assetBundle, TileChange tileChange)
        {
            container = new GameObject();

            container.name               = tileChange.X.ToString() + "-" + tileChange.Y.ToString();
            container.transform.parent   = transform.gameObject.transform;
            container.layer              = container.transform.parent.gameObject.layer;
            container.transform.position = CoordConvert.RDtoUnity(new Vector2(tileChange.X + 500, tileChange.Y + 500));

            container.SetActive(isEnabled);
            //Mesh[] meshesInAssetbundle = new Mesh[0];
            try
            {
                meshesInAssetbundle = assetBundle.LoadAllAssets <Mesh>();
            }
            catch (Exception)
            {
                Destroy(container);
                assetBundle.Unload(true);
                return(null);
            }
            mesh = meshesInAssetbundle[0];

            int count = mesh.vertexCount;

            // creating the UV-s runtime takes a lot of time and causes the garbage-collector to kick in.
            // uv's should be built in in to the meshes in the assetbundles.
            if (addHighlightuvs)
            {
                uvs = new Vector2[count];
                for (int i = 0; i < count; i++)
                {
                    uvs[i] = (defaultUV);
                }
                mesh.uv2 = uvs;
            }

            container.AddComponent <MeshFilter>().sharedMesh = mesh;

            meshRenderer = container.AddComponent <MeshRenderer>();
            meshRenderer.sharedMaterials   = DefaultMaterialList.ToArray();
            meshRenderer.shadowCastingMode = tileShadowCastingMode;

            if (createMeshcollider)
            {
                container.AddComponent <MeshCollider>().sharedMesh = mesh;
            }

            assetBundle.Unload(false);

            return(container);
        }
        void ReadTreesFromCsv()
        {
            var lines = File.ReadAllLines(CsvFile);

            foreach (var line in lines.Skip(1))
            {
                try
                {
                    var columns = line.Split(';');
                    var tree    = new Tree();

                    tree.OBJECTNUMMER = columns[0];
                    tree.Soortnaam_NL = columns[1];
                    tree.Boomhoogte   = columns[2];
                    tree.Plantjaar    = int.Parse(columns[3]);
                    tree.RD           = new Vector3RD(Convert.ToDouble(columns[5]), Convert.ToDouble(columns[6]), 0);

                    //var longlat = ConvertToLatLong(tree.RD.x, tree.RD.y);

                    tree.position = CoordConvert.RDtoUnity(tree.RD);
                    //tree.position = CoordConvert.WGS84toUnity(longlat.longitude, longlat.latitude);


                    tree.averageTreeHeight = EstimateTreeHeight(tree.Boomhoogte);
                    tree.prefab            = FindClosestPrefabTypeByName(tree.Soortnaam_NL);
                    //tree.prefab = TestCube;
                    trees.Add(tree);
                }
                catch
                {
                }
            }

            //398 soorten bomen
            var soorten    = trees.GroupBy(o => o.Soortnaam_NL).ToArray();
            var hoogtrd    = trees.GroupBy(o => o.Boomhoogte).ToArray();
            var oldestTree = trees.Min(o => o.Plantjaar);

            Debug.Log($"Aantal bomen:{trees.Count} soorten:{soorten.Length} Oudste boom:{oldestTree}");

            var minx = trees.Min(o => o.RD.x);
            var miny = trees.Min(o => o.RD.y);
            var maxx = trees.Max(o => o.RD.x);
            var maxy = trees.Max(o => o.RD.y);

            var avgHoogteMin = trees.Min(o => o.averageTreeHeight);
            var avgHoogteMax = trees.Max(o => o.averageTreeHeight);

            Debug.Log($"minx:{minx} maxx:{maxx} miny:{miny} maxy:{maxy}");

            //minx:126805.07 maxx:141827.31 miny:448979.02 maxy:461149.85
        }
Example #18
0
        private List <Vector3> CreateVectorlist(List <Vector3Double> vectors)
        {
            List <Vector3> output = new List <Vector3>();
            Vector3        vect;

            for (int i = 0; i < vectors.Count; i++)
            {
                vect = CoordConvert.RDtoUnity(new Vector3RD(vectors[i].x, vectors[i].y, vectors[i].z)) - offset;
                output.Add(vect);
            }
            output.Reverse();
            return(output);
        }
        /// <summary>
        /// uses CameraExtent
        /// updates the variable viewrange
        /// updates the variable cameraPositionRD
        /// updates the variable cameraPosition
        /// </summary>
        private Vector4 GetViewRange(ICameraExtents cameraExtents)
        {
            var     bottomLeft = CoordConvert.WGS84toRD(cameraExtents.GetExtent().MinX, cameraExtents.GetExtent().MinY);
            var     topRight   = CoordConvert.WGS84toRD(cameraExtents.GetExtent().MaxX, cameraExtents.GetExtent().MaxY);
            Vector4 viewRange  = new Vector4();

            viewRange.x = (float)bottomLeft.x;
            viewRange.y = (float)bottomLeft.y;
            viewRange.z = (float)(topRight.x - bottomLeft.x);
            viewRange.w = (float)(topRight.y - bottomLeft.y);

            return(viewRange);
        }
Example #20
0
        private List <Vector3RD> GetVertsRD(CityModel cityModel)
        {
            List <Vector3RD> vertsRD          = new List <Vector3RD>();
            Vector3          vertexCoordinate = new Vector3();

            foreach (Vector3Double vertex in cityModel.vertices)
            {
                vertexCoordinate.x = (float)vertex.x;
                vertexCoordinate.y = (float)vertex.z;
                vertexCoordinate.z = (float)vertex.y;
                vertsRD.Add(CoordConvert.UnitytoRD(vertexCoordinate));
            }
            return(vertsRD);
        }
        private Tile CreateNewTile(TileChange tileChange)
        {
            Tile tile = new Tile();

            tile.LOD        = 0;
            tile.tileKey    = new Vector2Int(tileChange.X, tileChange.Y);
            tile.layer      = transform.gameObject.GetComponent <Layer>();
            tile.gameObject = new GameObject();
            tile.gameObject.transform.parent   = transform.gameObject.transform;
            tile.gameObject.layer              = tile.gameObject.transform.parent.gameObject.layer;
            tile.gameObject.transform.position = CoordConvert.RDtoUnity(new Vector2(tileChange.X, tileChange.Y));

            return(tile);
        }
Example #22
0
        private List <Vector3> GetVerts(CityModel cityModel, Vector3RD origin)
        {
            List <Vector3> verts            = new List <Vector3>();
            Vector3        unityOrigin      = CoordConvert.RDtoUnity(origin);
            Vector3RD      vertexCoordinate = new Vector3RD();

            foreach (Vector3Double vertex in cityModel.vertices)
            {
                vertexCoordinate.x = vertex.x;
                vertexCoordinate.y = vertex.y;
                vertexCoordinate.z = vertex.z;
                verts.Add(CoordConvert.RDtoUnity(vertexCoordinate) - unityOrigin);
            }

            return(verts);
        }
Example #23
0
    private IEnumerator createFile(Bounds UnityBounds, List <Layer> layerList)
    {
        freezeLayers(layerList, true);
        Debug.Log(layerList.Count);
        Vector3RD bottomLeftRD = CoordConvert.UnitytoRD(UnityBounds.min);
        Vector3RD topRightRD   = CoordConvert.UnitytoRD(UnityBounds.max);

        boundingbox = new MeshClipper.RDBoundingBox(bottomLeftRD.x, bottomLeftRD.y, topRightRD.x, topRightRD.y);
        DxfFile file = new DxfFile();

        file.SetupDXF();
        yield return(null);

        MeshClipper meshClipper = new MeshClipper();

        loadingScreen.ShowMessage("dxf-bestand genereren...");
        loadingScreen.ProgressBar.Percentage(0f);

        int layercounter = 0;

        foreach (var layer in layerList)
        {
            List <GameObject> gameObjectsToClip = getTilesInLayer(layer, bottomLeftRD, topRightRD);
            if (gameObjectsToClip.Count == 0)
            {
                continue;
            }
            foreach (var gameObject in gameObjectsToClip)
            {
                meshClipper.SetGameObject(gameObject);
                for (int submeshID = 0; submeshID < gameObject.GetComponent <MeshFilter>().sharedMesh.subMeshCount; submeshID++)
                {
                    meshClipper.clipSubMesh(boundingbox, submeshID);
                    string layerName = gameObject.GetComponent <MeshRenderer>().sharedMaterials[submeshID].name.Replace(" (Instance)", "");

                    file.AddLayer(meshClipper.clippedVerticesRD, layerName, getColor(gameObject.GetComponent <MeshRenderer>().sharedMaterials[submeshID]));
                    yield return(null);
                }
            }
            loadingScreen.ProgressBar.Percentage(50 * layercounter / layerList.Count);
            layercounter++;
        }
        freezeLayers(layerList, false);
        file.Save();
        loadingScreen.Hide();
        Debug.Log("file saved");
    }
Example #24
0
    // for debugging, create a mesh from the triangleList
    private void CreateMesh(List <Vector3RD> points)
    {
        List <Vector3> vertices = new List <Vector3>();
        List <int>     indices  = new List <int>();

        for (int i = 0; i < points.Count; i++)
        {
            vertices.Add(CoordConvert.RDtoUnity(points[i]));
            indices.Add(i);
        }
        Mesh mesh = new Mesh();

        mesh.vertices = vertices.ToArray();
        mesh.SetIndices(indices.ToArray(), MeshTopology.Triangles, 0);
        mesh.RecalculateNormals();
        gameObject.GetComponent <MeshFilter>().sharedMesh = mesh;
    }
 public void Start()
 {
     //Calculate offset. ( Our viewer expects tiles with the origin in the center )
     tileOffset = new Vector3RD()
     {
         x = Config.activeConfiguration.RelativeCenterRD.x,
         y = Config.activeConfiguration.RelativeCenterRD.y,
         z = 0
     };
     tileOffset.x      -= 500;
     tileOffset.y      -= 500;
     unityTileOffset    = CoordConvert.RDtoUnity(tileOffset);
     trees              = new List <Tree>();
     treeLines          = new List <string>();
     noPrefabFoundNames = new List <string>();
     ParseTreeData();
 }
Example #26
0
        private Vector2[] RDuv2(Vector3[] verts, Vector3 UnityOrigin, float tileSize)
        {
            Vector3   UnityCoordinate;
            Vector3RD rdCoordinate;
            Vector3RD rdOrigin = CoordConvert.UnitytoRD(UnityOrigin);
            float     offset   = -tileSize / 2;

            Vector2[] uv2 = new Vector2[verts.Length];
            for (int i = 0; i < verts.Length; i++)
            {
                UnityCoordinate = verts[i] + UnityOrigin;
                rdCoordinate    = CoordConvert.UnitytoRD(UnityCoordinate);
                uv2[i].x        = ((float)(rdCoordinate.x - rdOrigin.x) + offset) / tileSize;
                uv2[i].y        = ((float)(rdCoordinate.y - rdOrigin.y) + offset) / tileSize;
            }
            return(uv2);
        }
Example #27
0
        /// <summary>
        /// Splits an unsupported multidimensional array into a Vector3 array.
        /// </summary>
        /// <param name="coordinates">The string containing the multidimensional array</param>
        /// <returns>An array of unity coordinates</returns>
        private Vector3[] SplitToCoordinatesArray(string coordinates, string startHeight, string endHeight)
        {
            splitArray = coordinates.Split(new string[] { "],[" }, StringSplitOptions.None);
            newVector2Array.Clear();

            //Convert string with RD coordinates into unity coordinates
            for (int i = 0; i < splitArray.Length; i++)
            {
                vector2String = splitArray[i].Split(',');
                Vector3WGS newWGSVector3 = new Vector3WGS(
                    double.Parse(vector2String[0], CultureInfo.InvariantCulture),
                    double.Parse(vector2String[1], CultureInfo.InvariantCulture),
                    (i == 0) ? double.Parse(startHeight, CultureInfo.InvariantCulture) + napOffset : double.Parse(endHeight, CultureInfo.InvariantCulture) + napOffset
                    );

                Vector3 unityCoordinate = CoordConvert.WGS84toUnity(newWGSVector3);
                newVector2Array.Add(unityCoordinate);
            }
            return(newVector2Array.ToArray());
        }
        public void Start()
        {
            Directory.CreateDirectory("Assets/TreeTileAssets/");

            //Calculate offset. ( Our viewer expects tiles with the origin in the center )
            tileOffset      = Config.activeConfiguration.RelativeCenterRD;       // CoordConvert.referenceRD;
            tileOffset.x   -= 500;
            tileOffset.y   -= 500;
            unityTileOffset = CoordConvert.RDtoUnity(new Vector2((float)tileOffset.x, (float)tileOffset.y));

            trees = new List <Tree>();

            noPrefabFoundNames = new List <string>();

            ReadTreesFromCsv();

            //DrawTrees(bomen.Take(100).ToList());
            //DrawTrees(bomen);

            StartCoroutine(TraverseTileFiles());
        }
        private void GetTileDistancesInView(List <int> tileSizes, Vector4 viewRange, Vector3Int cameraPosition)
        {
            //Godview only frustum check
            if (filterByCameraFrustum && CameraModeChanger.Instance.CameraMode == CameraMode.GodView)
            {
                GeometryUtility.CalculateFrustumPlanes(CameraModeChanger.Instance.ActiveCamera, cameraFrustumPlanes);
            }
            tileDistances.Clear();

            foreach (int tileSize in tileSizes)
            {
                startX = (int)Math.Floor(viewRange.x / tileSize) * tileSize;
                startY = (int)Math.Floor(viewRange.y / tileSize) * tileSize;
                endX   = (int)Math.Ceiling((viewRange.x + viewRange.z) / tileSize) * tileSize;
                endY   = (int)Math.Ceiling((viewRange.y + viewRange.w) / tileSize) * tileSize;
                tileList.Clear();

                for (int x = startX; x <= endX; x += tileSize)
                {
                    for (int y = startY; y <= endY; y += tileSize)
                    {
                        Vector3Int tileID = new Vector3Int(x, y, tileSize);
                        if (filterByCameraFrustum && CameraModeChanger.Instance.CameraMode == CameraMode.GodView)
                        {
                            tileBounds.SetMinMax(CoordConvert.RDtoUnity(new Vector2(x, y)), CoordConvert.RDtoUnity(new Vector2(x + tileSize, y + tileSize)));
                            if (GeometryUtility.TestPlanesAABB(cameraFrustumPlanes, tileBounds))
                            {
                                tileList.Add(new Vector3Int(x, y, (int)GetTileDistanceSquared(tileID, cameraPosition)));
                            }
                        }
                        else
                        {
                            tileList.Add(new Vector3Int(x, y, (int)GetTileDistanceSquared(tileID, cameraPosition)));
                        }
                    }
                }

                tileDistances.Add(tileList);
            }
        }
Example #30
0
    IEnumerator GetAssetFromWebserver(TileChange tileChange, System.Action <TileChange> callback = null)
    {
        var x = tileChange.X;
        var y = tileChange.Y;

        var name = _replaceString.Replace("{x}", x.ToString()).Replace("{y}", y.ToString());

        if (_tiles.ContainsKey(name) == false)
        {
            Uri baseUri = new Uri(Config.activeConfiguration.webserverRootPath);
            var uri     = new Uri(baseUri, name);
            var tilepos = CoordConvert.RDtoUnity(new Vector3(x, y, 0));
            using (UnityWebRequest uwr = UnityWebRequestAssetBundle.GetAssetBundle(uri.AbsoluteUri))
            {
                yield return(uwr.SendWebRequest());

                if (!uwr.isNetworkError && !uwr.isHttpError)
                {
                    AssetBundle assetBundle = DownloadHandlerAssetBundle.GetContent(uwr);

                    // yield return new WaitUntil(() => pauseLoading == false);

                    var        mesh = assetBundle.LoadAllAssets <Mesh>().First();
                    GameObject gam  = new GameObject();
                    gam.transform.localScale = Vector3.one * _scale;
                    gam.name               = name;
                    gam.transform.parent   = transform;
                    gam.transform.position = tilepos + _offset;
                    gam.AddComponent <MeshFilter>().sharedMesh = mesh;
                    gam.AddComponent <MeshRenderer>().material = _material;

                    callback(tileChange);

                    _tiles.Add(name, gam);
                }
            }
        }
        callback(tileChange);
    }