示例#1
0
        //!!!!если надо, то как EditorAction
        //public static void ShowObjectDetailsAsDocument( object obj )
        //{
        //	List<string> lines = new List<string>( 256 );

        //	lines.Add( obj.ToString() );
        //	lines.Add( "" );
        //	lines.Add( "----------------------------------------------------------------------------------------------------" );

        //	lines.Add( "Inheritance Hierarchy" );
        //	lines.Add( "" );

        //	var type = MetadataManager.MetadataGetType( obj );
        //	int step = 0;
        //	do
        //	{
        //		lines.Add( new string( ' ', step * 3 ) + type.ToString() );

        //		step++;
        //		type = type.BaseType;
        //	} while( type != null );

        //	//lines.Add( "Type \'" + MetadataManager.MetadataGetType( obj ).ToString() + "\'" );
        //	//lines.Add( ".NET type \'" + obj.GetType().ToString() + "\'" );
        //	lines.Add( "" );
        //	lines.Add( "----------------------------------------------------------------------------------------------------" );
        //	lines.Add( "" );

        //	foreach( var member in MetadataManager.MetadataGetMembers( obj ) )
        //	{
        //		Metadata.Method method = member as Metadata.Method;
        //		if( method != null )
        //		{
        //			lines.Add( method.Signature );
        //			lines.Add( "    " + method.ToString() );
        //			lines.Add( "" );
        //		}
        //	}

        //	lines.Add( "----------------------------------------------------------------------------------------------------" );
        //	lines.Add( "" );

        //	foreach( var member in MetadataManager.MetadataGetMembers( obj ) )
        //	{
        //		Metadata.Event evt = member as Metadata.Event;
        //		if( evt != null )
        //		{
        //			lines.Add( evt.Signature );
        //			lines.Add( "    " + evt.ToString() );
        //			lines.Add( "" );
        //		}
        //	}

        //	lines.Add( "----------------------------------------------------------------------------------------------------" );
        //	lines.Add( "" );

        //	foreach( var member in MetadataManager.MetadataGetMembers( obj ) )
        //	{
        //		Metadata.Property prop = member as Metadata.Property;
        //		if( prop != null )
        //		{
        //			lines.Add( prop.Signature );
        //			lines.Add( "    " + prop.ToString() );
        //			lines.Add( "" );
        //		}
        //	}

        //	//lines.Add( "Type: " + MetadataManager.MetadataGetType( obj ).ToString() );
        //	//lines.Add( "Net type: " + obj.GetType().ToString() );
        //	//lines.Add( "" );
        //	//lines.Add( "ToString(): " + obj.ToString() );
        //	//lines.Add( "" );
        //	//lines.Add( "----------------------------------------------------------------------------------------------------" );
        //	//lines.Add( "Metadata:" );



        //	//!!!!!!
        //	//if( component != null )
        //	//{
        //	//	List<string> list = new List<string>();

        //	//	var members = component.MetadataGetMembers( true );

        //	//	list.Add( component.ToString() );

        //	//	list.Add( "" );
        //	//	list.Add( "Events:" );
        //	//	foreach( var m in members )
        //	//	{
        //	//		var evn = m as Metadata.Event;
        //	//		if( evn != null )
        //	//			list.Add( evn.ToString() + " - " + evn.Signature );
        //	//	}

        //	//	list.Add( "" );
        //	//	list.Add( "Properties:" );
        //	//	foreach( var m in members )
        //	//	{
        //	//		var p = m as Metadata.Property;
        //	//		if( p != null )
        //	//			list.Add( p.ToString() + " - " + p.Signature );
        //	//	}

        //	//	list.Add( "" );
        //	//	list.Add( "Methods:" );
        //	//	foreach( var m in members )
        //	//	{
        //	//		var method = m as Metadata.Method;
        //	//		if( method != null )
        //	//			list.Add( method.ToString() + " - " + method.Signature );
        //	//	}

        //	//	//!!!!!!log out
        //	//	{
        //	//		Log.Info( "" );
        //	//		Log.Info( "" );
        //	//		Log.Info( "---------------------------------- START -------------------------------------" );

        //	//		foreach( var t in list )
        //	//			Log.Info( t );

        //	//		Log.Info( "----------------------------------- END --------------------------------------" );
        //	//	}

        //	//	viewport.GuiRenderer.AddTextLines( list, new Vec2( .03, .1 ), EHorizontalAlign.Left, EVerticalAlign.Top, 0,
        //	//		new ColorValue( 1, 1, 0 ) );
        //	//}

        //	StringBuilder text = new StringBuilder();
        //	foreach( var line in lines )
        //		text.Append( line + "\r\n" );
        //	EditorForm.Instance.OpenTextAsDocument( text.ToString(), MetadataManager.MetadataGetType( obj ).ToString(), true );
        //}

        public static void SetPropertyReference(DocumentInstance document, object /* Component*/[] objects, Metadata.Property property, object[] indexers, string[] referenceValues)
        {
            var netType        = property.Type.GetNetType();
            var underlyingType = ReferenceUtility.GetUnderlyingType(netType);

            var undoItems = new List <UndoActionPropertiesChange.Item>();

            //!!!!try, catch? где еще

            for (int n = 0; n < objects.Length; n++)
            {
                var obj = objects[n];

                var value    = ReferenceUtility.MakeReference(underlyingType, null, referenceValues[n]);
                var oldValue = (IReference)property.GetValue(obj, indexers);

                //bool change = true;
                //if( /*skipSame && */oldValue != null && value.GetByReference == oldValue.GetByReference )
                //	change = false;

                if (!value.Equals(oldValue))
                {
                    property.SetValue(obj, value, indexers);
                    undoItems.Add(new UndoActionPropertiesChange.Item(obj, property, oldValue, indexers));
                }
            }

            //undo
            if (undoItems.Count != 0)
            {
                var action = new UndoActionPropertiesChange(undoItems.ToArray());
                document.UndoSystem.CommitAction(action);
                document.Modified = true;
            }
        }
