public override void OnDragEnter(FileDropEventArgs fileDropEventArgs) { base.OnDragEnter(fileDropEventArgs); if (!fileDropEventArgs.AcceptDrop) { // no child has accepted the drop foreach (string file in fileDropEventArgs.DroppedFiles) { string extension = Path.GetExtension(file).ToUpper(); if ((extension != "" && MeshFileIo.ValidFileExtensions().Contains(extension)) || extension == ".GCODE" || extension == ".ZIP") { fileDropEventArgs.AcceptDrop = true; } } dropWasOnChild = false; } else { dropWasOnChild = true; } }
void createThumbnailWorker_DoWork(object sender, DoWorkEventArgs e) { PartThumbnailWidget thumbnailWidget = e.Argument as PartThumbnailWidget; if (thumbnailWidget != null) { if (thumbnailWidget.printItem == null) { thumbnailWidget.thumbnailImage = new ImageBuffer(thumbnailWidget.noThumbnailImage); thumbnailWidget.Invalidate(); return; } if (thumbnailWidget.PrintItem.FileLocation == QueueData.SdCardFileName) { switch (thumbnailWidget.Size) { case ImageSizes.Size115x115: { StaticData.Instance.LoadIcon(Path.ChangeExtension("icon_sd_card_115x115", partExtension), thumbnailWidget.thumbnailImage); } break; case ImageSizes.Size50x50: { StaticData.Instance.LoadIcon(Path.ChangeExtension("icon_sd_card_50x50", partExtension), thumbnailWidget.thumbnailImage); } break; default: throw new NotImplementedException(); } thumbnailWidget.thumbnailImage.SetRecieveBlender(new BlenderPreMultBGRA()); Graphics2D graphics = thumbnailWidget.thumbnailImage.NewGraphics2D(); Ellipse outline = new Ellipse(new Vector2(Width / 2.0, Height / 2.0), Width / 2 - Width / 12); graphics.Render(new Stroke(outline, Width / 12), RGBA_Bytes.White); UiThread.RunOnIdle(thumbnailWidget.EnsureImageUpdated); return; } else if (Path.GetExtension(thumbnailWidget.PrintItem.FileLocation).ToUpper() == ".GCODE") { CreateImage(thumbnailWidget, Width, Height); thumbnailWidget.thumbnailImage.SetRecieveBlender(new BlenderPreMultBGRA()); Graphics2D graphics = thumbnailWidget.thumbnailImage.NewGraphics2D(); Vector2 center = new Vector2(Width / 2.0, Height / 2.0); Ellipse outline = new Ellipse(center, Width / 2 - Width / 12); graphics.Render(new Stroke(outline, Width / 12), RGBA_Bytes.White); graphics.DrawString("GCode", center.x, center.y, 8 * Width / 50, Agg.Font.Justification.Center, Agg.Font.Baseline.BoundsCenter, color: RGBA_Bytes.White); UiThread.RunOnIdle(thumbnailWidget.EnsureImageUpdated); return; } else if (!File.Exists(thumbnailWidget.PrintItem.FileLocation)) { CreateImage(thumbnailWidget, Width, Height); thumbnailWidget.thumbnailImage.SetRecieveBlender(new BlenderPreMultBGRA()); Graphics2D graphics = thumbnailWidget.thumbnailImage.NewGraphics2D(); Vector2 center = new Vector2(Width / 2.0, Height / 2.0); graphics.DrawString("Missing", center.x, center.y, 8 * Width / 50, Agg.Font.Justification.Center, Agg.Font.Baseline.BoundsCenter, color: RGBA_Bytes.White); UiThread.RunOnIdle(thumbnailWidget.EnsureImageUpdated); return; } string stlHashCode = thumbnailWidget.PrintItem.FileHashCode.ToString(); Point2D bigRenderSize = new Point2D(460, 460); ImageBuffer bigRender = LoadImageFromDisk(thumbnailWidget, stlHashCode, bigRenderSize); if (bigRender == null) { if (!File.Exists(thumbnailWidget.PrintItem.FileLocation)) { return; } List <MeshGroup> loadedMeshGroups = MeshFileIo.Load(thumbnailWidget.PrintItem.FileLocation); thumbnailWidget.thumbnailImage = new ImageBuffer(thumbnailWidget.buildingThumbnailImage); thumbnailWidget.thumbnailImage.NewGraphics2D().Clear(new RGBA_Bytes(255, 255, 255, 0)); bigRender = BuildImageFromMeshGroups(loadedMeshGroups, stlHashCode, bigRenderSize); if (bigRender == null) { bigRender = new ImageBuffer(thumbnailWidget.noThumbnailImage); } } switch (thumbnailWidget.Size) { case ImageSizes.Size50x50: { ImageBuffer halfWay1 = new ImageBuffer(200, 200, 32, new BlenderBGRA()); halfWay1.NewGraphics2D().Clear(new RGBA_Bytes(255, 255, 255, 0)); halfWay1.NewGraphics2D().Render(bigRender, 0, 0, 0, (double)halfWay1.Width / bigRender.Width, (double)halfWay1.Height / bigRender.Height); ImageBuffer halfWay2 = new ImageBuffer(100, 100, 32, new BlenderBGRA()); halfWay2.NewGraphics2D().Clear(new RGBA_Bytes(255, 255, 255, 0)); halfWay2.NewGraphics2D().Render(halfWay1, 0, 0, 0, (double)halfWay2.Width / halfWay1.Width, (double)halfWay2.Height / halfWay1.Height); thumbnailWidget.thumbnailImage = new ImageBuffer((int)Width, (int)Height, 32, new BlenderBGRA()); thumbnailWidget.thumbnailImage.NewGraphics2D().Clear(new RGBA_Bytes(255, 255, 255, 0)); thumbnailWidget.thumbnailImage.NewGraphics2D().Render(halfWay2, 0, 0, 0, (double)thumbnailWidget.thumbnailImage.Width / halfWay2.Width, (double)thumbnailWidget.thumbnailImage.Height / halfWay2.Height); } break; case ImageSizes.Size115x115: { ImageBuffer halfWay1 = new ImageBuffer(230, 230, 32, new BlenderBGRA()); halfWay1.NewGraphics2D().Clear(new RGBA_Bytes(255, 255, 255, 0)); halfWay1.NewGraphics2D().Render(bigRender, 0, 0, 0, (double)halfWay1.Width / bigRender.Width, (double)halfWay1.Height / bigRender.Height); thumbnailWidget.thumbnailImage = new ImageBuffer((int)Width, (int)Height, 32, new BlenderBGRA()); thumbnailWidget.thumbnailImage.NewGraphics2D().Clear(new RGBA_Bytes(255, 255, 255, 0)); thumbnailWidget.thumbnailImage.NewGraphics2D().Render(halfWay1, 0, 0, 0, (double)thumbnailWidget.thumbnailImage.Width / halfWay1.Width, (double)thumbnailWidget.thumbnailImage.Height / halfWay1.Height); } break; default: throw new NotImplementedException(); } UiThread.RunOnIdle(thumbnailWidget.EnsureImageUpdated); } }
public static string[] GetStlFileLocations(string fileToSlice, bool doMergeInSlicer, ref string mergeRules) { extrudersUsed.Clear(); int extruderCount = ActiveSliceSettings.Instance.GetValue <int>(SettingsKey.extruder_count); for (int extruderIndex = 0; extruderIndex < extruderCount; extruderIndex++) { extrudersUsed.Add(false); } // If we have support enabled and are using an extruder other than 0 for it if (ActiveSliceSettings.Instance.GetValue <bool>("support_material")) { if (ActiveSliceSettings.Instance.GetValue <int>("support_material_extruder") != 0) { int supportExtruder = Math.Max(0, Math.Min(ActiveSliceSettings.Instance.GetValue <int>(SettingsKey.extruder_count) - 1, ActiveSliceSettings.Instance.GetValue <int>("support_material_extruder") - 1)); extrudersUsed[supportExtruder] = true; } } // If we have raft enabled and are using an extruder other than 0 for it if (ActiveSliceSettings.Instance.GetValue <bool>("create_raft")) { if (ActiveSliceSettings.Instance.GetValue <int>("raft_extruder") != 0) { int raftExtruder = Math.Max(0, Math.Min(ActiveSliceSettings.Instance.GetValue <int>(SettingsKey.extruder_count) - 1, ActiveSliceSettings.Instance.GetValue <int>("raft_extruder") - 1)); extrudersUsed[raftExtruder] = true; } } switch (Path.GetExtension(fileToSlice).ToUpper()) { case ".STL": case ".GCODE": extrudersUsed[0] = true; return(new string[] { fileToSlice }); case ".AMF": List <MeshGroup> meshGroups = MeshFileIo.Load(fileToSlice); if (meshGroups != null) { List <MeshGroup> extruderMeshGroups = new List <MeshGroup>(); for (int extruderIndex = 0; extruderIndex < extruderCount; extruderIndex++) { extruderMeshGroups.Add(new MeshGroup()); } int maxExtruderIndex = 0; foreach (MeshGroup meshGroup in meshGroups) { foreach (Mesh mesh in meshGroup.Meshes) { MeshMaterialData material = MeshMaterialData.Get(mesh); int extruderIndex = Math.Max(0, material.MaterialIndex - 1); 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); } } } int savedStlCount = 0; List <string> extruderFilesToSlice = new List <string>(); for (int extruderIndex = 0; extruderIndex < extruderMeshGroups.Count; extruderIndex++) { MeshGroup meshGroup = extruderMeshGroups[extruderIndex]; List <int> materialsToInclude = new List <int>(); materialsToInclude.Add(extruderIndex + 1); if (extruderIndex == 0) { for (int j = extruderCount + 1; j < maxExtruderIndex + 2; j++) { materialsToInclude.Add(j); } } if (doMergeInSlicer) { int meshCount = meshGroup.Meshes.Count; for (int meshIndex = 0; meshIndex < meshCount; meshIndex++) { Mesh mesh = meshGroup.Meshes[meshIndex]; if ((meshIndex % 2) == 0) { mergeRules += "({0}".FormatWith(savedStlCount); } else { if (meshIndex < meshCount - 1) { mergeRules += ",({0}".FormatWith(savedStlCount); } else { mergeRules += ",{0}".FormatWith(savedStlCount); } } int currentMeshMaterialIntdex = MeshMaterialData.Get(mesh).MaterialIndex; if (materialsToInclude.Contains(currentMeshMaterialIntdex)) { extruderFilesToSlice.Add(SaveAndGetFilenameForMesh(mesh)); } savedStlCount++; } for (int i = 0; i < meshCount - 1; i++) { mergeRules += ")"; } } else { extruderFilesToSlice.Add(SaveAndGetFilenameForMaterial(meshGroup, materialsToInclude)); } } return(extruderFilesToSlice.ToArray()); } return(new string[] { "" }); default: return(new string[] { "" }); } }
public List <PrintItem> ImportFromProjectArchive(string loadedFileName = null) { if (loadedFileName == null) { loadedFileName = defaultProjectPathAndFileName; } if (System.IO.File.Exists(loadedFileName)) { FileStream fs = File.OpenRead(loadedFileName); ZipArchive zip = new ZipArchive(fs); int projectHashCode = zip.GetHashCode(); //If the temp folder doesn't exist - create it, otherwise clear it string stagingFolder = Path.Combine(applicationDataPath, "data", "temp", "project-extract", projectHashCode.ToString()); if (!Directory.Exists(stagingFolder)) { Directory.CreateDirectory(stagingFolder); } else { System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(@stagingFolder); EmptyFolder(directory); } List <PrintItem> printItemList = new List <PrintItem>(); Project projectManifest = null; foreach (ZipArchiveEntry zipEntry in zip.Entries) { string sourceExtension = Path.GetExtension(zipEntry.Name).ToUpper(); // Note: directories have empty Name properties // // Only process ZipEntries that are: // - not directories and // - are in the ValidFileExtension list or // - have a .GCODE extension or // - are named manifest.json if (!string.IsNullOrWhiteSpace(zipEntry.Name) && (zipEntry.Name == "manifest.json" || MeshFileIo.ValidFileExtensions().Contains(sourceExtension) || sourceExtension == ".GCODE")) { string extractedFileName = Path.Combine(stagingFolder, zipEntry.Name); string neededPathForZip = Path.GetDirectoryName(extractedFileName); if (!Directory.Exists(neededPathForZip)) { Directory.CreateDirectory(neededPathForZip); } using (Stream zipStream = zipEntry.Open()) using (FileStream streamWriter = File.Create(extractedFileName)) { zipStream.CopyTo(streamWriter); } if (zipEntry.Name == "manifest.json") { using (StreamReader sr = new System.IO.StreamReader(extractedFileName)) { projectManifest = (Project)Newtonsoft.Json.JsonConvert.DeserializeObject(sr.ReadToEnd(), typeof(Project)); } } } } if (projectManifest != null) { foreach (ManifestItem item in projectManifest.ProjectFiles) { for (int i = 1; i <= item.ItemQuantity; i++) { printItemList.Add(this.GetPrintItemFromFile(Path.Combine(stagingFolder, item.FileName), item.Name)); } } } else { string[] files = Directory.GetFiles(stagingFolder, "*.*", SearchOption.AllDirectories); foreach (string fileName in files) { printItemList.Add(this.GetPrintItemFromFile(fileName, Path.GetFileNameWithoutExtension(fileName))); } } return(printItemList); } else { return(null); } }
private MatterControlApplication(double width, double height, out bool showWindow) : base(width, height) { Name = "MatterControl"; showWindow = false; // set this at startup so that we can tell next time if it got set to true in close UserSettings.Instance.Fields.StartCount = UserSettings.Instance.Fields.StartCount + 1; this.commandLineArgs = Environment.GetCommandLineArgs(); Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; bool forceSofwareRendering = false; for (int currentCommandIndex = 0; currentCommandIndex < commandLineArgs.Length; currentCommandIndex++) { string command = commandLineArgs[currentCommandIndex]; string commandUpper = command.ToUpper(); switch (commandUpper) { case "TEST": CheckKnownAssemblyConditionalCompSymbols(); return; case "FORCE_SOFTWARE_RENDERING": forceSofwareRendering = true; GL.ForceSoftwareRendering(); break; case "MHSERIAL_TO_ANDROID": { Dictionary <string, string> vidPid_NameDictionary = new Dictionary <string, string>(); string[] MHSerialLines = File.ReadAllLines(Path.Combine("..", "..", "StaticData", "Drivers", "MHSerial", "MHSerial.inf")); foreach (string line in MHSerialLines) { if (line.Contains("=DriverInstall,")) { string name = Regex.Match(line, "%(.*).name").Groups[1].Value; string vid = Regex.Match(line, "VID_(.*)&PID").Groups[1].Value; string pid = Regex.Match(line, "PID_([0-9a-fA-F]+)").Groups[1].Value; string vidPid = "{0},{1}".FormatWith(vid, pid); if (!vidPid_NameDictionary.ContainsKey(vidPid)) { vidPid_NameDictionary.Add(vidPid, name); } } } using (StreamWriter deviceFilter = new StreamWriter("deviceFilter.txt")) { using (StreamWriter serialPort = new StreamWriter("serialPort.txt")) { foreach (KeyValuePair <string, string> vidPid_Name in vidPid_NameDictionary) { string[] vidPid = vidPid_Name.Key.Split(','); int vid = Int32.Parse(vidPid[0], System.Globalization.NumberStyles.HexNumber); int pid = Int32.Parse(vidPid[1], System.Globalization.NumberStyles.HexNumber); serialPort.WriteLine("customTable.AddProduct(0x{0:X4}, 0x{1:X4}, cdcDriverType); // {2}".FormatWith(vid, pid, vidPid_Name.Value)); deviceFilter.WriteLine("<!-- {2} -->\n<usb-device vendor-id=\"{0}\" product-id=\"{1}\" />".FormatWith(vid, pid, vidPid_Name.Value)); } } } } return; case "CLEAR_CACHE": AboutWidget.DeleteCacheData(); break; case "SHOW_MEMORY": ShowMemoryUsed = true; break; case "DO_GC_COLLECT_EVERY_DRAW": ShowMemoryUsed = true; DoCGCollectEveryDraw = true; break; case "CREATE_AND_SELECT_PRINTER": if (currentCommandIndex + 1 <= commandLineArgs.Length) { currentCommandIndex++; string argument = commandLineArgs[currentCommandIndex]; string[] printerData = argument.Split(','); if (printerData.Length >= 2) { Printer ActivePrinter = new Printer(); ActivePrinter.Name = "Auto: {0} {1}".FormatWith(printerData[0], printerData[1]); ActivePrinter.Make = printerData[0]; ActivePrinter.Model = printerData[1]; if (printerData.Length == 3) { ActivePrinter.ComPort = printerData[2]; } PrinterSetupStatus test = new PrinterSetupStatus(ActivePrinter); test.LoadDefaultSliceSettings(ActivePrinter.Make, ActivePrinter.Model); ActivePrinterProfile.Instance.ActivePrinter = ActivePrinter; } } break; case "CONNECT_TO_PRINTER": if (currentCommandIndex + 1 <= commandLineArgs.Length) { PrinterConnectionAndCommunication.Instance.ConnectToActivePrinter(); } break; case "START_PRINT": if (currentCommandIndex + 1 <= commandLineArgs.Length) { bool hasBeenRun = false; currentCommandIndex++; string fullPath = commandLineArgs[currentCommandIndex]; QueueData.Instance.RemoveAll(); if (!string.IsNullOrEmpty(fullPath)) { string fileName = Path.GetFileNameWithoutExtension(fullPath); QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(fileName, fullPath))); PrinterConnectionAndCommunication.Instance.CommunicationStateChanged.RegisterEvent((sender, e) => { if (!hasBeenRun && PrinterConnectionAndCommunication.Instance.CommunicationState == PrinterConnectionAndCommunication.CommunicationStates.Connected) { hasBeenRun = true; PrinterConnectionAndCommunication.Instance.PrintActivePartIfPossible(); } }, ref unregisterEvent); } } break; case "SLICE_AND_EXPORT_GCODE": if (currentCommandIndex + 1 <= commandLineArgs.Length) { currentCommandIndex++; string fullPath = commandLineArgs[currentCommandIndex]; QueueData.Instance.RemoveAll(); if (!string.IsNullOrEmpty(fullPath)) { string fileName = Path.GetFileNameWithoutExtension(fullPath); PrintItemWrapper printItemWrapper = new PrintItemWrapper(new PrintItem(fileName, fullPath)); QueueData.Instance.AddItem(printItemWrapper); SlicingQueue.Instance.QueuePartForSlicing(printItemWrapper); ExportPrintItemWindow exportForTest = new ExportPrintItemWindow(printItemWrapper); exportForTest.ExportGcodeCommandLineUtility(fileName); } } break; } if (MeshFileIo.ValidFileExtensions().Contains(Path.GetExtension(command).ToUpper())) { // If we are the only instance running then do nothing. // Else send these to the running instance so it can load them. } } //WriteTestGCodeFile(); #if !DEBUG if (File.Exists("RunUnitTests.txt")) #endif { #if IS_WINDOWS_FORMS if (!Clipboard.IsInitialized) { Clipboard.SetSystemClipboard(new WindowsFormsClipboard()); } #endif // you can turn this on to debug some bounds issues //GuiWidget.DebugBoundsUnderMouse = true; } GuiWidget.DefaultEnforceIntegerBounds = true; if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Touchscreen) { TextWidget.GlobalPointSizeScaleRatio = 1.3; } this.AddChild(ApplicationController.Instance.MainView); this.MinimumSize = minSize; this.Padding = new BorderDouble(0); //To be re-enabled once native borders are turned off #if false // this is to test freeing gcodefile memory Button test = new Button("test"); test.Click += (sender, e) => { //MatterHackers.GCodeVisualizer.GCodeFile gcode = new GCodeVisualizer.GCodeFile(); //gcode.Load(@"C:\Users\lbrubaker\Downloads\drive assy.gcode"); SystemWindow window = new SystemWindow(100, 100); window.ShowAsSystemWindow(); }; allControls.AddChild(test); #endif this.AnchorAll(); if (!forceSofwareRendering) { UseOpenGL = true; } string version = "1.4"; Title = "MatterControl {0}".FormatWith(version); if (OemSettings.Instance.WindowTitleExtra != null && OemSettings.Instance.WindowTitleExtra.Trim().Length > 0) { Title = Title + " - {1}".FormatWith(version, OemSettings.Instance.WindowTitleExtra); } UiThread.RunOnIdle(CheckOnPrinter); string desktopPosition = ApplicationSettings.Instance.get("DesktopPosition"); if (desktopPosition != null && desktopPosition != "") { string[] sizes = desktopPosition.Split(','); //If the desktop position is less than -10,-10, override int xpos = Math.Max(int.Parse(sizes[0]), -10); int ypos = Math.Max(int.Parse(sizes[1]), -10); DesktopPosition = new Point2D(xpos, ypos); } showWindow = true; }
private MatterControlApplication(double width, double height) : base(width, height) { ApplicationSettings.Instance.set("HardwareHasCamera", "false"); Name = "MatterControl"; // set this at startup so that we can tell next time if it got set to true in close UserSettings.Instance.Fields.StartCount = UserSettings.Instance.Fields.StartCount + 1; this.commandLineArgs = Environment.GetCommandLineArgs(); Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; for (int currentCommandIndex = 0; currentCommandIndex < commandLineArgs.Length; currentCommandIndex++) { string command = commandLineArgs[currentCommandIndex]; string commandUpper = command.ToUpper(); switch (commandUpper) { case "FORCE_SOFTWARE_RENDERING": GL.HardwareAvailable = false; break; case "CLEAR_CACHE": AboutWidget.DeleteCacheData(0); break; case "SHOW_MEMORY": ShowMemoryUsed = true; break; case "DO_GC_COLLECT_EVERY_DRAW": ShowMemoryUsed = true; DoCGCollectEveryDraw = true; break; //case "CREATE_AND_SELECT_PRINTER": // if (currentCommandIndex + 1 <= commandLineArgs.Length) // { // currentCommandIndex++; // string argument = commandLineArgs[currentCommandIndex]; // string[] printerData = argument.Split(','); // if (printerData.Length >= 2) // { // Printer ActivePrinter = new Printer(); // ActivePrinter.Name = "Auto: {0} {1}".FormatWith(printerData[0], printerData[1]); // ActivePrinter.Make = printerData[0]; // ActivePrinter.Model = printerData[1]; // if (printerData.Length == 3) // { // ActivePrinter.ComPort = printerData[2]; // } // PrinterSetupStatus test = new PrinterSetupStatus(ActivePrinter); // test.LoadSettingsFromConfigFile(ActivePrinter.Make, ActivePrinter.Model); // ActiveSliceSettings.Instance = ActivePrinter; // } // } // break; case "CONNECT_TO_PRINTER": if (currentCommandIndex + 1 <= commandLineArgs.Length) { PrinterConnectionAndCommunication.Instance.ConnectToActivePrinter(); } break; case "START_PRINT": if (currentCommandIndex + 1 <= commandLineArgs.Length) { bool hasBeenRun = false; currentCommandIndex++; string fullPath = commandLineArgs[currentCommandIndex]; QueueData.Instance.RemoveAll(); if (!string.IsNullOrEmpty(fullPath)) { string fileName = Path.GetFileNameWithoutExtension(fullPath); QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(fileName, fullPath))); PrinterConnectionAndCommunication.Instance.CommunicationStateChanged.RegisterEvent((sender, e) => { if (!hasBeenRun && PrinterConnectionAndCommunication.Instance.CommunicationState == PrinterConnectionAndCommunication.CommunicationStates.Connected) { hasBeenRun = true; PrinterConnectionAndCommunication.Instance.PrintActivePartIfPossible(); } }, ref unregisterEvent); } } break; case "SLICE_AND_EXPORT_GCODE": if (currentCommandIndex + 1 <= commandLineArgs.Length) { currentCommandIndex++; string fullPath = commandLineArgs[currentCommandIndex]; QueueData.Instance.RemoveAll(); if (!string.IsNullOrEmpty(fullPath)) { string fileName = Path.GetFileNameWithoutExtension(fullPath); PrintItemWrapper printItemWrapper = new PrintItemWrapper(new PrintItem(fileName, fullPath)); QueueData.Instance.AddItem(printItemWrapper); SlicingQueue.Instance.QueuePartForSlicing(printItemWrapper); ExportPrintItemWindow exportForTest = new ExportPrintItemWindow(printItemWrapper); exportForTest.ExportGcodeCommandLineUtility(fileName); } } break; } if (MeshFileIo.ValidFileExtensions().Contains(Path.GetExtension(command).ToUpper())) { // If we are the only instance running then do nothing. // Else send these to the running instance so it can load them. } } //WriteTestGCodeFile(); #if !DEBUG if (File.Exists("RunUnitTests.txt")) #endif { #if IS_WINDOWS_FORMS if (!Clipboard.IsInitialized) { Clipboard.SetSystemClipboard(new WindowsFormsClipboard()); } #endif // you can turn this on to debug some bounds issues //GuiWidget.DebugBoundsUnderMouse = true; } GuiWidget.DefaultEnforceIntegerBounds = true; if (UserSettings.Instance.IsTouchScreen) { GuiWidget.DeviceScale = 1.3; SystemWindow.ShareSingleOsWindow = true; } //GuiWidget.DeviceScale = 2; using (new PerformanceTimer("Startup", "MainView")) { this.AddChild(ApplicationController.Instance.MainView); } this.MinimumSize = minSize; this.Padding = new BorderDouble(0); //To be re-enabled once native borders are turned off #if false // this is to test freeing gcodefile memory Button test = new Button("test"); test.Click += (sender, e) => { //MatterHackers.GCodeVisualizer.GCodeFile gcode = new GCodeVisualizer.GCodeFile(); //gcode.Load(@"C:\Users\lbrubaker\Downloads\drive assy.gcode"); SystemWindow window = new SystemWindow(100, 100); window.ShowAsSystemWindow(); }; allControls.AddChild(test); #endif this.AnchorAll(); if (GL.HardwareAvailable) { UseOpenGL = true; } string version = "1.6"; Title = "MatterHackers: MatterControl {0}".FormatWith(version); if (OemSettings.Instance.WindowTitleExtra != null && OemSettings.Instance.WindowTitleExtra.Trim().Length > 0) { Title = Title + " - {1}".FormatWith(version, OemSettings.Instance.WindowTitleExtra); } UiThread.RunOnIdle(CheckOnPrinter); string desktopPosition = ApplicationSettings.Instance.get(ApplicationSettingsKey.DesktopPosition); if (!string.IsNullOrEmpty(desktopPosition)) { string[] sizes = desktopPosition.Split(','); //If the desktop position is less than -10,-10, override int xpos = Math.Max(int.Parse(sizes[0]), -10); int ypos = Math.Max(int.Parse(sizes[1]), -10); DesktopPosition = new Point2D(xpos, ypos); } else { DesktopPosition = new Point2D(-1, -1); } this.Maximized = ApplicationSettings.Instance.get(ApplicationSettingsKey.MainWindowMaximized) == "true"; }
public void SavingFunction() { currentlySaving = true; countThatHaveBeenSaved = 0; // first create images for all the parts foreach (FileNameAndPresentationName queuePartFileName in queuPartFilesToAdd) { List <MeshGroup> loadedMeshGroups = null; if (File.Exists(queuePartFileName.fileName)) { loadedMeshGroups = MeshFileIo.Load(queuePartFileName.fileName); } if (loadedMeshGroups != null) { bool firstMeshGroup = true; AxisAlignedBoundingBox aabb = null; foreach (MeshGroup meshGroup in loadedMeshGroups) { if (firstMeshGroup) { aabb = meshGroup.GetAxisAlignedBoundingBox(); firstMeshGroup = false; } else { aabb = AxisAlignedBoundingBox.Union(aabb, meshGroup.GetAxisAlignedBoundingBox()); } } RectangleDouble bounds2D = new RectangleDouble(aabb.minXYZ.x, aabb.minXYZ.y, aabb.maxXYZ.x, aabb.maxXYZ.y); double widthInMM = bounds2D.Width + PartMarginMM * 2; double textSpaceMM = 5; double heightMM = textSpaceMM + bounds2D.Height + PartMarginMM * 2; TypeFacePrinter typeFacePrinter = new TypeFacePrinter(queuePartFileName.presentationName, 28, Vector2.Zero, Justification.Center, Baseline.BoundsCenter); double sizeOfNameX = typeFacePrinter.GetSize().x + PartMarginPixels * 2; Vector2 sizeOfRender = new Vector2(widthInMM * PixelPerMM, heightMM * PixelPerMM); ImageBuffer imageOfPart = new ImageBuffer((int)(Math.Max(sizeOfNameX, sizeOfRender.x)), (int)(sizeOfRender.y), 32, new BlenderBGRA()); typeFacePrinter.Origin = new Vector2(imageOfPart.Width / 2, (textSpaceMM / 2) * PixelPerMM); Graphics2D partGraphics2D = imageOfPart.NewGraphics2D(); RectangleDouble rectBounds = new RectangleDouble(0, 0, imageOfPart.Width, imageOfPart.Height); double strokeWidth = .5 * PixelPerMM; rectBounds.Inflate(-strokeWidth / 2); RoundedRect rect = new RoundedRect(rectBounds, PartMarginMM * PixelPerMM); partGraphics2D.Render(rect, RGBA_Bytes.LightGray); Stroke rectOutline = new Stroke(rect, strokeWidth); partGraphics2D.Render(rectOutline, RGBA_Bytes.DarkGray); foreach (MeshGroup meshGroup in loadedMeshGroups) { foreach (Mesh loadedMesh in meshGroup.Meshes) { PolygonMesh.Rendering.OrthographicZProjection.DrawTo(partGraphics2D, loadedMesh, new Vector2(-bounds2D.Left + PartMarginMM, -bounds2D.Bottom + textSpaceMM + PartMarginMM), PixelPerMM, RGBA_Bytes.Black); } } partGraphics2D.Render(typeFacePrinter, RGBA_Bytes.Black); partImagesToPrint.Add(new PartImage(imageOfPart)); countThatHaveBeenSaved++; } if (UpdateRemainingItems != null) { UpdateRemainingItems(this, new StringEventArgs(Path.GetFileName(queuePartFileName.presentationName))); } } partImagesToPrint.Sort(BiggestToLittlestImages); PdfDocument document = new PdfDocument(); document.Info.Title = "MatterHackers Parts Sheet"; document.Info.Author = "MatterHackers Inc."; document.Info.Subject = "This is a list of the parts that are in a queue from MatterControl."; document.Info.Keywords = "MatterControl, STL, 3D Printing"; int nextPartToPrintIndex = 0; int plateNumber = 1; bool done = false; while (!done && nextPartToPrintIndex < partImagesToPrint.Count) { PdfPage pdfPage = document.AddPage(); CreateOnePage(plateNumber++, ref nextPartToPrintIndex, pdfPage); } try { // save the final document document.Save(pathAndFileToSaveTo); // Now try and open the document. This will lanch whatever PDF viewer is on the system and ask it // to show the file (at least on Windows). Process.Start(pathAndFileToSaveTo); } catch (Exception) { } OnDoneSaving(); currentlySaving = false; }
private void CreateThumbnail() { string stlHashCode = this.PrintItem.FileHashCode.ToString(); ImageBuffer bigRender = new ImageBuffer(); if (!File.Exists(this.PrintItem.FileLocation)) { return; } List <MeshGroup> loadedMeshGroups = MeshFileIo.Load(this.PrintItem.FileLocation); RenderType renderType = GetRenderType(this.PrintItem.FileLocation); switch (renderType) { case RenderType.RAY_TRACE: { ThumbnailTracer tracer = new ThumbnailTracer(loadedMeshGroups, BigRenderSize.x, BigRenderSize.y); tracer.DoTrace(); bigRender = tracer.destImage; } break; case RenderType.PERSPECTIVE: { ThumbnailTracer tracer = new ThumbnailTracer(loadedMeshGroups, BigRenderSize.x, BigRenderSize.y); this.thumbnailImage = new ImageBuffer(this.buildingThumbnailImage); this.thumbnailImage.NewGraphics2D().Clear(new RGBA_Bytes(255, 255, 255, 0)); bigRender = new ImageBuffer(BigRenderSize.x, BigRenderSize.y, 32, new BlenderBGRA()); foreach (MeshGroup meshGroup in loadedMeshGroups) { double minZ = double.MaxValue; double maxZ = double.MinValue; foreach (Mesh loadedMesh in meshGroup.Meshes) { tracer.GetMinMaxZ(loadedMesh, ref minZ, ref maxZ); } foreach (Mesh loadedMesh in meshGroup.Meshes) { tracer.DrawTo(bigRender.NewGraphics2D(), loadedMesh, RGBA_Bytes.White, minZ, maxZ); } } if (bigRender == null) { bigRender = new ImageBuffer(this.noThumbnailImage); } } break; case RenderType.NONE: case RenderType.ORTHOGROPHIC: this.thumbnailImage = new ImageBuffer(this.buildingThumbnailImage); this.thumbnailImage.NewGraphics2D().Clear(new RGBA_Bytes(255, 255, 255, 0)); bigRender = BuildImageFromMeshGroups(loadedMeshGroups, stlHashCode, BigRenderSize); if (bigRender == null) { bigRender = new ImageBuffer(this.noThumbnailImage); } break; } // and save it to disk string imageFileName = GetImageFileName(stlHashCode); if (partExtension == ".png") { ImageIO.SaveImageData(imageFileName, bigRender); } else { ImageTgaIO.SaveImageData(imageFileName, bigRender); } ImageBuffer unScaledImage = new ImageBuffer(bigRender.Width, bigRender.Height, 32, new BlenderBGRA()); unScaledImage.NewGraphics2D().Render(bigRender, 0, 0); // If the source image (the one we downloaded) is more than twice as big as our dest image. while (unScaledImage.Width > Width * 2) { // The image sampler we use is a 2x2 filter so we need to scale by a max of 1/2 if we want to get good results. // So we scale as many times as we need to to get the Image to be the right size. // If this were going to be a non-uniform scale we could do the x and y separatly to get better results. ImageBuffer halfImage = new ImageBuffer(unScaledImage.Width / 2, unScaledImage.Height / 2, 32, new BlenderBGRA()); halfImage.NewGraphics2D().Render(unScaledImage, 0, 0, 0, halfImage.Width / (double)unScaledImage.Width, halfImage.Height / (double)unScaledImage.Height); unScaledImage = halfImage; } this.thumbnailImage = new ImageBuffer((int)Width, (int)Height, 32, new BlenderBGRA()); this.thumbnailImage.NewGraphics2D().Clear(new RGBA_Bytes(255, 255, 255, 0)); this.thumbnailImage.NewGraphics2D().Render(unScaledImage, 0, 0, 0, (double)this.thumbnailImage.Width / unScaledImage.Width, (double)this.thumbnailImage.Height / unScaledImage.Height); UiThread.RunOnIdle(this.EnsureImageUpdated); OnDoneRendering(); }
private void CreateThumbnail() { string stlHashCode = this.ItemWrapper.FileHashCode.ToString(); ImageBuffer bigRender = new ImageBuffer(); if (!File.Exists(this.ItemWrapper.FileLocation)) { return; } List <MeshGroup> loadedMeshGroups = MeshFileIo.Load(this.ItemWrapper.FileLocation); RenderType renderType = GetRenderType(this.ItemWrapper.FileLocation); switch (renderType) { case RenderType.RAY_TRACE: { ThumbnailTracer tracer = new ThumbnailTracer(loadedMeshGroups, BigRenderSize.x, BigRenderSize.y); tracer.DoTrace(); bigRender = tracer.destImage; } break; case RenderType.PERSPECTIVE: { ThumbnailTracer tracer = new ThumbnailTracer(loadedMeshGroups, BigRenderSize.x, BigRenderSize.y); this.thumbnailImage = new ImageBuffer(this.buildingThumbnailImage); this.thumbnailImage.NewGraphics2D().Clear(new RGBA_Bytes(255, 255, 255, 0)); bigRender = new ImageBuffer(BigRenderSize.x, BigRenderSize.y); foreach (MeshGroup meshGroup in loadedMeshGroups) { double minZ = double.MaxValue; double maxZ = double.MinValue; foreach (Mesh loadedMesh in meshGroup.Meshes) { tracer.GetMinMaxZ(loadedMesh, ref minZ, ref maxZ); } foreach (Mesh loadedMesh in meshGroup.Meshes) { tracer.DrawTo(bigRender.NewGraphics2D(), loadedMesh, RGBA_Bytes.White, minZ, maxZ); } } if (bigRender == null) { bigRender = new ImageBuffer(this.noThumbnailImage); } } break; case RenderType.NONE: case RenderType.ORTHOGROPHIC: this.thumbnailImage = new ImageBuffer(this.buildingThumbnailImage); this.thumbnailImage.NewGraphics2D().Clear(new RGBA_Bytes(255, 255, 255, 0)); bigRender = BuildImageFromMeshGroups(loadedMeshGroups, stlHashCode, BigRenderSize); if (bigRender == null) { bigRender = new ImageBuffer(this.noThumbnailImage); } break; } // and save it to disk string imageFileName = GetImageFileName(stlHashCode); if (partExtension == ".png") { ImageIO.SaveImageData(imageFileName, bigRender); } else { ImageTgaIO.SaveImageData(imageFileName, bigRender); } bigRender.SetRecieveBlender(new BlenderPreMultBGRA()); this.thumbnailImage = ImageBuffer.CreateScaledImage(bigRender, (int)Width, (int)Height); UiThread.RunOnIdle(this.EnsureImageUpdated); OnDoneRendering(); }
public override void OnDraw(Graphics2D graphics2D) { totalDrawTime.Restart(); GuiWidget.DrawCount = 0; using (new PerformanceTimer("Draw Timer", "MC Draw")) { base.OnDraw(graphics2D); } totalDrawTime.Stop(); millisecondTimer.Update((int)totalDrawTime.ElapsedMilliseconds); if (ShowMemoryUsed) { long memory = GC.GetTotalMemory(false); this.Title = "Allocated = {0:n0} : {1:000}ms, d{2} Size = {3}x{4}, onIdle = {5:00}:{6:00}, widgetsDrawn = {7}".FormatWith(memory, millisecondTimer.GetAverage(), drawCount++, this.Width, this.Height, UiThread.CountExpired, UiThread.Count, GuiWidget.DrawCount); if (DoCGCollectEveryDraw) { GC.Collect(); } } if (firstDraw) { firstDraw = false; foreach (string arg in commandLineArgs) { string argExtension = Path.GetExtension(arg).ToUpper(); if (argExtension.Length > 1 && MeshFileIo.ValidFileExtensions().Contains(argExtension)) { QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(Path.GetFileName(arg), Path.GetFullPath(arg)))); } } TerminalWindow.ShowIfLeftOpen(); #if false { SystemWindow releaseNotes = new SystemWindow(640, 480); string releaseNotesFile = Path.Combine("C:/Users/LarsBrubaker/Downloads", "test1.html"); string releaseNotesContent = StaticData.Instance.ReadAllText(releaseNotesFile); HtmlWidget content = new HtmlWidget(releaseNotesContent, RGBA_Bytes.Black); content.AddChild(new GuiWidget(HAnchor.AbsolutePosition, VAnchor.ParentBottomTop)); content.VAnchor |= VAnchor.ParentTop; content.BackgroundColor = RGBA_Bytes.White; releaseNotes.AddChild(content); releaseNotes.BackgroundColor = RGBA_Bytes.Cyan; UiThread.RunOnIdle((state) => { releaseNotes.ShowAsSystemWindow(); }, 1); } #endif AfterFirstDraw?.Invoke(); if (false && UserSettings.Instance.get("SoftwareLicenseAccepted") != "true") { UiThread.RunOnIdle(() => WizardWindow.Show <LicenseAgreementPage>("SoftwareLicense", "Software License Agreement")); } if (!ProfileManager.Instance.ActiveProfiles.Any()) { // Start the setup wizard if no profiles exist UiThread.RunOnIdle(() => WizardWindow.Show()); } } //msGraph.AddData("ms", totalDrawTime.ElapsedMilliseconds); //msGraph.Draw(MatterHackers.Agg.Transform.Affine.NewIdentity(), graphics2D); }
public override IEnumerable <PrintItemAction> GetMenuItems() { return(new List <PrintItemAction>() { new PrintItemAction() { SingleItemOnly = false, Title = "Merge".Localize() + "...", Action = (items, queueDataWidget) => { List <QueueRowItem> allRowItems = new List <QueueRowItem>(items); if (allRowItems.Count > 1) { RenameItemWindow renameItemWindow = new RenameItemWindow(allRowItems[0].PrintItemWrapper.Name, (returnInfo) => { Task.Run(() => { List <MeshGroup> combinedMeshes = new List <MeshGroup>(); // Load up all the parts and merge them together foreach (QueueRowItem item in allRowItems) { List <MeshGroup> loadedMeshGroups = MeshFileIo.Load(item.PrintItemWrapper.FileLocation); combinedMeshes.AddRange(loadedMeshGroups); } // save them out string[] metaData = { "Created By", "MatterControl", "BedPosition", "Absolute" }; MeshOutputSettings outputInfo = new MeshOutputSettings(MeshOutputSettings.OutputType.Binary, metaData); string libraryDataPath = ApplicationDataStorage.Instance.ApplicationLibraryDataPath; if (!Directory.Exists(libraryDataPath)) { Directory.CreateDirectory(libraryDataPath); } string tempFileNameToSaveTo = Path.Combine(libraryDataPath, Path.ChangeExtension(Path.GetRandomFileName(), "amf")); bool savedSuccessfully = MeshFileIo.Save(combinedMeshes, tempFileNameToSaveTo, outputInfo); // Swap out the files if the save operation completed successfully if (savedSuccessfully && File.Exists(tempFileNameToSaveTo)) { // create a new print item // add it to the queue PrintItemWrapper newPrintItem = new PrintItemWrapper(new PrintItem(returnInfo.newName, tempFileNameToSaveTo)); QueueData.Instance.AddItem(newPrintItem, 0); // select the part we added, if possible QueueData.Instance.SelectedIndex = 0; queueDataWidget.LeaveEditMode(); } }); }, "Set Name".Localize()) { Title = "MatterHackers - Set Name".Localize(), ElementHeader = "Set Name".Localize(), }; } } } }); }
public MatterControlApplication(double width, double height) : base(width, height) { CrashTracker.Reset(); this.commandLineArgs = Environment.GetCommandLineArgs(); Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; foreach (string command in commandLineArgs) { string commandUpper = command.ToUpper(); switch (commandUpper) { case "TEST": Testing.TestingDispatch testDispatch = new Testing.TestingDispatch(); testDispatch.RunTests(); return; case "CLEAR_CACHE": AboutPage.DeleteCacheData(); break; case "SHOW_MEMORY": ShowMemoryUsed = true; break; case "DO_GC_COLLECT_EVERY_DRAW": ShowMemoryUsed = true; DoCGCollectEveryDraw = true; break; } if (MeshFileIo.ValidFileExtensions().Contains(Path.GetExtension(command).ToUpper())) { // If we are the only instance running then do nothing. // Else send these to the running instance so it can load them. } } //WriteTestGCodeFile(); #if !DEBUG if (File.Exists("RunUnitTests.txt")) #endif { #if IS_WINDOWS_FORMS Clipboard.SetSystemClipboardFunctions(System.Windows.Forms.Clipboard.GetText, System.Windows.Forms.Clipboard.SetText, System.Windows.Forms.Clipboard.ContainsText); #endif MatterHackers.PolygonMesh.UnitTests.UnitTests.Run(); MatterHackers.RayTracer.UnitTests.Run(); MatterHackers.Agg.Tests.UnitTests.Run(); MatterHackers.VectorMath.Tests.UnitTests.Run(); MatterHackers.Agg.UI.Tests.UnitTests.Run(); // you can turn this on to debug some bounds issues //GuiWidget.DebugBoundsUnderMouse = true; } GuiWidget.DefaultEnforceIntegerBounds = true; if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Touchscreen) { TextWidget.GlobalPointSizeScaleRatio = 1.3; } this.AddChild(ApplicationController.Instance.MainView); this.MinimumSize = new Vector2(400, 400); this.Padding = new BorderDouble(0); //To be re-enabled once native borders are turned off #if false // this is to test freeing gcodefile memory Button test = new Button("test"); test.Click += (sender, e) => { //MatterHackers.GCodeVisualizer.GCodeFile gcode = new GCodeVisualizer.GCodeFile(); //gcode.Load(@"C:\Users\lbrubaker\Downloads\drive assy.gcode"); SystemWindow window = new SystemWindow(100, 100); window.ShowAsSystemWindow(); }; allControls.AddChild(test); #endif this.AnchorAll(); UseOpenGL = true; string version = "1.1"; Title = "MatterControl {0}".FormatWith(version); if (OemSettings.Instance.WindowTitleExtra != null && OemSettings.Instance.WindowTitleExtra.Trim().Length > 0) { Title = Title + " - {1}".FormatWith(version, OemSettings.Instance.WindowTitleExtra); } UiThread.RunOnIdle(CheckOnPrinter); string desktopPosition = ApplicationSettings.Instance.get("DesktopPosition"); if (desktopPosition != null && desktopPosition != "") { string[] sizes = desktopPosition.Split(','); //If the desktop position is less than -10,-10, override int xpos = Math.Max(int.Parse(sizes[0]), -10); int ypos = Math.Max(int.Parse(sizes[1]), -10); DesktopPosition = new Point2D(xpos, ypos); } ShowAsSystemWindow(); }
public static string[] GetStlFileLocations(string fileToSlice) { extrudersUsed.Clear(); int extruderCount = ActiveSliceSettings.Instance.ExtruderCount; for (int extruderIndex = 0; extruderIndex < extruderCount; extruderIndex++) { extrudersUsed.Add(false); } // If we have support enabled and and are using an extruder other than 0 for it if (ActiveSliceSettings.Instance.SupportEnabled) { if (ActiveSliceSettings.Instance.SupportExtruder != 0) { int supportExtruder = Math.Max(0, Math.Min(ActiveSliceSettings.Instance.ExtruderCount - 1, ActiveSliceSettings.Instance.SupportExtruder - 1)); extrudersUsed[supportExtruder] = true; } } // If we have raft enabled and are using an extruder other than 0 for it if (ActiveSliceSettings.Instance.RaftEnabled) { if (ActiveSliceSettings.Instance.RaftExtruder != 0) { int raftExtruder = Math.Max(0, Math.Min(ActiveSliceSettings.Instance.ExtruderCount - 1, ActiveSliceSettings.Instance.RaftExtruder - 1)); extrudersUsed[raftExtruder] = true; } } switch (Path.GetExtension(fileToSlice).ToUpper()) { case ".STL": case ".GCODE": extrudersUsed[0] = true; return(new string[] { fileToSlice }); case ".AMF": List <MeshGroup> meshGroups = MeshFileIo.Load(fileToSlice); List <MeshGroup> extruderMeshGroups = new List <MeshGroup>(); for (int extruderIndex = 0; extruderIndex < extruderCount; extruderIndex++) { extruderMeshGroups.Add(new MeshGroup()); } int maxExtruderIndex = 0; foreach (MeshGroup meshGroup in meshGroups) { foreach (Mesh mesh in meshGroup.Meshes) { MeshMaterialData material = MeshMaterialData.Get(mesh); int extruderIndex = Math.Max(0, material.MaterialIndex - 1); 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); } } } List <string> extruderFilesToSlice = new List <string>(); for (int i = 0; i < extruderMeshGroups.Count; i++) { MeshGroup meshGroup = extruderMeshGroups[i]; List <int> materialsToInclude = new List <int>(); materialsToInclude.Add(i + 1); if (i == 0) { for (int j = extruderCount + 1; j < maxExtruderIndex + 2; j++) { materialsToInclude.Add(j); } } extruderFilesToSlice.Add(SaveAndGetFilenameForMaterial(meshGroup, materialsToInclude)); } return(extruderFilesToSlice.ToArray()); default: throw new NotImplementedException(); } }
/// <summary> /// Creates a database PrintItem entity, if forceAMF is set, converts to AMF otherwise just copies /// the source file to a new library path and updates the PrintItem to point at the new target /// </summary> private void AddItem(Stream stream, string extension, string displayName, bool forceAMF = true) { // Create a new entity in the database PrintItem printItem = new PrintItem(); printItem.Name = displayName; printItem.PrintItemCollectionID = this.baseLibraryCollection.Id; printItem.Commit(); // Special load processing for mesh data, simple copy below for non-mesh if (forceAMF && (extension != "" && MeshFileIo.ValidFileExtensions().Contains(extension.ToUpper()))) { try { // Load mesh List <MeshGroup> meshToConvertAndSave = MeshFileIo.Load(stream, extension); // Create a new PrintItemWrapper if (!printItem.FileLocation.Contains(ApplicationDataStorage.Instance.ApplicationLibraryDataPath)) { string[] metaData = { "Created By", "MatterControl" }; if (false) //AbsolutePositioned { metaData = new string[] { "Created By", "MatterControl", "BedPosition", "Absolute" }; } // save a copy to the library and update this to point at it printItem.FileLocation = CreateLibraryPath(".amf"); var outputInfo = new MeshOutputSettings(MeshOutputSettings.OutputType.Binary, metaData); MeshFileIo.Save(meshToConvertAndSave, printItem.FileLocation, outputInfo); printItem.Commit(); } } catch (System.UnauthorizedAccessException) { UiThread.RunOnIdle(() => { //Do something special when unauthorized? StyledMessageBox.ShowMessageBox(null, "Oops! Unable to save changes, unauthorized access", "Unable to save"); }); } catch { UiThread.RunOnIdle(() => { StyledMessageBox.ShowMessageBox(null, "Oops! Unable to save changes.", "Unable to save"); }); } } else // it is not a mesh so just add it { // Non-mesh content - copy stream to new Library path printItem.FileLocation = CreateLibraryPath(extension); using (var outStream = File.Create(printItem.FileLocation)) { stream.CopyTo(outStream); } printItem.Commit(); } }
public MoveInZControl(IInteractionVolumeContext context) : base(context) { Name = "MoveInZControl"; zHeightDisplayInfo = new InlineEditControl() { ForceHide = () => { var selectedItem = InteractionContext.Scene.RootSelectedItem; // if the selection changes if (selectedItem != ActiveSelectedItem) { return(true); } // if another control gets a hover if (InteractionContext.HoveredInteractionVolume != this && InteractionContext.HoveredInteractionVolume != null) { return(true); } // if we clicked on the control if (HadClickOnControl) { return(false); } return(false); } , GetDisplayString = (value) => "{0:0.0#}mm".FormatWith(value) }; zHeightDisplayInfo.VisibleChanged += (s, e) => { if (!zHeightDisplayInfo.Visible) { HadClickOnControl = false; } }; zHeightDisplayInfo.EditComplete += (s, e) => { var selectedItem = InteractionContext.Scene.RootSelectedItem; Matrix4X4 startingTransform = selectedItem.Matrix; var newZPosition = zHeightDisplayInfo.Value; if (InteractionContext.SnapGridDistance > 0) { // snap this position to the grid double snapGridDistance = InteractionContext.SnapGridDistance; // snap this position to the grid newZPosition = ((int)((newZPosition / snapGridDistance) + .5)) * snapGridDistance; } AxisAlignedBoundingBox originalSelectedBounds = selectedItem.GetAxisAlignedBoundingBox(Matrix4X4.Identity); var moveAmount = newZPosition - originalSelectedBounds.minXYZ.Z; if (moveAmount != 0) { selectedItem.Matrix = selectedItem.Matrix * Matrix4X4.CreateTranslation(0, 0, moveAmount); Invalidate(); } context.AddTransformSnapshot(startingTransform); }; InteractionContext.GuiSurface.AddChild(zHeightDisplayInfo); DrawOnTop = true; string arrowFile = Path.Combine("Icons", "3D Icons", "up_pointer.stl"); using (Stream arrowStream = AggContext.StaticData.OpenStream(arrowFile)) { upArrowMesh = MeshFileIo.Load(arrowStream, Path.GetExtension(arrowFile), CancellationToken.None).Mesh; } CollisionVolume = upArrowMesh.CreateTraceData(); InteractionContext.GuiSurface.AfterDraw += InteractionLayer_AfterDraw; }