Example #1
0
        public CRefTree(string pFileName, int pTreeIndex, float pTreePointExtent, bool pLoadFromFile)
        {
            treeIndex       = pTreeIndex;
            fileName        = pFileName;
            treePointExtent = pTreePointExtent;
            isValid         = true;

            if (pLoadFromFile)
            {
                string[] lines = GetFileLines(pFileName);
                if (lines.Length == 0)
                {
                    isValid = false;
                    return;
                }

                LoadObj(pFileName);

                List <Tuple <EClass, Vector3> > parsedLines = CProgramLoader.ParseLines(lines, false);
                AddPointsFromLines(parsedLines);
                DateTime processStartTime = DateTime.Now;
                CDebug.WriteLine("Process");
                Process();
                CDebug.Duration("Processed", processStartTime);
            }
        }
Example #2
0
        /// <summary>
        /// Assigns ground points into arrays (main and detailed for precess and later bitmap generation).
        /// Fills missing heights in the array and applies smoothing.
        /// </summary>
        private void ProcessGroundPoints()
        {
            if (CRxpParser.IsRxp)
            {
                return;
            }

            for (int i = 0; i < ground.Count; i++)
            {
                if (CProjectData.backgroundWorker.CancellationPending)
                {
                    return;
                }

                Vector3 point = ground[i];
                groundArray.AddPointInField(point);
                //some points can be at border of detail array - not error -> dont log
                //detailArray?.AddPointInField(point, CGroundArray.EPointType.Ground, false);
            }

            if (groundArray == null)
            {
                CDebug.Error("No array defined");
                CDebug.WriteLine("setting height to " + lowestHeight);
                //CDebugData.DefineArray(true, lowestHeight);
            }

            groundArray.FillArray();

            groundArray?.SmoothenArray(1);
        }
Example #3
0
        public virtual void FillMissingHeight(EFillMethod pMethod, int pParam = -1)
        {
            if (IsDetail && Equals(63, 75))
            {
                CDebug.WriteLine();
            }

            //if(IsDefined()) { return; }
            if (MaxFilledHeight != null)
            {
                return;
            }

            int maxSteps = 1;

            switch (pMethod)
            {
            case EFillMethod.ClosestDefined:
                MaxFilledHeight = GetAverageHeightFromClosestDefined(10 * maxSteps, false, EHeight.Smooth);
                break;

            case EFillMethod.FromNeighbourhood:
                MaxFilledHeight = GetAverageHeightFromNeighbourhood(pParam);
                //MaxFilledHeight = GetMaxHeightFromNeigbourhood();
                break;
            }
        }
Example #4
0
        /*public void AddPointInField(Vector3 pPoint, EPointType pType, bool pLogErrorInAnalytics)
         * {
         *      Tuple<int, int> index = GetPositionInArray(pPoint);
         *      if (!IsWithinBounds(index))
         *      {
         *              CDebug.Error($"point {pPoint} is OOB {index}", pLogErrorInAnalytics);
         *              return;
         *      }
         *      switch (pType)
         *      {
         *              case EPointType.Ground:
         *                      array[index.Item1, index.Item2].AddGroundPoint(pPoint);
         *                      break;
         *              case EPointType.Vege:
         *                      array[index.Item1, index.Item2].AddVegePoint(pPoint);
         *                      break;
         *              case EPointType.Preprocess:
         *                      array[index.Item1, index.Item2].AddPreProcessVegePoint(pPoint);
         *                      break;
         *      }
         * }*/

        //public void SortPoints()
        //{
        //	foreach (CField field in fields)
        //	{
        //		field.SortPoints();
        //	}
        //}


        /// <summary>
        /// Approximates the height in undefined fields of ground array.
        /// </summary>
        public void FillArray()
        {
            CDebug.WriteLine("FillArray", true);

            DateTime fillAllHeightsStart = DateTime.Now;

            int counter = 1;

            while (!IsAllDefined())
            {
                if (CProjectData.backgroundWorker.CancellationPending)
                {
                    return;
                }

                DateTime fillHeightsStart = DateTime.Now;

                CDebug.Count("FillMissingHeights", counter);
                FillMissingHeights(counter);
                counter++;
                const int maxFillArrayIterations = 5;
                if (counter > maxFillArrayIterations + 1)
                {
                    CDebug.Error("FillMissingHeights");
                    CDebug.Count("too many iterations", counter);
                    break;
                }
                CDebug.Duration("FillMissingHeights", fillHeightsStart);
            }
            CAnalytics.fillAllHeightsDuration = CAnalytics.GetDuration(fillAllHeightsStart);
            CDebug.Duration("fillAllHeights", fillAllHeightsStart);
        }