示例#2
0
        public static void ShowRenameComponentDialog(Component component)
        {
            var document = GetDocumentByComponent(component);

            var form = new OKCancelTextBoxForm(EditorLocalization.TranslateLabel("General", "Name:"), component.Name, EditorLocalization.Translate("General", "Rename"),
                                               delegate(string text, ref string error)
            {
                if (!ComponentUtility.IsValidComponentName(text, out string error2))
                {
                    error = error2;
                    return(false);
                }
                return(true);
            },
                                               delegate(string text, ref string error)
            {
                if (text != component.Name)
                {
                    var oldValue = component.Name;

                    //change Name
                    component.Name = text;

                    //undo
                    var undoItems = new List <UndoActionPropertiesChange.Item>();
                    var property  = (Metadata.Property)MetadataManager.GetTypeOfNetType(
                        typeof(Component)).MetadataGetMemberBySignature("property:Name");
                    undoItems.Add(new UndoActionPropertiesChange.Item(component, property, oldValue, new object[0]));

                    var action = new UndoActionPropertiesChange(undoItems.ToArray());
                    document.UndoSystem.CommitAction(action);
                    document.Modified = true;
                }
                return(true);
            }
                                               );

            form.ShowDialog();
        }
示例#3
0
        private void CheckAutoUpdate_Click(ProcedureUI.Check obj)
        {
            if (checkAutoUpdate.Checked == ProcedureUI.Check.CheckValue.Indeterminate)
            {
                return;
            }

            var undoItems = new List <UndoActionPropertiesChange.Item>();

            foreach (var effect in GetObjects <Component_RenderingEffect_CodeGenerated>())
            {
                var oldValue = effect.EditorAutoUpdate;

                effect.EditorAutoUpdate = checkAutoUpdate.Checked == ProcedureUI.Check.CheckValue.Checked;

                var property = (Metadata.Property)effect.MetadataGetMemberBySignature("property:EditorAutoUpdate");
                undoItems.Add(new UndoActionPropertiesChange.Item(effect, property, oldValue));
            }

            var undoAction = new UndoActionPropertiesChange(undoItems);

            Provider.DocumentWindow.Document.CommitUndoAction(undoAction);
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (!IsHandleCreated || EditorUtility.IsDesignerHosted(this) || EditorAPI.ClosingApplication)
            {
                return;
            }

            var newValue = avalonTextEditor.Editor.Text;

            if (sentTextToEngineUndoSystem != newValue)
            {
                sentTextToEngineUndoSystem = newValue;

                var oldValue = Script.Code;

                //!!!!в опции редактора
                var time = 3.0;
                disableUpdateRestoreTime        = EngineApp.GetSystemTime() + time;
                Script.TemporarilyDisableUpdate = true;

                if (newValue != Script.Code.Value)
                {
                    //update Code
                    Script.Code = newValue;

                    //add undo
                    var undoItems = new List <UndoActionPropertiesChange.Item>();
                    var property  = (Metadata.Property)MetadataManager.GetTypeOfNetType(
                        typeof(Component_ShaderScript)).MetadataGetMemberBySignature("property:Code");
                    undoItems.Add(new UndoActionPropertiesChange.Item(Script, property, oldValue));
                    var undoAction = new UndoActionPropertiesChange(undoItems);
                    Document.CommitUndoAction(undoAction);
                }
            }

            if (disableUpdateRestoreTime != 0 && EngineApp.GetSystemTime() > disableUpdateRestoreTime)
            {
                Script.TemporarilyDisableUpdate = false;
                disableUpdateRestoreTime        = 0;

                //!!!!
                ////to refresh preview texture
                //Script.RaiseCodeChangedEventAndSetNeedUpdate();

                //update materials. EditorUpdateWhenDocumentModified
                Document.EditorUpdateWhenDocumentModified_NeedUpdate(EngineApp.GetSystemTime() + 0.1);
            }

            if (displayLineNumbers != ProjectSettings.Get.ShaderEditorDisplayLineNumbers)
            {
                displayLineNumbers = ProjectSettings.Get.ShaderEditorDisplayLineNumbers;
                avalonTextEditor.Editor.ShowLineNumbers = displayLineNumbers;
            }

            if (wordWrap != ProjectSettings.Get.ShaderEditorWordWrap)
            {
                wordWrap = ProjectSettings.Get.ShaderEditorWordWrap;
                avalonTextEditor.Editor.WordWrap = wordWrap;
            }

            UpdateBackgroundForeground();
            UpdateFont();
        }
