Пример #1
0
        public static void EditorActionClick(EditorAction.HolderEnum holder, EditorAction action)
        {
            var state = EditorActionGetState(holder, action);

            if (state.Enabled)
            {
                var objectsInFocus = state.ObjectsInFocus;
                //var objectsInFocus = GetObjectsInFocus();

                var context = new EditorAction.ClickContext(holder, objectsInFocus, action);

                //common
                action.PerformClick(context);
                //selected document
                objectsInFocus.DocumentWindow?.Document?.EditorActionClick(context);
                //selected window
                objectsInFocus.DocumentWindow?.EditorActionClick(context);
                //event
                EditorActionClickEvent?.Invoke(context);
            }
        }
Пример #2
0
            //

            internal ClickContext(HolderEnum holder, ObjectsInFocus objectsInFocus, EditorAction action)
            {
                this.holder         = holder;
                this.objectsInFocus = objectsInFocus;
                this.action         = action;
            }
Пример #3
0
        public override void Register()
        {
            //Add Constraint
            {
                var a = new EditorAction();
                //!!!!"New Constraint"?
                a.Name = "Add Constraint";
                //a.imageSmall = Properties.Resources.Save_16;
                //a.imageBig = Properties.Resources.Save_32;

                //!!!!выключить где-то?
                a.QatSupport = true;
                //a.qatAddByDefault = true;
                a.ContextMenuSupport = EditorContextMenuWinForms.MenuTypeEnum.Document;

                Component_PhysicalBody GetBody(object obj)
                {
                    if (obj is Component_PhysicalBody body)
                    {
                        return(body);
                    }

                    var c = obj as Component;

                    if (c != null)
                    {
                        var body2 = c.GetComponent <Component_PhysicalBody>();
                        if (body2 != null)
                        {
                            return(body2);
                        }
                    }

                    return(null);
                }

                a.GetState += delegate(EditorAction.GetStateContext context)
                {
                    if (context.ObjectsInFocus.DocumentWindow != null)
                    {
                        object[] selectedObjects = context.ObjectsInFocus.Objects;
                        if (selectedObjects.Length == 2)
                        {
                            var bodyA = GetBody(selectedObjects[0]);
                            var bodyB = GetBody(selectedObjects[1]);

                            if (bodyA != null && bodyB != null)
                            {
                                context.Enabled = true;
                            }
                            //if( selectedObjects[ 0 ] is Component_PhysicalBody && selectedObjects[ 1 ] is Component_PhysicalBody )
                            //	context.Enabled = true;
                        }
                    }
                };

                a.Click += delegate(EditorAction.ClickContext context)
                {
                    object[] selectedObjects = context.ObjectsInFocus.Objects;
                    if (selectedObjects.Length == 2)
                    {
                        var bodyA = GetBody(selectedObjects[0]);
                        var bodyB = GetBody(selectedObjects[1]);
                        //var bodyA = (Component_PhysicalBody)context.ObjectsInFocus.Objects[ 0 ];
                        //var bodyB = (Component_PhysicalBody)context.ObjectsInFocus.Objects[ 1 ];

                        var parent = ComponentUtility.FindNearestCommonParent(new Component[] { bodyA, bodyB });
                        if (parent != null)
                        {
                            var data = new NewObjectWindow.CreationDataClass();

                            data.initDocumentWindow = context.ObjectsInFocus.DocumentWindow;
                            data.initParentObjects  = new List <object>();
                            data.initParentObjects.Add(parent);
                            data.initLockType = MetadataManager.GetTypeOfNetType(typeof(Component_Constraint));
                            //data.initDemandedTypeDisableChange = true;

                            data.additionActionBeforeEnabled = delegate(NewObjectWindow window)
                            {
                                var constraint = (Component_Constraint)data.createdComponentsOnTopLevel[0];

                                constraint.BodyA = ReferenceUtility.MakeReference <Component_PhysicalBody>(
                                    null, ReferenceUtility.CalculateThisReference(constraint, bodyA));
                                constraint.BodyB = ReferenceUtility.MakeReference <Component_PhysicalBody>(
                                    null, ReferenceUtility.CalculateThisReference(constraint, bodyB));

                                var pos = (bodyA.Transform.Value.Position + bodyB.Transform.Value.Position) * 0.5;
                                constraint.Transform = new Transform(pos, Quaternion.Identity);
                            };

                            EditorAPI.OpenNewObjectWindow(data);
                        }
                    }
                };

                EditorActions.Register(a);
            }
        }
        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 = 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_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 = 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_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, EMessageBoxButtons.YesNo) == EDialogResult.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);
            }
        }