Example #5
0
        /// <summary>
        /// Returns true if tree was added
        /// </summary>
        public bool AddDetectedTree(CTree pTree, bool pIsPeak)
        {
            //if tree is not peak, dont set IsPeak to false, could be a peak from previous tree
            if (pIsPeak)
            {
                IsPeak = true;
            }

            if (this.indexInField.Item1 == 171 && this.indexInField.Item1 == 144)
            {
                CDebug.WriteLine();
            }

            if (!DetectedTrees.Contains(pTree))
            {
                if (IsDetail && DetectedTrees.Count > 0)
                {
                    CDebug.Error($"Adding tree to detail field {this} where tree {DetectedTrees[0]} altready is");
                }

                DetectedTrees.Add(pTree);
                pTree.AddField(this);
                return(true);
            }
            return(false);
        }
Example #6
0
        private void AddPointsFromLines(List <Tuple <EClass, Vector3> > pParsedLines)
        {
            DateTime addStartTime = DateTime.Now;

            CDebug.WriteLine("AddPointsFromLines " + pParsedLines.Count);
            int pointsToAddCount = pParsedLines.Count;

            pParsedLines.Sort((a, b) => b.Item2.Z.CompareTo(a.Item2.Z));
            //lines are sorted. first point is peak for sure
            Init(pParsedLines[0].Item2, treeIndex, treePointExtent);

            DateTime lineStartTime = DateTime.Now;

            for (int i = 1; i < Math.Min(pParsedLines.Count, pointsToAddCount); i++)
            {
                Tuple <EClass, Vector3> parsedLine = pParsedLines[i];
                Vector3 point = parsedLine.Item2;

                //all points belong to 1 tree. force add it
                AddPoint(point);

                CDebug.Progress(i, pParsedLines.Count, 100000, ref lineStartTime, addStartTime, "added point:");
            }
            CDebug.Duration("All points added", addStartTime);
        }
Example #7
0
        /// <summary>
        /// Assigns vege poins to trees. Handled in TreeManager
        /// </summary>
        private void ProcessVegePoints()
        {
            vege.Sort((b, a) => a.Z.CompareTo(b.Z));             //sort descending by height

            const int debugFrequency = 10000;

            DateTime processVegePointsStart = DateTime.Now;

            CDebug.WriteLine("ProcessVegePoints", true);

            DateTime previousDebugStart = DateTime.Now;


            int pointsToAddCount = vege.Count;

            //pointsToAddCount = 12000;

            for (int i = 0; i < pointsToAddCount; i++)
            {
                if (CProjectData.backgroundWorker.CancellationPending)
                {
                    return;
                }

                Vector3 point = vege[i];
                CTreeManager.AddPoint(point, i);

                CDebug.Progress(i, vege.Count, debugFrequency, ref previousDebugStart, processVegePointsStart, "added point");
            }
            CDebug.WriteLine("maxPossibleTreesAssignment = " + CTreeManager.maxPossibleTreesAssignment + " todo: investigate if too high");


            CAnalytics.processVegePointsDuration = CAnalytics.GetDuration(processVegePointsStart);
            CDebug.Duration("ProcessVegePoints", processVegePointsStart);
        }
Example #8
0
        private void LoadObj(string pFileName)
        {
            Obj = new Obj(pFileName);

            string refTreePath = GetRefTreeFilePath(pFileName, pFileName + ".obj");

            bool useReducedReftreeModels = CParameterSetter.GetBoolSettings(ESettings.useReducedReftreeModels);

            if (useReducedReftreeModels || !File.Exists(refTreePath))
            {
                Obj.Name += "_reduced";

                string reducedObjFileName = pFileName + "_reduced.obj";

                if (!useReducedReftreeModels)
                {
                    CDebug.WriteLine("Reftree " + refTreePath + " OBJ does not exist.");
                    CDebug.WriteLine("Try reduced file: " + reducedObjFileName);
                }
                refTreePath = GetRefTreeFilePath(pFileName, reducedObjFileName);
                if (!File.Exists(refTreePath))
                {
                    CDebug.Error("No ref tree OBJ found!");
                    return;
                }
            }

            Obj.LoadObj(refTreePath);
        }
