public bool ExecuteSequence(string name)
 {
     try
     {
         CommandSequence seq = Find(name);
         if (seq == null)
             return false;
         switch (seq.m_seqtype)
         {
             case CommandSequence.COMMAND_TYPE_GCODE:
                 //a gcode command sequence - execute it with a pseudo-build manager/sequencer
                 GCodeFile gcf = new GCodeFile(seq.m_seq);
                 if (!UVDLPApp.Instance().m_buildmgr.IsPrinting)
                 {
                     DebugLogger.Instance().LogInfo("Running GCode Sequence " + seq.m_name);
                     UVDLPApp.Instance().m_buildmgr.StartPrint(UVDLPApp.Instance().m_slicefile, gcf, true);
                 }
                 break;
         }
         return true;
     }
     catch (Exception ex)
     {
         DebugLogger.Instance().LogError(ex);
     }
     return false;
 }
Ejemplo n.º 2
0
        public static async Task <List <string> > RunSimulatedPrint(this PrinterConfig printer, Stream inputStream)
        {
            // set up our serial port finding
            FrostedSerialPortFactory.GetPlatformSerialPort = (_) =>
            {
                return(new Emulator());
            };

            FrostedSerialPort.AllowEmulator = true;

            var sentLines = new List <string>();

            // register to listen to the printer responses
            printer.Connection.LineSent += (s, line) =>
            {
                if (printer.Connection.Printing)
                {
                    sentLines.Add(line);
                }
            };

            // set up the emulator
            printer.Settings.SetValue($"{Environment.MachineName}_com_port", "Emulator");

            // connect to the emulator
            printer.Connection.Connect();

            var timer = Stopwatch.StartNew();

            // wait for the printer to be connected
            while (!printer.Connection.IsConnected &&
                   timer.ElapsedMilliseconds < (1000 * 40))
            {
                Thread.Sleep(100);
            }

            // start a print
            printer.Connection.CommunicationState = CommunicationStates.PreparingToPrint;
            await printer.Connection.StartPrint(inputStream);

            // wait up to 40 seconds for the print to finish
            timer = Stopwatch.StartNew();
            while (printer.Connection.Printing &&
                   timer.ElapsedMilliseconds < (1000 * 40))
            {
                Thread.Sleep(100);
            }

            // Project to string without checksum which is not an M105 request
            return(sentLines.Select(l => GCodeFile.GetLineWithoutChecksum(l)).Where(l => !l.StartsWith("M105")).ToList());
        }
Ejemplo n.º 3
0
        public override string ReadLine()
        {
            string lineToSend = base.ReadLine();

            if (lineToSend != null &&
                lineToSend.EndsWith("; NO_PROCESSING"))
            {
                return(lineToSend);
            }

            if (lineToSend != null &&
                lineToSend.StartsWith("T"))
            {
                int extruder = 0;
                if (GCodeFile.GetFirstNumberAfter("T", lineToSend, ref extruder))
                {
                    extruderIndex = extruder;
                }
            }

            if (lineToSend != null &&
                LineIsMovement(lineToSend))
            {
                inputNoBabyStepping = GetPosition(lineToSend, inputNoBabyStepping);

                // it is a struct so this is making a new copy we con modify
                PrinterMove moveToSend = inputNoBabyStepping;
                printer.Settings.ForTools <double>(SettingsKey.baby_step_z_offset, (key, value, i) =>
                {
                    if (extruderIndex == i)
                    {
                        moveToSend.position = new Vector3(moveToSend.position.X,
                                                          moveToSend.position.Y,
                                                          moveToSend.position.Z + GetBabbyStepOffset(i));
                    }
                });

                moveToSend.position -= extruderOffsets[Math.Min(extruderIndex, 4)];

                if (moveToSend.HaveAnyPosition)
                {
                    lineToSend = CreateMovementLine(moveToSend, outputWithBabyStepping);
                }

                outputWithBabyStepping = moveToSend;

                return(lineToSend);
            }

            return(lineToSend);
        }
        private void GetZProbeHeight(object sender, string line)
        {
            if (line != null)
            {
                double sampleRead = double.MinValue;
                if (line.StartsWith("Bed"))                 // marlin G30 return code (looks like: 'Bed Position X:20 Y:32 Z:.01')
                {
                    probePositions[probePositionsBeingEditedIndex].Position.X = probeStartPosition.X;
                    probePositions[probePositionsBeingEditedIndex].Position.Y = probeStartPosition.Y;
                    GCodeFile.GetFirstNumberAfter("Z:", line, ref sampleRead);
                }
                else if (line.StartsWith("Z:"))                 // smoothie G30 return code (looks like: 'Z:10.01')
                {
                    probePositions[probePositionsBeingEditedIndex].Position.X = probeStartPosition.X;
                    probePositions[probePositionsBeingEditedIndex].Position.Y = probeStartPosition.Y;
                    // smoothie returns the position relative to the start position
                    double reportedProbeZ = 0;
                    GCodeFile.GetFirstNumberAfter("Z:", line, ref reportedProbeZ);
                    sampleRead = probeStartPosition.Z - reportedProbeZ;
                }

                if (sampleRead != double.MinValue)
                {
                    samples.Add(sampleRead);

                    int numberOfSamples = printer.Settings.GetValue <int>(SettingsKey.z_probe_samples);
                    if (samples.Count == numberOfSamples)
                    {
                        samples.Sort();
                        if (samples.Count > 3)
                        {
                            // drop the high and low values
                            samples.RemoveAt(0);
                            samples.RemoveAt(samples.Count - 1);
                        }

                        probePositions[probePositionsBeingEditedIndex].Position.Z = Math.Round(samples.Average(), 2);

                        UiThread.RunOnIdle(() => NextButton.InvokeClick());
                    }
                    else if (!this.HasBeenClosed)
                    {
                        // add the next request for probe
                        printer.Connection.QueueLine("G30");
                        // raise the probe after each sample
                        printer.Connection.MoveAbsolute(adjustedProbePosition, feedRates.X);
                    }
                }
            }
        }