Пример #5
0
        public static EditorAction.GetStateContext EditorActionGetState(EditorAction.HolderEnum holder, EditorAction action)
        {
            var objectsInFocus = GetObjectsInFocus(action.CommonType == EditorAction.CommonTypeEnum.Document);
            var context        = new EditorAction.GetStateContext(holder, objectsInFocus, action);

            //common
            action.PerformGetState(context);
            //selected document
            objectsInFocus.DocumentWindow?.Document?.EditorActionGetState(context);
            //selected window
            objectsInFocus.DocumentWindow?.EditorActionGetState(context);
            //event
            EditorActionGetStateEvent?.Invoke(context);

            //context.Enabled = true;

            return(context);
        }
Пример #6
0
        void RibbonButtonsCheckForRecreate()
        {
            var config = ProjectSettings.Get.RibbonAndToolbarActions;

            if (ribbonUpdatedForConfiguration == null || !config.Equals(ribbonUpdatedForConfiguration) || needRecreatedRibbonButtons)
            {
                ribbonUpdatedForConfiguration = config.Clone();
                needRecreatedRibbonButtons    = false;

                ribbonLastSelectedTabTypeByUser_DisableUpdate = true;

                kryptonRibbon.RibbonTabs.Clear();

                foreach (var tabSettings in ProjectSettings.Get.RibbonAndToolbarActions.RibbonTabs)
                {
                    if (!tabSettings.Enabled)
                    {
                        continue;
                    }

                    //can be null
                    EditorRibbonDefaultConfiguration.Tab tab = null;
                    if (tabSettings.Type == Component_ProjectSettings.RibbonAndToolbarActionsClass.TabItem.TypeEnum.Basic)
                    {
                        tab = EditorRibbonDefaultConfiguration.GetTab(tabSettings.Name);
                    }

                    var ribbonTab = new KryptonRibbonTab();
                    ribbonTab.Tag = tab;

                    if (tabSettings.Type == Component_ProjectSettings.RibbonAndToolbarActionsClass.TabItem.TypeEnum.Basic)
                    {
                        ribbonTab.Text = EditorLocalization.Translate("Ribbon.Tab", tabSettings.Name);
                    }
                    else
                    {
                        ribbonTab.Text = tabSettings.Name;
                    }

                    ribbonTab.KeyTip = GetTabKeyTip(tabSettings.Name);

                    kryptonRibbon.RibbonTabs.Add(ribbonTab);

                    var usedKeyTips = new ESet <string>();

                    string GetKeyTip(string name)
                    {
                        foreach (var c in name + alphabetNumbers)
                        {
                            var s = c.ToString().ToUpper();
                            if (s != " " && !usedKeyTips.Contains(s))
                            {
                                usedKeyTips.AddWithCheckAlreadyContained(s);
                                return(s);
                            }
                        }
                        return("");
                    }

                    foreach (var groupSettings in tabSettings.Groups)
                    {
                        if (!groupSettings.Enabled)
                        {
                            continue;
                        }

                        var ribbonGroup = new KryptonRibbonGroup();

                        if (groupSettings.Type == Component_ProjectSettings.RibbonAndToolbarActionsClass.GroupItem.TypeEnum.Basic)
                        {
                            ribbonGroup.TextLine1 = EditorLocalization.Translate("Ribbon.Group", groupSettings.Name);
                        }
                        else
                        {
                            ribbonGroup.TextLine1 = groupSettings.Name;
                        }

                        ribbonGroup.DialogBoxLauncher = false;                        //!!!!для группы Transform можно было бы в настройки снеппинга переходить
                        //ribbonTab.Groups.Add( ribbonGroup );

                        foreach (var groupSettingsChild in groupSettings.Actions)
                        {
                            if (!groupSettingsChild.Enabled)
                            {
                                continue;
                            }

                            //sub group
                            if (groupSettingsChild.Type == Component_ProjectSettings.RibbonAndToolbarActionsClass.ActionItem.TypeEnum.SubGroupOfActions)
                            {
                                EditorRibbonDefaultConfiguration.Group subGroup = null;
                                if (tab != null)
                                {
                                    var group = tab.Groups.Find(g => g.Name == groupSettings.Name);
                                    if (group != null)
                                    {
                                        foreach (var child in group.Children)
                                        {
                                            var g = child as EditorRibbonDefaultConfiguration.Group;
                                            if (g != null && g.Name == groupSettingsChild.Name)
                                            {
                                                subGroup = g;
                                                break;
                                            }
                                        }
                                    }
                                }

                                if (subGroup != null)
                                {
                                    var tripple = new KryptonRibbonGroupTriple();
                                    ribbonGroup.Items.Add(tripple);

                                    var button = new KryptonRibbonGroupButton();
                                    button.Tag = "SubGroup";
                                    //button.Tag = action;

                                    var str = subGroup.DropDownGroupText.Item1;
                                    if (subGroup.DropDownGroupText.Item2 != "")
                                    {
                                        str += "\n" + subGroup.DropDownGroupText.Item2;
                                    }

                                    var str2 = EditorLocalization.Translate("Ribbon.Action", str);
                                    var strs = str2.Split(new char[] { '\n' });

                                    button.TextLine1 = strs[0];
                                    if (strs.Length > 1)
                                    {
                                        button.TextLine2 = strs[1];
                                    }

                                    //button.TextLine1 = subGroup.DropDownGroupText.Item1;
                                    //button.TextLine2 = subGroup.DropDownGroupText.Item2;

                                    if (subGroup.DropDownGroupImageSmall != null)
                                    {
                                        button.ImageSmall = subGroup.DropDownGroupImageSmall;
                                    }
                                    else if (subGroup.DropDownGroupImageLarge != null)
                                    {
                                        button.ImageSmall = EditorAction.ResizeImage(subGroup.DropDownGroupImageLarge, 16, 16);
                                    }
                                    button.ImageLarge = subGroup.DropDownGroupImageLarge;

                                    //EditorLocalization.Translate( "EditorAction.Description",

                                    if (!string.IsNullOrEmpty(subGroup.DropDownGroupDescription))
                                    {
                                        button.ToolTipBody = EditorLocalization.Translate("EditorAction.Description", subGroup.DropDownGroupDescription);
                                    }
                                    else
                                    {
                                        button.ToolTipBody = subGroup.Name;
                                    }

                                    button.ButtonType = GroupButtonType.DropDown;
                                    button.ShowArrow  = subGroup.ShowArrow;

                                    button.KryptonContextMenu = new KryptonContextMenu();
                                    RibbonSubGroupAddItemsRecursive(subGroup, button.KryptonContextMenu.Items);

                                    tripple.Items.Add(button);
                                }
                            }

                            //action
                            if (groupSettingsChild.Type == Component_ProjectSettings.RibbonAndToolbarActionsClass.ActionItem.TypeEnum.Action)
                            {
                                var action = EditorActions.GetByName(groupSettingsChild.Name);

                                if (action != null && !action.CompletelyDisabled)
                                {
                                    if (action.ActionType == EditorAction.ActionTypeEnum.Button || action.ActionType == EditorAction.ActionTypeEnum.DropDown)
                                    {
                                        //Button, DropDown

                                        var tripple = new KryptonRibbonGroupTriple();
                                        ribbonGroup.Items.Add(tripple);

                                        var control = new KryptonRibbonGroupButton();

                                        //!!!!
                                        //control.ImageSmall = NeoAxis.Properties.Resources.Android_16;

                                        control.Tag = action;

                                        var str = action.RibbonText.Item1;
                                        if (action.RibbonText.Item2 != "")
                                        {
                                            str += "\n" + action.RibbonText.Item2;
                                        }

                                        var str2 = EditorLocalization.Translate("Ribbon.Action", str);
                                        var strs = str2.Split(new char[] { '\n' });

                                        control.TextLine1 = strs[0];
                                        if (strs.Length > 1)
                                        {
                                            control.TextLine2 = strs[1];
                                        }

                                        //control.TextLine1 = action.RibbonText.Item1;
                                        //control.TextLine2 = action.RibbonText.Item2;

                                        control.ImageSmall  = action.GetImageSmall();
                                        control.ImageLarge  = action.GetImageBig();
                                        control.ToolTipBody = action.ToolTip;
                                        control.KeyTip      = GetKeyTip(action.Name);

                                        //_buttonType = GroupButtonType.Push;
                                        //_toolTipImageTransparentColor = Color.Empty;
                                        //_toolTipTitle = string.Empty;
                                        //_toolTipBody = string.Empty;
                                        //_toolTipStyle = LabelStyle.SuperTip;

                                        if (action.ActionType == EditorAction.ActionTypeEnum.DropDown)
                                        {
                                            control.ButtonType         = GroupButtonType.DropDown;
                                            control.KryptonContextMenu = action.DropDownContextMenu;
                                        }

                                        control.Click += Button_Click;

                                        tripple.Items.Add(control);
                                    }
                                    else if (action.ActionType == EditorAction.ActionTypeEnum.Slider)
                                    {
                                        //Slider

                                        var tripple = new KryptonRibbonGroupTriple();
                                        ribbonGroup.Items.Add(tripple);

                                        var control = new KryptonRibbonGroupSlider();
                                        control.Tag         = action;
                                        control.ToolTipBody = action.ToolTip;

                                        control.Control.Size = new System.Drawing.Size((int)((float)control.Control.Size.Width * EditorAPI.DPIScale), control.Control.Size.Height);
                                        control.Control.kryptonSplitContainer2.Size             = new System.Drawing.Size((int)((float)control.Control.kryptonSplitContainer2.Size.Width * EditorAPI.DPIScale), control.Control.Size.Height);
                                        control.Control.kryptonSplitContainer2.Panel1MinSize    = (int)((float)control.Control.kryptonSplitContainer2.Panel1MinSize * EditorAPI.DPIScale);
                                        control.Control.kryptonSplitContainer1.Panel2MinSize    = (int)((float)control.Control.kryptonSplitContainer1.Panel2MinSize * EditorAPI.DPIScale);
                                        control.Control.kryptonSplitContainer1.SplitterDistance = 10000;

                                        control.Control.kryptonLabel1.Text = EditorLocalization.Translate("Ribbon.Action", action.RibbonText.Item1);
                                        control.Control.Init(action.Slider.Minimum, action.Slider.Maximum, action.Slider.ExponentialPower);
                                        control.Control.SetValue(action.Slider.Value);

                                        control.Control.Tag           = action;
                                        control.Control.ValueChanged += Slider_ValueChanged;

                                        tripple.Items.Add(control);
                                    }
                                    //else if( action.ActionType == EditorAction.ActionTypeEnum.ComboBox )
                                    //{
                                    //	//ComboBox

                                    //	var tripple = new KryptonRibbonGroupTriple();
                                    //	ribbonGroup.Items.Add( tripple );

                                    //	var control = new KryptonRibbonGroupComboBox();
                                    //	control.Tag = action;

                                    //	control.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
                                    //	foreach( var item in action.ComboBox.Items )
                                    //		control.Items.Add( item );

                                    //	if( control.Items.Count != 0 )
                                    //		control.SelectedIndex = 0;

                                    //	//control.MinimumLength = action.Slider.Length;
                                    //	//control.MaximumLength = action.Slider.Length;

                                    //	control.SelectedIndexChanged += ComboBox_SelectedIndexChanged;

                                    //	tripple.Items.Add( control );
                                    //}
                                    else if (action.ActionType == EditorAction.ActionTypeEnum.ListBox)
                                    {
                                        //ListBox

                                        var tripple = new KryptonRibbonGroupTriple();
                                        ribbonGroup.Items.Add(tripple);

                                        var control = new KryptonRibbonGroupListBox();
                                        control.Tag         = action;
                                        control.ToolTipBody = action.ToolTip;

                                        control.Control.Size = new System.Drawing.Size((int)((float)action.ListBox.Length * EditorAPI.DPIScale), control.Control.Size.Height);
                                        control.Control.kryptonSplitContainer1.Size             = new System.Drawing.Size((int)((float)action.ListBox.Length * EditorAPI.DPIScale), control.Control.Size.Height);
                                        control.Control.kryptonSplitContainer1.Panel2MinSize    = (int)((float)control.Control.kryptonSplitContainer1.Panel2MinSize * EditorAPI.DPIScale);
                                        control.Control.kryptonSplitContainer1.SplitterDistance = 10000;
                                        //if( action.ListBox.Length != 172 )
                                        //	control.Control.Size = new System.Drawing.Size( action.ListBox.Length, control.Control.Size.Height );

                                        control.Control.kryptonLabel1.Text = EditorLocalization.Translate("Ribbon.Action", action.RibbonText.Item1);

                                        var browser = control.Control.contentBrowser1;

                                        if (action.ListBox.Mode == EditorAction.ListBoxSettings.ModeEnum.Tiles)
                                        {
                                            browser.ListViewModeOverride             = new ContentBrowserListModeTilesRibbon(browser);
                                            browser.Options.PanelMode                = ContentBrowser.PanelModeEnum.List;
                                            browser.Options.ListMode                 = ContentBrowser.ListModeEnum.Tiles;
                                            browser.UseSelectedTreeNodeAsRootForList = false;
                                            browser.Options.Breadcrumb               = false;
                                            browser.ListViewBorderDraw               = BorderSides.Left | BorderSides.Right | BorderSides.Bottom;
                                            browser.Options.TileImageSize            = 22;
                                        }
                                        else
                                        {
                                            browser.RemoveTreeViewIconsColumn();
                                            browser.TreeView.RowHeight -= 2;
                                        }

                                        browser.Tag = action;

                                        //update items
                                        control.SetItems(action.ListBox.Items);

                                        browser.ItemAfterSelect += ListBrowser_ItemAfterSelect;

                                        if (browser.Items.Count != 0)
                                        {
                                            browser.SelectItems(new ContentBrowser.Item[] { browser.Items.ToArray()[0] });
                                        }

                                        //browser.ItemAfterSelect += ListBrowser_ItemAfterSelect;

                                        tripple.Items.Add(control);
                                    }
                                }
                            }
                        }

                        if (ribbonGroup.Items.Count != 0)
                        {
                            ribbonTab.Groups.Add(ribbonGroup);
                        }
                    }

                    //select
                    var tabType = "";
                    if (tab != null)
                    {
                        tabType = tab.Type;
                    }
                    if (ribbonLastSelectedTabTypeByUser != "" && tabType == ribbonLastSelectedTabTypeByUser)
                    {
                        kryptonRibbon.SelectedTab = ribbonTab;
                    }
                }

                ribbonLastSelectedTabTypeByUser_DisableUpdate = false;
            }
        }