Example #9
0
        public static void TryMergeAllTrees(bool pOnlyInvalid)
        {
            IsMerging = true;
            DateTime mergeStartTime = DateTime.Now;

            CDebug.WriteLine("TryMergeAllTrees");

            Trees.Sort((a, b) => b.peak.Center.Z.CompareTo(a.peak.Center.Z));

            int treeCountBeforeMerge = Trees.Count;

            if (detectMethod == EDetectionMethod.AddFactor)
            {
                MergeGoodAddFactorTrees(pOnlyInvalid);
            }
            if (detectMethod == EDetectionMethod.Detection2D)
            {
                Merge2DTrees();
            }

            if (pOnlyInvalid)
            {
                CAnalytics.secondMergeDuration = CAnalytics.GetDuration(mergeStartTime);
            }
            else
            {
                CAnalytics.firstMergeDuration = CAnalytics.GetDuration(mergeStartTime);
            }
            IsMerging = false;

            CDebug.Duration("Trees merge", mergeStartTime);
            CDebug.Count("Number of trees merged", treeCountBeforeMerge - Trees.Count);
        }
Example #10
0
        /// <summary>
        /// Calculates rigid transformations between all permutations of pSetA and pSetB
        /// and returns the best one (having the smallest offset).
        /// This is done due to the expected indexing in function CalculateRigidTransform
        /// </summary>
        public static CRigidTransform GetRigidTransform(List <Vector3> pSetA, List <Vector3> pSetB)
        {
            CDebug.WriteLine($"GetRigidTransform from set : {CDebug.GetString(pSetA)} to {CDebug.GetString(pSetB)}");
            if (pSetA.Count != pSetB.Count)
            {
                CDebug.Error("Sets copunt dont match");
                return(null);
            }

            IEnumerable <IEnumerable <Vector3> > setApermutations = pSetA.Permute();
            List <CRigidTransform> rigTransforms = new List <CRigidTransform>();

            foreach (var permutation in setApermutations)
            {
                CRigidTransform rigTransform = CalculateRigidTransform(permutation.ToList(), pSetB);
                rigTransforms.Add(rigTransform);
                //CDebug.WriteLine($"{rigTransform}");
                if (rigTransform.offset < MAX_OFFSET)
                {
                    break;
                }
            }

            CRigidTransform minOffsetRigTransform = rigTransforms.Aggregate(
                (curMin, x) => x.offset < curMin.offset ? x : curMin);

            CDebug.WriteLine($"Selected {minOffsetRigTransform}", true, true);
            return(minOffsetRigTransform);
        }
Example #11
0
        public static void ExportObjs(List <Obj> pObjs, string pFileName, string pFolderPath, bool pReverseObjOrder = true)
        {
            string filePath = GetFileExportPath(pFileName, pFolderPath);

            //in this project we first add array, points and then a lot of trees
            //it is better for debugging to have trees at the end of the list
            if (pReverseObjOrder)
            {
                pObjs.Reverse();
            }

            using (var outStream = File.OpenWrite(filePath))
                using (var writer = new StreamWriter(outStream))
                {
                    // Write some header data
                    WriteHeader(writer, pObjs);

                    if (CProjectData.useMaterial)
                    {
                        writer.WriteLine(CMaterialManager.materials);
                        CMaterialManager.materials.WriteMtlFile(pFolderPath, new[] { "materials" });
                    }

                    int vertexIndexOffset = 0;
                    foreach (Obj obj in pObjs)
                    {
                        if (CProjectData.backgroundWorker.CancellationPending)
                        {
                            return;
                        }

                        if (obj == null)
                        {
                            CDebug.WriteLine("Error: obj is null...WTF!");
                            continue;
                        }
                        writer.WriteLine("o " + obj.Name);

                        int thisTreeVertexIndexOffset = vertexIndexOffset;
                        foreach (Vertex v in obj.VertexList)
                        {
                            string vertexString = v.ToString(obj.GetVertexTransform());
                            writer.WriteLine(vertexString);
                            vertexIndexOffset++;
                        }

                        if (CProjectData.useMaterial)
                        {
                            writer.WriteLine("usemtl " + obj.UseMtl);
                        }

                        foreach (Face f in obj.FaceList)
                        {
                            writer.WriteLine(f.ToString(thisTreeVertexIndexOffset));
                        }
                    }
                }
            CDebug.WriteLine("Exported to " + filePath, true);
        }