Ejemplo n.º 5
0
 private void SaveGCodeToNewLocation(string source, string dest)
 {
     if (PrinterCommunication.Instance.DoPrintLeveling)
     {
         GCodeFile unleveledGCode = new GCodeFile(source);
         PrintLeveling.Instance.ApplyLeveling(unleveledGCode);
         unleveledGCode.Save(dest);
     }
     else
     {
         File.Copy(source, dest, true);
     }
     ShowFileIfRequested(dest);
 }
        public override string ReadLine()
        {
            var baseLine = base.ReadLine();

            if (baseLine == null)
            {
                return(null);
            }

            if (baseLine.EndsWith("; NO_PROCESSING"))
            {
                return(baseLine);
            }

            // if the line has no content don't process it
            if (baseLine.Length == 0 ||
                baseLine.Trim().Length == 0)
            {
                return(baseLine);
            }

            var lines = ProcessWriteRegEx(baseLine, printer);

            for (int i = lines.Count - 1; i >= 1; i--)
            {
                queueStream.Add(lines[i], true);
            }

            var lineToSend = lines[0];

            if (lineToSend != null &&
                LineIsMovement(lineToSend))
            {
                currentMove = GetPosition(lineToSend, currentMove);
            }

            // is it a position set?
            if (lineToSend.StartsWith("G92"))
            {
                GCodeFile.GetFirstNumberAfter("X", lineToSend, ref this.currentMove.position.X);
                GCodeFile.GetFirstNumberAfter("Y", lineToSend, ref this.currentMove.position.Y);
                GCodeFile.GetFirstNumberAfter("Z", lineToSend, ref this.currentMove.position.Z);
                GCodeFile.GetFirstNumberAfter("E", lineToSend, ref this.currentMove.extrusion);

                // tell the stream pipeline what the actual printer position is
                this.SetPrinterPosition(this.currentMove);
            }

            return(lineToSend);
        }
        public Task OpenFileAsync(string path)
        {
            _file = GCodeFile.Load(path);
            if (_file != null)
            {
                RenderPaths();
            }
            else
            {
                ClearPaths();
            }

            return(Task.FromResult(default(object)));
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            CappedCylinderGenerator cylgen = new CappedCylinderGenerator()
            {
                BaseRadius = 10, TopRadius = 5, Height = 20, Slices = 32
            };
            DMesh3 mesh = cylgen.Generate().MakeDMesh();

            MeshTransforms.ConvertYUpToZUp(mesh);       // g3 meshes are usually Y-up

            // center mesh above origin
            AxisAlignedBox3d bounds       = mesh.CachedBounds;
            Vector3d         baseCenterPt = bounds.Center - bounds.Extents.z * Vector3d.AxisZ;

            MeshTransforms.Translate(mesh, -baseCenterPt);

            // create print mesh set
            PrintMeshAssembly meshes = new PrintMeshAssembly();

            meshes.AddMesh(mesh, PrintMeshOptions.Default());

            // create settings
            //MakerbotSettings settings = new MakerbotSettings(Makerbot.Models.Replicator2);
            //PrintrbotSettings settings = new PrintrbotSettings(Printrbot.Models.Plus);
            //MonopriceSettings settings = new MonopriceSettings(Monoprice.Models.MP_Select_Mini_V2);
            RepRapSettings settings = new RepRapSettings(RepRap.Models.Unknown);

            // do slicing
            MeshPlanarSlicer slicer = new MeshPlanarSlicer()
            {
                LayerHeightMM = settings.LayerHeightMM
            };

            slicer.Add(meshes);
            PlanarSliceStack slices = slicer.Compute();

            // run print generator
            SingleMaterialFFFPrintGenerator printGen =
                new SingleMaterialFFFPrintGenerator(meshes, slices, settings);

            if (printGen.Generate())
            {
                // export gcode
                GCodeFile gcode = printGen.Result;
                using (StreamWriter w = new StreamWriter("c:\\demo\\cone.gcode")) {
                    StandardGCodeWriter writer = new StandardGCodeWriter();
                    writer.WriteFile(gcode, w);
                }
            }
        }
Ejemplo n.º 9
0
 public static void CheckKnownAssemblyConditionalCompSymbols()
 {
     MatterControlApplication.AssertDebugNotDefined();
     GCodeFile.AssertDebugNotDefined();
     MatterHackers.Agg.Graphics2D.AssertDebugNotDefined();
     MatterHackers.Agg.UI.SystemWindow.AssertDebugNotDefined();
     MatterHackers.Agg.ImageProcessing.InvertLightness.AssertDebugNotDefined();
     MatterHackers.Localizations.TranslationMap.AssertDebugNotDefined();
     MatterHackers.MarchingSquares.MarchingSquaresByte.AssertDebugNotDefined();
     MatterHackers.MatterControl.PluginSystem.MatterControlPlugin.AssertDebugNotDefined();
     MatterHackers.MatterSlice.MatterSlice.AssertDebugNotDefined();
     MatterHackers.MeshVisualizer.MeshViewerWidget.AssertDebugNotDefined();
     MatterHackers.RenderOpenGl.GLMeshTrianglePlugin.AssertDebugNotDefined();
 }