Пример #7
0
        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);
            }
        }
Пример #8
0
        public override void Register()
        {
            var types = new List <Metadata.TypeInfo>();

            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Revolute)));
            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Prismatic)));
            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Distance)));
            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Weld)));
            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Fixed)));

            foreach (var type in types)
            {
                var displayName = TypeUtility.GetUserFriendlyNameForInstanceOfType(type.GetNetType());

                var a = new EditorAction();
                a.Name = "Add " + displayName;
                //a.ImageSmall = Properties.Resources.New_16;
                //a.ImageBig = Properties.Resources.New_32;

                a.QatSupport = true;
                //a.qatAddByDefault = true;
                a.ContextMenuSupport = EditorContextMenu.MenuTypeEnum.Document;

                Component_PhysicalBody2D GetBody(object obj)
                {
                    if (obj is Component_PhysicalBody2D body)
                    {
                        return(body);
                    }

                    var c = obj as Component;

                    if (c != null)
                    {
                        var body2 = c.GetComponent <Component_PhysicalBody2D>();
                        if (body2 != null)
                        {
                            return(body2);
                        }
                    }

                    return(null);
                }

                a.GetState += delegate(EditorAction.GetStateContext context)
                {
                    if (context.ObjectsInFocus.DocumentWindow != null)
                    {
                        object[] selectedObjects = context.ObjectsInFocus.Objects;
                        if (selectedObjects.Length == 2)
                        {
                            var bodyA = GetBody(selectedObjects[0]);
                            var bodyB = GetBody(selectedObjects[1]);

                            if (bodyA != null && bodyB != null)
                            {
                                context.Enabled = true;
                            }
                            //if( selectedObjects[ 0 ] is Component_PhysicalBody2D && selectedObjects[ 1 ] is Component_PhysicalBody2D )
                            //	context.Enabled = true;
                        }
                    }
                };

                a.Click += delegate(EditorAction.ClickContext context)
                {
                    object[] selectedObjects = context.ObjectsInFocus.Objects;
                    if (selectedObjects.Length == 2)
                    {
                        var bodyA = GetBody(selectedObjects[0]);
                        var bodyB = GetBody(selectedObjects[1]);
                        //var bodyA = (Component_PhysicalBody2D)context.ObjectsInFocus.Objects[ 0 ];
                        //var bodyB = (Component_PhysicalBody2D)context.ObjectsInFocus.Objects[ 1 ];

                        var parent = ComponentUtility.FindNearestCommonParent(new Component[] { bodyA, bodyB });
                        if (parent != null)
                        {
                            var data = new NewObjectWindow.CreationDataClass();

                            data.initDocumentWindow = context.ObjectsInFocus.DocumentWindow;
                            data.initParentObjects  = new List <object>();
                            data.initParentObjects.Add(parent);
                            data.initLockType = type;

                            data.additionActionBeforeEnabled = delegate(NewObjectWindow window)
                            {
                                var constraint = (Component_Constraint2D)data.createdComponentsOnTopLevel[0];

                                constraint.BodyA = ReferenceUtility.MakeReference <Component_PhysicalBody2D>(
                                    null, ReferenceUtility.CalculateThisReference(constraint, bodyA));
                                constraint.BodyB = ReferenceUtility.MakeReference <Component_PhysicalBody2D>(
                                    null, ReferenceUtility.CalculateThisReference(constraint, bodyB));

                                if (constraint is Component_Constraint2D_Distance)
                                {
                                    var pos  = bodyA.Transform.Value.Position;
                                    var posB = bodyB.Transform.Value.Position;

                                    var distance = (posB - pos).Length();

                                    var rot = Quaternion.FromDirectionZAxisUp((posB - pos).GetNormalize());
                                    var scl = new Vector3(distance, distance, distance);

                                    constraint.Transform = new Transform(pos, rot, scl);
                                }
                                else
                                {
                                    var pos = (bodyA.Transform.Value.Position + bodyB.Transform.Value.Position) * 0.5;
                                    constraint.Transform = new Transform(pos, Quaternion.Identity);
                                }
                            };

                            EditorAPI.OpenNewObjectWindow(data);
                        }
                    }
                };

                EditorActions.Register(a);
            }
        }