Пример #1
0
        /// <summary>
        /// Чтение тела из файла. 
        /// </summary>
        /// <param name="source">Пишется относительный путь к файлу, пример - source/car.txt</param>
        /// <param name="shouldClear">Нужно ли очистить тело, перед чтением из файла. </param>
        public bool LoadingFromResource(string source, bool shouldClear)
        {
            if (shouldClear)
            {
                points.Clear();
                connections.Clear();                                                        //очищаем тело
                axles.customs.Clear();
            }

            try
            {
                FileStream stream = File.Open(source, FileMode.Open, FileAccess.Read);
                StreamReader reader = new StreamReader(stream);                         // открытие файла и запуск читалки

                try
                {
                    string currentPositionInFile = reader.ReadLine();                   // начниаем с точек
                    if (currentPositionInFile == "Points")
                    {
                        currentPositionInFile = reader.ReadLine();
                        do
                        {
                            var coordinates = currentPositionInFile.Split(' ');         // разбиваем строку на массив
                            points.Add(new Point()                                      // создаём точку, парсим координаты, заносим в список
                            {
                                X = int.Parse(coordinates[0]),
                                Y = int.Parse(coordinates[1]),
                                Z = int.Parse(coordinates[2])
                            });
                            currentPositionInFile = reader.ReadLine();

                        }
                        while (currentPositionInFile != "Connections");                 // заканчиваем соединенями
                    }
                    else return false;

                    if (currentPositionInFile == "Connections")                         // продолжаем соединениями
                    {
                        currentPositionInFile = reader.ReadLine();
                        do
                        {
                            var connectionPointsNumbers = currentPositionInFile.Split(' ').ToList();      // разбиваем на массив номеров точек
                            var newConnection = new Connection();                                // создаём новое соединение

                            var nameAndColorCheckTemp = 0;
                            while (!int.TryParse(connectionPointsNumbers[0], out nameAndColorCheckTemp)) // проверяем на кастомные имя и цвет
                            {
                                var nameAndColorParseTemp = connectionPointsNumbers[0];
                                if (nameAndColorParseTemp[0] != '#')
                                    newConnection.name = nameAndColorParseTemp;
                                else
                                {
                                    System.Windows.Media.Color currentColor = System.Windows.Media.Colors.Red;
                                    try
                                    {
                                        try
                                        {
                                            currentColor = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString(nameAndColorParseTemp);
                                        }
                                        catch
                                        {
                                            var color = Color.FromName(nameAndColorParseTemp.Substring(1));
                                            {
                                                currentColor = new System.Windows.Media.Color()
                                                {
                                                    A = color.A,
                                                    R = color.R,
                                                    G = color.G,
                                                    B = color.B
                                                };
                                            }
                                        }
                                    }
                                    catch
                                    {

                                    }

                                   newConnection.color = new System.Windows.Media.SolidColorBrush(currentColor);
                                }
                                connectionPointsNumbers.Remove(nameAndColorParseTemp);
                            }
                            foreach (string pointNumber in connectionPointsNumbers)              // идём по номерам
                            {
                                var currentPoint = points[int.Parse(pointNumber) - 1];           // парсим номер, берём точку, заносим в соединение
                                newConnection.points.Add(currentPoint);
                            }

                            connections.Add(newConnection);                                      // добавляем соединение в тело

                            currentPositionInFile = reader.ReadLine();
                        }
                        while (currentPositionInFile != "Axles");
                    }
                    else return false;

                    if (currentPositionInFile == "Axles")                               // продолжаем осями
                    {
                        var axlesSet = new AxleSet() { customs = axles.customs };                                   // создаем сет осей
                        currentPositionInFile = reader.ReadLine();
                        do
                        {

                            var axleInfo = currentPositionInFile.Split(' ');            // разбиваем строку на инфу. собираем две точки и ось
                            var firstPointInfo = axleInfo.Skip(1).TakeWhile(x => x != ",").ToArray();
                            var secondPointInfo = axleInfo.Skip(5).ToArray();
                            var firstPoint = new Point()
                                        {
                                            X = double.Parse(firstPointInfo[0]),
                                            Y = double.Parse(firstPointInfo[1]),
                                            Z = double.Parse(firstPointInfo[2])
                                        };
                            var secondPoint = new Point()
                                        {
                                            X = double.Parse(secondPointInfo[0]),
                                            Y = double.Parse(secondPointInfo[1]),
                                            Z = double.Parse(secondPointInfo[2])
                                        };
                            var axle = new Axle()
                                    {
                                        info = axleInfo[0],
                                        firstPoint = firstPoint,
                                        secondPoint = secondPoint

                                    };
                            switch (axle.info)                                        // заносим ось в сет
                            {
                                case "x":
                                    axlesSet.X = axle;
                                    break;
                                case "y":
                                    axlesSet.Y = axle;
                                    break;
                                case "z":
                                    axlesSet.Z = axle;
                                    break;
                                default:
                                    axlesSet.customs.Add(axle);
                                    break;
                            }

                            points.Add(firstPoint);                                     // обязательно заносим точки в тело, потому что они у нас динамические
                            points.Add(secondPoint);

                            currentPositionInFile = reader.ReadLine();
                        }
                        while (currentPositionInFile != "End");
                        axles = axlesSet;                                               // добавляем ось в сет

                    }
                    else return false;
                }
                catch (Exception exp)
                {
                    return false;
                }
                reader.Close();
                stream.Close();
                ReloadBody();                                                           // переобрабатываем тело
                return true;
            }
            catch (Exception exp)
            {
                return false;                                                                 // Если произошла ошибка в чтении файла
            }
        }
Пример #2
0
        /// <summary>
        /// Переработка тела. Пересоздаёт все ссылки. Разбивает на детали.
        /// </summary>
        public void ReloadBody()
        {
            points.Clear();
            var newConnections = new List<Connection>();
            foreach (var connection in connections)
            {
                var newConnection = connection.export();
                new Connection();
                foreach (var point in newConnection.points)
                {
                    points.Add(point);
                }
                newConnections.Add(newConnection);

            }

            var newAxlesSet = axles.export();

            connections = newConnections;
            axles = newAxlesSet;
            points.AddRange(axles.GetPoints());
        }
Пример #3
0
 /// <summary>
 /// Пересоздаёт оси. Учитывайте, что оси идут к началам координат.
 /// </summary>
 public void GenerateAxles()
 {
     var center = GetCenter();
     axles = new AxleSet()
     {
         X = new Axle()
         {
             info = "x",
             firstPoint = new Point()
             {
                 X = 0,
                 Y = center.Y,
                 Z = center.Z
             },
             secondPoint = center
         },
         Y = new Axle()
         {
             info = "y",
             firstPoint = new Point()
             {
                 X = center.X,
                 Y = 0,
                 Z = center.Z
             },
             secondPoint = center
         },
         Z = new Axle()
         {
             info = "z",
             firstPoint = new Point()
             {
                 X = center.X,
                 Y = center.Y,
                 Z = 0
             },
             secondPoint = center
         },
         customs = axles.customs
     };
     ReloadBody();
 }