Ejemplo n.º 10
0
        private static string InstructionTime(this GCodeFile loadedGCode, int startLayer, int endLayer)
        {
            if (loadedGCode == null || loadedGCode.LayerCount == 0)
            {
                return("---");
            }

            int startInstruction      = loadedGCode.GetFirstLayerInstruction(startLayer);
            int endInstruction        = loadedGCode.GetFirstLayerInstruction(endLayer);
            var secondsToEndFromStart = loadedGCode.Instruction(startInstruction).SecondsToEndFromHere;
            var secondsToEndFromEnd   = loadedGCode.Instruction(endInstruction).SecondsToEndFromHere;

            return(SecondsToTime(secondsToEndFromStart - secondsToEndFromEnd));
        }
Ejemplo n.º 11
0
        public void Load(string path)
        {
            if (System.IO.File.Exists(path))
            {
                File = new GCodeFile
                {
                    FilePath  = path,
                    FileState = FileState.Unchanged,
                    FileData  = new TextDocument(System.IO.File.ReadAllText(path))
                };

                _fileSystemWatcher.Path = Path.GetDirectoryName(path);
                _fileSystemWatcher.EnableRaisingEvents = true;
            }
        }
        private void SaveGCodeToNewLocation(string source, string dest)
        {
            if (ActivePrinterProfile.Instance.DoPrintLeveling)
            {
                GCodeFile unleveledGCode = new GCodeFile(source);
                if (applyLeveling.Checked)
                {
                    PrintLevelingPlane.Instance.ApplyLeveling(unleveledGCode);

                    PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(ActivePrinterProfile.Instance.ActivePrinter);
                    if (levelingData != null)
                    {
                        for (int i = 0; i < unleveledGCode.Count; i++)
                        {
                            PrinterMachineInstruction instruction = unleveledGCode.Instruction(i);

                            List <string> linesToWrite = null;
                            switch (levelingData.levelingSystem)
                            {
                            case PrintLevelingData.LevelingSystem.Probe2Points:
                                linesToWrite = LevelWizard2Point.ProcessCommand(instruction.Line);
                                break;

                            case PrintLevelingData.LevelingSystem.Probe3Points:
                                linesToWrite = LevelWizard3Point.ProcessCommand(instruction.Line);
                                break;
                            }

                            instruction.Line = linesToWrite[0];
                            linesToWrite.RemoveAt(0);

                            // now insert any new lines
                            foreach (string line in linesToWrite)
                            {
                                PrinterMachineInstruction newInstruction = new PrinterMachineInstruction(line);
                                unleveledGCode.Insert(++i, newInstruction);
                            }
                        }
                    }
                }
                unleveledGCode.Save(dest);
            }
            else
            {
                File.Copy(source, dest, true);
            }
            ShowFileIfRequested(dest);
        }
Ejemplo n.º 13
0
        public override string ReadLine()
        {
            string processedLine = offsetStream.ReadLine();

            if (processedLine != null &&
                layerCount < 1 &&
                GCodeFile.IsLayerChange(processedLine))
            {
                layerCount++;
                if (layerCount == 1)
                {
                    maxLengthStream.MaxSegmentLength = 5;
                }
            }
            return(processedLine);
        }
Ejemplo n.º 14
0
        public GCodeDebugView(PrinterTabPage printerTabPage, GCodeFile gCodeMemoryFile, ISceneContext sceneContext, ThemeConfig theme)
            : base(theme)
        {
            this.printerTabPage = printerTabPage;
            this.sceneContext   = sceneContext;

            startPointWidget = this.AddSetting("Start".Localize(), "");
            endPointWidget   = this.AddSetting("End".Localize(), "");
            lengthWidget     = this.AddSetting("Length".Localize(), "");
            slopeWidget      = this.AddSetting("Slope".Localize(), "");
            yInterceptWidget = this.AddSetting("Y Intercept".Localize(), "");
            xInterceptWidget = this.AddSetting("X Intercept".Localize(), "");

            // Register listeners
            printerTabPage.LayerFeaturesScrollbar.SecondValueChanged += this.LayerFeaturesScrollbar_SecondValueChanged;
        }
        private void RenderPaths(GCodeFile file)
        {
            ClearPaths();

            foreach (var cmd in file.Commands)
            {
                if (cmd is GCodeLine)
                {
                    var gcodeLine = cmd as GCodeLine;
                    if (gcodeLine.Rapid)
                    {
                        RapidMoves.Add(new Line3D()
                        {
                            Start = gcodeLine.Start,
                            End   = gcodeLine.End
                        });
                    }
                    else
                    {
                        Lines.Add(new Line3D()
                        {
                            Start = gcodeLine.Start,
                            End   = gcodeLine.End
                        });
                    }
                }

                if (cmd is GCodeArc)
                {
                    var arc           = cmd as GCodeArc;
                    var segmentLength = arc.Length / 50;
                    var segments      = (cmd as GCodeArc).Split(segmentLength);
                    foreach (var segment in segments)
                    {
                        Arcs.Add(new Line3D()
                        {
                            Start = segment.Start,
                            End   = segment.End
                        });
                    }
                }
            }

            RaisePropertyChanged(nameof(Lines));
            RaisePropertyChanged(nameof(RapidMoves));
            RaisePropertyChanged(nameof(Arcs));
        }
