diff --git a/CLEditor/CLEngine.Editor.csproj b/CLEditor/CLEngine.Editor.csproj index 1063f3778ef0d2c546a653d9941edc6b6d402eac..e26fbdd581377a0a4cd8a74bc8082dd15920f55c 100644 --- a/CLEditor/CLEngine.Editor.csproj +++ b/CLEditor/CLEngine.Editor.csproj @@ -433,6 +433,7 @@ NodeScriptWindow.xaml + @@ -446,6 +447,9 @@ CreateMapWindow.xaml + + CustomPropWindow.xaml + DataBaseWindow.xaml @@ -479,6 +483,9 @@ ScriptingEditorWindow.xaml + + SelectScriptWindow.xaml + SettingsWindow.xaml @@ -560,6 +567,10 @@ Designer MSBuild:Compile + + Designer + MSBuild:Compile + Designer MSBuild:Compile @@ -604,6 +615,10 @@ Designer MSBuild:Compile + + Designer + MSBuild:Compile + Designer MSBuild:Compile diff --git a/CLEditor/Project Templates/CLEngine.Core.xml b/CLEditor/Project Templates/CLEngine.Core.xml index bdb31d28b3c591533cea892619798440633559ab..19d274922a0cc593098719f2ba05f68f832945fb 100644 --- a/CLEditor/Project Templates/CLEngine.Core.xml +++ b/CLEditor/Project Templates/CLEngine.Core.xml @@ -325,14 +325,14 @@ 播放.mp3或.wav音频文件 - The relative path to the audio file + The relative path to the audio file Determine if the sound should loop 播放.mp3或.wav音频文件 - The relative path to the audio file + The relative path to the audio file diff --git a/CLEditor/core/EditorCommands.cs b/CLEditor/core/EditorCommands.cs index e07809f70b087ec50fe38b6716f2750dd650afe2..8ec6bdb2cb251e08e040064e527da1bd8e5db7f8 100644 --- a/CLEditor/core/EditorCommands.cs +++ b/CLEditor/core/EditorCommands.cs @@ -1,20 +1,20 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using System.Windows; +using System.Runtime.InteropServices.ComTypes; using System.Windows.Forms; -using System.Windows.Threading; -using CLEngine.Editor.controls; using CLEngine.Editor.model; using CLEngine.Editor.windows; using CLEngine.Core; using CLEngine.Core.framework; +using EnvDTE; using Clipboard = System.Windows.Clipboard; using MessageBox = System.Windows.Forms.MessageBox; +using Process = System.Diagnostics.Process; +using Thread = System.Threading.Thread; namespace CLEngine.Editor.core { @@ -26,25 +26,14 @@ namespace CLEngine.Editor.core { Directory.Delete(path, true); } - catch (Exception ex) + catch (Exception) { Thread.Sleep(1); DeleteDirectoryRecursively(path); } } - internal static void UpdatePropertyGrid() - { - if (EditorHandler.SelectedObjectPG != null) - { - EditorHandler.SelectedObjectPG.Dispatcher.BeginInvoke((Action)(() => - { - EditorHandler.SelectedObjectPG.Update(); - })); - } - } - - static object lockPaste = new object(); + static readonly object lockPaste = new object(); internal static void CopySelectedObjects() { lock (lockPaste) @@ -59,8 +48,19 @@ namespace CLEngine.Editor.core } } + internal static void UpdatePropertyGrid() + { + if (EditorHandler.SelectedObjectPG != null) + { + EditorHandler.SelectedObjectPG.Dispatcher.BeginInvoke((Action)(() => + { + EditorHandler.SelectedObjectPG.Update(); + })); + } + } + - internal static void PasteSelectedObjects() + internal static void PasteSelectedObjects() { lock (lockPaste) { @@ -70,7 +70,7 @@ namespace CLEngine.Editor.core if (list == null || list.Count == 0) return; EditorHandler.SelectedGameObjects.Clear(); - // verificar se tem um pai + foreach (var obj in list) { var parent = obj.Transform.Parent; @@ -83,8 +83,7 @@ namespace CLEngine.Editor.core } else { - var selected = EditorHandler.SceneTreeView.SelectedItem as DragDropTreeViewItem; - EditorHandler.SceneTreeView.AddGameObject(obj, string.Empty, false, true); + EditorHandler.SceneTreeView.AddGameObject(obj, string.Empty, false, true); } EditorHandler.SelectedGameObjects.Add(obj); @@ -103,23 +102,19 @@ namespace CLEngine.Editor.core // TODO: handle multiple selection if (EditorHandler.SelectedGameObjects.Count == 1) { - PropertyBox properties; + var properties = new PropertyBox {SelectedObject = EditorHandler.SelectedGameObjects[0]}; - properties = new PropertyBox(); - - properties.SelectedObject = EditorHandler.SelectedGameObjects[0] as GameObject; - EditorHandler.SelectedObjectPG = properties.PropertyGrid; + EditorHandler.SelectedObjectPG = properties.PropertyGrid; properties.ToggleExpand(); EditorHandler.PropertyGridContainer.Children.Add(properties); - if (EditorHandler.SelectedGameObjects[0] is GameObject) + if (EditorHandler.SelectedGameObjects[0] != null) { foreach (var component in EditorHandler.SelectedGameObjects[0].GetComponents()) { - properties = new PropertyBox(); - properties.SelectedObject = component; - properties.Title.Content += " (Component)"; + properties = new PropertyBox {SelectedObject = component}; + properties.Title.Content += " (Component)"; if (component.EditorExpanded) properties.ToggleExpand(); @@ -135,11 +130,9 @@ namespace CLEngine.Editor.core { for (int i = EditorHandler.PropertyGridContainer.Children.Count - 1; i >= 0; i--) { - if ((EditorHandler.PropertyGridContainer.Children[i] as PropertyBox).SelectedObject is ObjectComponent) + if ((EditorHandler.PropertyGridContainer.Children[i] as PropertyBox)?.SelectedObject is ObjectComponent) { - ObjectComponent component = (EditorHandler.PropertyGridContainer.Children[i] as PropertyBox).SelectedObject as ObjectComponent; - - if (component.Transform.GameObject.GetComponents().Find(o => o == component) == null) + if (((PropertyBox) EditorHandler.PropertyGridContainer.Children[i]).SelectedObject is ObjectComponent component && component.Transform.GameObject.GetComponents().Find(o => o == component) == null) EditorHandler.PropertyGridContainer.Children.RemoveAt(i); } } @@ -148,23 +141,25 @@ namespace CLEngine.Editor.core /// /// Loads a saved project /// + [SuppressMessage("ReSharper", "LocalizableElement")] + [SuppressMessage("ReSharper", "StringLiteralTypo")] internal static bool LoadProject() { - OpenFileDialog ofd = new OpenFileDialog(); - ofd.Title = "打开工程"; - ofd.Filter = @"(*.clengine)|*.clengine"; + OpenFileDialog ofd = new OpenFileDialog {Title = "打开工程", Filter = @"(*.clengine)|*.clengine"}; - if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) + if (ofd.ShowDialog() == DialogResult.OK) { LoadProject(ofd.FileName); - EditorCommands.AddToProjectHistory(ofd.FileName); + AddToProjectHistory(ofd.FileName); } - EditorCommands.ShowOutputMessage("工程加载成功"); + ShowOutputMessage("工程加载成功"); return false; } + [SuppressMessage("ReSharper", "LocalizableElement")] + [SuppressMessage("ReSharper", "StringLiteralTypo")] internal static bool LoadProject(string filename) { try @@ -263,7 +258,7 @@ namespace CLEngine.Editor.core /// internal static void ShowOutputMessage(string message) { - EditorHandler.OutputMessages.Add(new OutputMessage() { Time = DateTime.Now.ToString("HH:mm:ss").ToString(), Message = message.ToString() }); + EditorHandler.OutputMessages.Add(new OutputMessage() { Time = DateTime.Now.ToString("HH:mm:ss"), Message = message }); } /// @@ -284,16 +279,18 @@ namespace CLEngine.Editor.core /// /// /// + [SuppressMessage("ReSharper", "LocalizableElement")] internal static void SaveScene(bool saveAs) { if (SceneManager.ActiveScene == null) return; if (!File.Exists(SceneManager.ActiveScenePath)) { - SaveFileDialog sfd = new SaveFileDialog(); - sfd.InitialDirectory = SceneManager.GameProject.ProjectPath; - sfd.Filter = "(*.scene)|*.scene"; - DialogResult dr = sfd.ShowDialog(); + SaveFileDialog sfd = new SaveFileDialog + { + InitialDirectory = SceneManager.GameProject.ProjectPath, Filter = "(*.scene)|*.scene" + }; + DialogResult dr = sfd.ShowDialog(); if (dr == DialogResult.Yes || dr == DialogResult.OK) { @@ -320,6 +317,7 @@ namespace CLEngine.Editor.core /// /// 使用不同的线程保存当前项目 /// + [SuppressMessage("ReSharper", "StringLiteralTypo")] internal static void SaveProject() { if (SceneManager.GameProject != null) @@ -332,7 +330,7 @@ namespace CLEngine.Editor.core CHelper.SerializeObject(SceneManager.GameProject.ProjectPath + "\\_userPrefs.pgb", UserPreferences.Instance); }); - EditorCommands.ShowOutputMessage("Project Saved"); + ShowOutputMessage("Project Saved"); saveThread.Start(); } } @@ -340,6 +338,7 @@ namespace CLEngine.Editor.core /// /// /// + [SuppressMessage("ReSharper", "LocalizableElement")] internal static void DebugGame() { if (SceneManager.ActiveScene == null) @@ -374,7 +373,7 @@ namespace CLEngine.Editor.core CompilerWindow cf = new CompilerWindow(); cf.ShowDialog(); - if (cf.DialogResult.Value) return; + if (cf.DialogResult != null && cf.DialogResult.Value) return; // Update path dllpath = SceneManager.GameProject.ProjectPath + "\\bin\\" + (SceneManager.GameProject.Debug ? "Debug" : "Release") + "\\" + SceneManager.ScriptsAssembly.GetName().Name + ".dll"; @@ -384,19 +383,22 @@ namespace CLEngine.Editor.core try { - Process debug = new Process(); - debug.StartInfo.WorkingDirectory = SceneManager.GameProject.ProjectPath; - debug.StartInfo.FileName = SceneManager.GameProject.ProjectPath + "\\CLEngine.Windows.exe"; - debug.StartInfo.Arguments = ""; - debug.StartInfo.CreateNoWindow = true; - debug.Start(); + Process debug = new Process + { + StartInfo = + { + WorkingDirectory = SceneManager.GameProject.ProjectPath, + FileName = SceneManager.GameProject.ProjectPath + "\\CLEngine.Windows.exe", + Arguments = "", + CreateNoWindow = true + } + }; + debug.Start(); if (Properties.Settings.Default.AttachVisualStudio) { - EnvDTE.DTE vsInstance; - - // Try to restore the current project visual studio solution instance, returning it if successful - if (TryToRestoreSolution(out vsInstance)) + // Try to restore the current project visual studio solution instance, returning it if successful + if (TryToRestoreSolution(out var vsInstance)) { // Tries to attach the retrieved instance to the game debug process debug.Attach(vsInstance); @@ -448,7 +450,7 @@ namespace CLEngine.Editor.core /// /// the visual studio solution instance /// Whether the restore happened or not - internal static bool RestoreSolution(EnvDTE.DTE instance) + internal static bool RestoreSolution(DTE instance) { // if the instance is valid if (instance != null) @@ -465,10 +467,10 @@ namespace CLEngine.Editor.core /// /// The visual studio solution instance /// Whether the restore was successful or not - internal static bool TryToRestoreSolution(out EnvDTE.DTE instance) + internal static bool TryToRestoreSolution(out DTE instance) { // the visual studio instance - EnvDTE.DTE vsInstance; + DTE vsInstance; // if visual studio instance process Id is valid if (VisualStudioInstancePID != 0) @@ -512,18 +514,17 @@ namespace CLEngine.Editor.core /// /// Apply Blur Effect on the window /// - /// + /// internal static void ApplyBlurEffect(System.Windows.Window win) { - System.Windows.Media.Effects.BlurEffect objBlur = new System.Windows.Media.Effects.BlurEffect(); - objBlur.Radius = 4; - win.Effect = objBlur; + System.Windows.Media.Effects.BlurEffect objBlur = new System.Windows.Media.Effects.BlurEffect {Radius = 4}; + win.Effect = objBlur; } /// /// Remove Blur Effects /// - /// + /// internal static void ClearEffect(System.Windows.Window win) { win.Effect = null; @@ -532,41 +533,41 @@ namespace CLEngine.Editor.core public static class Extensions { - internal static void Attach(this System.Diagnostics.Process process, EnvDTE.DTE dte) + internal static void Attach(this Process process, DTE dte) { int tryCount = 5; while (tryCount-- > 0) { try { - EnvDTE.Processes processes = dte.Debugger.LocalProcesses; + var processes = dte.Debugger.LocalProcesses; foreach (EnvDTE.Process proc in processes.Cast().Where( - proc => proc.Name.IndexOf(process.ProcessName) != -1)) + proc => proc.Name.IndexOf(process.ProcessName, StringComparison.Ordinal) != -1)) { proc.Attach(); - Debug.WriteLine(String.Format - ("Attached to process {0} successfully.", process.ProcessName)); + Debug.WriteLine($"Attached to process {process.ProcessName} successfully."); break; } break; } catch (System.Runtime.InteropServices.COMException) { - System.Threading.Thread.Sleep(1000); + Thread.Sleep(1000); } } } - internal static EnvDTE.DTE GetInstance(string displayName) + internal static DTE GetInstance(string displayName) { //List names = new List(); //names.AddRange(from i in GetVisualStudioInstances() select i.Solution.FullName); - IEnumerable instances = GetVisualStudioInstances(); + IEnumerable instances = GetVisualStudioInstances(); - bool exists = instances.Any(x => x.Solution.FullName.Equals(displayName)); + var enumerable = instances as DTE[] ?? instances.ToArray(); + bool exists = enumerable.Any(x => x.Solution.FullName.Equals(displayName)); if (exists) - return instances.First(x => x.Solution.FullName.Equals(displayName)); + return enumerable.First(x => x.Solution.FullName.Equals(displayName)); return null; } @@ -575,33 +576,26 @@ namespace CLEngine.Editor.core /// Retrieve every visual studio instance /// /// List of visual studio instances - internal static IEnumerable GetVisualStudioInstances() + internal static IEnumerable GetVisualStudioInstances() { - System.Runtime.InteropServices.ComTypes.IRunningObjectTable rot; - System.Runtime.InteropServices.ComTypes.IEnumMoniker enumMoniker; - int retVal = GetRunningObjectTable(0, out rot); + int retVal = GetRunningObjectTable(0, out var rot); if (retVal == 0) { - rot.EnumRunning(out enumMoniker); + rot.EnumRunning(out var enumMoniker); IntPtr fetched = IntPtr.Zero; - System.Runtime.InteropServices.ComTypes.IMoniker[] moniker = new System.Runtime.InteropServices.ComTypes.IMoniker[1]; + var moniker = new IMoniker[1]; while (enumMoniker.Next(1, moniker, fetched) == 0) { - System.Runtime.InteropServices.ComTypes.IBindCtx bindCtx; - CreateBindCtx(0, out bindCtx); - string displayName; - moniker[0].GetDisplayName(bindCtx, null, out displayName); + CreateBindCtx(0, out var bindCtx); + moniker[0].GetDisplayName(bindCtx, null, out var displayName); //Console.Info("Display Name: {0}", displayName); bool isVisualStudio = displayName.StartsWith("!VisualStudio"); if (isVisualStudio) { - int currentProcessId = int.Parse(displayName.Split(':')[1]); - - object obj; - rot.GetObject(moniker[0], out obj); - var dte = obj as EnvDTE.DTE; + rot.GetObject(moniker[0], out var obj); + var dte = obj as DTE; yield return dte; } } @@ -614,29 +608,24 @@ namespace CLEngine.Editor.core /// Visual Studio instance PID /// Visual Studio instance if able to found. Null otherwise. /// Whether the visual studio instance was found or not. - internal static bool TryToRetrieveVSInstance(int processId, out EnvDTE.DTE instance) + internal static bool TryToRetrieveVSInstance(int processId, out DTE instance) { IntPtr numFetched = IntPtr.Zero; - System.Runtime.InteropServices.ComTypes.IRunningObjectTable runningObjectTable; - System.Runtime.InteropServices.ComTypes.IEnumMoniker monikerEnumerator; - System.Runtime.InteropServices.ComTypes.IMoniker[] monikers = new System.Runtime.InteropServices.ComTypes.IMoniker[1]; + var monikers = new IMoniker[1]; - GetRunningObjectTable(0, out runningObjectTable); - runningObjectTable.EnumRunning(out monikerEnumerator); + GetRunningObjectTable(0, out var runningObjectTable); + runningObjectTable.EnumRunning(out var monikerEnumerator); monikerEnumerator.Reset(); while (monikerEnumerator.Next(1, monikers, numFetched) == 0) { - System.Runtime.InteropServices.ComTypes.IBindCtx ctx; - CreateBindCtx(0, out ctx); + CreateBindCtx(0, out var ctx); - string runningObjectName; - monikers[0].GetDisplayName(ctx, null, out runningObjectName); + monikers[0].GetDisplayName(ctx, null, out var runningObjectName); - object runningObjectVal; - runningObjectTable.GetObject(monikers[0], out runningObjectVal); + runningObjectTable.GetObject(monikers[0], out var runningObjectVal); - if (runningObjectVal is EnvDTE.DTE && runningObjectName.StartsWith("!VisualStudio")) + if (runningObjectVal is DTE dte && runningObjectName.StartsWith("!VisualStudio")) { // retrieve process id - "process_name:pid" int currentProcessId = int.Parse(runningObjectName.Split(':')[1]); @@ -644,7 +633,7 @@ namespace CLEngine.Editor.core // 如果它是匹配的 if (currentProcessId == processId) { - instance = (EnvDTE.DTE)runningObjectVal; + instance = dte; return true; } } @@ -655,9 +644,9 @@ namespace CLEngine.Editor.core } [System.Runtime.InteropServices.DllImport("ole32.dll")] - private static extern void CreateBindCtx(int reserved, out System.Runtime.InteropServices.ComTypes.IBindCtx ppbc); + private static extern void CreateBindCtx(int reserved, out IBindCtx ppbc); [System.Runtime.InteropServices.DllImport("ole32.dll")] - private static extern int GetRunningObjectTable(int reserved, out System.Runtime.InteropServices.ComTypes.IRunningObjectTable prot); + private static extern int GetRunningObjectTable(int reserved, out IRunningObjectTable prot); } } \ No newline at end of file diff --git a/CLEditor/core/EditorHandler.cs b/CLEditor/core/EditorHandler.cs index 63b4d9f750ebcf8ea543127347680ef431d24de3..2ec3de0a9499aedbf51e18568359c25faf1b48ae 100644 --- a/CLEditor/core/EditorHandler.cs +++ b/CLEditor/core/EditorHandler.cs @@ -1,12 +1,8 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Forms; -using System.Windows.Media; -using CLEngine.Editor.controls; using CLEngine.Editor.graphics_device; using CLEngine.Editor.model; using CLEngine.Editor.windows; @@ -17,16 +13,9 @@ namespace CLEngine.Editor.core { public static class EditorHandler { - internal static Xceed.Wpf.Toolkit.PropertyGrid.PropertyGrid SelectedObjectPG = null; + internal static PropertyGrid SelectedObjectPG = null; - private static ObservableCollection outputMessages = new ObservableCollection(); - public static ObservableCollection OutputMessages - { - get - { - return outputMessages; - } - } + public static ObservableCollection OutputMessages { get; } = new ObservableCollection(); private static PicturePreview picturePreview; internal static PicturePreview PicturePreview @@ -35,9 +24,8 @@ namespace CLEngine.Editor.core { if (picturePreview == null) { - picturePreview = new PicturePreview(); - picturePreview.ShowInTaskbar = false; - //picturePreview.Topmost = true; + picturePreview = new PicturePreview {ShowInTaskbar = false}; + //picturePreview.Topmost = true; } return picturePreview; @@ -65,8 +53,7 @@ namespace CLEngine.Editor.core { PropertyGridContainer.Children.Clear(); - PropertyBox properties = new PropertyBox(); - properties.SelectedObject = value; + PropertyBox properties = new PropertyBox {SelectedObject = value}; properties.ToggleExpand(); diff --git a/CLEditor/core/EditorUtils.cs b/CLEditor/core/EditorUtils.cs index 8f68ac2019d3da5ca81a96a058220b2378bc31f7..58ec46a027e85e78af70967efda21399306a3832 100644 --- a/CLEditor/core/EditorUtils.cs +++ b/CLEditor/core/EditorUtils.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Windows; using System.Windows.Controls; @@ -13,20 +14,7 @@ namespace CLEngine.Editor.core { public static class EditorUtils { - public static BitmapSource ConvertBitmapToSource96DPI(BitmapImage bitmapImage) - { - double dpi = 96; - int width = bitmapImage.PixelWidth; - int height = bitmapImage.PixelHeight; - - int stride = width * 4; // 4 bytes per pixel - byte[] pixelData = new byte[stride * height]; - bitmapImage.CopyPixels(pixelData, stride, 0); - - return BitmapSource.Create(width, height, dpi, dpi, PixelFormats.Bgra32, null, pixelData, stride); - } - - public static BitmapImage ConvertBitmapToImage96DPI(BitmapImage bitmapImage) + public static BitmapImage ConvertBitmapToImage96DPI(BitmapImage bitmapImage) { double dpi = 96; int width = bitmapImage.PixelWidth; @@ -54,36 +42,49 @@ namespace CLEngine.Editor.core return bImg; } - internal static CMenuItem CreateMenuItem(string text, ImageSource imageSource = null) - { - CMenuItem menuItem = new CMenuItem(); + internal static StackPanel CreateHeader(string text, ImageSource imageSource) + { + StackPanel stackPanel = new StackPanel(); + stackPanel.Orientation = Orientation.Horizontal; + if (imageSource != null) + stackPanel.Children.Add(new Image() { Source = imageSource, Margin = new Thickness(0, 0, 4, 0) }); + stackPanel.Children.Add(new TextBlock() { Text = text }); - menuItem.Header = text; + return stackPanel; + } - if (imageSource != null) - menuItem.Icon = new Image() { Source = imageSource, HorizontalAlignment = HorizontalAlignment.Center }; + public static BitmapSource ConvertBitmapToSource96DPI(BitmapImage bitmapImage) + { + double dpi = 96; + int width = bitmapImage.PixelWidth; + int height = bitmapImage.PixelHeight; - return menuItem; - } + int stride = width * 4; // 4 bytes per pixel + byte[] pixelData = new byte[stride * height]; + bitmapImage.CopyPixels(pixelData, stride, 0); - internal static StackPanel CreateHeader(string text, ImageSource imageSource) + return BitmapSource.Create(width, height, dpi, dpi, PixelFormats.Bgra32, null, pixelData, stride); + } + + internal static CMenuItem CreateMenuItem(string text, ImageSource imageSource = null) { - StackPanel stackPanel = new StackPanel(); - stackPanel.Orientation = Orientation.Horizontal; - if (imageSource != null) - stackPanel.Children.Add(new Image() { Source = imageSource, Margin = new Thickness(0, 0, 4, 0) }); - stackPanel.Children.Add(new TextBlock() { Text = text }); + CMenuItem menuItem = new CMenuItem {Header = text}; + - return stackPanel; + if (imageSource != null) + menuItem.Icon = new Image() { Source = imageSource, HorizontalAlignment = HorizontalAlignment.Center }; + + return menuItem; } internal static DependencyObject GetParent(DependencyObject obj, int levels = 1) { - DependencyObject result = obj, t; + DependencyObject result = obj; - for (int i = 0; i < levels; i++) + for (int i = 0; i < levels; i++) { - if ((t = VisualTreeHelper.GetParent(result)) == null) + DependencyObject t; + if ((t = VisualTreeHelper.GetParent(result)) == null) break; result = t; @@ -103,8 +104,7 @@ namespace CLEngine.Editor.core while (parent != null) { - TObject found = parent as TObject; - if (found != null) + if (parent is TObject found) { return found; } @@ -124,9 +124,9 @@ namespace CLEngine.Editor.core for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) { DependencyObject child = VisualTreeHelper.GetChild(depObj, i); - if (child != null && child is T) + if (child is T dependencyObject) { - yield return (T)child; + yield return dependencyObject; } foreach (T childOfChild in FindVisualChildren(child)) @@ -138,20 +138,12 @@ namespace CLEngine.Editor.core } - private static Dictionary installedApps = new Dictionary(); - internal static Dictionary InstalledApps - { - get { return installedApps; } - - private set { installedApps = value; } - } + internal static Dictionary InstalledApps { get; } = new Dictionary(); internal static void StoreInstalledApplications() { - string keyName; - - // store: CurrentUser - keyName = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"; + // store: CurrentUser + var keyName = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"; StoreSubKey(Registry.CurrentUser, keyName); // store: LocalMachine_32 @@ -163,25 +155,23 @@ namespace CLEngine.Editor.core StoreSubKey(Registry.LocalMachine, keyName); } + [SuppressMessage("ReSharper", "ConvertToUsingDeclaration")] private static void StoreSubKey(RegistryKey root, string subKeyName) { - RegistryKey subkey; - string displayName; - string pathName; - - using (RegistryKey key = root.OpenSubKey(subKeyName)) + using (RegistryKey key = root.OpenSubKey(subKeyName)) { if (key != null) { foreach (string kn in key.GetSubKeyNames()) { - using (subkey = key.OpenSubKey(kn)) + RegistryKey subkey; + using (subkey = key.OpenSubKey(kn)) { - displayName = (subkey.GetValue("DisplayName") as string); - pathName = (subkey.GetValue("InstallLocation") as string); + var displayName = (subkey?.GetValue("DisplayName") as string); + var pathName = (subkey?.GetValue("InstallLocation") as string); - if (displayName != null && displayName != string.Empty && !installedApps.ContainsKey(displayName)) - installedApps.Add(displayName, pathName); + if (!string.IsNullOrEmpty(displayName) && !InstalledApps.ContainsKey(displayName)) + InstalledApps.Add(displayName, pathName); //if (displayName != null && displayName.Replace(" ", "").ToLower().Contains(p_name.ToLower())) //return true; @@ -199,7 +189,7 @@ namespace CLEngine.Editor.core /// internal static bool CheckVisualStudioExistance(string version) { - string src = string.Empty; + string src; switch (version) { case "VisualStudio2015": @@ -221,7 +211,8 @@ namespace CLEngine.Editor.core // break; } - using (Microsoft.Win32.RegistryKey Key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\" + src)) + var Key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\" + src); + using (Key) if (Key != null) { return true; @@ -251,8 +242,8 @@ namespace CLEngine.Editor.core } else { - double ratioX = (double)maxWidth / (double)image.Width; - double ratioY = (double)maxHeight / (double)image.Height; + double ratioX = maxWidth / image.Width; + double ratioY = maxHeight / image.Height; // use whichever multiplier is smaller double ratio = ratioX < ratioY ? ratioX : ratioY; @@ -271,14 +262,14 @@ namespace CLEngine.Editor.core internal static void SelectAnotherElement(DependencyObject obj) where T : FrameworkElement { - FrameworkElement parent = (FrameworkElement)(obj as T).Parent; - while (parent != null && parent is IInputElement && !((IInputElement)parent).Focusable) + FrameworkElement parent = (FrameworkElement)(obj as T)?.Parent; + while (parent != null && !((IInputElement)parent).Focusable) { parent = (FrameworkElement)parent.Parent; } - DependencyObject scope = FocusManager.GetFocusScope((obj as T)); - FocusManager.SetFocusedElement(scope, parent as IInputElement); + DependencyObject scope = FocusManager.GetFocusScope((obj as T) ?? throw new InvalidOperationException()); + FocusManager.SetFocusedElement(scope, parent); } internal static bool isDirectory(string fullPath) diff --git a/CLEditor/core/InsertionAdorner.cs b/CLEditor/core/InsertionAdorner.cs index 4e2ed3daebc33c0dbbb33303e4d1ee2349902a18..f61f71dc3341ea4c359e752cbaaad3601be4e1d6 100644 --- a/CLEditor/core/InsertionAdorner.cs +++ b/CLEditor/core/InsertionAdorner.cs @@ -6,11 +6,11 @@ namespace CLEngine.Editor.core { public class InsertionAdorner : Adorner { - private bool isSeparatorHorizontal; + private readonly bool isSeparatorHorizontal; public bool IsInFirstHalf { get; set; } - private AdornerLayer adornerLayer; - private static Pen pen; - private static PathGeometry triangle; + private readonly AdornerLayer adornerLayer; + private static readonly Pen pen; + private static readonly PathGeometry triangle; // Create the pen and triangle in a static constructor and freeze them to improve performance. static InsertionAdorner() @@ -37,9 +37,9 @@ namespace CLEngine.Editor.core : base(adornedElement) { this.isSeparatorHorizontal = isSeparatorHorizontal; - this.IsInFirstHalf = isInFirstHalf; + IsInFirstHalf = isInFirstHalf; this.adornerLayer = adornerLayer; - this.IsHitTestVisible = false; + IsHitTestVisible = false; this.adornerLayer.Add(this); } @@ -47,13 +47,10 @@ namespace CLEngine.Editor.core // This draws one line and two triangles at each end of the line. protected override void OnRender(DrawingContext drawingContext) { - Point startPoint; - Point endPoint; - - CalculateStartAndEndPoint(out startPoint, out endPoint); + CalculateStartAndEndPoint(out var startPoint, out var endPoint); drawingContext.DrawLine(pen, startPoint, endPoint); - if (this.isSeparatorHorizontal) + if (isSeparatorHorizontal) { DrawTriangle(drawingContext, startPoint, 0); DrawTriangle(drawingContext, endPoint, 180); @@ -81,13 +78,13 @@ namespace CLEngine.Editor.core startPoint = new Point(); endPoint = new Point(); - double width = this.AdornedElement.RenderSize.Width; - double height = this.AdornedElement.RenderSize.Height; + double width = AdornedElement.RenderSize.Width; + double height = AdornedElement.RenderSize.Height; - if (this.isSeparatorHorizontal) + if (isSeparatorHorizontal) { endPoint.X = width; - if (!this.IsInFirstHalf) + if (!IsInFirstHalf) { startPoint.Y = height; endPoint.Y = height; @@ -96,7 +93,7 @@ namespace CLEngine.Editor.core else { endPoint.Y = height; - if (!this.IsInFirstHalf) + if (!IsInFirstHalf) { startPoint.X = width; endPoint.X = width; @@ -106,7 +103,7 @@ namespace CLEngine.Editor.core public void Detach() { - this.adornerLayer.Remove(this); + adornerLayer.Remove(this); } } } \ No newline at end of file diff --git a/CLEditor/core/LayoutHelper.cs b/CLEditor/core/LayoutHelper.cs index 2faf303bcbf40fe76a91409755b59e28cf45ff11..360a3bc070a1be76be8710d66ef3aa3a4cac3127 100644 --- a/CLEditor/core/LayoutHelper.cs +++ b/CLEditor/core/LayoutHelper.cs @@ -11,7 +11,7 @@ namespace CLEngine.Editor.core private const string layoutPath = @".\Layout\"; private const string layoutExtension = ".layout"; - public static string LayoutExtension { get { return layoutExtension; } } + public static string LayoutExtension => layoutExtension; public static DockingManager DockManager { get; set; } @@ -51,7 +51,7 @@ namespace CLEngine.Editor.core { layoutName = layoutName.Trim(); string path = layoutPath + layoutName + layoutExtension; - if (System.IO.File.Exists(path)) + if (File.Exists(path)) return true; return false; } @@ -87,7 +87,7 @@ namespace CLEngine.Editor.core try { EditorCommands.ShowOutputMessage("试图保存布局"); - var serializer = new Xceed.Wpf.AvalonDock.Layout.Serialization.XmlLayoutSerializer(DockManager); + var serializer = new XmlLayoutSerializer(DockManager); using (var stream = new StreamWriter(layoutPath + layoutName + LayoutExtension)) serializer.Serialize(stream); @@ -107,9 +107,9 @@ namespace CLEngine.Editor.core { List Layouts = new List(); - foreach (var layout in System.IO.Directory.GetFiles(layoutPath, "*.layout")) + foreach (var layout in Directory.GetFiles(layoutPath, "*.layout")) { - string name = System.IO.Path.GetFileNameWithoutExtension(layout); + string name = Path.GetFileNameWithoutExtension(layout); if (!name.Equals("Default")) Layouts.Add(name); } @@ -130,7 +130,7 @@ namespace CLEngine.Editor.core if (LayoutExists(layoutName)) try { - System.IO.File.Delete(layoutPath + layoutName + layoutExtension); + File.Delete(layoutPath + layoutName + layoutExtension); if (Properties.Settings.Default.Layout == layoutName) { Properties.Settings.Default.Layout = string.Empty; diff --git a/CLEditor/core/Page.cs b/CLEditor/core/Page.cs index 75d8bf63822356d365d022ad9eacdbf825247348..f64657947040ef84c75a86b9ea603a3ea1b663e3 100644 --- a/CLEditor/core/Page.cs +++ b/CLEditor/core/Page.cs @@ -14,14 +14,14 @@ public Page() { - this.Subtitle = string.Empty; - this.Description = string.Empty; + Subtitle = string.Empty; + Description = string.Empty; } public Page(string subtitle, string description, string picturePath) { - this.Subtitle = subtitle; - this.Description = description; - this.PicturePath = picturePath; + Subtitle = subtitle; + Description = description; + PicturePath = picturePath; } #endregion diff --git a/CLEditor/core/TreeViewExtension.cs b/CLEditor/core/TreeViewExtension.cs index 300cbb300c8950881ed7040cf9fca6f30db99a5d..21325b07cb20e3b6900621605eb5f3f910e1e3d0 100644 --- a/CLEditor/core/TreeViewExtension.cs +++ b/CLEditor/core/TreeViewExtension.cs @@ -11,18 +11,18 @@ namespace CLEngine.Editor.core { public class TreeViewExtension : DependencyObject { - public static bool GetEnableMultiSelect(DependencyObject obj) - { - return (bool)obj.GetValue(EnableMultiSelectProperty); - } - - public static void SetEnableMultiSelect(DependencyObject obj, bool value) + public static void SetEnableMultiSelect(DependencyObject obj, bool value) { obj.SetValue(EnableMultiSelectProperty, value); } - // Using a DependencyProperty as the backing store for EnableMultiSelect. This enables animation, styling, binding, etc... - public static readonly DependencyProperty EnableMultiSelectProperty = + public static bool GetEnableMultiSelect(DependencyObject obj) + { + return (bool)obj.GetValue(EnableMultiSelectProperty); + } + + // Using a DependencyProperty as the backing store for EnableMultiSelect. This enables animation, styling, binding, etc... + public static readonly DependencyProperty EnableMultiSelectProperty = DependencyProperty.RegisterAttached("EnableMultiSelect", typeof(bool), typeof(TreeViewExtension), new FrameworkPropertyMetadata(false) { PropertyChangedCallback = EnableMultiSelectChanged, @@ -64,15 +64,15 @@ namespace CLEngine.Editor.core var isEnabled = (bool)args.NewValue; if (wasEnable) { - tree.RemoveHandler(TreeViewItem.PreviewMouseUpEvent, new MouseButtonEventHandler(ItemClicked)); - tree.RemoveHandler(TreeViewItem.PreviewMouseDownEvent, new MouseButtonEventHandler(ItemDown)); - tree.RemoveHandler(TreeView.KeyDownEvent, new KeyEventHandler(KeyDown)); + tree.RemoveHandler(UIElement.PreviewMouseUpEvent, new MouseButtonEventHandler(ItemClicked)); + tree.RemoveHandler(UIElement.PreviewMouseDownEvent, new MouseButtonEventHandler(ItemDown)); + tree.RemoveHandler(UIElement.KeyDownEvent, new KeyEventHandler(KeyDown)); } if (isEnabled) { - tree.AddHandler(TreeViewItem.PreviewMouseUpEvent, new MouseButtonEventHandler(ItemClicked)); - tree.AddHandler(TreeViewItem.PreviewMouseDownEvent, new MouseButtonEventHandler(ItemDown), true); - tree.AddHandler(TreeView.KeyDownEvent, new KeyEventHandler(KeyDown)); + tree.AddHandler(UIElement.PreviewMouseUpEvent, new MouseButtonEventHandler(ItemClicked)); + tree.AddHandler(UIElement.PreviewMouseDownEvent, new MouseButtonEventHandler(ItemDown), true); + tree.AddHandler(UIElement.KeyDownEvent, new KeyEventHandler(KeyDown)); } } @@ -87,8 +87,6 @@ namespace CLEngine.Editor.core { TreeViewItem item = FindTreeViewItem(e.OriginalSource); MakeSingleSelection(GetTree(item), item); - - return; } } @@ -132,18 +130,16 @@ namespace CLEngine.Editor.core if (!GetIsSelected(item)) // item is already selected? MakeSingleSelection(tree, item); - - return; } } public static TreeView GetTree(TreeViewItem item) { - Func getParent = (o) => VisualTreeHelper.GetParent(o); - FrameworkElement currentItem = item; - while (!(getParent(currentItem) is TreeView)) - currentItem = (FrameworkElement)getParent(currentItem); - return (TreeView)getParent(currentItem); + DependencyObject GetParent(DependencyObject o) => VisualTreeHelper.GetParent(o); + FrameworkElement currentItem = item; + while (!(GetParent(currentItem) is TreeView)) + currentItem = (FrameworkElement)GetParent(currentItem); + return (TreeView)GetParent(currentItem); } static void RealSelectedChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) @@ -188,8 +184,8 @@ namespace CLEngine.Editor.core DependencyObject dpObj = obj as DependencyObject; if (dpObj == null) return null; - if (dpObj is TreeViewItem) - return (TreeViewItem)dpObj; + if (dpObj is TreeViewItem item) + return item; return FindTreeViewItem(VisualTreeHelper.GetParent(dpObj)); } @@ -212,14 +208,10 @@ namespace CLEngine.Editor.core if (GetAnchorItem(tree) == null) { var selectedItems = GetSelectedTreeViewItems(tree); - if (selectedItems.Count > 0) - { - SetAnchorItem(tree, selectedItems[selectedItems.Count - 1]); - } - else - { - SetAnchorItem(tree, GetExpandedTreeViewItems(tree).Skip(3).FirstOrDefault()); - } + SetAnchorItem(tree, + selectedItems.Count > 0 + ? selectedItems[selectedItems.Count - 1] + : GetExpandedTreeViewItems(tree).Skip(3).FirstOrDefault()); if (GetAnchorItem(tree) == null) { return; @@ -230,7 +222,6 @@ namespace CLEngine.Editor.core var items = GetExpandedTreeViewItems(tree); bool betweenBoundary = false; - bool end = false; foreach (var item in items) { bool isBoundary = item == anchor || item == actionItem; @@ -242,7 +233,7 @@ namespace CLEngine.Editor.core SetIsSelected(item, true); else if (clearCurrent) - SetIsSelected(item, false); + SetIsSelected(item, false); else break; @@ -251,21 +242,16 @@ namespace CLEngine.Editor.core public static List GetSelectedTreeViewItems(TreeView tree) { - return GetExpandedTreeViewItems(tree).Where(i => GetIsSelected(i)).ToList(); + return GetExpandedTreeViewItems(tree).Where(GetIsSelected).ToList(); } private static void MakeSingleSelection(TreeView tree, TreeViewItem item) { foreach (TreeViewItem selectedItem in GetExpandedTreeViewItems(tree)) { - if (selectedItem == null) + if (selectedItem == null) continue; - if (selectedItem != item) - SetIsSelected(selectedItem, false); - else - { - SetIsSelected(selectedItem, true); - } + SetIsSelected(selectedItem, selectedItem == item); } UpdateAnchorAndActionItem(tree, item); } diff --git a/CLEditor/core/converts/EditorImageConvert.cs b/CLEditor/core/converts/EditorImageConvert.cs index 594f72ab80e9d48c459a635757786719b1796d02..5732ed8461658d3a27945ade87516e89635963df 100644 --- a/CLEditor/core/converts/EditorImageConvert.cs +++ b/CLEditor/core/converts/EditorImageConvert.cs @@ -18,13 +18,38 @@ namespace CLEngine.Editor.core.converts { // 先转绝对路径 var relativePath = Path.Combine(SceneManager.GameProject.ProjectPath, path); - return new BitmapImage(new Uri(relativePath, UriKind.Absolute)); - } + + return InitImage(relativePath); + } return null; } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + /// + /// 解决不同进程读取同一张图片的问题 + /// + /// + /// + private BitmapImage InitImage(string filePath) + { + BitmapImage bitmapImage; + using (var reader = new BinaryReader(File.Open(filePath, FileMode.Open))) + { + var fi = new FileInfo(filePath); + byte[] bytes = reader.ReadBytes((int)fi.Length); + reader.Close(); + + bitmapImage = new BitmapImage(); + bitmapImage.BeginInit(); + bitmapImage.StreamSource = new MemoryStream(bytes); + bitmapImage.EndInit(); + bitmapImage.CacheOption = BitmapCacheOption.OnLoad; + reader.Dispose(); + } + return bitmapImage; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } diff --git a/CLEditor/graphics_device/SceneViewGameControl.cs b/CLEditor/graphics_device/SceneViewGameControl.cs index 42f331c77809790ee32560586344abb15fe1f9f1..09eeb777e9e7583652988a8bc7db3ffc7f28a69b 100644 --- a/CLEditor/graphics_device/SceneViewGameControl.cs +++ b/CLEditor/graphics_device/SceneViewGameControl.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.IO; -using System.Linq; using System.Runtime.InteropServices; using System.Windows.Forms; using CLEngine.Editor.core; @@ -34,10 +34,10 @@ namespace CLEngine.Editor.graphics_device private const int HANDLER_SIZE = 24; private const int AXIS_OFFSET = 65; private const int AXIS_OPT_SIZE = 18; - private bool usingYAxis = false; - private bool usingXAxis = false; - private bool hoverYAxis = false; - private bool hoverXAxis = false; + private bool usingYAxis; + private bool usingXAxis; + private bool hoverYAxis; + private bool hoverXAxis; private EditorMapModes editorMapMode = EditorMapModes.None; private EditorModes editorMode = EditorModes.Select; @@ -48,24 +48,24 @@ namespace CLEngine.Editor.graphics_device private Rectangle selectionArea; private ContentManager content; private SpriteBatch spriteBatch; - private bool initialized = false; + private bool initialized; private BitmapFontRenderer bmFontRenderer; private Vector2 selectionStart; private Vector2 selectionEnd; private Vector2 mouseLastPosition = Vector2.Zero; - private bool takingScreenshot = false; + private bool takingScreenshot; private bool lastLeftKeyState; private float delta; private float scrollerValue; - private bool tilesetDragStarted = false; + private bool tilesetDragStarted; private Vector2 tilesetMouseDownPos; private Rectangle tilesetSelectedArea; private Vector2 panStart; private Tile[,] memTiles; private bool objectHandled; - private bool mouseDragStarted = false; + private bool mouseDragStarted; private Dictionary objectIcons = new Dictionary(); private List sceneGameObjects = new List(); @@ -125,10 +125,10 @@ namespace CLEngine.Editor.graphics_device set { editorMapMode = value; } } - private bool selectionStarted = false; + private bool selectionStarted; private Vector2 panMouseLastPos; private bool panStarted; - private bool leftMouseKeyStateChanged = false; + private bool leftMouseKeyStateChanged; public bool LeftMouseKeyPressed { get; set; } private Vector2 mouseClickPosition = Vector2.Zero; @@ -191,7 +191,7 @@ namespace CLEngine.Editor.graphics_device } } - Vector2 controlPosition; + public Vector2 controlPosition; protected override void Update(GameTime gameTime) { @@ -226,7 +226,7 @@ namespace CLEngine.Editor.graphics_device if (SceneManager.ActiveScene != null) { - if (this.Focusable) + if (Focusable) { // Update list of gameObjects: sceneGameObjects = GameObject.GetAllGameObjects(); @@ -242,7 +242,7 @@ namespace CLEngine.Editor.graphics_device public void Input(GameTime gameTime) { - delta = (float)gameTime.ElapsedGameTime.Milliseconds; + delta = gameTime.ElapsedGameTime.Milliseconds; if (GameInput.IsKeyDown(Keys.LeftShift)) delta *= 3; //Console.Info(MousePosition.X); @@ -435,7 +435,7 @@ namespace CLEngine.Editor.graphics_device { foreach (GameObject gameObject in EditorHandler.SelectedGameObjects) { - beforeState[gameObject] = (Transform)gameObject.Transform.DeepCopy(); + beforeState[gameObject] = gameObject.Transform.DeepCopy(); beforeState[gameObject].GameObject = new GameObject(); } } @@ -675,11 +675,7 @@ namespace CLEngine.Editor.graphics_device } else { - float dx = (gameObject.Transform.Position.X - mouseWorldPosition.X) - (gameObject.Transform.Position.X - mouseClickPosition.X); - float dy = (gameObject.Transform.Position.Y - mouseWorldPosition.Y) - (gameObject.Transform.Position.Y - mouseClickPosition.Y); - float h = (dx * dx) + (dy * dy); - - gameObject.Transform.Scale = new Vector2(Math.Abs((gameObject.Transform.Position.X - mouseWorldPosition.X) * beforeState[gameObject].Scale.X / (gameObject.Transform.Position.X - mouseClickPosition.X)), + gameObject.Transform.Scale = new Vector2(Math.Abs((gameObject.Transform.Position.X - mouseWorldPosition.X) * beforeState[gameObject].Scale.X / (gameObject.Transform.Position.X - mouseClickPosition.X)), Math.Abs(((gameObject.Transform.Position.Y - mouseWorldPosition.Y) * beforeState[gameObject].Scale.Y / (gameObject.Transform.Position.Y - mouseClickPosition.Y)))); } } @@ -821,10 +817,10 @@ namespace CLEngine.Editor.graphics_device { if (!tilesetDragStarted) { - memTiles = (EditorHandler.SelectedGameObjects[0] as Tileset).DeepCopy(); + memTiles = (EditorHandler.SelectedGameObjects[0] as Tileset)?.DeepCopy(); } - (EditorHandler.SelectedGameObjects[0] as Tileset).PlaceTiles(EditorHandler.TilesetBrushControl.CurrentSelectionXNA, SnapToTilesetGrid(mouseWorldPosition)); + (EditorHandler.SelectedGameObjects[0] as Tileset)?.PlaceTiles(EditorHandler.TilesetBrushControl.CurrentSelectionXNA, SnapToTilesetGrid(mouseWorldPosition)); tilesetDragStarted = true; } @@ -832,7 +828,7 @@ namespace CLEngine.Editor.graphics_device { if (tilesetDragStarted) { - TilesetCommand tc = new TilesetCommand((EditorHandler.SelectedGameObjects[0] as Tileset).Tiles, memTiles, (EditorHandler.SelectedGameObjects[0] as Tileset)); + TilesetCommand tc = new TilesetCommand((EditorHandler.SelectedGameObjects[0] as Tileset)?.Tiles, memTiles, (EditorHandler.SelectedGameObjects[0] as Tileset)); EditorHandler.UnDoRedo.InsertUndoRedo(tc); tilesetDragStarted = false; @@ -852,8 +848,8 @@ namespace CLEngine.Editor.graphics_device { X = tilesetSelectedArea.X, Y = tilesetSelectedArea.Y, - Width = tilesetSelectedArea.Width + (EditorHandler.SelectedGameObjects[0] as Tileset).TileWidth, - Height = tilesetSelectedArea.Height + (EditorHandler.SelectedGameObjects[0] as Tileset).TileHeight + Width = tilesetSelectedArea.Width + ((Tileset) EditorHandler.SelectedGameObjects[0]).TileWidth, + Height = tilesetSelectedArea.Height + ((Tileset) EditorHandler.SelectedGameObjects[0]).TileHeight }; } else @@ -868,11 +864,11 @@ namespace CLEngine.Editor.graphics_device { if (EditorHandler.TilesetBrushControl.CurrentSelectionXNA != Rectangle.Empty) { - Tile[,] _tiles = (EditorHandler.SelectedGameObjects[0] as Tileset).DeepCopy(); + Tile[,] _tiles = (EditorHandler.SelectedGameObjects[0] as Tileset)?.DeepCopy(); - (EditorHandler.SelectedGameObjects[0] as Tileset).PlaceTiles(EditorHandler.TilesetBrushControl.CurrentSelectionXNA, tilesetSelectedArea); + (EditorHandler.SelectedGameObjects[0] as Tileset)?.PlaceTiles(EditorHandler.TilesetBrushControl.CurrentSelectionXNA, tilesetSelectedArea); - TilesetCommand tc = new TilesetCommand((EditorHandler.SelectedGameObjects[0] as Tileset).Tiles, _tiles, (EditorHandler.SelectedGameObjects[0] as Tileset)); + TilesetCommand tc = new TilesetCommand((EditorHandler.SelectedGameObjects[0] as Tileset)?.Tiles, _tiles, (EditorHandler.SelectedGameObjects[0] as Tileset)); EditorHandler.UnDoRedo.InsertUndoRedo(tc); } } @@ -894,8 +890,8 @@ namespace CLEngine.Editor.graphics_device { X = tilesetSelectedArea.X, Y = tilesetSelectedArea.Y, - Width = tilesetSelectedArea.Width + (EditorHandler.SelectedGameObjects[0] as Tileset).TileWidth, - Height = tilesetSelectedArea.Height + (EditorHandler.SelectedGameObjects[0] as Tileset).TileHeight + Width = tilesetSelectedArea.Width + ((Tileset) EditorHandler.SelectedGameObjects[0]).TileWidth, + Height = tilesetSelectedArea.Height + ((Tileset) EditorHandler.SelectedGameObjects[0]).TileHeight }; } else @@ -908,11 +904,11 @@ namespace CLEngine.Editor.graphics_device { if (tilesetDragStarted) { - Tile[,] _tiles = (EditorHandler.SelectedGameObjects[0] as Tileset).DeepCopy(); + Tile[,] _tiles = (EditorHandler.SelectedGameObjects[0] as Tileset)?.DeepCopy(); - (EditorHandler.SelectedGameObjects[0] as Tileset).RemoveTiles(tilesetSelectedArea); + (EditorHandler.SelectedGameObjects[0] as Tileset)?.RemoveTiles(tilesetSelectedArea); - TilesetCommand tc = new TilesetCommand((EditorHandler.SelectedGameObjects[0] as Tileset).Tiles, _tiles, (EditorHandler.SelectedGameObjects[0] as Tileset)); + TilesetCommand tc = new TilesetCommand((EditorHandler.SelectedGameObjects[0] as Tileset)?.Tiles, _tiles, (EditorHandler.SelectedGameObjects[0] as Tileset)); EditorHandler.UnDoRedo.InsertUndoRedo(tc); } @@ -978,6 +974,7 @@ namespace CLEngine.Editor.graphics_device } } + [SuppressMessage("ReSharper", "LocalizableElement")] private void GlobalInput() { //if (GameInput.IsKeyPressed(Keys.F6)) @@ -1001,14 +998,17 @@ namespace CLEngine.Editor.graphics_device } } } - else if (GameInput.IsKeyPressed(Keys.F9) && !takingScreenshot) + else lock (this) { - lock (this) - { - takingScreenshot = true; - TakeScreenshot(); - takingScreenshot = false; - } + if (GameInput.IsKeyPressed(Keys.F9) && !takingScreenshot) + { + lock (this) + { + takingScreenshot = true; + TakeScreenshot(); + takingScreenshot = false; + } + } } if (TileSetMode) @@ -1023,12 +1023,13 @@ namespace CLEngine.Editor.graphics_device //if (GameInput.IsKeyPressed(Keys.F5)) // EditorCommands.DebugGame(); - if (this.Focusable) + if (Focusable) { if (GameInput.IsKeyPressed(Keys.Delete)) { if (EditorHandler.SelectedGameObjects.Count > 0 && - System.Windows.Forms.MessageBox.Show("您确定要删除所选的游戏对象吗?", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) + MessageBox.Show("您确定要删除所选的游戏对象吗?", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == + DialogResult.Yes) { foreach (GameObject gameObject in EditorHandler.SelectedGameObjects) { @@ -1078,7 +1079,8 @@ namespace CLEngine.Editor.graphics_device { ProcessStartInfo runExplorer = new ProcessStartInfo(); runExplorer.FileName = "explorer.exe"; - runExplorer.Arguments = System.IO.Path.GetDirectoryName(path); + runExplorer.Arguments = Path.GetDirectoryName(path) ?? + throw new InvalidOperationException(); Process.Start(runExplorer); } } @@ -1345,9 +1347,11 @@ namespace CLEngine.Editor.graphics_device spriteBatch.End(); } + [SuppressMessage("ReSharper", "PossibleLossOfFraction")] private void DrawSceneCamera() { - Vector2 vertex = new Vector2(-SceneManager.GameProject.Settings.ScreenWidth / 2 + SceneManager.ActiveScene.Camera.Position.X, + Vector2 vertex = new Vector2( + -SceneManager.GameProject.Settings.ScreenWidth / 2 + SceneManager.ActiveScene.Camera.Position.X, -SceneManager.GameProject.Settings.ScreenHeight / 2 + SceneManager.ActiveScene.Camera.Position.Y); vertex = Vector2.Transform(vertex, SceneManager.ActiveCamera.TransformMatrix); @@ -1360,6 +1364,7 @@ namespace CLEngine.Editor.graphics_device Primitives.DrawBox(spriteBatch, new Rectangle((int)vertex.X, (int)vertex.Y, (int)(SceneManager.GameProject.Settings.ScreenWidth * Camera.Zoom), (int)(SceneManager.GameProject.Settings.ScreenHeight * SceneManager.ActiveCamera.Zoom)), Color.Yellow, 2); } + [SuppressMessage("ReSharper", "PossibleLossOfFraction")] private void DrawCurrentObjectHandler() { foreach (GameObject gameObject in EditorHandler.SelectedGameObjects) @@ -1374,8 +1379,6 @@ namespace CLEngine.Editor.graphics_device //Vector2.Transform(EditorHandler.SelectedGameObject.Transform.Position,SceneManager.ActiveCamera.TransformMatrix); // 画中心箭头 - Vector2 start = new Vector2(spos.X, spos.Y - HANDLER_SIZE); - Vector2 end = new Vector2(spos.X, spos.Y + HANDLER_SIZE); //start = new Vector2(spos.X - HANDLER_SIZE, spos.Y); //end = new Vector2(spos.X + HANDLER_SIZE, spos.Y); @@ -1383,7 +1386,9 @@ namespace CLEngine.Editor.graphics_device if (editorMode == EditorModes.Move || editorMode == EditorModes.Scale) { - // Y axis: + Vector2 end; + Vector2 start; + // Y axis: { start = new Vector2(spos.X, spos.Y - AXIS_OFFSET); end = new Vector2(spos.X, spos.Y); @@ -1391,11 +1396,13 @@ namespace CLEngine.Editor.graphics_device if (editorMode == EditorModes.Move) { - start = new Vector2(spos.X - AXIS_OPT_SIZE / 2, spos.Y - AXIS_OFFSET + AXIS_OPT_SIZE / 2); + start = new Vector2(spos.X - 9, + spos.Y - AXIS_OFFSET + 9); end = new Vector2(spos.X + 1, spos.Y - AXIS_OFFSET); Primitives.DrawLine(spriteBatch, start, end, Color.Green, 4); - start = new Vector2(spos.X + AXIS_OPT_SIZE / 2, spos.Y - AXIS_OFFSET + AXIS_OPT_SIZE / 2); + start = new Vector2(spos.X + 9, + spos.Y - AXIS_OFFSET + 9); end = new Vector2(spos.X - 1, spos.Y - AXIS_OFFSET); Primitives.DrawLine(spriteBatch, start, end, Color.Green, 4); @@ -1438,7 +1445,7 @@ namespace CLEngine.Editor.graphics_device if (editorMode == EditorModes.Move) { - start = new Vector2(spos.X + AXIS_OFFSET - AXIS_OPT_SIZE / 2, spos.Y - AXIS_OPT_SIZE / 2); + start = new Vector2(spos.X + AXIS_OFFSET - 9, spos.Y - 9); end = new Vector2(spos.X + AXIS_OFFSET, spos.Y + 1); Primitives.DrawLine(spriteBatch, start, end, Color.Red, 4); @@ -1479,6 +1486,7 @@ namespace CLEngine.Editor.graphics_device } } + [SuppressMessage("ReSharper", "PossibleLossOfFraction")] private void DrawObjectIcons() { foreach (GameObject gameObject in sceneGameObjects) @@ -1542,6 +1550,7 @@ namespace CLEngine.Editor.graphics_device } + [SuppressMessage("ReSharper", "RedundantCheckBeforeAssignment")] internal string Screenshot(int captureWidth = 0, int captureHeight = 0) { RenderTarget2D renderTarget = new RenderTarget2D( @@ -1604,7 +1613,6 @@ namespace CLEngine.Editor.graphics_device } if (data != null) { - data = null; } } diff --git a/CLEditor/model/ErrorLog.cs b/CLEditor/model/ErrorLog.cs index 9754585ef7cc1ae539f7d4fefa1c8969020c80dd..4b81ee728edd9e191563c93f5898b78c491e26f9 100644 --- a/CLEditor/model/ErrorLog.cs +++ b/CLEditor/model/ErrorLog.cs @@ -61,10 +61,7 @@ namespace CLEngine.Editor.model /// public void Initialize(IEventSource eventSource) { - if (eventSource != null) - { - eventSource.ErrorRaised += ErrorRaised; - } + eventSource.ErrorRaised += ErrorRaised; } /// /// 关闭自定义记录器 diff --git a/CLEditor/model/FileHelper.cs b/CLEditor/model/FileHelper.cs index 0fc7590be797a936bb2fc1005a9332cb161f01fe..1d741aaabad29529615604df32536e30df681cb8 100644 --- a/CLEditor/model/FileHelper.cs +++ b/CLEditor/model/FileHelper.cs @@ -12,7 +12,7 @@ namespace CLEngine.Editor.model path = ResolveFilename(path); // 创建文件或追加 - using (System.IO.FileStream fs = new System.IO.FileStream(path, FileMode.Append)) + using (new FileStream(path, FileMode.Append)) { } diff --git a/CLEditor/model/ScaleCommand.cs b/CLEditor/model/ScaleCommand.cs index 90d41f201bf6626d3387e2a725fc91b8c2a0e3ad..6bc6162ba0cbbd8ac096a7372e3ffba9752f6496 100644 --- a/CLEditor/model/ScaleCommand.cs +++ b/CLEditor/model/ScaleCommand.cs @@ -19,6 +19,7 @@ namespace CLEngine.Editor.model /// /// /// + /// /// public ScaleCommand(Vector2 change, Vector2 before, GameObject element) { diff --git a/CLEditor/model/ScriptsBuilder.cs b/CLEditor/model/ScriptsBuilder.cs index bcd0f264fb1d570745ca07603d99bda8f12362e5..ff57c8a8f3d9662664abb84aeddabd02c9e7871f 100644 --- a/CLEditor/model/ScriptsBuilder.cs +++ b/CLEditor/model/ScriptsBuilder.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.IO; using System.Reflection; using System.Xml; @@ -12,40 +14,42 @@ namespace CLEngine.Editor.model { public static class ScriptsBuilder { - private static object locker = new object(); + private static readonly object locker = new object(); private static ErrorLogger logger; - public static ErrorLogger Logger { get { return logger; } } + public static ErrorLogger Logger => logger; public static bool IsFileLocked(FileInfo file) { - FileStream stream = null; - - try - { - stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); - } - catch (IOException) - { - //该文件不可用,因为它是: - //仍然被写入 - //或由另一个线程处理 - //或者不存在(已经处理过) - return true; - } - finally - { - if (stream != null) - stream.Close(); - } - - //file is not locked - return false; + FileStream stream = null; + + try + { + stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); + } + catch (IOException) + { + //该文件不可用,因为它是: + //仍然被写入 + //或由另一个线程处理 + //或者不存在(已经处理过) + return true; + } + finally + { + if (stream != null) + stream.Close(); + } + + //file is not locked + return false; } - /// - /// - /// + /// + /// + /// + [SuppressMessage("ReSharper", "PossibleNullReferenceException")] + [SuppressMessage("ReSharper", "CommentTypo")] public static bool ReloadScripts() { if (SceneManager.GameProject == null) return false; @@ -60,11 +64,11 @@ namespace CLEngine.Editor.model //搜索.sln和.csproj文件 foreach (string filename in Directory.GetFiles(SceneManager.GameProject.ProjectPath)) { - if (System.IO.Path.GetExtension(filename).ToLower().Equals(".csproj")) + if (Path.GetExtension(filename).ToLower().Equals(".csproj")) { UserPreferences.Instance.ProjectCsProjFilePath = filename; } - else if (System.IO.Path.GetExtension(filename).ToLower().Equals(".sln")) + else if (Path.GetExtension(filename).ToLower().Equals(".sln")) { UserPreferences.Instance.ProjectSlnFilePath = filename; } @@ -78,15 +82,15 @@ namespace CLEngine.Editor.model doc.Load(projectFileName); while (doc.GetElementsByTagName("ItemGroup").Count < 2) - doc.GetElementsByTagName("Project").Item(0).AppendChild(doc.CreateElement("ItemGroup")); + doc.GetElementsByTagName("Project").Item(0)?.AppendChild(doc.CreateElement("ItemGroup")); - foreach (XmlNode _node in doc.GetElementsByTagName("ItemGroup").Item(1).ChildNodes) + foreach (XmlNode _node in doc.GetElementsByTagName("ItemGroup").Item(1)?.ChildNodes) { if (_node.Name.ToLower().Equals("compile")) { - if (!File.Exists(SceneManager.GameProject.ProjectPath + "\\" + _node.Attributes.GetNamedItem("Include").Value)) + if (_node.Attributes != null && !File.Exists(SceneManager.GameProject.ProjectPath + "\\" + _node.Attributes.GetNamedItem("Include").Value)) { - doc.GetElementsByTagName("ItemGroup").Item(1).RemoveChild(_node); + doc.GetElementsByTagName("ItemGroup").Item(1)?.RemoveChild(_node); removed = true; } } @@ -96,9 +100,8 @@ namespace CLEngine.Editor.model doc.Save(projectFileName); string tmpProjectFileName = SceneManager.GameProject.ProjectPath + @"\_Scripts.csproj"; - string hash = string.Empty; - hash = CHelper.EncryptMD5(DateTime.Now.ToString()); + var hash = CHelper.EncryptMD5(DateTime.Now.ToString(CultureInfo.InvariantCulture)); //try //{ @@ -115,21 +118,22 @@ namespace CLEngine.Editor.model /* Compile project */ ProjectCollection projectCollection = new ProjectCollection(); - Dictionary GlobalProperty = new Dictionary(); - GlobalProperty.Add("Configuration", SceneManager.GameProject.Debug ? "Debug" : "Release"); - GlobalProperty.Add("Platform", "x86"); + Dictionary GlobalProperty = new Dictionary + { + {"Configuration", SceneManager.GameProject.Debug ? "Debug" : "Release"}, {"Platform", "x86"} + }; //FileLogger logger = new FileLogger() { Parameters = @"logfile=C:\clengine_log.txt" }; logger = new ErrorLogger(); - BuildRequestData buildRequest = new BuildRequestData(tmpProjectFileName, GlobalProperty, null, new string[] { "Build" }, null); - BuildResult buildResult = BuildManager.DefaultBuildManager.Build( - new BuildParameters(projectCollection) - { - BuildThreadPriority = System.Threading.ThreadPriority.AboveNormal, - Loggers = new List() { logger } - }, - buildRequest); + BuildRequestData buildRequest = new BuildRequestData(tmpProjectFileName, GlobalProperty, null, new[] { "Build" }, null); + BuildManager.DefaultBuildManager.Build( + new BuildParameters(projectCollection) + { + BuildThreadPriority = System.Threading.ThreadPriority.AboveNormal, + Loggers = new List() { logger } + }, + buildRequest); //foreach (var tr in logger.Errors) //{ diff --git a/CLEditor/model/TilesetCommand.cs b/CLEditor/model/TilesetCommand.cs index 2f0e2d1455df1e7f489f5a2361f421c539b444f7..62e6f8a9d8ec7a3dfdee45bfc3d46e2e3cde40b7 100644 --- a/CLEditor/model/TilesetCommand.cs +++ b/CLEditor/model/TilesetCommand.cs @@ -1,5 +1,4 @@ -using System; -using CLEngine.Core; +using CLEngine.Core; namespace CLEngine.Editor.model { diff --git a/CLEditor/model/commands/MoveCommand.cs b/CLEditor/model/commands/MoveCommand.cs index 7fb07caef577f3b6835c4b0fa2885a9b0ea02933..054a4c12b60b18f8352ed6a3b0761ad8df799978 100644 --- a/CLEditor/model/commands/MoveCommand.cs +++ b/CLEditor/model/commands/MoveCommand.cs @@ -19,6 +19,7 @@ namespace CLEngine.Editor.model.commands /// /// /// + /// /// public MoveCommand(Vector2 change, Vector2 before, GameObject element) { diff --git a/CLEditor/model/commands/RotateCommand.cs b/CLEditor/model/commands/RotateCommand.cs index 2e41f7e855cf78e322f31211960411b54ddc62f3..81b334d3679bc0343989cc80fc6cf65acfe19290 100644 --- a/CLEditor/model/commands/RotateCommand.cs +++ b/CLEditor/model/commands/RotateCommand.cs @@ -18,6 +18,7 @@ namespace CLEngine.Editor.model.commands /// /// /// + /// /// public RotateCommand(float change, float before, GameObject element) { diff --git a/CLEditor/theme/IgniteDark.xaml b/CLEditor/theme/IgniteDark.xaml index d7654c7bf478457b3e76102612e6216360b13798..aa4e9af99369fd1eb359061fe9d8338743dbf7e3 100644 --- a/CLEditor/theme/IgniteDark.xaml +++ b/CLEditor/theme/IgniteDark.xaml @@ -93,16 +93,129 @@ + #444444 + #333333 + #595959 + #3D3D3D + #424242 + #666666 + #EFEFEF + + #BDBDBD + #525252 + - + + + + - + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + M-0.7,5.2 L-2.2,6.7 3.6,12.6 9.5,6.7 8,5.2 3.6,9.6 z + M-2.2,10.9 L-0.7,12.4 3.7,8 8,12.4 9.5,10.9 3.7,5 z + M1.0E-41,4.2 L0,2.1 2.5,4.5 6.7,4.4E-47 6.7,2.3 2.5,6.7 z + M7.2,5 L5.5,7.16 4.16,6.3 3.5,6.7 5.5,8.4 8.6,5.25 C8.6,5.25 8,4.7 7.22,5 + M 0,0 L 4,3.5 L 0,7 Z + M 1,1.5 L 4.5,5 L 8,1.5 + M 1,4.5 L 4.5,1 L 8,4.5 + M6.5,2.6C4.767,0.973 2.509,0 0,0 0,0 0,19 0,19L23,19z + M3.5445026,0 L7.0890052,7.0890053 L3.0459049E-09,7.0890053 z + M-0,6 L-0,8 8,8 8,-0 6,-0 6,6 z + M5,-0 L9,5 1,5 z @@ -149,7 +262,8 @@ - + + @@ -1322,7 +1436,7 @@ - + --> @@ -1584,7 +1698,9 @@ - + @@ -1598,29 +1714,13 @@ - - - - - - - - - + @@ -3041,8 +3141,6 @@ - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +