Ejemplo n.º 1
0
        /// <summary>
        /// Установить стрелку направления обработки
        /// </summary>
        /// <param name="curve">Траектория обработки</param>
        /// <param name="isVertical">Вертикальная прямая</param>
        private ObjectId SetDirectLine(Curve curve, bool isVertical = false)
        {
            var curveLength = curve.GetLength();

            if (curveLength < 10)
            {
                return(ObjectId.Null);
            }
            var dist = Math.Min(50, curveLength / 2);

            if (_position == curve.StartPoint)
            {
                dist = curveLength - dist;
            }
            var points = new Point3dCollection {
                curve.GetPointAtDist(dist)
            };
            var arrowLength = Math.Min(10, curveLength / 3);
            var vector      = curve.GetFirstDerivative(points[0]).GetNormal() * arrowLength;

            if (_position == curve.EndPoint)
            {
                vector = vector.Negate();
            }
            var          sidn  = _compensation == CompensationSide.Left ? -1 : 1;
            const double angle = 0.4;
            var          axis  = isVertical ? Vector3d.YAxis : Vector3d.ZAxis;

            points.Add(points[0] + vector.RotateBy(angle * sidn, axis));
            points.Add(_compensation == CompensationSide.None
                    ? points[0] + vector.RotateBy(-angle * sidn, axis)
                    : curve.GetClosestPointTo(points[1], false));
            var directCurve = new Polyline3d(Poly3dType.SimplePoly, points, true);

            return(AutocadUtils.AddCurve(directCurve, ActionType.Direction));
        }