示例#5
0
        private void ButtonImport_Click(ProcedureUI.Button sender)
        {
            var sky = GetFirstObject <Component_Skybox>();

            if (sky == null)
            {
                return;
            }
            var scene = sky.FindParent <Component_Scene>();

            if (scene == null)
            {
                return;
            }

            var link = editLink.Text;

            var notification = ScreenNotifications.ShowSticky("Importing...");

            try
            {
                string destVirtualFileName;
                {
                    string name = sky.GetPathFromRoot();
                    foreach (char c in new string( Path.GetInvalidFileNameChars()) + new string( Path.GetInvalidPathChars()))
                    {
                        name = name.Replace(c.ToString(), "_");
                    }
                    name = name.Replace(" ", "_");
                    destVirtualFileName = Path.Combine(ComponentUtility.GetOwnedFileNameOfComponent(scene) + "_Files", name);

                    destVirtualFileName += Path.GetExtension(link);
                }

                var destRealFileName = VirtualPathUtility.GetRealPathByVirtual(destVirtualFileName);


                if (File.Exists(destRealFileName))
                {
                    if (EditorMessageBox.ShowQuestion($"Overwrite \'{destRealFileName}\'?", EMessageBoxButtons.OKCancel) == EDialogResult.Cancel)
                    {
                        return;
                    }
                }

                Directory.CreateDirectory(Path.GetDirectoryName(destRealFileName));

                if (File.Exists(link))
                {
                    File.Copy(link, destRealFileName, true);
                }
                else
                {
                    //if( Uri.IsWellFormedUriString( link, UriKind.Absolute ) )
                    //{
                    using (var client = new WebClient())
                        client.DownloadFile(link, destRealFileName);
                    //}
                }

                var oldValue = sky.Cubemap;

                sky.Cubemap = ReferenceUtility.MakeReference(destVirtualFileName);

                //undo
                var property   = (Metadata.Property)sky.MetadataGetMemberBySignature("property:Cubemap");
                var undoItem   = new UndoActionPropertiesChange.Item(sky, property, oldValue);
                var undoAction = new UndoActionPropertiesChange(undoItem);
                Provider.DocumentWindow.Document.CommitUndoAction(undoAction);
            }
            catch (Exception e)
            {
                EditorMessageBox.ShowWarning(e.Message);
            }
            finally
            {
                notification.Close();
            }
        }
