mattercontrol/SlicerConfiguration/Slicer.cs

440 lines
14 KiB
C#
Raw Normal View History

/*
2017-10-17 12:42:52 -07:00
Copyright (c) 2017, Lars Brubaker, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
2015-04-08 15:20:10 -07:00
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
2015-04-08 15:20:10 -07:00
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
2015-04-08 15:20:10 -07:00
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
2015-04-08 15:20:10 -07:00
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
2015-04-08 15:20:10 -07:00
using System;
2014-01-29 19:09:30 -08:00
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using MatterHackers.Agg;
using MatterHackers.Agg.Platform;
using MatterHackers.DataConverters3D;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.MatterControl.PrintQueue;
using MatterHackers.MatterControl.SettingsManagement;
using MatterHackers.MeshVisualizer;
using MatterHackers.PolygonMesh;
2014-01-29 19:09:30 -08:00
namespace MatterHackers.MatterControl.SlicerConfiguration
2014-01-29 19:09:30 -08:00
{
2017-10-17 12:42:52 -07:00
public static class Slicer
2015-04-08 15:20:10 -07:00
{
2017-10-17 12:42:52 -07:00
private static Dictionary<Mesh, MeshPrintOutputSettings> meshPrintOutputSettings = new Dictionary<Mesh, MeshPrintOutputSettings>();
2014-01-29 19:09:30 -08:00
2015-04-08 15:20:10 -07:00
public static List<bool> extrudersUsed = new List<bool>();
public static bool runInProcess = false;
public static string[] GetStlFileLocations(string fileToSlice, ref string mergeRules, PrinterConfig printer, IProgress<ProgressStatus> progressReporter, CancellationToken cancellationToken)
2015-04-08 15:20:10 -07:00
{
var progressStatus = new ProgressStatus();
2015-04-08 15:20:10 -07:00
extrudersUsed.Clear();
int extruderCount = printer.Settings.GetValue<int>(SettingsKey.extruder_count);
2015-04-08 15:20:10 -07:00
for (int extruderIndex = 0; extruderIndex < extruderCount; extruderIndex++)
{
extrudersUsed.Add(false);
}
2016-01-04 21:18:57 -08:00
// If we have support enabled and are using an extruder other than 0 for it
if (printer.Settings.GetValue<bool>("support_material"))
2015-04-08 15:20:10 -07:00
{
if (printer.Settings.GetValue<int>("support_material_extruder") != 0)
2015-04-08 15:20:10 -07:00
{
int supportExtruder = Math.Max(0, Math.Min(printer.Settings.GetValue<int>(SettingsKey.extruder_count) - 1, printer.Settings.GetValue<int>("support_material_extruder") - 1));
2015-04-08 15:20:10 -07:00
extrudersUsed[supportExtruder] = true;
}
}
// If we have raft enabled and are using an extruder other than 0 for it
if (printer.Settings.GetValue<bool>("create_raft"))
2015-04-08 15:20:10 -07:00
{
if (printer.Settings.GetValue<int>("raft_extruder") != 0)
2015-04-08 15:20:10 -07:00
{
int raftExtruder = Math.Max(0, Math.Min(printer.Settings.GetValue<int>(SettingsKey.extruder_count) - 1, printer.Settings.GetValue<int>("raft_extruder") - 1));
2015-04-08 15:20:10 -07:00
extrudersUsed[raftExtruder] = true;
}
}
switch (Path.GetExtension(fileToSlice).ToUpper())
{
case ".STL":
case ".GCODE":
extrudersUsed[0] = true;
return new string[] { fileToSlice };
2017-03-15 16:17:06 -07:00
case ".MCX":
2015-04-08 15:20:10 -07:00
case ".AMF":
2017-05-22 17:52:08 -07:00
case ".OBJ":
2017-03-15 16:17:06 -07:00
// TODO: Once graph parsing is added to MatterSlice we can remove and avoid this flattening
2017-07-20 12:44:55 -07:00
meshPrintOutputSettings.Clear();
progressStatus.Status = "Loading";
progressReporter.Report(progressStatus);
var reloadedItem = Object3D.Load(fileToSlice, cancellationToken);
progressStatus.Status = "Flattening";
progressReporter.Report(progressStatus);
// Flatten the scene, filtering out items outside of the build volume
var flattenScene = reloadedItem.Flatten(meshPrintOutputSettings, (item) => item.InsideBuildVolume(printer));
var meshGroups = new List<MeshGroup> { flattenScene };
if (meshGroups != null)
2015-04-08 15:20:10 -07:00
{
List<MeshGroup> extruderMeshGroups = new List<MeshGroup>();
for (int extruderIndex = 0; extruderIndex < extruderCount; extruderIndex++)
2015-04-08 15:20:10 -07:00
{
extruderMeshGroups.Add(new MeshGroup());
}
// and add one more extruder mesh group for user generated support (if exists)
extruderMeshGroups.Add(new MeshGroup());
int maxExtruderIndex = 0;
foreach (MeshGroup meshGroup in meshGroups)
{
foreach (Mesh mesh in meshGroup.Meshes)
2015-04-08 15:20:10 -07:00
{
2017-07-20 12:44:55 -07:00
MeshPrintOutputSettings material = meshPrintOutputSettings[mesh];
switch(material.PrintOutputTypes)
{
case PrintOutputTypes.Solid:
int extruderIndex = Math.Max(0, material.ExtruderIndex);
maxExtruderIndex = Math.Max(maxExtruderIndex, extruderIndex);
if (extruderIndex >= extruderCount)
{
extrudersUsed[0] = true;
extruderMeshGroups[0].Meshes.Add(mesh);
}
else
{
extrudersUsed[extruderIndex] = true;
extruderMeshGroups[extruderIndex].Meshes.Add(mesh);
}
break;
case PrintOutputTypes.Support:
// add it to the group reserved for user support
extruderMeshGroups[extruderCount].Meshes.Add(mesh);
break;
}
2015-04-08 15:20:10 -07:00
}
}
2015-12-14 08:29:24 -08:00
int savedStlCount = 0;
List<string> extruderFilesToSlice = new List<string>();
2015-12-14 08:29:24 -08:00
for (int extruderIndex = 0; extruderIndex < extruderMeshGroups.Count; extruderIndex++)
2015-04-08 15:20:10 -07:00
{
2015-12-14 08:29:24 -08:00
MeshGroup meshGroup = extruderMeshGroups[extruderIndex];
2015-04-08 15:20:10 -07:00
2017-06-15 16:54:36 -07:00
int meshCount = meshGroup.Meshes.Count;
if (meshCount > 0)
2015-12-14 08:29:24 -08:00
{
2017-06-15 16:54:36 -07:00
for (int meshIndex = 0; meshIndex < meshCount; meshIndex++)
2015-12-14 08:29:24 -08:00
{
2017-06-15 16:54:36 -07:00
Mesh mesh = meshGroup.Meshes[meshIndex];
2017-07-17 16:41:04 -07:00
if (meshIndex == 0)
2015-12-14 08:29:24 -08:00
{
2017-06-15 16:54:36 -07:00
mergeRules += "({0}".FormatWith(savedStlCount);
}
else
{
if (meshIndex < meshCount - 1)
2015-12-14 08:29:24 -08:00
{
2017-06-15 16:54:36 -07:00
mergeRules += ",({0}".FormatWith(savedStlCount);
2015-12-14 08:29:24 -08:00
}
else
{
2017-06-15 16:54:36 -07:00
mergeRules += ",{0}".FormatWith(savedStlCount);
2015-12-14 08:29:24 -08:00
}
}
2017-07-20 12:44:55 -07:00
int meshExtruderIndex = meshPrintOutputSettings[mesh].ExtruderIndex;
if(cancellationToken.IsCancellationRequested)
{
return new string[0];
}
var fileName = SaveAndGetFilePathForMesh(mesh, cancellationToken);
extruderFilesToSlice.Add(fileName);
2017-06-15 16:54:36 -07:00
savedStlCount++;
2015-12-14 08:29:24 -08:00
}
2017-06-15 16:54:36 -07:00
2017-07-17 16:41:04 -07:00
int closeParentsCount = (meshCount == 1 || meshCount == 2) ? 1 : meshCount - 1;
for (int i = 0; i < closeParentsCount; i++)
2015-12-14 08:29:24 -08:00
{
2017-06-15 16:54:36 -07:00
mergeRules += ")";
2015-12-14 08:29:24 -08:00
}
}
else if(extruderIndex <= maxExtruderIndex) // this extruder has no meshes
2017-06-07 15:56:02 -07:00
{
2017-06-15 16:54:36 -07:00
// check if there are any more meshes after this extruder that will be added
int otherMeshCounts = 0;
for (int otherExtruderIndex = extruderIndex + 1; otherExtruderIndex < extruderMeshGroups.Count; otherExtruderIndex++)
{
otherMeshCounts += extruderMeshGroups[otherExtruderIndex].Meshes.Count;
}
if (otherMeshCounts > 0) // there are more extrudes to use after this not used one
{
// add in a blank for this extruder
mergeRules += $"({savedStlCount})";
}
// save an empty mesh
extruderFilesToSlice.Add(SaveAndGetFilePathForMesh(PlatonicSolids.CreateCube(.001, .001, .001), cancellationToken));
2017-06-15 16:54:36 -07:00
savedStlCount++;
2017-06-07 15:56:02 -07:00
}
}
2017-05-19 14:39:57 -07:00
// if we added user generated support
if(extruderMeshGroups[extruderCount].Meshes.Count > 0)
{
// add a flag to the merge rules to let us know there was support
2017-07-21 13:24:16 -07:00
mergeRules += "S";
}
return extruderFilesToSlice.ToArray();
2015-04-08 15:20:10 -07:00
}
return new string[] { "" };
2015-04-08 15:20:10 -07:00
default:
return new string[] { "" };
2015-04-08 15:20:10 -07:00
}
}
private static string SaveAndGetFilePathForMesh(Mesh meshToSave, CancellationToken cancellationToken)
2015-12-14 08:29:24 -08:00
{
string folderToSaveStlsTo = Path.Combine(ApplicationDataStorage.ApplicationUserDataPath, "data", "temp", "amf_to_stl");
// Create directory if needed
Directory.CreateDirectory(folderToSaveStlsTo);
string filePath = Path.Combine(folderToSaveStlsTo, Path.ChangeExtension(Path.GetRandomFileName(), ".stl"));
MeshFileIo.Save(meshToSave, filePath, cancellationToken);
return filePath;
2015-12-14 08:29:24 -08:00
}
public static Task<bool> SliceFile(string sourceFile, string gcodeFilePath, PrinterConfig printer, IProgress<ProgressStatus> progressReporter, CancellationToken cancellationToken)
{
bool slicingSucceeded = true;
string mergeRules = "";
string[] stlFileLocations = GetStlFileLocations(sourceFile, ref mergeRules, printer, progressReporter, cancellationToken);
if(stlFileLocations.Length > 0)
{
var progressStatus = new ProgressStatus()
{
Status = "Generating Config"
};
progressReporter.Report(progressStatus);
string configFilePath = Path.Combine(
ApplicationDataStorage.Instance.GCodeOutputPath,
string.Format("config_{0}.ini", printer.Settings.GetLongHashCode().ToString()));
progressStatus.Status = "Starting slicer";
progressReporter.Report(progressStatus);
if (!File.Exists(gcodeFilePath)
|| !HasCompletedSuccessfully(gcodeFilePath))
{
string commandArgs;
EngineMappingsMatterSlice.WriteSliceSettingsFile(configFilePath);
if (mergeRules == "")
{
commandArgs = $"-v -o \"{gcodeFilePath}\" -c \"{configFilePath}\"";
}
else
{
commandArgs = $"-b {mergeRules} -v -o \"{gcodeFilePath}\" -c \"{configFilePath}\"";
}
foreach (string filename in stlFileLocations)
{
commandArgs += $" \"{filename}\"";
}
if (AggContext.OperatingSystem == OSType.Android
|| AggContext.OperatingSystem == OSType.Mac
|| runInProcess)
{
EventHandler WriteOutput = (s, e) =>
{
if(cancellationToken.IsCancellationRequested)
{
MatterSlice.MatterSlice.Stop();
}
if (s is string stringValue)
{
progressReporter?.Report(new ProgressStatus()
{
Status = stringValue
});
}
};
MatterSlice.LogOutput.GetLogWrites += WriteOutput;
MatterSlice.MatterSlice.ProcessArgs(commandArgs);
MatterSlice.LogOutput.GetLogWrites -= WriteOutput;
}
else
{
bool forcedExit = false;
var slicerProcess = new Process()
{
StartInfo = new ProcessStartInfo()
2015-04-08 15:20:10 -07:00
{
Arguments = commandArgs,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardError = true,
RedirectStandardOutput = true,
FileName = MatterSliceInfo.GetEnginePath(),
UseShellExecute = false
2015-04-08 15:20:10 -07:00
}
};
slicerProcess.OutputDataReceived += (s, e) =>
{
if (e.Data is string stringValue)
2015-04-08 15:20:10 -07:00
{
if (cancellationToken.IsCancellationRequested)
{
slicerProcess?.Kill();
slicerProcess?.Dispose();
forcedExit = true;
}
string message = stringValue.Replace("=>", "").Trim();
if (message.Contains(".gcode"))
{
message = "Saving intermediate file";
}
message += "...";
2015-04-08 15:20:10 -07:00
progressReporter?.Report(new ProgressStatus()
{
Status = message
});
}
};
slicerProcess.Start();
slicerProcess.BeginOutputReadLine();
2015-04-08 15:20:10 -07:00
string stdError = slicerProcess.StandardError.ReadToEnd();
2015-04-08 15:20:10 -07:00
if (!forcedExit)
{
slicerProcess.WaitForExit();
}
slicingSucceeded = !forcedExit;
}
}
try
{
if (File.Exists(gcodeFilePath)
&& File.Exists(configFilePath))
{
// make sure we have not already written the settings onto this file
bool fileHasSettings = false;
int bufferSize = 32000;
using (Stream fileStream = File.OpenRead(gcodeFilePath))
{
// Read the tail of the file to determine if the given token exists
byte[] buffer = new byte[bufferSize];
fileStream.Seek(Math.Max(0, fileStream.Length - bufferSize), SeekOrigin.Begin);
int numBytesRead = fileStream.Read(buffer, 0, bufferSize);
string fileEnd = System.Text.Encoding.UTF8.GetString(buffer);
if (fileEnd.Contains("GCode settings used"))
{
fileHasSettings = true;
2015-04-08 15:20:10 -07:00
}
}
if (!fileHasSettings)
2015-04-08 15:20:10 -07:00
{
using (StreamWriter gcodeWriter = File.AppendText(gcodeFilePath))
2015-04-08 15:20:10 -07:00
{
string oemName = "MatterControl";
if (OemSettings.Instance.WindowTitleExtra != null && OemSettings.Instance.WindowTitleExtra.Trim().Length > 0)
{
oemName += $" - {OemSettings.Instance.WindowTitleExtra}";
}
gcodeWriter.WriteLine("; {0} Version {1} Build {2} : GCode settings used", oemName, VersionInfo.Instance.ReleaseVersion, VersionInfo.Instance.BuildVersion);
gcodeWriter.WriteLine("; Date {0} Time {1}:{2:00}", DateTime.Now.Date, DateTime.Now.Hour, DateTime.Now.Minute);
foreach (string line in File.ReadLines(configFilePath))
{
gcodeWriter.WriteLine("; {0}", line);
}
2015-04-08 15:20:10 -07:00
}
}
}
}
catch (Exception)
{
}
2015-04-08 15:20:10 -07:00
}
return Task.FromResult(slicingSucceeded);
2015-04-08 15:20:10 -07:00
}
private static bool HasCompletedSuccessfully(string gcodeFilePath)
2015-04-08 15:20:10 -07:00
{
using (var reader = new StreamReader(gcodeFilePath))
2015-01-13 10:34:27 -08:00
{
if (reader.BaseStream.Length > 10000)
2015-01-13 10:34:27 -08:00
{
reader.BaseStream.Seek(-10000, SeekOrigin.End);
2015-01-13 10:34:27 -08:00
}
string endText = reader.ReadToEnd();
return endText.Contains("; MatterSlice Completed Successfully");
2015-01-13 10:34:27 -08:00
}
2015-04-08 15:20:10 -07:00
}
}
}