Example #12
0
 private static void DebugReftrees()
 {
     CDebug.WriteLine("Loaded reftrees: ");
     foreach (CRefTree refTree in Trees)
     {
         CDebug.WriteLine(refTree.ToString());
     }
 }
        public static string LasSplit(string classifyFilePath)
        {
            SSplitRange range = CParameterSetter.GetSplitRange();

            if (!range.IsValid())
            {
                throw new Exception($"range {range} is not valid");
            }

            string splitFileName = $"{forestFileName}_s[{range.MinX},{range.MinY}]-[{range.MaxX},{range.MaxY}]";

            string keepXY        = $" -keep_xy {range.MinX} {range.MinY} {range.MaxX} {range.MaxY}";
            string splitFilePath = currentTmpFolder + splitFileName + LAZ;

            if (File.Exists(splitFilePath))
            {
                return(splitFilePath);                //already created
            }
            string split =
                "lassplit -i " +
                classifyFilePath +
                keepXY +
                " -o " +
                splitFilePath;

            //todo: when split file not created there is no error...(ie when invalid range is given)
            try
            {
                //todo: split fails on jen2_merged_preprocessed.laz
                CCmdController.RunLasToolsCmd(split, splitFilePath);
            }
            catch (Exception e)
            {
                //split command creates file with other name...
                CDebug.WriteLine($"exception {e}");
            }

            //for some reason output split file gets appendix: "_0000000" => rename it
            #region rename
            //rename split file

            //todo: move to Utils
            string   sourceFile = splitFileName + "_0000000" + LAZ;
            FileInfo fi         = new FileInfo(currentTmpFolder + sourceFile);
            if (fi.Exists)
            {
                fi.MoveTo(currentTmpFolder + splitFileName + LAZ);
                Console.WriteLine("Split file Renamed.");
            }
            else
            {
                //todo: implement my own exception
                throw new Exception($"Split file not created. Perhaps there are no points at range {range}?");
            }
            #endregion

            return(splitFilePath);
        }
Example #14
0
        private static void ExportCsv(List <Tuple <string, object> > pParams, string pName, bool pExportGlobal = false)
        {
            string fileName = pName + ".csv";
            string filePath = CProjectData.outputTileSubfolder + "/" + fileName;

            string[] pathSplit  = CProjectData.outputTileSubfolder.Split('\\');
            string   folderName = pathSplit[pathSplit.Length - 2];

            string line;

            using (var outStream = File.OpenWrite(filePath))
                using (var writer = new StreamWriter(outStream))
                {
                    writer.WriteLine(GetHeaderString(pParams));

                    writer.Write(folderName);
                    line = folderName;
                    foreach (Tuple <string, object> param in pParams)
                    {
                        string val = "," + param.Item2;
                        writer.Write(val);
                        line += val;
                    }
                }

            string   mainSummaryFile = CParameterSetter.GetStringSettings(ESettings.analyticsFilePath);
            FileMode fileMode        = FileMode.Append;

            if (!File.Exists(mainSummaryFile))
            {
                CDebug.WriteLine("analytics file not defined");
                if (!string.IsNullOrEmpty(mainSummaryFile))
                {
                    fileMode = FileMode.Create;
                    CDebug.WriteLine(" - creating");
                }
                else
                {
                    return;
                }
            }

            //if Append => file exists
            //just check if already contains some text
            //we expect, that if it already has text, it also contains header
            bool hasHeader = fileMode == FileMode.Append && File.ReadAllLines(mainSummaryFile).Length != 0;

            using (FileStream fs = new FileStream(mainSummaryFile, fileMode, FileAccess.Write))
                using (var writer = new StreamWriter(fs))
                {
                    if (!hasHeader)
                    {
                        writer.WriteLine(GetHeaderString(pParams));
                    }
                    writer.WriteLine(line);
                }
        }