Ejemplo n.º 16
0
        public static List <List <Vector2> > GetExtrusionsForLayer(this GCodeFile gcode, int layerIndex)
        {
            var extrusions = new List <List <Vector2> >();

            bool           addingExtrudePath  = false;
            List <Vector2> currentExtrudePath = null;

            int startRenderIndex = gcode.GetFirstLayerInstruction(layerIndex);
            int endRenderIndex   = gcode.LineCount - 1;

            if (layerIndex < gcode.LayerCount - 1)
            {
                endRenderIndex = gcode.GetFirstLayerInstruction(layerIndex + 1);
            }

            for (int instructionIndex = startRenderIndex; instructionIndex < endRenderIndex; instructionIndex++)
            {
                PrinterMachineInstruction currentInstruction  = gcode.Instruction(instructionIndex);
                PrinterMachineInstruction previousInstruction = currentInstruction;
                if (instructionIndex > 0)
                {
                    previousInstruction = gcode.Instruction(instructionIndex - 1);
                }

                if (currentInstruction.Position != previousInstruction.Position)
                {
                    if (gcode.IsExtruding(instructionIndex))
                    {
                        if (!addingExtrudePath)
                        {
                            currentExtrudePath = new List <Vector2>();
                            extrusions.Add(currentExtrudePath);
                            addingExtrudePath = true;
                        }

                        currentExtrudePath.Add(new Vector2(currentInstruction.Position.X, currentInstruction.Position.Y));
                    }
                    else
                    {
                        addingExtrudePath = false;
                    }
                }
            }

            return(extrusions);
        }
Ejemplo n.º 17
0
        public void InvalidateToolpaths()
        {
            cancel_active_compute();

            CurrentGCode    = null;
            Toolpaths       = null;
            LayerInfo       = null;
            Settings        = null;
            Slices          = null;
            ToolpathsValid  = false;
            ToolpathsFailed = false;

            // [TODO] do via event?
            CC.Objects.DiscardToolpaths();

            ToolpathsInvalidatedEvent?.Invoke();
        }
Ejemplo n.º 18
0
 public void SetGCodeAfterLoad(GCodeFile loadedGCode)
 {
     this.LoadedGCode = loadedGCode;
     if (loadedGCode == null)
     {
         TextWidget noGCodeLoaded = new TextWidget(string.Format("Not a valid GCode file."));
         noGCodeLoaded.Margin  = new BorderDouble(0, 0, 0, 0);
         noGCodeLoaded.VAnchor = Agg.UI.VAnchor.ParentCenter;
         noGCodeLoaded.HAnchor = Agg.UI.HAnchor.ParentCenter;
         this.AddChild(noGCodeLoaded);
     }
     else
     {
         SetInitalLayer();
         CenterPartInView();
     }
 }
Ejemplo n.º 19
0
        private void GetZProbeHeight(object sender, EventArgs e)
        {
            StringEventArgs currentEvent = e as StringEventArgs;

            if (currentEvent != null)
            {
                double sampleRead = double.MinValue;
                if (currentEvent.Data.StartsWith("Bed"))                 // marlin G30 return code (looks like: 'Bed Position X:20 Y:32 Z:.01')
                {
                    probePositions[probePositionsBeingEditedIndex].position.X = probeStartPosition.X;
                    probePositions[probePositionsBeingEditedIndex].position.Y = probeStartPosition.Y;
                    GCodeFile.GetFirstNumberAfter("Z:", currentEvent.Data, ref sampleRead);
                }
                else if (currentEvent.Data.StartsWith("Z:"))                 // smoothie G30 return code (looks like: 'Z:10.01')
                {
                    probePositions[probePositionsBeingEditedIndex].position.X = probeStartPosition.X;
                    probePositions[probePositionsBeingEditedIndex].position.Y = probeStartPosition.Y;
                    // smoothie returns the position relative to the start position
                    double reportedProbeZ = 0;
                    GCodeFile.GetFirstNumberAfter("Z:", currentEvent.Data, ref reportedProbeZ);
                    sampleRead = probeStartPosition.Z - reportedProbeZ;
                }

                if (sampleRead != double.MinValue)
                {
                    samples.Add(sampleRead);

                    int numberOfSamples = printer.Settings.GetValue <int>(SettingsKey.z_probe_samples);
                    if (samples.Count == numberOfSamples)
                    {
                        samples.Sort();
                        if (samples.Count > 3)
                        {
                            // drop the high and low values
                            samples.RemoveAt(0);
                            samples.RemoveAt(samples.Count - 1);
                        }

                        probePositions[probePositionsBeingEditedIndex].position.Z = Math.Round(samples.Average(), 2);

                        UiThread.RunOnIdle(() => nextButton.InvokeClick());
                    }
                }
            }
        }
Ejemplo n.º 20
0
        private void TrackExtruderState(string line)
        {
            if (line == null)
            {
                return;
            }

            if (line.StartsWith("G28)"))
            {
                activeExtruderIndex = 0;
                requestedExtruder   = 0;
            }

            if (line.StartsWith("T"))
            {
                GCodeFile.GetFirstNumberAfter("T", line, ref requestedExtruder);
            }
        }