Ejemplo n.º 2
0
        private static bool CheckParams(ProcessObject processObject)
        {
            var par   = processObject.ProcessingParams;
            var error = String.Empty;

            if ((Settings.ProcessMode == ProcessMode.StepByStepDescent || Settings.ProcessMode == ProcessMode.ContinuousDescent) &&
                Settings.Thickness < 0.1)
            {
                error = "укажите толщину";
            }
            if (Settings.ProcessMode == ProcessMode.ContinuousDescent && par.DepthAll == 0)
            {
                error = "укажите суммарную глубину";
            }
            if (par.DepthAll > 0 && par.Depth < 0.1)
            {
                error = "укажите шаг";
            }
            if (!String.IsNullOrEmpty(error))
            {
                AutocadUtils.ShowError(String.Format("Объект {0}: {1}", processObject.Curve.Name, error));
            }
            return(String.IsNullOrEmpty(error));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Расчет внешней стороны для цепочки объектов
        /// </summary>
        /// <param name="curve">Начальный объект</param>
        public static void CalcOutside(ProcessCurve curve)
        {
            if (curve.Type == CurveType.Circle)
            {
                curve.OutsideSign = -1;
                return;
            }
            var vector = AutocadUtils.GetFirstDerivative(curve.ObjectId, curve.StartPoint);
            // набор вершин
            var vertexSet = new HashSet <Point3d>(ProcessCurves.SelectMany(p => p.Type == CurveType.Polyline
                ? AutocadUtils.GetPoints(p.ObjectId)
                : new List <Point3d> {
                p.StartPoint, p.EndPoint
            }));

            var sign = -Math.Sign(vertexSet.Sum(p => Math.Sign(vector.CrossProduct(p - curve.StartPoint).Z)));

            curve.OutsideSign = sign != 0 ? sign : 1;              //если не определили то берем 1

            if (!SetOutsideConnectObjects(curve, curve.EndPoint))  // если не замкнута
            {
                SetOutsideConnectObjects(curve, curve.StartPoint); // то проставляем с другого конца
            }
        }
Ejemplo n.º 4
0
        public static List <string> Generate(IEnumerable <ProcessingAction> actions)
        {
            Settings = Settings.GetInstance();
            MachineProgram.Clear();
            _lineNo = 0;

            foreach (var action in actions)
            {
                switch (action.ActionType)
                {
                // Начало программы
                case ActionType.StartOfProgram:
                    AddLine("; Start of Program \"" + Settings.MachineName + "\"");
                    AddLine(";");
                    AddLine("; PART NAME   :");
                    AddLine("; DATE TIME   : " + DateTime.Now);
                    AddLine(";");
                    if (Settings.Machine == MachineKind.Krea)
                    {
                        AddLine("(UAO,E30)");
                        AddLine("(UIO,Z(E31))");
                    }
                    if (Settings.Machine == MachineKind.Ravelli)
                    {
                        AddLine("G54G17G90G642");
                        AddLine("G0G90G153D0Z0");
                    }
                    break;

                // Конец программы
                case ActionType.EndOfProgram:
                    AddLine("; End of Program");
                    AddLine("M30");
                    break;

                // Плоскость обработки
                case ActionType.PlaneProcessing:
                    AddLine("G17");
                    break;

                // Смена инструмента
                case ActionType.ChangeTool:
                    AddLine("; Start of Path");
                    AddLine(";");
                    AddLine("; Tool Change");
                    var par = action.Param.Split(';');
                    AddLine("T" + (par.Any() ? par[0] : "?"));
                    if (Settings.Machine == MachineKind.Ravelli)
                    {
                        AddLine("M6");
                        AddLine("D" + (par.Count() > 1 ? par[1] : "?"));
                        AddLine("G54");
                        AddLine("G0 B0 C0");
                    }
                    break;

                // Включение шпинделя
                case ActionType.SpindleStart:
                    AddLine(String.Format("S{0} M3", action.Param));
                    AddLine("M7");
                    AddLine("M8");
                    break;

                // Выключение шпинделя
                case ActionType.SpindleStop:
                    AddLine("; End of Path");
                    AddLine("M5");                  // выключение шпинделя
                    if (Settings.Machine == MachineKind.Krea)
                    {
                        AddLine("M9 M10");              // выключение воды
                        AddLine("G0 G79 Z(@ZUP)");      // подъем в верхнюю точку
                    }
                    if (Settings.Machine == MachineKind.Ravelli)
                    {
                        AddLine("M9");
                        AddLine("G0G90G153D0Z0");
                    }
                    break;

                // Компенсация
                case ActionType.Compensation:
                    AddLine(action.CompensationSide == CompensationSide.Left ? "G41" : (action.CompensationSide == CompensationSide.Right ? "G42" : "G40"));
                    break;

                // Подвод к точке опускания, Перемещение инструмента, Опускание инструмента, Подъем инструмента
                // Заход, Резка, Выход, Опускание инструмента, Подъем инструмента
                case ActionType.InitialMove:
                case ActionType.Move:
                case ActionType.EngageMove:
                case ActionType.Cutting:
                case ActionType.RetractMove:
                case ActionType.AapproachMove:
                case ActionType.DepartureMove:
                    AddGCommand(action);
                    break;

                default:
                    AutocadUtils.ShowError(String.Format("Ошибка при генерации программы: не распознана команда \"{0}\"", action.ActionType));
                    break;
                }
            }

            return(MachineProgram);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Движение инструмента по траектории
        /// </summary>
        /// <param name="actionType">Тип действия</param>
        /// <param name="path">Траектория</param>
        private ProcessingAction PathMovement(ActionType actionType, Curve path, int?speed = null)
        {
            if (path == null)
            {
                return(null);
            }

            var oldPosition = _position;

            if ((_position == path.StartPoint) || (Math.Abs(_position.X - path.StartPoint.X) < CalcUtils.Tolerance) && (Math.Abs(_position.Y - path.StartPoint.Y) < CalcUtils.Tolerance))
            {
                _position = path.EndPoint;
            }
            else if ((_position == path.EndPoint) || (Math.Abs(_position.X - path.EndPoint.X) < CalcUtils.Tolerance) && (Math.Abs(_position.Y - path.EndPoint.Y) < CalcUtils.Tolerance))
            {
                _position = path.StartPoint;
            }
            else
            {
                AutocadUtils.ShowError("Ошибка: не соответствие позиции при расчете траектории");
                return(null);
            }

            var action = CreateProcessAction(actionType, speed: speed);

            action.ObjectId       = path.ObjectId != ObjectId.Null ? path.ObjectId : AutocadUtils.AddCurve(path, actionType);
            action.DirectObjectId = SetDirectLine(path);
            SetCoordinates(action, oldPosition, _position, path is Arc);

            if (path is Line)
            {
                action.ToolpathCurveType = ToolpathCurveType.Line;
            }
            if (path is Arc)
            {
                var arc = path as Arc;
                action.ToolpathCurveType = (_position == arc.StartPoint
                                                              ? ToolpathCurveType.ArcClockwise
                                                              : ToolpathCurveType.ArcCounterclockwise);
                if (action.ToolpathCurveType == ToolpathCurveType.ArcClockwise ^ _compensation == CompensationSide.Left) // инструмент внутри дуги
                {
                    if (arc.Radius <= _tool.Diameter / 2)
                    {
                        action.Note    = "Радиус дуги меньше или равен радиусу инструмента";
                        action.IsError = true;
                        var message = String.Format("Строка {0}: {1}", action.No, action.Note);
                        AutocadUtils.ShowError(message);
                    }
                    if (arc.Radius <= 1.5 * _tool.Diameter)
                    {
                        action.Speed    = 200;
                        _isSpeedChanged = true;
                    }
                }
                action.I = Round(arc.Center.X);
                action.J = Round(arc.Center.Y);
                var vector = oldPosition.GetVectorTo(arc.Center);
                action.Irel = Round(vector.X);
                action.Jrel = Round(vector.Y);
            }
            action.Param = action.ToolpathCurveType.ToString();

            return(action);
        }
Ejemplo n.º 6
0
 public void ShowPaletteSet()
 {
     AutocadUtils.ShowPaletteSet();
 }
Ejemplo n.º 7
0
        public void Initialize()
        {
            AutocadUtils.WriteMessage("Инициализация плагина ProcessingProgram. Версия с режимом обработки."); // + DateTime.Today.ToShortDateString()); TODO Assemlly.DateTime()

            ObjectForm.DeleteAll        += (sender, args) => DeleteAll();
            ObjectForm.DeleteProcessing += (sender, args) => DeleteProcessing();
            ObjectForm.Calculate        += (sender, args) => Calculate();
            ObjectForm.Quit             += (sender, args) => AutocadUtils.Close();
            ObjectForm.AddObjects       += (sender, args) => AddObjects();
            ObjectForm.ShowTools        += (sender, args) => AutocadUtils.ShowModalDialog(ToolStoreForm);
            ObjectForm.CurrentChanged   += (sender, args) => AutocadUtils.SelectObject(args.Data.Curve.ObjectId);
            ObjectForm.ChangeOutside    += (sender, args) =>
            {
                CalcUtils.ChangeOutside(args.Data.Curve.ObjectId);
                Calculate();
            };
            ObjectForm.ReverseProcess += (sender, args) =>
            {
                args.Data.Direction *= -1;
                Calculate();
            };
            ObjectForm.DeleteObject += (sender, args) =>
            {
                ProcessObjects.Remove(args.Data);
                if (ProcessObjects.All(p => p.Curve != args.Data.Curve))
                {
                    ProcessCurves.Remove(args.Data.Curve);
                }
                Calculate();
            };
            SettingForm.AddSectionObjects += (sender, args) =>
            {
                AddSectionObjects();
                SettingForm.SetSectionDesc(SectionCurves.Any() ? String.Format("Сечение установлено. {0} элемента", SectionCurves.Count) : "");
            };

            AutocadUtils.AddPaletteSet("Объекты", ObjectForm);

            ProcessingForm.CurrentChanged   += (sender, args) => AutocadUtils.SelectObjects(args.Data.ObjectId, args.Data.ToolObjectId);
            ProcessingForm.DeleteProcessing += (sender, args) => DeleteProcessing();
            ProcessingForm.Calculate        += (sender, args) => Calculate();
            AutocadUtils.AddPaletteSet("Обработка", ProcessingForm);

            AutocadUtils.AddPaletteSet("Программа", ProgramForm);
            AutocadUtils.AddPaletteSet("Настройки", SettingForm);

            AutocadUtils.Selected += (sender, args) => ProcessingForm.SelectObjects(args.Data);
            AutocadUtils.Focused  += (sender, args) => ProcessingForm.SetFocus(args.Data);
            AutocadUtils.Focused  += (sender, args) => ObjectForm.SetFocus(args.Data);

            CalcUtils.Init(ProcessObjects, ProcessCurves);
            ProcessObjectFactory.Init(ProcessObjects, ProcessCurves);

            var machine = new Machine();

            machine.ChangeActionsCount += (sender, args) => ObjectForm.ShowProgress(String.Format("Генерация обработки... {0} строк", args.Data));
            ActionGenerator.SetMachine(machine);

            //AutocadUtils.CreateTest();
            //RunTest();
        }
Ejemplo n.º 8
0
        public static FeedGroup CalcFeedGroup(Curve curve, bool isStartCurve, int sign, FeedType feedType, int radius, int angle, int length)
        {
            var      feedGroup = new FeedGroup();
            Vector3d vector;
            Point3d  point = isStartCurve ? curve.StartPoint : curve.EndPoint;

            if (!curve.Closed || isStartCurve)
            {
                vector = curve.GetFirstDerivative(point);
            }
            else if (curve is Circle)
            {
                vector = new Vector3d(0, 1, 0);
            }
            else // расчет касательной в конце замкнутой полилинии
            {
                int param;
                var polyline = curve as Polyline;
                if (polyline != null)
                {
                    param = polyline.NumberOfVertices - 1;
                }
                else
                {
                    var polyline2d = curve as Polyline2d;
                    if (polyline2d != null)
                    {
                        param = polyline2d.Cast <object>().Count();
                    }
                    else
                    {
                        AutocadUtils.ShowError("Ошибка в расчете подвода-отвода");
                        feedGroup.Point = point;
                        return(feedGroup);
                    }
                }
                vector = curve.GetFirstDerivative(param);
            }

            switch (feedType)
            {
            case FeedType.None:
                feedGroup.Point = point;
                break;

            case FeedType.Line:
                vector          = (isStartCurve ? -1 : 1) * vector.GetNormal() * length;
                feedGroup.Point = point + vector;
                feedGroup.Line  = new Line(point, feedGroup.Point);
                break;

            case FeedType.Arc:
                vector          = vector.GetPerpendicularVector() * sign * radius;
                feedGroup.Point = point + vector;
                vector          = vector.Negate();
                var angle1   = vector.GetAngleTo(Vector3d.XAxis, Vector3d.ZAxis.Negate());
                var turnSign = (isStartCurve ? -1 : 1) * sign;
                vector         = vector.RotateBy(DegreesToRadians(angle) * turnSign, Vector3d.ZAxis);
                feedGroup.Line = new Line(feedGroup.Point, feedGroup.Point + vector);
                var angle2      = feedGroup.Line.Angle;
                var isCrossAxis = Math.Abs(angle2 - angle1) > Pi;
                feedGroup.Arc = new Arc(feedGroup.Point, radius,
                                        isCrossAxis ? Math.Max(angle1, angle2) : Math.Min(angle1, angle2),
                                        isCrossAxis ? Math.Min(angle1, angle2) : Math.Max(angle1, angle2));
                break;
            }
            return(feedGroup);
        }