private void kryptonButtonUninstall_Click(object sender, EventArgs e) { var filesToDelete = new List <string>(); bool mustRestart = false; //get list of files to delete if (File.Exists(selectedPackage.FullFilePath)) { //get list of files from the package archive var info = PackageManager.ReadPackageArchiveInfo(selectedPackage.FullFilePath, out var error); if (info == null) { ScreenNotifications.Show("Could not read the package info.", true); Log.Warning(error); return; } foreach (var file in info.Files) { var fullName = Path.Combine(VirtualFileSystem.Directories.Project, file); if (File.Exists(fullName)) { filesToDelete.Add(file); } } mustRestart = info.MustRestart; } else { //get list of files from selectedPackage.Files in case when the archive file is not exists var str = selectedPackage.Files.Trim(new char[] { ' ', '\r', '\n' }); var files = str.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (var file in files) { var fullName = Path.Combine(VirtualFileSystem.Directories.Project, file); if (File.Exists(fullName)) { filesToDelete.Add(file); } } //!!!!mustRestart mustRestart = true; } if (filesToDelete.Count == 0) { return; } var text = string.Format(Translate("Uninstall {0}?\n\n{1} files will deleted."), selectedPackage.GetDisplayName(), filesToDelete.Count); if (EditorMessageBox.ShowQuestion(text, EMessageBoxButtons.YesNo) != EDialogResult.Yes) { return; } var filesToDeletionAtStartup = new List <string>(); try { //remove cs files from Project.csproj try { var toRemove = new List <string>(); foreach (var file in filesToDelete) { var fullName = Path.Combine(VirtualFileSystem.Directories.Project, file); if (Path.GetExtension(fullName).ToLower() == ".cs") { toRemove.Add(VirtualPathUtility.NormalizePath(fullName)); } } if (toRemove.Count != 0) { CSharpProjectFileUtility.UpdateProjectFile(null, toRemove, out _); } } catch { } //delete files foreach (var file in filesToDelete) { var fullName = Path.Combine(VirtualFileSystem.Directories.Project, file); try { File.Delete(fullName); } catch (UnauthorizedAccessException) { filesToDeletionAtStartup.Add(file); } catch (IOException) { filesToDeletionAtStartup.Add(file); } } //delete empty folders { var allFolders = new ESet <string>(); foreach (var file in filesToDelete) { var f = Path.GetDirectoryName(file); while (!string.IsNullOrEmpty(f)) { allFolders.AddWithCheckAlreadyContained(f); f = Path.GetDirectoryName(f); } } var list = allFolders.ToArray(); CollectionUtility.MergeSort(list, delegate(string f1, string f2) { var levels1 = f1.Split(new char[] { '\\' }).Length; var levels2 = f2.Split(new char[] { '\\' }).Length; return(levels2 - levels1); }); foreach (var folder in list) { var fullName = Path.Combine(VirtualFileSystem.Directories.Project, folder); if (Directory.Exists(fullName) && IsDirectoryEmpty(fullName)) { Directory.Delete(fullName); } } } PackageManager.ChangeInstalledState(selectedPackage.Name, false); } catch (Exception e2) { EditorMessageBox.ShowWarning(e2.Message); return; } if (filesToDeletionAtStartup.Count != 0) { PackageManager.AddFilesToDeletionAtStartup(filesToDeletionAtStartup); } needUpdateList = true; if (mustRestart) { ShowRestartLabel(); } ScreenNotifications.Show(EditorLocalization.Translate("General", "The package has been successfully uninstalled.")); }
void CreationFunction(object parameter) { var tag = (string)parameter; creationProgressBarValue = 0; try { string sourcePath = VirtualFileSystem.Directories.Project; FileInfo[] allFiles = new DirectoryInfo(sourcePath).GetFiles("*.*", SearchOption.AllDirectories); long totalLength = 0; foreach (var fileInfo in allFiles) { totalLength += fileInfo.Length; } foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories)) { if (Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath.Replace(sourcePath, creationDirectory)); } } long processedLength = 0; foreach (var fileInfo in allFiles) { if (File.Exists(fileInfo.FullName)) { File.Copy(fileInfo.FullName, fileInfo.FullName.Replace(sourcePath, creationDirectory), false); } processedLength += fileInfo.Length; creationProgressBarValue = (int)((double)processedLength / (double)totalLength * 100.0); if (creationProgressBarValue > 100) { creationProgressBarValue = 100; } if (!creationInProgress) { return; } } creationProgressBarValue = 100; //open folder try { Win32Utility.ShellExecuteEx(null, creationDirectory); //Process.Start( "explorer.exe", creationDirectory ); } catch { } ////run process //string executableFileName = Path.Combine( creationDirectory, "NeoAxis.Studio.exe" ); //var runMapProcess = Process.Start( executableFileName, "" ); //end creationInProgress = false; ScreenNotifications.Show(Translate("The project was created successfully.")); } catch (Exception ex) { EditorMessageBox.ShowWarning(ex.Message); } }
private void kryptonButtonInstall_Click(object sender, EventArgs e) { var info = PackageManager.ReadPackageArchiveInfo(selectedPackage.FullFilePath, out var error); if (info == null) { return; } var filesToCopy = new List <string>(); foreach (var file in info.Files) { var fullName = Path.Combine(VirtualFileSystem.Directories.Project, file); filesToCopy.Add(fullName); } var text = string.Format(Translate("Install {0}?\n\n{1} files will created."), selectedPackage.GetDisplayName(), filesToCopy.Count); //var text = string.Format( Translate( "Install {0}?\r\n\r\n{1} files will created." ), selectedPackage.Name, filesToCopy.Count ); //var text = $"Install {selectedPackage.Name}?\r\n\r\n{filesToCopy.Count} files will created."; if (EditorMessageBox.ShowQuestion(text, EMessageBoxButtons.YesNo) != EDialogResult.Yes) { return; } var notification = ScreenNotifications.ShowSticky("Installing the package..."); try { using (var archive = ZipFile.OpenRead(selectedPackage.FullFilePath)) { foreach (var entry in archive.Entries) { var fileName = entry.FullName; bool directory = fileName[fileName.Length - 1] == '/'; if (fileName != "Package.info" && !directory) { var fullPath = Path.Combine(VirtualFileSystem.Directories.Project, fileName); var directoryName = Path.GetDirectoryName(fullPath); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } entry.ExtractToFile(fullPath, true); } } } PackageManager.ChangeInstalledState(selectedPackage.Name, true); } catch (Exception e2) { EditorMessageBox.ShowWarning(e2.Message); return; } finally { notification.Close(); } if (!string.IsNullOrEmpty(info.AddCSharpFilesToProject)) { var toAdd = new ESet <string>(); var path = Path.Combine(VirtualFileSystem.Directories.Assets, info.AddCSharpFilesToProject); if (Directory.Exists(path)) { var fullPaths = CSharpProjectFileUtility.GetProjectFileCSFiles(false, true); var files = Directory.GetFiles(path, "*.cs", SearchOption.AllDirectories); foreach (var file in files) { if (!fullPaths.Contains(file)) { toAdd.AddWithCheckAlreadyContained(file); } } } // if( !fileItem.IsDirectory && Path.GetExtension( fileItem.FullPath ).ToLower() == ".cs" ) // { // bool added = CSharpProjectFileUtility.GetProjectFileCSFiles( false, true ).Contains( fileItem.FullPath ); // if( !added ) // toAdd.Add( fileItem.FullPath ); // } if (toAdd.Count != 0) { if (CSharpProjectFileUtility.UpdateProjectFile(toAdd, null, out var error2)) { if (toAdd.Count > 1) { Log.Info(EditorLocalization.Translate("General", "Items have been added to the Project.csproj.")); } else { Log.Info(EditorLocalization.Translate("General", "The item has been added to the Project.csproj.")); } } else { Log.Warning(error2); } } } needUpdateList = true; if (info.MustRestart) { ShowRestartLabel(); } if (!string.IsNullOrEmpty(info.OpenAfterInstall)) { var realFileName = VirtualPathUtility.GetRealPathByVirtual(info.OpenAfterInstall); if (info.MustRestart) { EditorSettingsSerialization.OpenFileAtStartup = realFileName; } else { EditorAPI.SelectFilesOrDirectoriesInMainResourcesWindow(new string[] { realFileName }, Directory.Exists(realFileName)); EditorAPI.OpenFileAsDocument(realFileName, true, true); } } ScreenNotifications.Show(EditorLocalization.Translate("General", "The package has been successfully installed.")); //restart application if (info.MustRestart) { var text2 = EditorLocalization.Translate("General", "To apply changes need restart the editor. Restart?"); if (EditorMessageBox.ShowQuestion(text2, EMessageBoxButtons.YesNo) == EDialogResult.Yes) { EditorAPI.BeginRestartApplication(); } } }
void ThreadDownload() { //var fileName = Path.Combine( PackageManager.PackagesFolder, Path.GetFileName( downloadingAddress ) ); var cancelled = false; Exception error = null; try { using (WebClient client = new WebClient()) { downloadingClient = client; var tempFileName = Path.GetTempFileName(); client.DownloadProgressChanged += delegate(object sender, DownloadProgressChangedEventArgs e) { //check already ended if (cancelled) { return; } if (e.TotalBytesToReceive != 0) { downloadProgress = MathEx.Saturate((float)e.BytesReceived / (float)e.TotalBytesToReceive); } }; client.DownloadFileCompleted += delegate(object sender, AsyncCompletedEventArgs e) { //check already ended if (cancelled) { return; } //releases blocked thread lock (e.UserState) Monitor.Pulse(e.UserState); cancelled = e.Cancelled; error = e.Error; //copy to destination path if (!cancelled && error == null) { File.Copy(tempFileName, downloadingDestinationPath); } try { File.Delete(tempFileName); } catch { } }; using (var task = client.DownloadFileTaskAsync(new Uri(downloadingAddress), tempFileName)) { while (!string.IsNullOrEmpty(downloadingAddress) && !task.Wait(10)) { } } //var syncObject = new object(); //lock( syncObject ) //{ // client.DownloadFileAsync( new Uri( downloadingAddress ), downloadingDestinationPath, syncObject ); // //This would block the thread until download completes // Monitor.Wait( syncObject ); //} downloadingClient = null; } } catch (Exception e) { Log.Warning(e.Message); return; } finally { try { if (!cancelled) { if (File.Exists(downloadingDestinationPath) && new FileInfo(downloadingDestinationPath).Length == 0) { File.Delete(downloadingDestinationPath); cancelled = true; } } if (!cancelled && !File.Exists(downloadingDestinationPath)) { cancelled = true; } if (cancelled || error != null) { if (File.Exists(downloadingDestinationPath)) { File.Delete(downloadingDestinationPath); } } } catch { } if (error != null && !cancelled) { Log.Warning((error.InnerException ?? error).Message); } downloadingPackageName = ""; downloadingAddress = ""; downloadingDestinationPath = ""; downloadProgress = 0; downloadingClient = null; } needUpdateList = true; if (!cancelled) { if (error != null) { ScreenNotifications.Show(EditorLocalization.Translate("General", "Error downloading the package."), true); } else { ScreenNotifications.Show(EditorLocalization.Translate("General", "The package has been successfully downloaded.")); } } }
public override void Register() { //Add Collision { const string bodyName = "Collision Body"; var a = new EditorAction(); a.Name = "Add Collision"; a.Description = "Adds a collision body to selected objects."; a.ImageSmall = Properties.Resources.Add_16; a.ImageBig = Properties.Resources.MeshCollision_32; a.ActionType = EditorAction.ActionTypeEnum.DropDown; a.QatSupport = true; //a.qatAddByDefault = true; a.ContextMenuSupport = EditorContextMenu.MenuTypeEnum.Document; a.GetState += delegate(EditorAction.GetStateContext context) { if (context.ObjectsInFocus.DocumentWindow != null) { object[] selectedObjects = context.ObjectsInFocus.Objects; if (selectedObjects.Length != 0 && Array.TrueForAll(selectedObjects, obj => obj is Component_MeshInSpace)) { context.Enabled = Array.Exists(selectedObjects, delegate(object obj) { var c = ((Component)obj).GetComponent(bodyName); if (c != null) { if (c is Component_RigidBody) { return(false); } if (c is Component_RigidBody2D) { return(false); } } return(true); }); } a.DropDownContextMenu.Tag = (context.ObjectsInFocus.DocumentWindow.Document, selectedObjects); } }; //context menu { a.DropDownContextMenu = new KryptonContextMenu(); a.DropDownContextMenu.Opening += delegate(object sender, CancelEventArgs e) { var menu = (KryptonContextMenu)sender; var tuple = ((DocumentInstance, object[]))menu.Tag; //"Collision Body of the Mesh" { var items2 = (KryptonContextMenuItems)menu.Items[0]; var item2 = (KryptonContextMenuItem)items2.Items[0]; bool enabled = false; foreach (var obj in tuple.Item2) { var meshInSpace = obj as Component_MeshInSpace; if (meshInSpace != null) { Component_RigidBody collisionDefinition = null; { var mesh = meshInSpace.Mesh.Value; if (mesh != null) { collisionDefinition = mesh.GetComponent("Collision Definition") as Component_RigidBody; } } if (collisionDefinition != null) { enabled = true; } } } item2.Enabled = enabled; } }; EventHandler clickHandler = delegate(object s, EventArgs e2) { var item = (KryptonContextMenuItem)s; var itemTag = ((KryptonContextMenu, string))item.Tag; var menu = itemTag.Item1; var collisionName = itemTag.Item2; var menuTag = ((DocumentInstance, object[]))menu.Tag; var document = menuTag.Item1; var selectedObjects = menuTag.Item2; List <UndoSystem.Action> undoActions = new List <UndoSystem.Action>(); foreach (var obj in selectedObjects) { if (obj is Component_MeshInSpace meshInSpace && meshInSpace.GetComponent(bodyName) as Component_RigidBody == null && meshInSpace.GetComponent(bodyName) as Component_RigidBody2D == null) { var mesh = meshInSpace.MeshOutput; if (mesh == null) { continue; } Component body = null; bool skip = false; if (collisionName == "Use Collision of the Mesh") { var collisionDefinition = mesh.GetComponent("Collision Definition") as Component_RigidBody; if (collisionDefinition != null) { var body2 = (Component_RigidBody)collisionDefinition.Clone(); body = body2; body2.Enabled = false; body2.Name = bodyName; body2.MotionType = Component_RigidBody.MotionTypeEnum.Static; body2.Transform = meshInSpace.Transform; meshInSpace.AddComponent(body2); } else { skip = true; } } else { Component_RigidBody CreateRigidBody() { var body2 = meshInSpace.CreateComponent <Component_RigidBody>(enabled: false); body2.Name = bodyName; body2.Transform = meshInSpace.Transform; return(body2); } Component_RigidBody2D CreateRigidBody2D() { var body2 = meshInSpace.CreateComponent <Component_RigidBody2D>(enabled: false); body2.Name = bodyName; body2.Transform = meshInSpace.Transform; return(body2); } switch (collisionName) { case "Box": { body = CreateRigidBody(); var shape = body.CreateComponent <Component_CollisionShape_Box>(); var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox; shape.TransformRelativeToParent = new Transform(bounds.GetCenter(), Quaternion.Identity); shape.Dimensions = bounds.GetSize(); } break; case "Sphere": { body = CreateRigidBody(); var shape = body.CreateComponent <Component_CollisionShape_Sphere>(); var sphere = mesh.Result.SpaceBounds.CalculatedBoundingSphere; shape.TransformRelativeToParent = new Transform(sphere.Origin, Quaternion.Identity); shape.Radius = sphere.Radius; } break; case "Capsule": { body = CreateRigidBody(); var shape = body.CreateComponent <Component_CollisionShape_Capsule>(); var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox; shape.TransformRelativeToParent = new Transform(bounds.GetCenter(), Quaternion.Identity); shape.Radius = Math.Max(bounds.GetSize().X, bounds.GetSize().Y) / 2; shape.Height = Math.Max(bounds.GetSize().Z - shape.Radius * 2, 0); } break; case "Cylinder": { body = CreateRigidBody(); var shape = body.CreateComponent <Component_CollisionShape_Cylinder>(); var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox; shape.TransformRelativeToParent = new Transform(bounds.GetCenter(), Quaternion.Identity); shape.Radius = Math.Max(bounds.GetSize().X, bounds.GetSize().Y) / 2; shape.Height = bounds.GetSize().Z; } break; case "Convex": { body = CreateRigidBody(); var shape = body.CreateComponent <Component_CollisionShape_Mesh>(); shape.ShapeType = Component_CollisionShape_Mesh.ShapeTypeEnum.Convex; shape.Mesh = ReferenceUtility.MakeThisReference(shape, meshInSpace, "Mesh"); } break; case "Convex Decomposition": { body = CreateRigidBody(); var settings = new ConvexDecomposition.Settings(); var form = new SpecifyParametersForm("Convex Decomposition", settings); form.CheckHandler = delegate(ref string error2) { return(true); }; if (form.ShowDialog() != DialogResult.OK) { skip = true; } else { var clusters = ConvexDecomposition.Decompose(mesh.Result.ExtractedVerticesPositions, mesh.Result.ExtractedIndices, settings); if (clusters == null) { Log.Warning("Unable to decompose."); skip = true; } else { foreach (var cluster in clusters) { var shape = body.CreateComponent <Component_CollisionShape_Mesh>(); shape.Vertices = cluster.Vertices; shape.Indices = cluster.Indices; shape.ShapeType = Component_CollisionShape_Mesh.ShapeTypeEnum.Convex; } } } } break; case "Mesh": { body = CreateRigidBody(); var shape = body.CreateComponent <Component_CollisionShape_Mesh>(); shape.Mesh = ReferenceUtility.MakeThisReference(shape, meshInSpace, "Mesh"); } break; case "Box 2D": { body = CreateRigidBody2D(); var shape = body.CreateComponent <Component_CollisionShape2D_Box>(); var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox; shape.TransformRelativeToParent = new Transform(bounds.GetCenter(), Quaternion.Identity); shape.Dimensions = bounds.GetSize().ToVector2(); } break; case "Circle 2D": { body = CreateRigidBody2D(); var shape = body.CreateComponent <Component_CollisionShape2D_Ellipse>(); var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox; shape.TransformRelativeToParent = new Transform(bounds.GetCenter(), Quaternion.Identity); var size = bounds.GetSize().ToVector2().MaxComponent(); shape.Dimensions = new Vector2(size, size); } break; case "Ellipse 2D": { body = CreateRigidBody2D(); var shape = body.CreateComponent <Component_CollisionShape2D_Ellipse>(); var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox; shape.TransformRelativeToParent = new Transform(bounds.GetCenter(), Quaternion.Identity); shape.Dimensions = bounds.GetSize().ToVector2(); } break; case "Capsule 2D": { body = CreateRigidBody2D(); var shape = body.CreateComponent <Component_CollisionShape2D_Capsule>(); var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox; shape.TransformRelativeToParent = new Transform(bounds.GetCenter(), Quaternion.Identity); var size = bounds.GetSize(); if (size.X > size.Y) { shape.Axis = 0; shape.Radius = size.Y / 2; shape.Height = Math.Max(size.X - shape.Radius * 2, 0); } else { shape.Axis = 0; shape.Radius = size.X / 2; shape.Height = Math.Max(size.Y - shape.Radius * 2, 0); } } break; case "Convex 2D": { body = CreateRigidBody2D(); var meshPoints = new Vector2[mesh.Result.ExtractedVerticesPositions.Length]; for (int n = 0; n < meshPoints.Length; n++) { meshPoints[n] = mesh.Result.ExtractedVerticesPositions[n].ToVector2(); } var points = MathAlgorithms.GetConvexByPoints(meshPoints); var vertices = new Vector3F[points.Count]; var indices = new int[(points.Count - 2) * 3]; { for (int n = 0; n < points.Count; n++) { vertices[n] = new Vector3F(points[n].ToVector2F(), 0); } for (int nTriangle = 0; nTriangle < points.Count - 2; nTriangle++) { indices[nTriangle * 3 + 0] = 0; indices[nTriangle * 3 + 1] = nTriangle + 1; indices[nTriangle * 3 + 2] = nTriangle + 2; } } var shape = body.CreateComponent <Component_CollisionShape2D_Mesh>(); shape.Vertices = vertices; shape.Indices = indices; shape.ShapeType = Component_CollisionShape2D_Mesh.ShapeTypeEnum.Convex; //var polygons = new List<List<Vector2>>(); //{ // var currentList = new List<Vector2>(); // for( int vertex = 0; vertex < points.Count; vertex++ ) // { // currentList.Add( points[ vertex ] ); // if( currentList.Count == Settings.MaxPolygonVertices ) // { // polygons.Add( currentList ); // currentList = new List<Vector2>(); // currentList.Add( points[ 0 ] ); // currentList.Add( points[ vertex ] ); // } // } // if( currentList.Count >= 3 ) // polygons.Add( currentList ); //} //foreach( var points2 in polygons ) //{ // var vertices = new Vector3F[ points2.Count ]; // var indices = new int[ ( points2.Count - 2 ) * 3 ]; // { // for( int n = 0; n < points2.Count; n++ ) // vertices[ n ] = new Vector3F( points2[ n ].ToVector2F(), 0 ); // for( int nTriangle = 0; nTriangle < points2.Count - 2; nTriangle++ ) // { // indices[ nTriangle * 3 + 0 ] = 0; // indices[ nTriangle * 3 + 1 ] = nTriangle + 1; // indices[ nTriangle * 3 + 2 ] = nTriangle + 2; // } // } // var shape = body.CreateComponent<Component_CollisionShape2D_Mesh>(); // shape.Vertices = vertices; // shape.Indices = indices; // shape.ShapeType = Component_CollisionShape2D_Mesh.ShapeTypeEnum.Convex; //} } break; //case "Convex Decomposition 2D": // { // body = CreateRigidBody2D(); // var settings = new ConvexDecomposition.Settings(); // var form = new SpecifyParametersForm( "Convex Decomposition 2D", settings ); // form.CheckHandler = delegate ( ref string error2 ) // { // return true; // }; // if( form.ShowDialog() != DialogResult.OK ) // skip = true; // else // { // //var sourceVertices = (Vector3F[])mesh.Result.ExtractedVerticesPositions.Clone(); // ////reset Z // //for( int n = 0; n < sourceVertices.Length; n++ ) // // sourceVertices[ n ] = new Vector3F( sourceVertices[ n ].ToVector2(), 0 ); // //var sourceIndices = mesh.Result.ExtractedIndices; // //var epsilon = 0.0001f; // //MathAlgorithms.MergeEqualVerticesRemoveInvalidTriangles( sourceVertices, sourceIndices, epsilon, out var processedVertices, out var processedIndices, out var processedTrianglesToSourceIndex ); // //var vertices = new Vector3F[ mesh.Result.ExtractedVerticesPositions.Length ]; // ////reset Z // //for( int n = 0; n < vertices.Length; n++ ) // // vertices[ n ] = new Vector3F( mesh.Result.ExtractedVerticesPositions[ n ].ToVector2(), 0 ); // //var clusters = ConvexDecomposition.Decompose( processedVertices, processedIndices, settings ); // var vertices = new Vector3F[ mesh.Result.ExtractedVerticesPositions.Length ]; // //reset Z // for( int n = 0; n < vertices.Length; n++ ) // vertices[ n ] = new Vector3F( mesh.Result.ExtractedVerticesPositions[ n ].ToVector2(), 0 ); // var clusters = ConvexDecomposition.Decompose( vertices, mesh.Result.ExtractedIndices, settings ); // if( clusters == null ) // { // Log.Warning( "Unable to decompose." ); // skip = true; // } // else // { // foreach( var cluster in clusters ) // { // var shape = body.CreateComponent<Component_CollisionShape2D_Mesh>(); // shape.Vertices = cluster.Vertices; // shape.Indices = cluster.Indices; // shape.ShapeType = Component_CollisionShape2D_Mesh.ShapeTypeEnum.Convex; // } // } // } // //var sourceVertices = new Vertices(); // //foreach( var p in mesh.Result.ExtractedVerticesPositions ) // // sourceVertices.Add( Physics2DUtility.Convert( p.ToVector2() ) ); // //var list = Triangulate.ConvexPartition( sourceVertices, TriangulationAlgorithm.Seidel, tolerance: 0.001f ); // //body = CreateRigidBody2D(); // //foreach( var convexVertices in list ) // //{ // // var shape = body.CreateComponent<Component_CollisionShape2D_Mesh>(); // // var points = new List<Vector2>(); // // foreach( var p in convexVertices ) // // points.Add( Physics2DUtility.Convert( p ) ); // // //var meshPoints = new Vector2[ mesh.Result.ExtractedVerticesPositions.Length ]; // // //for( int n = 0; n < meshPoints.Length; n++ ) // // // meshPoints[ n ] = mesh.Result.ExtractedVerticesPositions[ n ].ToVector2(); // // //var points = MathAlgorithms.GetConvexByPoints( meshPoints ); // // var vertices = new Vector3F[ points.Count + 1 ]; // // var indices = new int[ points.Count * 3 ]; // // { // // var center = Vector2.Zero; // // foreach( var p in points ) // // center += p; // // center /= points.Count; // // vertices[ 0 ] = new Vector3F( center.ToVector2F(), 0 ); // // for( int n = 0; n < points.Count; n++ ) // // { // // vertices[ 1 + n ] = new Vector3F( points[ n ].ToVector2F(), 0 ); // // indices[ n * 3 + 0 ] = 0; // // indices[ n * 3 + 1 ] = 1 + n; // // indices[ n * 3 + 2 ] = 1 + ( ( n + 1 ) % points.Count ); // // } // // } // // shape.Vertices = vertices; // // shape.Indices = indices; // // shape.ShapeType = Component_CollisionShape2D_Mesh.ShapeTypeEnum.Convex; // //} // //body = CreateRigidBody2D(); // //var shape = body.CreateComponent<Component_CollisionShape2D_Mesh>(); // //var meshPoints = new Vector2[ mesh.Result.ExtractedVerticesPositions.Length ]; // //for( int n = 0; n < meshPoints.Length; n++ ) // // meshPoints[ n ] = mesh.Result.ExtractedVerticesPositions[ n ].ToVector2(); // //var points = MathAlgorithms.GetConvexByPoints( meshPoints ); // //var vertices = new Vector3F[ points.Count + 1 ]; // //var indices = new int[ points.Count * 3 ]; // //{ // // var center = Vector2.Zero; // // foreach( var p in points ) // // center += p; // // center /= points.Count; // // vertices[ 0 ] = new Vector3F( center.ToVector2F(), 0 ); // // for( int n = 0; n < points.Count; n++ ) // // { // // vertices[ 1 + n ] = new Vector3F( points[ n ].ToVector2F(), 0 ); // // indices[ n * 3 + 0 ] = 0; // // indices[ n * 3 + 1 ] = 1 + n; // // indices[ n * 3 + 2 ] = 1 + ( ( n + 1 ) % points.Count ); // // } // //} // //shape.Vertices = vertices; // //shape.Indices = indices; // //shape.ShapeType = Component_CollisionShape2D_Mesh.ShapeTypeEnum.Convex; // //var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox; // //shape.TransformRelativeToParent = new Transform( bounds.GetCenter(), Quaternion.Identity ); // //shape.Mesh = ReferenceUtility.MakeThisReference( shape, meshInSpace, "Mesh" ); // //var shapeVertices = new Vector3F[ points.Count ]; // //for( int n = 0; n < shapeVertices.Length; n++ ) // // shapeVertices[ n ] = new Vector3F( points[ n ].ToVector2F(), 0 ); // //shape.Vertices = shapeVertices; // } // break; case "Mesh 2D": { body = CreateRigidBody2D(); var shape = body.CreateComponent <Component_CollisionShape2D_Mesh>(); shape.Mesh = ReferenceUtility.MakeThisReference(shape, meshInSpace, "Mesh"); shape.ShapeType = Component_CollisionShape2D_Mesh.ShapeTypeEnum.TriangleMesh; //var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox; //shape.TransformRelativeToParent = new Transform( bounds.GetCenter(), Quaternion.Identity ); //var halfSize = bounds.GetSize().ToVector2() * 0.5; //var meshPoints = new List<Vector2>( mesh.Result.ExtractedVerticesPositions.Length ); //foreach( var p in mesh.Result.ExtractedVerticesPositions ) // meshPoints.Add( p.ToVector2() ); //var convexPoints = MathAlgorithms.GetConvexByPoints( meshPoints ); //var points = shape.PropertyGet( "Points" ); //foreach( var p in convexPoints ) // points.MethodInvoke( "Add", p ); //points.MethodInvoke( "Add", new Vector2( -halfSize.X, -halfSize.Y ) ); //points.MethodInvoke( "Add", new Vector2( halfSize.X, -halfSize.Y ) ); //points.MethodInvoke( "Add", new Vector2( halfSize.X, halfSize.Y ) ); //points.MethodInvoke( "Add", new Vector2( -halfSize.X, halfSize.Y ) ); } break; //case "Polygon 2D": // { // body = CreateRigidBody2D(); // if( body != null ) // { // var shapeType = MetadataManager.GetType( "NeoAxis.Component_CollisionShape2D_Polygon" ); // if( shapeType != null ) // { // var shape = body.CreateComponent( shapeType ); // var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox; // shape.PropertySet( "TransformRelativeToParent", new Transform( bounds.GetCenter(), Quaternion.Identity ) ); // var halfSize = bounds.GetSize().ToVector2() * 0.5; // var meshPoints = new List<Vector2>( mesh.Result.ExtractedVerticesPositions.Length ); // foreach( var p in mesh.Result.ExtractedVerticesPositions ) // meshPoints.Add( p.ToVector2() ); // var convexPoints = MathAlgorithms.GetConvexByPoints( meshPoints ); // var points = shape.PropertyGet( "Points" ); // foreach( var p in convexPoints ) // points.MethodInvoke( "Add", p ); // //points.MethodInvoke( "Add", new Vector2( -halfSize.X, -halfSize.Y ) ); // //points.MethodInvoke( "Add", new Vector2( halfSize.X, -halfSize.Y ) ); // //points.MethodInvoke( "Add", new Vector2( halfSize.X, halfSize.Y ) ); // //points.MethodInvoke( "Add", new Vector2( -halfSize.X, halfSize.Y ) ); // } // else // skip = true; // } // } // break; default: Log.Warning("No implementation."); skip = true; continue; } } if (skip) { body?.Dispose(); continue; } if (body != null) { body.Enabled = true; undoActions.Add(new UndoActionComponentCreateDelete(document, new Component[] { body }, true)); //change Transform { //undo action var property = (Metadata.Property)meshInSpace.MetadataGetMemberBySignature("property:Transform"); var undoItem = new UndoActionPropertiesChange.Item(meshInSpace, property, meshInSpace.Transform, new object[0]); undoActions.Add(new UndoActionPropertiesChange(new UndoActionPropertiesChange.Item[] { undoItem })); //configure reference meshInSpace.Transform = ReferenceUtility.MakeReference <Transform>(null, ReferenceUtility.CalculateThisReference(meshInSpace, body, "Transform")); } } } } if (undoActions.Count != 0) { document.UndoSystem.CommitAction(new UndoMultiAction(undoActions)); document.Modified = true; ScreenNotifications.Show(Translate("The collision was added successfully.")); } }; var items = new List <KryptonContextMenuItemBase>(); var names = new string[] { "Use Collision of the Mesh", "", "Box", "Sphere", "Capsule", "Cylinder", "Convex", "Convex Decomposition", "Mesh", "", "Box 2D", "Circle 2D", "Ellipse 2D", "Capsule 2D", "Convex 2D", /*"Convex Decomposition 2D", */ "Mesh 2D" }; foreach (var name in names) { if (name == "") { items.Add(new KryptonContextMenuSeparator()); } else { var item = new KryptonContextMenuItem(name, null, clickHandler); item.Tag = (a.DropDownContextMenu, name); items.Add(item); } } a.DropDownContextMenu.Items.Add(new KryptonContextMenuItems(items.ToArray())); } EditorActions.Register(a); } //Delete Collision { const string bodyName = "Collision Body"; var a = new EditorAction(); a.Name = "Delete Collision"; a.Description = "Deletes the collision body of selected objects."; a.ImageSmall = Properties.Resources.Delete_16; a.ImageBig = Properties.Resources.Delete_32; a.QatSupport = true; //a.qatAddByDefault = true; a.ContextMenuSupport = EditorContextMenu.MenuTypeEnum.Document; a.GetState += delegate(EditorAction.GetStateContext context) { if (context.ObjectsInFocus.DocumentWindow != null) { object[] selectedObjects = context.ObjectsInFocus.Objects; if (selectedObjects.Length != 0 && Array.TrueForAll(selectedObjects, obj => obj is Component_MeshInSpace)) { context.Enabled = Array.Exists(selectedObjects, delegate(object obj) { var c = ((Component)obj).GetComponent(bodyName); if (c != null) { if (c is Component_RigidBody) { return(true); } if (c is Component_RigidBody2D) { return(true); } } return(false); }); } } }; a.Click += delegate(EditorAction.ClickContext context) { var text = string.Format(Translate("Delete \'{0}\'?"), bodyName); if (EditorMessageBox.ShowQuestion(text, MessageBoxButtons.YesNo) == DialogResult.Yes) { List <UndoSystem.Action> undoActions = new List <UndoSystem.Action>(); foreach (Component_MeshInSpace meshInSpace in context.ObjectsInFocus.Objects) { Component body = null; { var c = meshInSpace.GetComponent(bodyName); if (c != null && (c is Component_RigidBody || c is Component_RigidBody2D)) { body = c; } } if (body != null) { var restoreValue = meshInSpace.Transform; undoActions.Add(new UndoActionComponentCreateDelete(context.ObjectsInFocus.DocumentWindow.Document, new Component[] { body }, false)); //change Transform if (meshInSpace.Transform.GetByReference == string.Format("this:${0}\\Transform", bodyName)) { //undo action var property = (Metadata.Property)meshInSpace.MetadataGetMemberBySignature("property:Transform"); var undoItem = new UndoActionPropertiesChange.Item(meshInSpace, property, restoreValue, new object[0]); undoActions.Add(new UndoActionPropertiesChange(new UndoActionPropertiesChange.Item[] { undoItem })); //reset reference meshInSpace.Transform = restoreValue.Value; } } } if (undoActions.Count != 0) { context.ObjectsInFocus.DocumentWindow.Document.UndoSystem.CommitAction(new UndoMultiAction(undoActions)); context.ObjectsInFocus.DocumentWindow.Document.Modified = true; ScreenNotifications.Show(Translate("The collision was deleted.")); } } }; EditorActions.Register(a); } }
public override void Register() { //Attach second selected to first { const string transformOffsetName = "Attach Transform Offset"; var a = new EditorAction(); a.Name = "Attach Second to First"; a.Description = "Attaches the second, third and next selected objects to the first selected object."; a.ImageSmall = Properties.Resources.Attach_16; a.ImageBig = Properties.Resources.Attach_32; a.RibbonText = ("Attach", ""); //!!!!выключить где-то? a.QatSupport = true; //a.qatAddByDefault = true; a.ContextMenuSupport = EditorContextMenuWinForms.MenuTypeEnum.Document; a.GetState += delegate(EditorAction.GetStateContext context) { if (context.ObjectsInFocus.DocumentWindow != null) { object[] selectedObjects = context.ObjectsInFocus.Objects; if (selectedObjects.Length > 1) { var first = selectedObjects[0] as Component_ObjectInSpace; if (first != null) { for (int n = 1; n < selectedObjects.Length; n++) { var second = selectedObjects[n] as Component_ObjectInSpace; if (second != null) { var objectToTransform = Component_ObjectInSpace_Utility.CalculateObjectToTransform(second); if (objectToTransform != null) { second = objectToTransform; } //!!!!проверять? second.GetComponentByName( transformOffsetName ) as Component_TransformOffset == null if (!second.Transform.ReferenceSpecified && second.GetComponent(transformOffsetName) as Component_TransformOffset == null) { context.Enabled = true; } } ////!!!!проверять? second.GetComponentByName( transformOffsetName ) as Component_TransformOffset == null //if( second != null && !second.Transform.ReferenceSpecified && second.GetComponent( transformOffsetName ) as Component_TransformOffset == null ) //{ // context.Enabled = true; //} } } } } }; a.Click += delegate(EditorAction.ClickContext context) { object[] selectedObjects = context.ObjectsInFocus.Objects; var undoMultiAction = new UndoMultiAction(); var first = selectedObjects[0] as Component_ObjectInSpace; for (int n = 1; n < selectedObjects.Length; n++) { var second = selectedObjects[n] as Component_ObjectInSpace; if (second != null) { Component_ObjectInSpace_Utility.Attach(first, second, context.ObjectsInFocus.DocumentWindow.Document, undoMultiAction); } } context.ObjectsInFocus.DocumentWindow.Document.UndoSystem.CommitAction(undoMultiAction); context.ObjectsInFocus.DocumentWindow.Document.Modified = true; ScreenNotifications.Show(Translate("The object was attached to another object.")); //var undoActions = new List<UndoSystem.Action>(); //var first = selectedObjects[ 0 ] as Component_ObjectInSpace; //for( int n = 1; n < selectedObjects.Length; n++ ) //{ // var second = selectedObjects[ n ] as Component_ObjectInSpace; // if( second != null ) // { // var objectToTransform = Component_ObjectInSpace_Utility.CalculateObjectToTransform( second ); // if( objectToTransform != null ) // second = objectToTransform; // //create _TransformOffset // Component_TransformOffset transformOffset; // { // transformOffset = second.CreateComponent<Component_TransformOffset>( -1, false ); // transformOffset.Name = transformOffsetName; // transformOffset.Source = ReferenceUtility.MakeReference<Transform>( null, ReferenceUtility.CalculateThisReference( transformOffset, first, "Transform" ) ); // try // { // var f = first.Transform.Value; // var s = second.Transform.Value; // var offset = f.ToMatrix4().GetInverse() * s.ToMatrix4(); // offset.Decompose( out Vector3 pos, out Quaternion rot, out Vector3 scl ); // transformOffset.PositionOffset = pos; // transformOffset.RotationOffset = rot; // transformOffset.ScaleOffset = scl; // //transformOffset.Matrix = offset; // //var offset = new Mat4( s.Rotation.ToMat3(), s.Position ) * new Mat4( f.Rotation.ToMat3(), f.Position ).GetInverse(); // //var f = first.Transform.Value; // //var s = second.Transform.Value; // //var offset = new Mat4( s.Rotation.ToMat3(), s.Position ) * new Mat4( f.Rotation.ToMat3(), f.Position ).GetInverse(); // ////var offset = second.Transform.Value.ToMat4() * first.Transform.Value.ToMat4().GetInverse(); // //offset.Decompose( out Vec3 pos, out Quat rot, out Vec3 scl ); // //transformOffset.PositionOffset = pos / f.Scale;// / s.Scale; // //transformOffset.RotationOffset = rot; // //transformOffset.ScaleOffset = s.Scale / f.Scale; // ////transformOffset.ScaleOffset = scl; // } // catch { } // transformOffset.Enabled = true; // undoActions.Add( new UndoActionComponentCreateDelete( context.ObjectsInFocus.DocumentWindow.Document, new Component[] { transformOffset }, true ) ); // } // //change Transform // { // //undo action // var property = (Metadata.Property)second.MetadataGetMemberBySignature( "property:Transform" ); // var undoItem = new UndoActionPropertiesChange.Item( second, property, second.Transform, new object[ 0 ] ); // undoActions.Add( new UndoActionPropertiesChange( new UndoActionPropertiesChange.Item[] { undoItem } ) ); // //configure reference // second.Transform = ReferenceUtility.MakeReference<Transform>( null, ReferenceUtility.CalculateThisReference( second, transformOffset, "Result" ) ); // } // } //} //context.ObjectsInFocus.DocumentWindow.Document.UndoSystem.CommitAction( new UndoMultiAction( undoActions ) ); //context.ObjectsInFocus.DocumentWindow.Document.Modified = true; //ScreenNotifications.Show( "The object was attached to another object." ); }; EditorActions.Register(a); } //Detach from Another Object { //const string transformOffsetName = "Attach Transform Offset"; var a = new EditorAction(); a.Name = "Detach from Another Object"; a.Description = "Detaches selected objects from another object."; a.ImageSmall = Properties.Resources.Detach_16; a.ImageBig = Properties.Resources.Detach_32; a.RibbonText = ("Detach", ""); //!!!!выключить где-то? a.QatSupport = true; //a.qatAddByDefault = true; a.ContextMenuSupport = EditorContextMenuWinForms.MenuTypeEnum.Document; a.GetState += delegate(EditorAction.GetStateContext context) { if (context.ObjectsInFocus.DocumentWindow != null) { object[] selectedObjects = context.ObjectsInFocus.Objects; if (selectedObjects.Length != 0 && Array.TrueForAll(selectedObjects, obj => obj is Component_ObjectInSpace)) { foreach (Component_ObjectInSpace objectInSpace in selectedObjects) { var objectToDetach = Component_ObjectInSpace_Utility.FindObjectToDetach(objectInSpace); if (objectToDetach != null) { context.Enabled = true; break; } //var objectInSpace = objectInSpace2; //var objectToTransform = Component_ObjectInSpace_Utility.CalculateObjectToTransform( objectInSpace ); //if( objectToTransform != null ) // objectInSpace = objectToTransform; //if( objectInSpace.GetComponent( transformOffsetName ) as Component_TransformOffset != null ) //{ // context.Enabled = true; // break; //} } //context.Enabled = Array.Exists( selectedObjects, // obj => ( (Component)obj ).GetComponent( transformOffsetName ) as Component_TransformOffset != null ); } } }; a.Click += delegate(EditorAction.ClickContext context) { if (EditorMessageBox.ShowQuestion(Translate("Detach from another object?"), EMessageBoxButtons.YesNo) == EDialogResult.Yes) { var undoMultiAction = new UndoMultiAction(); foreach (Component_ObjectInSpace objectInSpace in context.ObjectsInFocus.Objects) { var objectToDetach = Component_ObjectInSpace_Utility.FindObjectToDetach(objectInSpace); if (objectToDetach != null) { Component_ObjectInSpace_Utility.Detach(objectToDetach, context.ObjectsInFocus.DocumentWindow.Document, undoMultiAction); } } if (undoMultiAction.Actions.Count != 0) { context.ObjectsInFocus.DocumentWindow.Document.UndoSystem.CommitAction(undoMultiAction); context.ObjectsInFocus.DocumentWindow.Document.Modified = true; ScreenNotifications.Show(Translate("The object was detached from another object.")); } //var undoActions = new List<UndoSystem.Action>(); //foreach( Component_ObjectInSpace objectInSpace2 in context.ObjectsInFocus.Objects ) //{ // var objectInSpace = objectInSpace2; // var objectToTransform = Component_ObjectInSpace_Utility.CalculateObjectToTransform( objectInSpace ); // if( objectToTransform != null ) // objectInSpace = objectToTransform; // var transformOffset = objectInSpace.GetComponent( transformOffsetName ) as Component_TransformOffset; // if( transformOffset != null ) // { // //change Transform // { // //undo action // var property = (Metadata.Property)objectInSpace.MetadataGetMemberBySignature( "property:Transform" ); // var undoItem = new UndoActionPropertiesChange.Item( objectInSpace, property, objectInSpace.Transform, new object[ 0 ] ); // undoActions.Add( new UndoActionPropertiesChange( new UndoActionPropertiesChange.Item[] { undoItem } ) ); // //remove reference // objectInSpace.Transform = new Reference<Transform>( objectInSpace.Transform, "" ); // } // //delete // undoActions.Add( new UndoActionComponentCreateDelete( context.ObjectsInFocus.DocumentWindow.Document, new Component[] { transformOffset }, false ) ); // } //} //if( undoActions.Count != 0 ) //{ // context.ObjectsInFocus.DocumentWindow.Document.UndoSystem.CommitAction( new UndoMultiAction( undoActions ) ); // context.ObjectsInFocus.DocumentWindow.Document.Modified = true; // ScreenNotifications.Show( "The object was detached from another object." ); //} } }; EditorActions.Register(a); } }
void RenderScreenshot(Component_Camera camera, string destRealFileName) { var renderToFile = RenderToFile; var scene = renderToFile.ParentRoot as Component_Scene; Component_Image texture = null; Component_Image textureRead = null; try { //create var resolution = renderToFile.Resolution.Value; //!!!!impl var hdr = false; //HDR.Value; PixelFormat format = hdr ? PixelFormat.Float16RGBA : PixelFormat.A8R8G8B8; //PixelFormat format = hdr ? PixelFormat.Float32RGBA : PixelFormat.A8R8G8B8; texture = ComponentUtility.CreateComponent <Component_Image>(null, true, false); texture.CreateType = Component_Image.TypeEnum._2D; texture.CreateSize = resolution; texture.CreateMipmaps = false; texture.CreateFormat = format; texture.CreateUsage = Component_Image.Usages.RenderTarget; texture.CreateFSAA = 0; texture.Enabled = true; var renderTexture = texture.Result.GetRenderTarget(0, 0); var viewport = renderTexture.AddViewport(true, true); viewport.AttachedScene = scene; textureRead = ComponentUtility.CreateComponent <Component_Image>(null, true, false); textureRead.CreateType = Component_Image.TypeEnum._2D; textureRead.CreateSize = resolution; textureRead.CreateMipmaps = false; textureRead.CreateFormat = format; textureRead.CreateUsage = Component_Image.Usages.ReadBack | Component_Image.Usages.BlitDestination; textureRead.CreateFSAA = 0; textureRead.Enabled = true; //!!!! textureRead.Result.PrepareNativeObject(); //render //var image2D = new ImageUtility.Image2D( PixelFormat.Float32RGB, new Vector2I( size * 4, size * 3 ) ); //var position = Transform.Value.Position; //for( int face = 0; face < 6; face++ ) //{ //Vector3 dir = Vector3.Zero; //Vector3 up = Vector3.Zero; ////flipped //switch( face ) //{ //case 0: dir = -Vector3.YAxis; up = Vector3.ZAxis; break; //case 1: dir = Vector3.YAxis; up = Vector3.ZAxis; break; //case 2: dir = Vector3.ZAxis; up = -Vector3.XAxis; break; //case 3: dir = -Vector3.ZAxis; up = Vector3.XAxis; break; //case 4: dir = Vector3.XAxis; up = Vector3.ZAxis; break; //case 5: dir = -Vector3.XAxis; up = Vector3.ZAxis; break; //} try { scene.GetDisplayDevelopmentDataInThisApplicationOverride += Scene_GetDisplayDevelopmentDataInThisApplicationOverride; var cameraSettings = new Viewport.CameraSettingsClass(viewport, camera); //var cameraSettings = new Viewport.CameraSettingsClass( viewport, 1, 90, NearClipPlane.Value, FarClipPlane.Value, position, dir, up, ProjectionType.Perspective, 1, 1, 1 ); viewport.Update(true, cameraSettings); //clear temp data viewport.RenderingContext.MultiRenderTarget_DestroyAll(); viewport.RenderingContext.DynamicTexture_DestroyAll(); } finally { scene.GetDisplayDevelopmentDataInThisApplicationOverride -= Scene_GetDisplayDevelopmentDataInThisApplicationOverride; } texture.Result.GetRealObject(true).BlitTo(viewport.RenderingContext.CurrentViewNumber, textureRead.Result.GetRealObject(true), 0, 0); //!!!!pitch //get data var totalBytes = PixelFormatUtility.GetNumElemBytes(format) * resolution.X * resolution.Y; var data = new byte[totalBytes]; unsafe { fixed(byte *pBytes = data) { var demandedFrame = textureRead.Result.GetRealObject(true).Read((IntPtr)pBytes, 0); while (RenderingSystem.CallBgfxFrame() < demandedFrame) { } } } var image = new ImageUtility.Image2D(format, resolution, data); //reset alpha channel for (int y = 0; y < image.Size.Y; y++) { for (int x = 0; x < image.Size.X; x++) { var pixel = image.GetPixel(new Vector2I(x, y)); pixel.W = 1.0f; image.SetPixel(new Vector2I(x, y), pixel); } } //image.Data //image2D.Blit( index * size, faceImage ); //Vector2I index = Vector2I.Zero; //switch( face ) //{ //case 0: index = new Vector2I( 2, 1 ); break; //case 1: index = new Vector2I( 0, 1 ); break; //case 2: index = new Vector2I( 1, 0 ); break; //case 3: index = new Vector2I( 1, 2 ); break; //case 4: index = new Vector2I( 1, 1 ); break; //case 5: index = new Vector2I( 3, 1 ); break; //} //var faceImage = new ImageUtility.Image2D( format, new Vector2I( size, size ), data ); //image2D.Blit( index * size, faceImage ); //} if (!Directory.Exists(Path.GetDirectoryName(destRealFileName))) { Directory.CreateDirectory(Path.GetDirectoryName(destRealFileName)); } if (!ImageUtility.Save(destRealFileName, image.Data, image.Size, 1, image.Format, 1, 0, out var error)) { throw new Exception(error); } } catch (Exception e) { EditorMessageBox.ShowWarning(e.Message); return; } finally { texture?.Dispose(); textureRead?.Dispose(); } ScreenNotifications.Show("Rendering completed successfully."); }
void ThreadDownload() { //var fileName = Path.Combine( PackageManager.PackagesFolder, Path.GetFileName( downloadingAddress ) ); var cancelled = false; try { using (WebClient client = new WebClient()) { downloadingClient = client; client.DownloadProgressChanged += MyWebClient_DownloadProgressChanged; client.DownloadFileCompleted += delegate(object sender, AsyncCompletedEventArgs e) { //releases blocked thread lock (e.UserState) Monitor.Pulse(e.UserState); cancelled = e.Cancelled; }; var syncObject = new object(); lock ( syncObject ) { client.DownloadFileAsync(new Uri(downloadingAddress), downloadingDestinationPath, syncObject); //This would block the thread until download completes Monitor.Wait(syncObject); } downloadingClient = null; } } catch (Exception e) { Log.Warning(e.Message); return; } finally { try { if (!cancelled) { if (File.Exists(downloadingDestinationPath) && new FileInfo(downloadingDestinationPath).Length == 0) { File.Delete(downloadingDestinationPath); cancelled = true; } } if (cancelled) { if (File.Exists(downloadingDestinationPath)) { File.Delete(downloadingDestinationPath); } } } catch { } downloadingPackageName = ""; downloadingAddress = ""; downloadingDestinationPath = ""; downloadProgress = 0; downloadingClient = null; } needUpdateList = true; if (!cancelled) { ScreenNotifications.Show(EditorLocalization.Translate("General", "The package has been successfully downloaded.")); } }