Ejemplo n.º 21
0
    internal FiveAxisToRobots(CartesianTarget refTarget, Vector3d alignment, GCodeFile file)
    {
        _refTarget = refTarget;
        _alignment = alignment;

        var constructionPlane = Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport.GetConstructionPlane().Plane;

        constructionPlane.Origin = Point3d.Origin;
        var workPlane = _refTarget.Frame.Plane;
        var xform     = Transform.PlaneToPlane(Plane.WorldXY, workPlane);

        constructionPlane.Transform(xform);

        _mcs = new Frame(plane: constructionPlane, name: "MCS");

        _gCodeMap = new Dictionary <(GCodeLine.LType letter, int number), Action <GCodeLine> >
        {
            { (GCodeLine.LType.GCode, 0), RapidMove },
Ejemplo n.º 22
0
        private string ApplyFeedRateMultiplier(string lineBeingSent)
        {
            if (lineBeingSent != null
                && FeedRateRatio != 1)
            {
                lineBeingSent = lineBeingSent.ToUpper().Trim();
                if (lineBeingSent.StartsWith("G0") || lineBeingSent.StartsWith("G1"))
                {
                    double feedRate = 0;
                    if (GCodeFile.GetFirstNumberAfter("F", lineBeingSent, ref feedRate))
                    {
                        lineBeingSent = GCodeFile.ReplaceNumberAfter('F', lineBeingSent, feedRate * FeedRateRatio);
                    }
                }
            }

            return lineBeingSent;
        }
Ejemplo n.º 23
0
        public string DoApplyLeveling(string lineBeingSent, Vector3 currentDestination,
                                      PrinterMachineInstruction.MovementTypes movementMode)
        {
            double extruderDelta = 0;

            GCodeFile.GetFirstNumberAfter("E", lineBeingSent, ref extruderDelta);
            double feedRate = 0;

            GCodeFile.GetFirstNumberAfter("F", lineBeingSent, ref feedRate);

            StringBuilder newLine = new StringBuilder("G1 ");

            if (lineBeingSent.Contains("X") || lineBeingSent.Contains("Y") || lineBeingSent.Contains("Z"))
            {
                Vector3 outPosition = GetPositionWithZOffset(currentDestination);

                if (movementMode == PrinterMachineInstruction.MovementTypes.Relative)
                {
                    Vector3 delta = outPosition - lastDestinationWithLevelingApplied;
                    lastDestinationWithLevelingApplied = outPosition;
                    outPosition = delta;
                }
                else
                {
                    lastDestinationWithLevelingApplied = outPosition;
                }

                newLine = newLine.Append(String.Format("X{0:0.##} Y{1:0.##} Z{2:0.###}", outPosition.x, outPosition.y, outPosition.z));
            }

            if (extruderDelta != 0)
            {
                newLine = newLine.Append(String.Format(" E{0:0.###}", extruderDelta));
            }

            if (feedRate != 0)
            {
                newLine = newLine.Append(String.Format(" F{0:0.##}", feedRate));
            }

            lineBeingSent = newLine.ToString();

            return(lineBeingSent);
        }
Ejemplo n.º 24
0
        private void FindExtents(GCodeFile file)
        {
            var min = new Point3D <double>()
            {
                X = 99999.0, Y = 99999.0, Z = 99999.0
            };
            var max = new Point3D <double>()
            {
                X = -99999.0, Y = -99999.0, Z = -999999.0
            };

            bool first = true;

            foreach (var cmd in file.Commands)
            {
                var motionCmd = cmd as GCodeMotion;
                if (motionCmd != null)
                {
                    if (!first)
                    {
                        min.X = Math.Min(min.X, motionCmd.Start.X);
                        min.Y = Math.Min(min.Y, motionCmd.Start.Y);
                        min.Z = Math.Min(min.Z, motionCmd.Start.Z);
                        min.X = Math.Min(min.X, motionCmd.End.X);
                        min.Y = Math.Min(min.Y, motionCmd.End.Y);
                        min.Z = Math.Min(min.Z, motionCmd.End.Z);
                    }
                    else
                    {
                        first = false;
                    }

                    max.X = Math.Max(max.X, motionCmd.Start.X);
                    max.Y = Math.Max(max.Y, motionCmd.Start.Y);
                    max.Z = Math.Max(max.Z, motionCmd.Start.Z);
                    max.X = Math.Max(max.X, motionCmd.End.X);
                    max.Y = Math.Max(max.Y, motionCmd.End.Y);
                    max.Z = Math.Max(max.Z, motionCmd.End.Z);
                }
            }

            Max = max;
            Min = min;
        }
Ejemplo n.º 25
0
        public GCodeSwitcher(Stream gcodeStream, PrinterConfig printer, int startLine = 0)
            : base(printer)
        {
            var settings        = this.printer.Settings;
            var maxAcceleration = settings.GetValue <double>(SettingsKey.max_acceleration);
            var maxVelocity     = settings.GetValue <double>(SettingsKey.max_velocity);
            var jerkVelocity    = settings.GetValue <double>(SettingsKey.jerk_velocity);
            var multiplier      = settings.GetValue <double>(SettingsKey.print_time_estimate_multiplier) / 100.0;

            var fileStreaming = GCodeFile.Load(gcodeStream,
                                               new Vector4(maxAcceleration, maxAcceleration, maxAcceleration, maxAcceleration),
                                               new Vector4(maxVelocity, maxVelocity, maxVelocity, maxVelocity),
                                               new Vector4(jerkVelocity, jerkVelocity, jerkVelocity, jerkVelocity),
                                               new Vector4(multiplier, multiplier, multiplier, multiplier),
                                               CancellationToken.None);

            this.GCodeFile = fileStreaming;
            LineIndex      = startLine;
        }
Ejemplo n.º 26
0
        bool process_completed_compute()
        {
            if (active_compute != null)
            {
                if (active_compute.Finished)
                {
                    lock (active_compute_lock) {
                        if (active_compute.Success)
                        {
                            CurrentGCode    = active_compute.gcode;
                            Toolpaths       = active_compute.paths;
                            LayerInfo       = active_compute.layerInfo;
                            Settings        = active_compute.PrintSettings;
                            Slices          = active_compute.SliceSet;
                            ToolpathsValid  = true;
                            ToolpathsFailed = false;

                            ToolpathsProgressEvent?.Invoke(new ToolpathProgressStatus(1, 1));

                            CC.Objects.SetToolpaths(this);
                        }
                        else
                        {
                            CurrentGCode    = null;
                            Toolpaths       = null;
                            LayerInfo       = null;
                            Settings        = null;
                            Slices          = null;
                            ToolpathsValid  = false;
                            ToolpathsFailed = true;

                            // notify of failure here?
                            ToolpathsProgressEvent?.Invoke(ToolpathProgressStatus.Failed);
                        }

                        active_compute        = null;
                        active_compute_thread = null;
                        return(true);
                    }
                }
            }
            return(false);
        }
Ejemplo n.º 27
0
        public static PrinterMove GetPosition(string lineBeingSent, PrinterMove startPositionPosition)
        {
            if (lineBeingSent.StartsWith("G28") ||
                lineBeingSent.StartsWith("G29") ||
                lineBeingSent.StartsWith("G30"))
            {
                return(PrinterMove.Unknown);
            }

            PrinterMove currentDestination = startPositionPosition;

            GCodeFile.GetFirstNumberAfter("X", lineBeingSent, ref currentDestination.position.X);
            GCodeFile.GetFirstNumberAfter("Y", lineBeingSent, ref currentDestination.position.Y);
            GCodeFile.GetFirstNumberAfter("Z", lineBeingSent, ref currentDestination.position.Z);
            GCodeFile.GetFirstNumberAfter("E", lineBeingSent, ref currentDestination.extrusion);
            GCodeFile.GetFirstNumberAfter("F", lineBeingSent, ref currentDestination.feedRate);

            return(currentDestination);
        }
Ejemplo n.º 28
0
        public override string ReadLine()
        {
            string lineToSend = base.ReadLine();

            if (lineToSend != null &&
                lineToSend.EndsWith("; NO_PROCESSING"))
            {
                return(lineToSend);
            }

            if (lineToSend != null &&
                lineToSend.StartsWith("T"))
            {
                int extruder = 0;
                if (GCodeFile.GetFirstNumberAfter("T", lineToSend, ref extruder))
                {
                    extruderIndex = extruder;
                }
            }

            if (lineToSend != null &&
                LineIsMovement(lineToSend))
            {
                PrinterMove currentMove = GetPosition(lineToSend, lastDestination);

                PrinterMove moveToSend = currentMove;
                if (extruderIndex < 4)
                {
                    moveToSend.position += BabbyStepOffset;
                    moveToSend.position -= extruderOffsets[extruderIndex];
                }

                if (moveToSend.HaveAnyPosition)
                {
                    lineToSend = CreateMovementLine(moveToSend, lastDestination);
                }
                lastDestination = currentMove;

                return(lineToSend);
            }

            return(lineToSend);
        }
Ejemplo n.º 29
0
        public string ApplyLeveling(Vector3 currentDestination, PrinterMachineInstruction.MovementTypes movementMode, string lineBeingSent)
        {
            if ((lineBeingSent.StartsWith("G0") || lineBeingSent.StartsWith("G1")) &&
                lineBeingSent.Length > 2 &&
                lineBeingSent[2] == ' ')
            {
                double extruderDelta = 0;
                GCodeFile.GetFirstNumberAfter("E", lineBeingSent, ref extruderDelta);
                double feedRate = 0;
                GCodeFile.GetFirstNumberAfter("F", lineBeingSent, ref feedRate);

                string newLine = "G1 ";

                if (lineBeingSent.Contains('X') || lineBeingSent.Contains('Y') || lineBeingSent.Contains('Z'))
                {
                    Vector3 outPosition = PrintLevelingPlane.Instance.ApplyLeveling(currentDestination);
                    if (movementMode == PrinterMachineInstruction.MovementTypes.Relative)
                    {
                        Vector3 relativeMove = Vector3.Zero;
                        GCodeFile.GetFirstNumberAfter("X", lineBeingSent, ref relativeMove.x);
                        GCodeFile.GetFirstNumberAfter("Y", lineBeingSent, ref relativeMove.y);
                        GCodeFile.GetFirstNumberAfter("Z", lineBeingSent, ref relativeMove.z);
                        outPosition = PrintLevelingPlane.Instance.ApplyLevelingRotation(relativeMove);
                    }

                    newLine = newLine + String.Format("X{0:0.##} Y{1:0.##} Z{2:0.###}", outPosition.x, outPosition.y, outPosition.z);
                }

                if (extruderDelta != 0)
                {
                    newLine = newLine + String.Format(" E{0:0.###}", extruderDelta);
                }
                if (feedRate != 0)
                {
                    newLine = newLine + String.Format(" F{0:0.##}", feedRate);
                }

                lineBeingSent = newLine;
            }

            return(lineBeingSent);
        }
Ejemplo n.º 30
0
        public void Leveling7PointsNeverGetsTooHigh()
        {
            StaticData.Instance = new MatterHackers.Agg.FileSystemStaticData(Path.Combine("..", "..", "..", "..", "StaticData"));

            MatterControlUtilities.OverrideAppDataLocation();

            var levelingData = new PrintLevelingData(ActiveSliceSettings.Instance);

            double radius = 100;

            levelingData.SampledPositions = new List <Vector3>();
            levelingData.SampledPositions.Add(new Vector3(130.00, 0.00, 0));
            levelingData.SampledPositions.Add(new Vector3(65.00, 112.58, 10));
            levelingData.SampledPositions.Add(new Vector3(-65.00, 112.58, 0));
            levelingData.SampledPositions.Add(new Vector3(-130.00, 0.00, 10));
            levelingData.SampledPositions.Add(new Vector3(-65.00, -112.58, 0));
            levelingData.SampledPositions.Add(new Vector3(65.00, -112.58, 10));

            levelingData.SampledPositions.Add(new Vector3(0, 0, 0));

            levelingData.SampledPositions.Add(new Vector3(0, 0, 6));

            Vector2 bedCenter = Vector2.Zero;

            RadialLevlingFunctions levelingFunctions7Point = new RadialLevlingFunctions(6, levelingData, bedCenter);
            int totalPoints = 2000;

            for (int curPoint = 0; curPoint < totalPoints; curPoint++)
            {
                Vector2 currentTestPoint = new Vector2(radius, 0);
                currentTestPoint.Rotate(MathHelper.Tau / totalPoints * curPoint);
                Vector3 destPosition = new Vector3(currentTestPoint, 0);

                Vector3 outPosition = levelingFunctions7Point.GetPositionWithZOffset(destPosition);
                Assert.IsTrue(outPosition.z <= 10);

                string outPositionString = levelingFunctions7Point.DoApplyLeveling(GetGCodeString(destPosition), destPosition, PrinterMachineInstruction.MovementTypes.Absolute);
                double outZ = 0;
                Assert.IsTrue(GCodeFile.GetFirstNumberAfter("Z", outPositionString, ref outZ));
                Assert.IsTrue(outZ <= 10);
            }
        }
Ejemplo n.º 31
0
        private void SaveGCodeToNewLocation(string gcodeFilename, string dest)
        {
            try
            {
                if (ActiveSliceSettings.Instance.GetValue <bool>(SettingsKey.print_leveling_enabled))
                {
                    if (applyLeveling.Checked)
                    {
                        GCodeFile           loadedGCode          = GCodeFile.Load(gcodeFilename);
                        GCodeFileStream     gCodeFileStream0     = new GCodeFileStream(loadedGCode);
                        PrintLevelingStream printLevelingStream4 = new PrintLevelingStream(gCodeFileStream0, false);
                        // this is added to ensure we are rewriting the G0 G1 commands as needed
                        FeedRateMultiplyerStream extrusionMultiplyerStream = new FeedRateMultiplyerStream(printLevelingStream4);

                        using (StreamWriter file = new StreamWriter(dest))
                        {
                            string nextLine = extrusionMultiplyerStream.ReadLine();
                            while (nextLine != null)
                            {
                                file.WriteLine(nextLine);
                                nextLine = extrusionMultiplyerStream.ReadLine();
                            }
                        }
                    }
                    else
                    {
                        File.Copy(gcodeFilename, dest, true);
                    }
                }
                else
                {
                    File.Copy(gcodeFilename, dest, true);
                }
                ShowFileIfRequested(dest);
            }
            catch (Exception e)
            {
                UiThread.RunOnIdle(() => {
                    StyledMessageBox.ShowMessageBox(null, e.Message, "Couldn't save file".Localize());
                });
            }
        }
 public bool ExecuteSequence(string name)
 {
     try
     {
         CommandSequence seq = Find(name);
         if (seq == null)
             return false;
         switch (seq.m_seqtype)
         {
             case CommandSequence.COMMAND_TYPE_GCODE:
                 //a gcode command sequence - execute it with a pseudo-build manager/sequencer
                 GCodeFile gcf = new GCodeFile(seq.m_seq);
                 if (!UVDLPApp.Instance().m_buildmgr.IsPrinting)
                 {
                     DebugLogger.Instance().LogInfo("Running GCode Sequence " + seq.m_name);
                     UVDLPApp.Instance().m_buildmgr.StartPrint(UVDLPApp.Instance().m_slicefile, gcf, true);
                 }
                 break;
             case CommandSequence.COMMAND_TYPE_SPAWN_PROCESS:
                 //use the parameter variables to fill in the args, then spawn the process
                 // a flag can be to wait for the process to end , or simply start it.
                 ProcessSequence psc = (ProcessSequence)seq;
                 foreach (ProcessEntry pe in psc.m_entries)
                 {
                     pe.RunProcess();
                 }
                 break;
         }
         return true;
     }
     catch (Exception ex)
     {
         DebugLogger.Instance().LogError(ex);
     }
     return false;
 }
Ejemplo n.º 33
0
 public GCodeFile LoadGCodeFromScene(string scenefilename) 
 {
     if (OpenSceneFile(scenefilename))
     {
         XmlNode gcn = mManifest.FindSection(mManifest.m_toplevel, "GCode");
         string gcodename = mManifest.GetString(gcn, "name", "none");
         if (!gcodename.Equals("none"))
         {
             try
             {
                 ZipEntry gcodeentry = mZip[gcodename];
                 MemoryStream gcstr = new MemoryStream();
                 gcodeentry.Extract(gcstr);
                 //rewind to beginning
                 gcstr.Seek(0, SeekOrigin.Begin);
                 GCodeFile gcf = new GCodeFile(gcstr);
                 return gcf;
             }
             catch (Exception ex)
             {
                 DebugLogger.Instance().LogError(ex);
             }
         }
     }
     return null;
 }
Ejemplo n.º 34
0
 public GCodeFile LoadGCodeFromScene(string scenefilename)
 {
     GCodeFile gcf = null;
     try
     {
         //load the latest version of the manifest
         LoadManifest(scenefilename);
         //find the gcode section
         XmlNode gcn = mManifest.FindSection(mManifest.m_toplevel, "GCode");
         //get the name of the gcode file
         string gcodename = mManifest.GetString(gcn, "name", "none");
         // if there is a gcode file, open the zip and load it
         if (!gcodename.Equals("none"))
         {
             //open the zip
             using (ZipFile mZip = ZipFile.Read(scenefilename))
             {
                 ZipEntry gcodeentry = mZip[gcodename];
                 MemoryStream gcstr = new MemoryStream();
                 gcodeentry.Extract(gcstr);
                 //rewind to beginning
                 gcstr.Seek(0, SeekOrigin.Begin);
                 gcf = new GCodeFile(gcstr);
             }
         }
     }
     catch (Exception ex)
     {
         DebugLogger.Instance().LogError(ex);
     }
     return gcf;
 }
Ejemplo n.º 35
0
        public bool LoadSceneFile(string scenefilename)
        {
            try
            {
                UVDLPApp.Instance().SceneFileName = scenefilename;
                LoadManifest(scenefilename);
                using (ZipFile mZip = ZipFile.Read(scenefilename))
                {

                    //examine manifest
                    //find the node with models
                    XmlNode topnode = mManifest.m_toplevel;

                    //load gcode if present
                    XmlNode gcn = mManifest.FindSection(mManifest.m_toplevel, "GCode");
                    //get the name of the gcode file
                    string gcodename = mManifest.GetString(gcn, "name", "none");
                    if (!gcodename.Equals("none"))
                    {
                        //open the zip
                        ZipEntry gcodeentry = mZip[gcodename];
                        MemoryStream gcstr = new MemoryStream();
                        gcodeentry.Extract(gcstr);
                        //rewind to beginning
                        gcstr.Seek(0, SeekOrigin.Begin);
                        GCodeFile gcf = new GCodeFile(gcstr);
                        UVDLPApp.Instance().m_gcode = gcf;
                        UVDLPApp.Instance().RaiseAppEvent(eAppEvent.eGCodeLoaded, "GCode Loaded ");
                    }
                    else
                    {
                        UVDLPApp.Instance().m_gcode = new GCodeFile(""); // empty
                    }

                    // load slice profile if present
                    XmlNode spn = mManifest.FindSection(mManifest.m_toplevel, "SliceProfile");
                    string sliceprofilename = mManifest.GetString(spn, "name", "none");
                    if (!sliceprofilename.Equals("none"))
                    {
                        ZipEntry gcodeentry = mZip[sliceprofilename];
                        MemoryStream gcstr = new MemoryStream();
                        gcodeentry.Extract(gcstr);
                        //rewind to beginning
                        gcstr.Seek(0, SeekOrigin.Begin);
                        //GCodeFile gcf = new GCodeFile(gcstr);
                        UVDLPApp.Instance().m_buildparms = new SliceBuildConfig();
                        UVDLPApp.Instance().m_buildparms.Load(gcstr, sliceprofilename);
                        //create a new slice file based off of the build and slicing parameters
                        UVDLPApp.Instance().m_slicefile = new SliceFile(UVDLPApp.Instance().m_buildparms);
                        UVDLPApp.Instance().m_slicefile.m_mode = SliceFile.SFMode.eLoaded;
                        UVDLPApp.Instance().m_slicer.SliceFile = UVDLPApp.Instance().m_slicefile;
                        UVDLPApp.Instance().m_slicefile.NumSlices = UVDLPApp.Instance().m_slicer.GetNumberOfSlices(UVDLPApp.Instance().m_buildparms);
                        //raise the event to indicate it's loaded
                        UVDLPApp.Instance().RaiseAppEvent(eAppEvent.eSliceProfileChanged, "Slice Profile loaded");
                        UVDLPApp.Instance().RaiseAppEvent(eAppEvent.eSlicedLoaded, "Slice Profile loaded");

                    }

                    // now load the models
                    XmlNode models = mManifest.FindSection(topnode, "Models");
                    List<XmlNode> modelnodes = mManifest.FindAllChildElement(models, "model");
                    // bool supportLoaded = false;
                    foreach (XmlNode nd in modelnodes)
                    {
                        string name = mManifest.GetString(nd, "name", "noname");
                        string modstlname = name + ".stl";
                        int tag = mManifest.GetInt(nd, "tag", 0);
                        ZipEntry modelentry = mZip[modstlname]; // the model name will have the _XXXX on the end with the stl extension
                        MemoryStream modstr = new MemoryStream();
                        modelentry.Extract(modstr);
                        //rewind to beginning
                        modstr.Seek(0, SeekOrigin.Begin);
                        //fix the name
                        name = name.Substring(0, name.Length - 5);// get rid of the _XXXX at the end
                        string parentName = mManifest.GetString(nd, "parent", "noname");
                        Object3d obj, tmpObj;
                        switch (tag)
                        {
                            case Object3d.OBJ_SUPPORT:
                            case Object3d.OBJ_SUPPORT_BASE:
                                if (tag == Object3d.OBJ_SUPPORT)
                                    obj = (Object3d)(new Support());
                                else
                                    obj = (Object3d)(new SupportBase());
                                //load the model
                                obj.LoadSTL_Binary(modstr, name);
                                //add to the 3d engine
                                UVDLPApp.Instance().m_engine3d.AddObject(obj);
                                //set the tag
                                obj.tag = tag;
                                obj.SetColor(System.Drawing.Color.Yellow);
                                //find and set the parent
                                tmpObj = UVDLPApp.Instance().m_engine3d.Find(parentName);
                                if (tmpObj != null)
                                {
                                    tmpObj.AddSupport(obj);
                                }
                                //supportLoaded = true;
                                break;

                            default:
                                //load as normal object
                                obj = new Object3d();
                                //load the model
                                obj.LoadSTL_Binary((MemoryStream)modstr, name);
                                //add to the 3d engine
                                UVDLPApp.Instance().m_engine3d.AddObject(obj);
                                //set the tag
                                obj.tag = tag;
                                break;
                        }
                    }
                }

                UVDLPApp.Instance().RaiseAppEvent(eAppEvent.eModelAdded, "Scene loaded");
                return true;
            }
            catch (Exception ex)
            {
                DebugLogger.Instance().LogError(ex);
                return false;
            }
        }