Example #15
0
        public static void ToggleConsoleVisibility()
        {
            IntPtr handle         = CConsole.GetConsoleWindow();
            bool   consoleVisible = GetBoolSettings(ESettings.consoleVisible);

            CConsole.ShowWindow(handle, consoleVisible ? SW_HIDE : SW_SHOW);

            CDebug.WriteLine("ToggleConsoleVisibility " + !consoleVisible);
            SetParameter(ParamInfo.Name(() => consoleVisible), !consoleVisible);
        }
Example #16
0
        public string WriteBounds(bool pConsole = true)
        {
            string output = "[" + botLeftCorner + "," + topRightCorner + "]";

            if (pConsole)
            {
                CDebug.WriteLine(output);
            }
            return(output);
        }
Example #17
0
        /// <summary>
        /// If not-tree is very close to some tree then it is probably part of that tree.
        /// Not-tree will be merged into the closest one.
        /// </summary>
        public static void TryMergeNotTrees()
        {
            IsMerging = true;
            DateTime mergeStartTime = DateTime.Now;

            CDebug.WriteLine("TryMergeNotTrees");

            //sort in descending order - trees will be processed from the end
            NotTrees.Sort((b, a) => b.peak.Center.Z.CompareTo(a.peak.Center.Z));
            //TODO: CHECK!!! THIS IS NOT DESCENDING ORDER???


            int treeCountBeforeMerge = NotTrees.Count;

            for (int i = NotTrees.Count - 1; i >= 0; i--)
            {
                CTree notTree = NotTrees[i];
                //if(notTree.Equals(335))
                //	CDebug.WriteLine("");

                //just debug
                //List<CTree> closeTrees2 = CProjectData.Points.treeNormalArray.
                //		  GetTreesInMaxStepsFrom(notTree.peak.Center, 1);

                List <CTree> closeTrees = new List <CTree>();
                //fisrt try to get a tree on the same detail field
                CTree t = CProjectData.Points.treeDetailArray.
                          GetFieldContainingPoint(notTree.peak.Center).GetSingleDetectedTree();
                if (t != null)
                {
                    closeTrees.Add(t);
                }

                //if no tree is on the same field get some in close distance
                if (closeTrees.Count == 0)
                {
                    closeTrees = CProjectData.Points.treeDetailArray.
                                 GetTreesInMaxStepsFrom(notTree.peak.Center, 2);
                }

                //merge not-tree with the closest tree but only if it is higher.
                //if not then it is probably some noise above the regular tree
                if (closeTrees.Count > 0 &&
                    closeTrees[0].GetTreeHeight() > notTree.GetTreeHeight() &&
                    !notTree.IsLocalMaximum())
                {
                    closeTrees[0].MergeWith(notTree);
                    NotTrees.RemoveAt(i);
                }
            }
            IsMerging = false;

            CDebug.Duration("Not-trees merge", mergeStartTime);
            CDebug.Count("Number of not-trees merged", treeCountBeforeMerge - Trees.Count);
        }
Example #18
0
 public static void DebugTree(int pIndex)
 {
     foreach (CTree tree in Trees)
     {
         if (tree.treeIndex == pIndex)
         {
             CDebug.WriteLine("DebugTree " + tree);
             return;
         }
     }
 }