示例#6
0
        private void ButtonAddEventHandler_Click(object sender, EventArgs e)
        {
            var items = new List <KryptonContextMenuItemBase>();

            var subscribeTo = GetOneControlledObject <Component>();

            if (subscribeTo == null)
            {
                return;
            }

            //add handler to C# class
            {
                bool   enable         = false;
                string className      = null;
                string csharpFileName = null;

                var fileName = subscribeTo.ParentRoot.HierarchyController?.CreatedByResource?.Owner.Name;
                if (!string.IsNullOrEmpty(fileName))
                {
                    className = subscribeTo.ParentRoot.GetType().Name;

                    try
                    {
                        //find by same class name
                        if (string.Compare(Path.GetFileNameWithoutExtension(fileName), className, true) == 0)
                        //if( Path.GetFileNameWithoutExtension( fileName ) == className )
                        {
                            csharpFileName = VirtualPathUtility.GetRealPathByVirtual(Path.ChangeExtension(fileName, "cs"));
                            if (File.Exists(csharpFileName))
                            {
                                enable = true;
                            }
                        }

                        //find by same file name
                        if (!enable)
                        {
                            csharpFileName = VirtualPathUtility.GetRealPathByVirtual(Path.Combine(Path.GetDirectoryName(fileName), className + ".cs"));
                            if (File.Exists(csharpFileName))
                            {
                                enable = true;
                            }
                        }
                    }
                    catch { }
                }

                var item = new KryptonContextMenuItem(Translate("Add Handler to C# File"), null, delegate(object s, EventArgs e2)
                {
                    AddHandlerToSharpClass(subscribeTo, csharpFileName, className);
                });
                item.Enabled = enable;
                items.Add(item);
            }

            //add handler to C# script
            {
                var groupItem  = new KryptonContextMenuItem(Translate("Add Handler to C# Script"), null);
                var childItems = new List <KryptonContextMenuItemBase>();

                //create new C# script
                {
                    var itemsData = new List <(string, Component)>();
                    itemsData.Add((Translate("Add C# Script in This Component"), subscribeTo));
                    if (subscribeTo != subscribeTo.ParentRoot)
                    {
                        itemsData.Add((Translate("Add C# Script in the Root Component"), subscribeTo.ParentRoot));
                    }

                    foreach (var itemData in itemsData)
                    {
                        var childItem = new KryptonContextMenuItem(itemData.Item1, null, delegate(object s, EventArgs e2)
                        {
                            var parent   = (Component)((KryptonContextMenuItem)s).Tag;
                            var document = Owner.DocumentWindow.Document;

                            //create script
                            var script     = parent.CreateComponent <Component_CSharpScript>(enabled: false);
                            script.Name    = script.BaseType.GetUserFriendlyNameForInstance();
                            script.Code    = "class _Temp{\r\n}";
                            script.Enabled = true;

                            //activate flow graph window
                            var scriptDocumentWindow = EditorAPI.OpenDocumentWindowForObject(document, script) as Component_CSharpScript_DocumentWindow;

                            Owner.DocumentWindow.SelectObjects(new object[] { script });

                            GetMethodInfo(subscribeTo, out var parameters, out var parametersSignature);
                            var methodNameNotUnique = subscribeTo.Name.Replace(" ", "") + "_" + _event.Name;
                            var methodName          = methodNameNotUnique;
                            var methodSignature     = $"method:{methodName}({parametersSignature})";

                            if (!scriptDocumentWindow.ScriptEditorControl.AddMethod(methodName, parameters, out var error))
                            {
                                Log.Warning("Unable to add a code of the method. " + error);
                                //!!!!
                            }

                            //fix code
                            try
                            {
                                scriptDocumentWindow.ScriptEditorControl.GetCode(out var code);

                                code = code.Replace("class _Temp{", "");

                                var index = code.LastIndexOf('}');
                                code      = code.Substring(0, index);

                                string newCode = "";
                                var lines      = code.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                                foreach (var line in lines)
                                {
                                    newCode += line.Trim() + "\r\n";
                                }

                                script.Code = newCode;
                            }
                            catch (Exception e3)
                            {
                                Log.Warning("Unable to fix code of the method. " + e3.Message);
                                //!!!!
                            }

                            //create event handler
                            {
                                var handler   = script.CreateComponent <Component_EventHandler>(enabled: false);
                                handler.Name  = handler.BaseType.GetUserFriendlyNameForInstance() + " " + _event.Name;
                                handler.Event = ReferenceUtility.MakeReference <ReferenceValueType_Event>(null,
                                                                                                          ReferenceUtility.CalculateThisReference(handler, subscribeTo, _event.Signature));
                                handler.HandlerMethod = ReferenceUtility.MakeReference <ReferenceValueType_Method>(null,
                                                                                                                   ReferenceUtility.CalculateThisReference(handler, script, methodSignature));
                                handler.Enabled = true;
                            }

                            //undo
                            var action = new UndoActionComponentCreateDelete(document, new Component[] { script }, true);
                            document.UndoSystem.CommitAction(action);
                            document.Modified = true;
                        });
                        childItem.Tag = itemData.Item2;
                        childItems.Add(childItem);
                    }
                }

                //add handler to one of already created C# scripts
                foreach (var script in subscribeTo.ParentRoot.GetComponents <Component_CSharpScript>(false, true))
                {
                    if (script.TypeSettingsIsPublic())
                    {
                        var text = string.Format(Translate("Add Handler to \'{0}\'"), script.GetPathFromRoot(true));
                        var item = new KryptonContextMenuItem(text, null, delegate(object s, EventArgs e2)
                        {
                            var script2  = (Component_CSharpScript)((KryptonContextMenuItem)s).Tag;
                            var document = Owner.DocumentWindow.Document;

                            var oldCode = script2.Code;

                            script2.Code = "class _Temp{\r\n}";

                            //activate flow graph window
                            var scriptDocumentWindow = EditorAPI.OpenDocumentWindowForObject(document, script2) as Component_CSharpScript_DocumentWindow;

                            Owner.DocumentWindow.SelectObjects(new object[] { script2 });

                            GetMethodInfo(subscribeTo, out var parameters, out var parametersSignature);

                            //get unique method name
                            string methodName;
                            string methodSignature;
                            {
                                var methodNameNotUnique = subscribeTo.Name.Replace(" ", "") + "_" + _event.Name;

                                for (int n = 1; ; n++)
                                {
                                    methodName = methodNameNotUnique;
                                    if (n != 1)
                                    {
                                        methodName += n.ToString();
                                    }
                                    methodSignature = $"method:{methodName}({parametersSignature})";

                                    bool found = false;
                                    if (script2.CompiledScript != null)
                                    {
                                        foreach (var m in script2.CompiledScript.Methods)
                                        {
                                            if (m.Name == methodName)
                                            {
                                                found = true;
                                            }
                                        }
                                    }
                                    if (!found)
                                    {
                                        break;
                                    }
                                    //if( subscribeTo.ParentRoot.MetadataGetMemberBySignature( methodSignature ) == null )
                                    //	break;
                                }
                            }

                            //GetMethodInfo( subscribeTo, out var parameters, out var methodName, out var methodSignature );

                            if (!scriptDocumentWindow.ScriptEditorControl.AddMethod(methodName, parameters, out var error))
                            {
                                Log.Warning("Unable to add a code of the method. " + error);
                                //!!!!
                            }

                            //set Code
                            try
                            {
                                scriptDocumentWindow.ScriptEditorControl.GetCode(out var code);

                                code = code.Replace("class _Temp{", "");

                                var index = code.LastIndexOf('}');
                                code      = code.Substring(0, index);

                                string newCode = "";
                                var lines      = code.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                                foreach (var line in lines)
                                {
                                    newCode += line.Trim() + "\r\n";
                                }

                                script2.Code = oldCode + "\r\n" + newCode;
                            }
                            catch (Exception e3)
                            {
                                Log.Warning("Unable to fix code of the method. " + e3.Message);
                                //!!!!
                            }

                            //create event handler
                            Component_EventHandler handler;
                            {
                                handler       = script2.CreateComponent <Component_EventHandler>(enabled: false);
                                handler.Name  = handler.BaseType.GetUserFriendlyNameForInstance() + " " + _event.Name;
                                handler.Event = ReferenceUtility.MakeReference <ReferenceValueType_Event>(null,
                                                                                                          ReferenceUtility.CalculateThisReference(handler, subscribeTo, _event.Signature));
                                handler.HandlerMethod = ReferenceUtility.MakeReference <ReferenceValueType_Method>(null,
                                                                                                                   ReferenceUtility.CalculateThisReference(handler, script2, methodSignature));
                                handler.Enabled = true;
                            }

                            //undo
                            {
                                var property = (Metadata.Property)script2.MetadataGetMemberBySignature("property:Code");
                                var undoItem = new UndoActionPropertiesChange.Item(script2, property, oldCode, new object[0]);
                                var action1  = new UndoActionPropertiesChange(new UndoActionPropertiesChange.Item[] { undoItem });

                                var action2 = new UndoActionComponentCreateDelete(document, new Component[] { handler }, true);

                                document.UndoSystem.CommitAction(new UndoMultiAction(new UndoSystem.Action[] { action1, action2 }));
                                document.Modified = true;
                            }
                        });
                        item.Tag = script;
                        childItems.Add(item);
                    }
                }

                groupItem.Items.Add(new KryptonContextMenuItems(childItems.ToArray()));
                items.Add(groupItem);
            }

            //Add Handler to Flow Graph
            {
                var groupItem  = new KryptonContextMenuItem(Translate("Add Handler to Flow Graph"), null);
                var childItems = new List <KryptonContextMenuItemBase>();

                //create new flow graph
                {
                    var itemsData = new List <(string, Component)>();
                    itemsData.Add((Translate("Add Flow Graph in This Component"), subscribeTo));
                    if (subscribeTo != subscribeTo.ParentRoot)
                    {
                        itemsData.Add((Translate("Add Flow Graph in the Root Component"), subscribeTo.ParentRoot));
                    }

                    foreach (var itemData in itemsData)
                    {
                        var childItem = new KryptonContextMenuItem(itemData.Item1, null, delegate(object s, EventArgs e2)
                        {
                            var parent = (Component)((KryptonContextMenuItem)s).Tag;

                            //create flow graph
                            var graph     = parent.CreateComponent <Component_FlowGraph>(enabled: false);
                            graph.Name    = graph.BaseType.GetUserFriendlyNameForInstance();
                            graph.Enabled = true;

                            //create node with handler
                            var node      = AddFlowGraphNode(graph, subscribeTo);
                            node.Position = new Vector2I(-20, -10);

                            //undo
                            var document = Owner.DocumentWindow.Document;
                            var action   = new UndoActionComponentCreateDelete(document, new Component[] { graph }, true);
                            document.UndoSystem.CommitAction(action);
                            document.Modified = true;

                            //activate flow graph window
                            EditorAPI.OpenDocumentWindowForObject(document, graph);
                        });
                        childItem.Tag = itemData.Item2;
                        childItems.Add(childItem);
                    }
                }

                //add handler to one of already created flow graph
                foreach (var graph in subscribeTo.ParentRoot.GetComponents <Component_FlowGraph>(false, true))
                {
                    if (graph.TypeSettingsIsPublic())
                    {
                        var text = string.Format(Translate("Add Handler to \'{0}\'"), graph.GetPathFromRoot(true));
                        var item = new KryptonContextMenuItem(text, null, delegate(object s, EventArgs e2)
                        {
                            var graph2 = (Component_FlowGraph)((KryptonContextMenuItem)s).Tag;

                            //create node with handler
                            var node = AddFlowGraphNode(graph2, subscribeTo);

                            //undo
                            var document = Owner.DocumentWindow.Document;
                            var action   = new UndoActionComponentCreateDelete(document, new Component[] { node }, true);
                            document.UndoSystem.CommitAction(action);
                            document.Modified = true;

                            //activate flow graph window
                            EditorAPI.OpenDocumentWindowForObject(document, graph2);
                        });
                        item.Tag = graph;
                        childItems.Add(item);
                    }
                }

                groupItem.Items.Add(new KryptonContextMenuItems(childItems.ToArray()));
                items.Add(groupItem);
            }

            ////add handler (component only)
            //{
            //	var item = new KryptonContextMenuItem( Translate( "Add handler (component only)" ), null, delegate ( object s, EventArgs e2 )
            //	{
            //		var newObjects = new List<Component>();

            //		var handler = subscribeTo.CreateComponent<Component_EventHandler>( enable: false );
            //		handler.Name = handler.BaseType.GetUserFriendlyNameForInstance() + " " + _event.Name;
            //		handler.Event = ReferenceUtility.MakeReference<ReferenceValueType_Event>( null,
            //			ReferenceUtility.CalculateThisReference( handler, subscribeTo, _event.Signature ) );
            //		handler.Enabled = true;
            //		newObjects.Add( handler );

            //		var document = Owner.DocumentWindow.Document;
            //		var action = new UndoActionComponentCreateDelete( document, newObjects, true );
            //		document.UndoSystem.CommitAction( action );
            //		document.Modified = true;

            //		Owner.DocumentWindow.SelectObjects( newObjects.ToArray() );
            //	} );
            //	item.Enabled = GetOneControlledObject<Component>() != null;
            //	items.Add( item );
            //}

            EditorContextMenu.Show(items, Owner);
        }
示例#7
0
        protected virtual void ToolPutTickPaint(Viewport viewport, double delta)
        {
            if (!GetToolPosition(viewport, out var selectedTerrain, out var position))
            {
                return;
            }

            var layer = DocumentWindow.TerrainPaintLayersGetSelected();

            if (layer == null)
            {
                return;
            }

            var toolRadius    = (float)Component_Scene_DocumentWindow.TerrainToolRadius;
            var toolHardness  = (float)Component_Scene_DocumentWindow.TerrainToolHardness;
            var toolShapeType = Component_Scene_DocumentWindow.TerrainToolShape;

            float strength = (float)(delta * Component_Scene_DocumentWindow.TerrainToolStrength * toolRadius * 0.5 * 2.0);

            Vector2 positionMin = position.ToVector2() - new Vector2(toolRadius, toolRadius);
            Vector2 positionMax = position.ToVector2() + new Vector2(toolRadius, toolRadius);

            List <Component_Terrain> terrains;

            //!!!!
            //if( selectedTerrain.HeightmapTerrainManager != null && HeightmapTerrainManager.Instance != null )
            //{
            //	terrains = HeightmapTerrainManager.Instance.GetTerrainsByArea( positionMin, positionMax, true );
            //}
            //else
            //{
            terrains = new List <Component_Terrain>();
            terrains.Add(selectedTerrain);
            //}

            foreach (var terrain in terrains)
            {
                UndoActionPropertiesChange undoSetPropertyAction = paintSetPropertyUndoActions.Find(a => a.Items[0].Obj == layer);
                var undoChangeAction = paintChangeUndoActions.Find(a => a.Terrain == terrain);

                Vector2I indexMin = terrain.GetMaskIndexByPosition(positionMin);
                Vector2I indexMax = terrain.GetMaskIndexByPosition(positionMax) + new Vector2I(1, 1);
                terrain.ClampMaskIndex(ref indexMin);
                terrain.ClampMaskIndex(ref indexMax);

                for (int y = indexMin.Y; y <= indexMax.Y; y++)
                {
                    for (int x = indexMin.X; x <= indexMax.X; x++)
                    {
                        Vector2 point = terrain.GetPositionXYByMaskIndex(new Vector2I(x, y));

                        float coef;
                        {
                            double length;
                            if (toolShapeType == ToolShape.Circle)
                            {
                                length = (point - position.ToVector2()).Length();
                            }
                            else
                            {
                                length = Math.Max(Math.Abs(point.X - position.X), Math.Abs(point.Y - position.Y));
                            }

                            if (length >= toolRadius)
                            {
                                coef = 0;
                            }
                            else if (length == 0)
                            {
                                coef = 1;
                            }
                            else if (length <= toolHardness * toolRadius)
                            {
                                coef = 1;
                            }
                            else
                            {
                                double c;
                                if (toolRadius - toolRadius * toolHardness != 0)
                                {
                                    c = (length - toolRadius * toolHardness) / (toolRadius - toolRadius * toolHardness);
                                }
                                else
                                {
                                    c = 0;
                                }
                                coef = (float)Math.Cos(Math.PI / 2 * c);
                            }
                        }

                        if (coef != 0)
                        {
                            float oldValue = layer.GetMaskValue(new Vector2I(x, y));

                            float value = oldValue;

                            //near corner (x == 0 or y == 0) take value from near terrain.
                            bool takeValueFromNearTerrain = false;
                            //!!!!
                            //if( selectedTerrain.HeightmapTerrainManager != null && HeightmapTerrainManager.Instance != null )
                            //{
                            //	if( x == 0 )
                            //	{
                            //		HeightmapTerrain terrain2 =
                            //			FindTerrainWithIndex( terrains, terrain.HeightmapTerrainManagerIndex - new Vector2I( 1, 0 ) );
                            //		if( terrain2 != null )
                            //		{
                            //			value = terrain2.GetHeight( terrain.GetPositionXY( new Vector2I( x, y ) ), false ) + terrain2.Position.Z;
                            //			value -= terrain.Position.Z;

                            //			takeValueFromNearTerrain = true;
                            //		}
                            //	}
                            //	else if( y == 0 )
                            //	{
                            //		HeightmapTerrain terrain2 =
                            //			FindTerrainWithIndex( terrains, terrain.HeightmapTerrainManagerIndex - new Vector2I( 0, 1 ) );
                            //		if( terrain2 != null )
                            //		{
                            //			value = terrain2.GetHeight( terrain.GetPositionXY( new Vector2I( x, y ) ), false ) + terrain2.Position.Z;
                            //			value -= terrain.Position.Z;

                            //			takeValueFromNearTerrain = true;
                            //		}
                            //	}
                            //}

                            if (!takeValueFromNearTerrain)
                            {
                                switch (mode)
                                {
                                case ModeEnum.PaintPaint:
                                case ModeEnum.PaintClear:
                                {
                                    bool paint = mode == ModeEnum.PaintPaint;
                                    if ((Form.ModifierKeys & Keys.Shift) != 0)
                                    {
                                        paint = !paint;
                                    }

                                    if (paint)
                                    {
                                        value = oldValue + strength * coef;
                                    }
                                    else
                                    {
                                        value = oldValue - strength * coef;
                                    }
                                }
                                break;

                                case ModeEnum.PaintSmooth:
                                {
                                    float needValue = 0;
                                    {
                                        needValue += layer.GetMaskValue(new Vector2I(x - 1, y));
                                        needValue += layer.GetMaskValue(new Vector2I(x + 1, y));
                                        needValue += layer.GetMaskValue(new Vector2I(x, y - 1));
                                        needValue += layer.GetMaskValue(new Vector2I(x, y + 1));
                                        //needValue += layer.GetMaskValue( GetClampedMaskIndex( terrain, new Vec2I( x - 1, y ) ) );
                                        //needValue += layer.GetMaskValue( GetClampedMaskIndex( terrain, new Vec2I( x + 1, y ) ) );
                                        //needValue += layer.GetMaskValue( GetClampedMaskIndex( terrain, new Vec2I( x, y - 1 ) ) );
                                        //needValue += layer.GetMaskValue( GetClampedMaskIndex( terrain, new Vec2I( x, y + 1 ) ) );
                                        needValue /= 4;
                                    }

                                    if (oldValue < needValue)
                                    {
                                        value = oldValue + strength * coef;
                                        if (value > needValue)
                                        {
                                            value = needValue;
                                        }
                                    }
                                    else if (oldValue > needValue)
                                    {
                                        value = oldValue - strength * coef;
                                        if (value < needValue)
                                        {
                                            value = needValue;
                                        }
                                    }
                                }
                                break;

                                case ModeEnum.PaintFlatten:
                                {
                                    float needValue = toolModifyStartMaskValue;

                                    if (oldValue < needValue)
                                    {
                                        value = oldValue + strength * coef;
                                        if (value > needValue)
                                        {
                                            value = needValue;
                                        }
                                    }
                                    else if (oldValue > needValue)
                                    {
                                        value = oldValue - strength * coef;
                                        if (value < needValue)
                                        {
                                            value = needValue;
                                        }
                                    }
                                }
                                break;
                                }
                            }

                            MathEx.Clamp(ref value, 0, 1);

                            if (oldValue != value)
                            {
                                //undo
                                if (layer.Mask.Value == null || layer.Mask.Value.Length == 0 || undoSetPropertyAction != null)
                                {
                                    if (undoSetPropertyAction == null)
                                    {
                                        var oldValue2 = layer.Mask;

                                        layer.Mask = new byte[terrain.GetPaintMaskSizeInteger() * terrain.GetPaintMaskSizeInteger()];

                                        var property = (Metadata.Property)layer.MetadataGetMemberBySignature("property:Mask");
                                        var undoItem = new UndoActionPropertiesChange.Item(layer, property, oldValue2);
                                        undoSetPropertyAction = new UndoActionPropertiesChange(undoItem);
                                        paintSetPropertyUndoActions.Add(undoSetPropertyAction);
                                    }
                                }
                                else
                                {
                                    if (undoChangeAction == null)
                                    {
                                        undoChangeAction = new Component_Terrain_PaintChangeUndoAction(terrain);
                                        paintChangeUndoActions.Add(undoChangeAction);
                                    }
                                    undoChangeAction.SaveValue(layer, new Vector2I(x, y), oldValue);
                                }

                                //update terrain
                                layer.SetMaskValue(new Vector2I(x, y), value);
                            }
                        }
                    }
                }

                //!!!!use mask indexes
                //var updateRectangle = new RectangleI( indexMin, indexMax );

                //terrain.UpdateRenderingData( updateRectangle, false );

                //bool foundItemForTerrain = false;
                //foreach( var updateItem in needUpdateRectangle )
                //{
                //	if( updateItem.Terrain == terrain )
                //	{
                //		updateItem.Rectangle.Add( updateRectangle );
                //		foundItemForTerrain = true;
                //		break;
                //	}
                //}
                //if( !foundItemForTerrain )
                //{
                //	NeedUpdateRectangleItem item = new NeedUpdateRectangleItem();
                //	item.Terrain = terrain;
                //	item.Rectangle = updateRectangle;
                //	needUpdateRectangle.Add( item );
                //}
            }
        }
        //private void Editor_TextChanged( object sender, EventArgs e )
        //{
        //if( disableTextChanged )
        //	return;

        //var newText = scriptEditorControl.Editor.Text;

        //if( Script.Code.Value != newText )
        //{
        //	var oldValue = Script.Code;

        //	//!!!!
        //	Script.DisableUpdate = true;

        //	Script.Code = newText;

        //	var undoItems = new List<UndoActionPropertiesChange.Item>();
        //	var property = (Metadata.Property)MetadataManager.GetTypeOfNetType(
        //		typeof( Component_CSharpScript ) ).MetadataGetMemberBySignature( "property:Code" );
        //	undoItems.Add( new UndoActionPropertiesChange.Item( Script, property, oldValue ) );

        //	var undoAction = new UndoActionPropertiesChange( undoItems );
        //	Document.CommitUndoAction( undoAction );

        //	//!!!!
        //	Log.Info( "undo added" );

        //	//!!!!
        //	scriptEditorControl.Editor.Document.UndoStack.ClearAll();
        //}
        //}

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (!IsHandleCreated || EditorUtility.IsDesignerHosted(this) || EditorAPI.ClosingApplication)
            {
                return;
            }

            var newValue = scriptEditorControl.Editor.Text;

            if (sentTextToEngineUndoSystem != newValue)
            {
                sentTextToEngineUndoSystem = newValue;

                var oldValue = Script.Code;

                //!!!!в опции редактора
                var time = 3.0;
                disableUpdateRestoreTime = EngineApp.GetSystemTime() + time;
                Script.DisableUpdate     = true;

                if (newValue != Script.Code.Value)
                {
                    //update Code
                    Script.Code = newValue;

                    //add undo
                    var undoItems = new List <UndoActionPropertiesChange.Item>();
                    var property  = (Metadata.Property)MetadataManager.GetTypeOfNetType(
                        typeof(Component_CSharpScript)).MetadataGetMemberBySignature("property:Code");
                    undoItems.Add(new UndoActionPropertiesChange.Item(Script, property, oldValue));
                    var undoAction = new UndoActionPropertiesChange(undoItems);
                    Document.CommitUndoAction(undoAction);
                }
            }

            if (disableUpdateRestoreTime != 0 && EngineApp.GetSystemTime() > disableUpdateRestoreTime)
            {
                Script.DisableUpdate     = false;
                disableUpdateRestoreTime = 0;

                //to refresh preview texture
                Script.RaiseCodeChangedEventAndSetNeedUpdate();
            }


            //scriptEditorControl.Editor.Document.UndoStack.ClearAll();

            ////check for update Script.Code
            //{
            //	var editor = scriptEditorControl.Editor;
            //	if( Script.Code.Value != editor.Text )
            //	{
            //		////var caret = editor.TextArea.Caret.Location;
            //		//var selectionStart = editor.SelectionStart;
            //		//var selectionLength = editor.SelectionLength;

            //		disableTextChanged = true;

            //		//xx xx;
            //		editor.Document.Text = Script.Code.Value;
            //		scriptEditorControl.Editor.Document.UndoStack.ClearAll();
            //		disableTextChanged = false;

            //		//try
            //		//{
            //		//	//editor.TextArea.Caret.Location = caret;
            //		//	editor.Select( selectionStart, selectionLength );
            //		//}
            //		//catch { }
            //	}
            //}
        }
        bool SetProperty()
        {
            //!!!!multiselection
            //!!!!!!also this support for different objects

            string referenceValue = SelectedReference;

            var netType        = setReferenceModeData.property.Type.GetNetType();
            var underlyingType = ReferenceUtility.GetUnderlyingType(netType);

            List <UndoActionPropertiesChange.Item> undoItems = null;

            if (documentWindow != null)
            {
                undoItems = new List <UndoActionPropertiesChange.Item>();
            }


            //!!!!try, catch? где еще

            foreach (var obj in setReferenceModeData.propertyOwners)
            {
                //object oldValue = null;
                //if( undoItems != null )
                var oldValue = setReferenceModeData.property.GetValue(obj, setReferenceModeData.propertyIndexes);

                object value = null;
                if (referenceValue == "")
                {
                    //reset reference with saving value for not components

                    var unrefOldValue = ReferenceUtility.GetUnreferencedValue(oldValue);
                    //Component specific: set null for Component
                    if (unrefOldValue as Component != null)
                    {
                        unrefOldValue = null;
                    }

                    value = ReferenceUtility.MakeReference(underlyingType, unrefOldValue, "");
                }
                else
                {
                    value = ReferenceUtility.MakeReference(underlyingType, null, referenceValue);
                }

                setReferenceModeData.property.SetValue(obj, value, setReferenceModeData.propertyIndexes);

                if (undoItems != null)
                {
                    var undoItem = new UndoActionPropertiesChange.Item(obj, setReferenceModeData.property, oldValue, setReferenceModeData.propertyIndexes);
                    undoItems.Add(undoItem);
                }
            }

            //undo
            if (undoItems != null && undoItems.Count != 0)
            {
                var action = new UndoActionPropertiesChange(undoItems.ToArray());
                documentWindow.Document.UndoSystem.CommitAction(action);
                documentWindow.Document.Modified = true;
            }

            return(true);
        }