Example #19
0
        public static void RunLasToolsCmd(string pLasToolCommand, string pOutputFilePath)
        {
            if (!CanRunCommand(pLasToolCommand))
            {
                throw new Exception($"Cannot run command: {ParseCommand(pLasToolCommand)} {Environment.NewLine} {pLasToolCommand}");
            }

            //string outputFilePath = tmpFolder + pOutputFilePath;
            bool outputFileExists = File.Exists(pOutputFilePath);

            CDebug.WriteLine($"file: {pOutputFilePath} exists = {outputFileExists}");

            if (!outputFileExists)
            {
                string command = "/C " + pLasToolCommand;

                //if(!Directory.Exists(lasToolsFolder))
                //{
                //	//todo: make own exception
                //	throw new Exception("LasToolsFolder not found");
                //}

                ProcessStartInfo processStartInfo = new ProcessStartInfo
                {
                    WorkingDirectory = lasToolsFolder,
                    FileName         = "CMD.exe",
                    Arguments        = command,
                    CreateNoWindow   = true,
                    WindowStyle      = ProcessWindowStyle.Hidden,
                    UseShellExecute  = false
                };

                //ProcessStartInfo processStartInfo = new ProcessStartInfo(
                //	lasToolsFolder + "lasinfo.exe", "D:\\Resources\\ForestReco\\podklady\\data-velka\\try\\ANE_1000_part04\\ANE_1000_part04_merged.laz -o D:\\Resources\\ForestReco\\podklady\\data-small\\tmpFiles\\ANE_1000_part04_merged_tmp\\ANE_1000_part04_merged_i.txt");


                Process currentProcess = Process.Start(processStartInfo);
                currentProcess.WaitForExit();

                int result = currentProcess.ExitCode;

                //todo: throw and handle exception?
                if (result == 1)                //0 = OK, 1 = error...i.e. the .exe file is missing
                {
                    throw new Exception($"Command {command} resulted in error");
                }
                // Check if command generated desired result
                outputFileExists = File.Exists(pOutputFilePath);
                if (!outputFileExists)
                {
                    throw new Exception($"File {pOutputFilePath} not created");
                }
            }
        }
Example #20
0
        private static void DebugPoint(Vector3 pPoint, int pPointIndex)
        {
            if (DEBUG)
            {
                CDebug.WriteLine("\n" + pointCounter + " AddPoint " + pPoint);
            }

            Vector3 debugPoint = CObjExporter.GetMovedPoint(pPoint);

            debugPoint.Z *= -1;
        }
Example #21
0
        private static string[] GetReftreeLines(string refTreeXyzPath)
        {
            if (!File.Exists(refTreeXyzPath))
            {
                //not errror. all files doesnt have to be specified
                CDebug.Warning("Reftree " + refTreeXyzPath + " XYZ does not exist.");
                return(new string[0]);
            }

            string[] lines = File.ReadAllLines(refTreeXyzPath);
            CDebug.WriteLine("load: " + refTreeXyzPath);
            return(lines);
        }
Example #22
0
        /// <summary>
        /// Assigns all vege points in preprocess arrays.
        /// Then it calculates the expected average tree height.
        /// </summary>
        private void PreprocessVegePoints()
        {
            const int debugFrequency = 10000;

            DateTime PreprocessVegePointsStart = DateTime.Now;

            CDebug.WriteLine("PreprocessVegePoints", true);

            DateTime preprocessVegePointsStart = DateTime.Now;
            DateTime previousDebugStart        = DateTime.Now;

            for (int i = 0; i < vege.Count; i++)
            {
                if (CProjectData.backgroundWorker.CancellationPending)
                {
                    return;
                }

                Vector3 point = vege[i];
                preprocessDetailArray.AddPointInField(point);
                preprocessNormalArray.AddPointInField(point);

                CDebug.Progress(i, vege.Count, debugFrequency, ref previousDebugStart, preprocessVegePointsStart, "preprocessed point");
            }

            //fill missing heigh - will be used in detection process
            //rank 2 - rank 1 (max) extends local maximas -> unwanted effect
            preprocessDetailArray.FillMissingHeights(2);
            preprocessDetailArray.FillMissingHeights(2);

            CDebug.Duration("PreprocessVegePoints", PreprocessVegePointsStart);

            //determine average tree height
            if (CParameterSetter.GetBoolSettings(ESettings.autoAverageTreeHeight))
            {
                //not valid anymore //why not valid??...seems to work fine
                CTreeManager.AVERAGE_TREE_HEIGHT = preprocessNormalArray.GetAverageZ();

                if (float.IsNaN(CTreeManager.AVERAGE_TREE_HEIGHT))
                {
                    CDebug.Error("AVERAGE_TREE_HEIGHT = NaN. using input value");
                    CTreeManager.AVERAGE_TREE_HEIGHT = CParameterSetter.GetIntSettings(ESettings.avgTreeHeigh);
                }
            }
            else
            {
                CTreeManager.AVERAGE_TREE_HEIGHT = CParameterSetter.GetIntSettings(ESettings.avgTreeHeigh);
            }
        }
Example #23
0
        /// <summary>
        /// Iterates through possible centers and selects the on having smallest diff
        /// to distance-to-mainPoints function
        /// </summary>
        /// <returns></returns>
        private Vector3 CalculateCenter()
        {
            CDebug.WriteLine($"Ball = {this}");

            List <Vector3> possibleCenters = GetPossibleCenters();
            Vector3        center          = SelectBestCenter(possibleCenters);

            CDebug.WriteLine($"center = {center}");

            possibleCenters = GetPointsInRadius(center, 0.01f, 0.001f);
            center          = SelectBestCenter(possibleCenters);
            CDebug.WriteLine($"new center = {center}");

            return(center);
        }
Example #24
0
 public static void DebugTrees()
 {
     CDebug.WriteLine("===============", true);
     CDebug.WriteLine("Detected trees");
     foreach (CTree t in Trees)
     {
         CDebug.WriteLine(Trees.IndexOf(t).ToString("00") + ": " + t);
         if (Trees.IndexOf(t) > MAX_DEBUG_COUNT)
         {
             CDebug.WriteLine("too much to debug...total = " + Trees.Count);
             return;
         }
     }
     CDebug.WriteLine("\n===============\n");
 }
Example #25
0
        private static void LoadTrees(List <string> pFileNames)
        {
            DateTime loadTreesStartTime = DateTime.Now;
            DateTime lastDebugTime      = DateTime.Now;

            CDebug.WriteLine("Load reftrees: ");
            foreach (string fileName in pFileNames)
            {
                CDebug.WriteLine(" - " + fileName);
            }

            for (int i = 0; i < pFileNames.Count; i++)
            {
                if (CProjectData.backgroundWorker.CancellationPending)
                {
                    return;
                }

                string fileName = pFileNames[i];
                CDebug.Progress(i, pFileNames.Count, 1, ref lastDebugTime, loadTreesStartTime, "load reftree");

                CRefTree deserializedRefTree     = CRefTree.Deserialize(fileName);
                bool     isDeserializedTreeValid = deserializedRefTree != null &&
                                                   deserializedRefTree.IsCurrentVersion();
                CRefTree refTree = isDeserializedTreeValid ?
                                   deserializedRefTree : new CRefTree(fileName, i, TREE_POINT_EXTENT, true);

                refTree.RefTreeTypeName = fileName;                 //GetTypeName(fileName);

                if (!refTree.isValid)
                {
                    //this reftree is not valid. case for reftrees in 'ignore' folder
                    CDebug.Warning($"Skipping reftree {fileName}");
                    continue;
                }
                //material set durring assigning to tree
                //refTree.Obj.UseMtl = CMaterialManager.GetRefTreeMaterial(counter);

                Trees.Add(refTree);
                CDebug.WriteLine($"Loaded tree: {fileName}. height = {refTree.GetTreeHeight()}");
            }
            CAnalytics.loadReftreesDuration = CAnalytics.GetDuration(loadTreesStartTime);
            CDebug.Duration("Load reftrees", loadTreesStartTime);

            CAnalytics.loadedReftrees = Trees.Count;

            DebugReftrees();
        }
Example #26
0
        public static CRefTree Deserialize(string pFileName)
        {
            string filePath = GetRefTreeFilePath(pFileName, pFileName + ".reftree");

            CDebug.WriteLine("\nDeserialize. filePath = " + filePath);

            if (!File.Exists(filePath))
            {
                //not error. reftree files doesnt have to be generated yet
                CDebug.Warning(".reftree file does not exist.");
                return(null);
            }

            string[] serialisedLines = File.ReadAllLines(filePath);

            CRefTree refTree = new CRefTree(pFileName, serialisedLines);

            return(refTree);
        }
Example #27
0
        //public static Vector3 ParseHeaderVector3(string pXstring, string pYstring, string pZstring)
        //{
        //	float x = float.Parse(pXstring);
        //	float y = float.Parse(pYstring);
        //	float z = float.Parse(pZstring);
        //	return new Vector3(x, y, z);
        //}

        public static Tuple <EClass, Vector3> ParseLine(string pLine, bool pUseHeader)
        {
            string[] split = pLine.Split(null);
            if (split.Length < 4 || (split.Length > 0 && split[0].Contains("#")))
            {
                CDebug.WriteLine(pLine + " not valid");
                return(null);
            }
            double x      = double.Parse(split[0]);
            double y      = double.Parse(split[1]);
            double z      = double.Parse(split[2]);
            int    _class = int.Parse(split[3]);

            //we don't use prescribed coordinate parsing as it produces badly visualisable terrain (with offset etc)
            //it should not have any effect on data processing
            Vector3 headerOffset = pUseHeader ? CProjectData.GetOffset() : Vector3.Zero;
            float   xFloat       = (float)(x - headerOffset.X);
            float   yFloat       = (float)(y - headerOffset.Y);
            float   zFloat       = (float)(z - headerOffset.Z);

            //swap canceled

            ////swap Y-Z. Y = height in this project
            //float tmp = yFloat;
            //yFloat = zFloat;
            //zFloat = tmp;

            EClass eClass = (EClass)_class;

            //Array acceptedClasses = Enum.GetValues(typeof(EClass));

            //if(IsAcceptedClass(eClass))
            //{
            //	_class = (int)EClass.Other;
            //}

            //if (_class != (int)EClass.Undefined && _class != (int)EClass.Ground && _class != (int)EClass.Vege)
            //{
            //	_class = (int)EClass.Other;
            //}
            return(new Tuple <EClass, Vector3>(eClass, new Vector3(xFloat, yFloat, zFloat)));
        }
Example #28
0
        /// <summary>
        /// Evaluates if tree is valid.
        /// More restrictive evaluation is optional.
        /// pCathegorize => assign invalid tree to InvalidTrees and remove from Trees
        /// pFinal => trees at array buffer positions will be invalid
        /// </summary>
        public static void ValidateTrees(bool pCathegorize, bool pRestrictive, bool pFinal = false)
        {
            CDebug.WriteLine("Detect invalid trees", true);

            for (int i = Trees.Count - 1; i >= 0; i--)
            {
                CTree tree = Trees[i];

                bool isValid = tree.Validate(pRestrictive, pFinal);

                if (!isValid)
                {
                    if (pCathegorize)
                    {
                        InvalidTrees.Add(tree);
                        Trees.RemoveAt(i);
                    }
                }
            }
        }
Example #29
0
        public static void ExportPartition(string pFileSuffix = "", string pIndexPrefix = "")
        {
            //folderPath = CObjExporter.CreateFolderIn(
            //	CProjectData.saveFileName, CProjectData.outputTileSubfolder);

            //just creates a folder (for analytics etc)
            if (!CParameterSetter.GetBoolSettings(ESettings.export3d) || CRxpParser.IsRxp)
            {
                CDebug.WriteLine("Skipping export");
                return;
            }

            int      counter = 0;
            DateTime exportPartitionStart = DateTime.Now;
            DateTime previousDebugStart   = DateTime.Now;
            int      partsCount           = partitionXRange * partitionYRange;

            int debugFrequency = 1;

            for (int x = 0; x < partitionXRange; x++)
            {
                for (int y = 0; y < partitionYRange; y++)
                {
                    if (CProjectData.backgroundWorker.CancellationPending)
                    {
                        return;
                    }

                    counter++;
                    List <Obj> objsInPartition = objPartition[x, y];
                    //export only if partition contains some objects (doesn't have to)
                    if (objsInPartition.Count > 0)
                    {
                        CObjExporter.ExportObjs(objsInPartition,
                                                $"{CProjectData.saveFileName}_{pIndexPrefix}[{x},{y}]{pFileSuffix}", CProjectData.outputTileSubfolder);
                    }

                    CDebug.Progress(counter, partsCount, debugFrequency, ref previousDebugStart, exportPartitionStart, "Export of part");
                }
            }
        }
Example #30
0
        private static void WriteObjFile(string pOutputFileName, ObjParser.Obj pObj)
        {
            string fileName       = pOutputFileName.Length > 0 ? pOutputFileName : DEFAULT_FILENAME;
            string chosenFileName = fileName;
            string extension      = ".Obj";
            string path           = Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\output\\";
            string fullPath  = path + chosenFileName + extension;
            int    fileIndex = 0;

            while (File.Exists(fullPath))
            {
                chosenFileName = fileName + "_" + fileIndex;
                fullPath       = path + chosenFileName + extension;
                fileIndex++;
            }

            CDebug.WriteLine("write to " + fullPath);

            pObj.WriteObjFile(fullPath, new[] { "ExportTreePointsToObj" });
        }