/// <summary>
        /// Reloads the scripts into the editor
        /// </summary>
        private void ReloadScripts(string[] files, string[] userFiles)
        {
            List <ForgeClassObject> correctFiles = new List <ForgeClassObject>();

            for (int i = 0; i < files.Length; ++i)
            {
                if (!files[i].EndsWith(".meta"))                 //Ignore all meta files
                {
                    correctFiles.Add(new ForgeClassObject(files[i]));
                }
            }

            for (int i = 0; i < userFiles.Length; ++i)
            {
                if (!userFiles[i].EndsWith(".meta"))                 //Ignore all meta files
                {
                    correctFiles.Add(new ForgeClassObject(userFiles[i]));
                }
            }

            if (!ForgeClassObject.HasExactFilename(correctFiles, "NetworkObjectFactory"))
            {
                MakeForgeFactory();                 //We do not have the Forge Factory, we need to make this!
            }
            for (int i = 0; i < correctFiles.Count; ++i)
            {
                var btn = new ForgeEditorButton(correctFiles[i]);

                if (btn.IsNetworkObject || btn.IsNetworkBehavior)
                {
                    _editorButtons.Add(btn);
                }
            }
        }
Exemplo n.º 2
0
        public ForgeEditorButton(ForgeClassObject fcObj)
        {
            _baseType  = fcObj.ObjectClassType;
            TiedObject = fcObj;
            Setup();

            if (fcObj.IsNetworkBehavior)
            {
                ButtonColor = ForgeNetworkingEditor.DarkBlue;
            }
            else if (fcObj.IsNetworkObject)
            {
                ButtonColor = ForgeNetworkingEditor.LightBlue;
            }
            else
            {
                ButtonColor = ForgeNetworkingEditor.CoolBlue;
            }

            if (IsNetworkObject)
            {
                for (int i = 0; i < ForgeNetworkingEditor.Instance._editorButtons.Count; ++i)
                {
                    if (ForgeNetworkingEditor.Instance._editorButtons[i].StrippedSearchName == StrippedSearchName &&
                        ForgeNetworkingEditor.Instance._editorButtons[i].IsNetworkBehavior)
                    {
                        _tiedBehavior = ForgeNetworkingEditor.Instance._editorButtons[i];
                        break;
                    }
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Validates Fields to ensure no conflicts on compilation
        /// </summary>
        public ValidationResult Validate(ForgeEditorButton btn)
        {
            ValidationResult result = new ValidationResult();
            Dictionary <string, ForgeEditorField> classVariables = btn.ClassVariables.ToDictionary(x => x.FieldName, y => y);

            foreach (var field in btn.ClassVariables)
            {
                string fieldName = field.FieldName;
                string duplicate = string.Empty;

                if (fieldName.EndsWith("Changed"))
                {
                    duplicate = fieldName.Substring(0, fieldName.LastIndexOf("Changed"));
                    if (classVariables.ContainsKey(duplicate))
                    {
                        result.ReportValidationError(String.Format("Field \"{0}\" conflicts with Changed event of {1}", fieldName, duplicate));
                    }
                }
                if (fieldName.EndsWith("Interpolation"))
                {
                    duplicate = fieldName.Substring(0, fieldName.LastIndexOf("Interpolation"));
                    if (classVariables.ContainsKey(duplicate))
                    {
                        result.ReportValidationError(String.Format("Field \"{0}\" conflicts with Interpolation field of {1}", fieldName, duplicate));
                    }
                }
            }
            return(result);
        }
        /// <summary>
        /// Generate a network behavior from a class object and a button that contains key information about the class
        /// </summary>
        /// <param name="cObj">The class object</param>
        /// <param name="btn">The button containing key information</param>
        /// <returns>The generated string to save to a file</returns>
        public string SourceCodeNetworkBehavior(ForgeClassObject cObj, ForgeEditorButton btn)
        {
            string behaviorPath = string.Empty;

            if (btn.BaseType == ForgeBaseClassType.NetworkBehavior)
            {
                behaviorPath = EDITOR_RESOURCES_DIR + "/StandAloneNetworkBehaviorTemplate";
            }
            else
            {
                behaviorPath = EDITOR_RESOURCES_DIR + "/NetworkBehaviorTemplate";
            }

            TextAsset      asset    = Resources.Load <TextAsset>(behaviorPath);
            TemplateSystem template = new TemplateSystem(asset.text);

            template.AddVariable("className", btn.StrippedSearchName + "Behavior");
            template.AddVariable("networkObject", btn.StrippedSearchName + "NetworkObject");
            StringBuilder generatedJSON            = new StringBuilder();
            StringBuilder generatedHelperTypesJSON = new StringBuilder();

            string          caps      = "QWERTYUIOPASDFGHJKLZXCVBNM";
            List <object[]> rpcs      = new List <object[]>();
            List <object[]> constRpcs = new List <object[]>();

            for (int i = 0; i < btn.RPCVariables.Count; ++i)
            {
                StringBuilder innerTypes           = new StringBuilder();
                StringBuilder helperNames          = new StringBuilder();
                StringBuilder innerJSON            = new StringBuilder();
                StringBuilder innerHelperTypesJSON = new StringBuilder();
                for (int x = 0; x < btn.RPCVariables[i].ArgumentCount; ++x)
                {
                    Type t = ForgeClassFieldRPCValue.GetTypeFromAcceptable(btn.RPCVariables[i].FieldTypes[x].Type);

                    helperNames.AppendLine("\t\t/// " + _referenceVariables[t.Name] + " " + btn.RPCVariables[i].FieldTypes[x].HelperName);

                    string fieldHelper = btn.RPCVariables[i].FieldTypes[x].HelperName;
                    if (x + 1 < btn.RPCVariables[i].ArgumentCount)
                    {
                        innerTypes.Append(", typeof(" + _referenceVariables[t.Name] + ")");
                        innerJSON.Append("\"" + _referenceVariables[t.Name] + "\", ");
                        innerHelperTypesJSON.Append("\"" + fieldHelper + "\", ");
                    }
                    else
                    {
                        innerTypes.Append(", typeof(" + _referenceVariables[t.Name] + ")");
                        innerJSON.Append("\"" + _referenceVariables[t.Name] + "\"");
                        innerHelperTypesJSON.Append("\"" + fieldHelper + "\"");
                    }
                }

                object[] rpcData = new object[]
                {
                    btn.RPCVariables[i].FieldName,                                              // The function name
                    innerTypes.ToString(),                                                      // The list of types
                    helperNames.ToString().TrimEnd()
                };

                string constRpc = "";
                for (int j = 0; j < btn.RPCVariables[i].FieldName.Length; j++)
                {
                    if (constRpc.Length > 0 && caps.Contains(btn.RPCVariables[i].FieldName[j]))
                    {
                        constRpc += "_";
                    }

                    constRpc += btn.RPCVariables[i].FieldName[j].ToString().ToUpper();
                }
                constRpc = constRpc.Replace("R_P_C_", "");

                object[] constRpcData = new object[]
                {
                    constRpc,                                                                       // The function name
                    innerTypes.ToString(),                                                          // The list of types
                    helperNames.ToString().TrimEnd()
                };

                rpcs.Add(rpcData);
                constRpcs.Add(constRpcData);
                generatedJSON.Append("[");
                generatedJSON.Append(innerJSON.ToString());
                generatedJSON.Append("]");
                generatedHelperTypesJSON.Append("[");
                generatedHelperTypesJSON.Append(innerHelperTypesJSON.ToString());
                generatedHelperTypesJSON.Append("]");
            }

            template.AddVariable("generatedTypes", generatedJSON.ToString().Replace("\"", "\\\""));
            template.AddVariable("generatedHelperTypes", generatedHelperTypesJSON.ToString().Replace("\"", "\\\""));
            template.AddVariable("rpcs", rpcs.ToArray());
            template.AddVariable("constRpcs", constRpcs.ToArray());

            return(template.Parse());
        }
        /// <summary>
        /// Generate a source network object based on the class and button provided
        /// </summary>
        /// <param name="cObj">The class we a generating</param>
        /// <param name="btn">The button that holds key information to this class</param>
        /// <param name="identity">The network identity that we will assing this class</param>
        /// <returns>The generated string to save to a file</returns>
        public string SourceCodeNetworkObject(ForgeClassObject cObj, ForgeEditorButton btn, int identity)
        {
            TextAsset      asset    = Resources.Load <TextAsset>(EDITOR_RESOURCES_DIR + "/NetworkObjectTemplate");
            TemplateSystem template = new TemplateSystem(asset.text);

            template.AddVariable("className", btn.StrippedSearchName + "NetworkObject");
            template.AddVariable("identity", cObj == null ? identity : cObj.IdentityValue);
            template.AddVariable("bitwiseSize", Math.Ceiling(btn.ClassVariables.Count / 8.0));

            List <object[]> variables         = new List <object[]>();
            List <object[]> rewinds           = new List <object[]>();
            string          interpolateValues = string.Empty;

            string interpolateType = string.Empty;
            int    i = 0, j = 0;

            for (i = 0, j = 0; i < btn.ClassVariables.Count; ++i)
            {
                Type t = ForgeClassFieldValue.GetTypeFromAcceptable(btn.ClassVariables[i].FieldType);
                interpolateType = ForgeClassFieldValue.GetInterpolateFromAcceptable(btn.ClassVariables[i].FieldType);

                if (i != 0 && i % 8 == 0)
                {
                    j++;
                }

                object[] fieldData = new object[]
                {
                    _referenceVariables[t.Name],                                                // Data type
                    btn.ClassVariables[i].FieldName.Replace(" ", string.Empty),                 // Field name
                    btn.ClassVariables[i].Interpolate,                                          // Interpolated
                    interpolateType,                                                            // Interpolate type
                    btn.ClassVariables[i].InterpolateValue,                                     // Interpolate time
                    _referenceBitWise[i % 8],                                                   // Hexcode
                    j                                                                           // Dirty fields index
                };

                if (i + 1 < btn.ClassVariables.Count)
                {
                    interpolateValues += btn.ClassVariables[i].InterpolateValue.ToString() + ",";
                }
                else
                {
                    interpolateValues += btn.ClassVariables[i].InterpolateValue.ToString();
                }

                variables.Add(fieldData);
            }

            // TODO:  This should relate to the rewind variables
            for (i = 0; i < 0; i++)
            {
                object[] rewindData = new object[]
                {
                    "Vector3",                                  // The data type for this rewind
                    "Position",                                 // The name except with the first letter uppercase
                    5000                                        // The time in ms for this rewind to track
                };

                rewinds.Add(rewindData);
            }

            template.AddVariable("variables", variables.ToArray());
            template.AddVariable("rewinds", rewinds.ToArray());
            template.AddVariable("interpolateValues", interpolateValues.Replace("\"", "\\\""));
            return(template.Parse());
        }
        /// <summary>
        /// This will render the main menu
        /// </summary>
        private void RenderMainMenu()
        {
            if (_editorButtons == null)
            {
                Initialize();
                return;                 //Editor is getting refreshed
            }

            EditorGUILayout.HelpBox("Please note when using source control to please ignore the FNWizardData.bin that is generated because of the NCW. This is because the serialization is based on the computer that has done it. The serialization is a process to help make upgrading easier, so this file is not necessary unless upgrading.", MessageType.Info);

            GUILayout.BeginHorizontal();
            GUILayout.Label("Search", GUILayout.Width(50));
            _searchField = GUILayout.TextField(_searchField);
            Rect verticleButton = EditorGUILayout.BeginVertical("Button", GUILayout.Width(100), GUILayout.Height(15));

            if (ProVersion)
            {
                GUI.color = TealBlue;
            }
            if (GUI.Button(verticleButton, GUIContent.none))
            {
                ActiveButton           = new ForgeEditorButton("");
                ActiveButton.IsCreated = true;
                ChangeMenu(ForgeEditorActiveMenu.Create);
            }
            GUI.color = Color.white;
            GUILayout.BeginHorizontal();
            GUILayout.Label(Star);
            GUILayout.Label("Create", EditorStyles.boldLabel);
            GUILayout.EndHorizontal();
            GUILayout.EndVertical();

            GUILayout.EndHorizontal();

            _scrollView = GUILayout.BeginScrollView(_scrollView);

            for (int i = 0; i < _editorButtons.Count; ++i)
            {
                if (_editorButtons[i].IsNetworkBehavior)
                {
                    continue;
                }

                if (string.IsNullOrEmpty(_searchField) || _editorButtons[i].PossiblyMatches(_searchField))
                {
                    _editorButtons[i].Render();
                }

                if (_editorButtons[i].MarkedForDeletion)
                {
                    if (EditorUtility.DisplayDialog("Confirmation", "Are you sure? This will delete the class", "Yes", "No"))
                    {
                        if (_editorButtons[i].TiedObject.IsNetworkObject || _editorButtons[i].TiedObject.IsNetworkBehavior)
                        {
                            //Then we will need to remove this from the factory and destroy the other object as well
                            string searchName           = _editorButtons[i].TiedObject.StrippedSearchName;
                            string folderPath           = _editorButtons[i].TiedObject.FileLocation.Substring(0, _editorButtons[i].TiedObject.FileLocation.Length - _editorButtons[i].TiedObject.Filename.Length);
                            string filePathBehavior     = Path.Combine(folderPath, searchName + "Behavior.cs");
                            string filePathNetworkedObj = Path.Combine(folderPath, searchName + "NetworkObject.cs");

                            if (File.Exists(filePathBehavior))                             //Delete the behavior
                            {
                                File.Delete(filePathBehavior);
                            }
                            if (File.Exists(filePathNetworkedObj))                             //Delete the object
                            {
                                File.Delete(filePathNetworkedObj);
                            }
                            _editorButtons.RemoveAt(i);

                            string factoryData = SourceCodeFactory();
                            using (StreamWriter sw = File.CreateText(Path.Combine(_storingPath, "NetworkObjectFactory.cs")))
                            {
                                sw.Write(factoryData);
                            }

                            string networkManagerData = SourceCodeNetworkManager();
                            using (StreamWriter sw = File.CreateText(Path.Combine(_storingPath, "NetworkManager.cs")))
                            {
                                sw.Write(networkManagerData);
                            }

                            //IFormatter previousSavedState = new BinaryFormatter();
                            //using (Stream s = new FileStream(Path.Combine(Application.persistentDataPath, FN_WIZARD_DATA), FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                            //{
                            //	previousSavedState.Serialize(s, _editorButtons);
                            //}
                        }
                        else
                        {
                            //Random object
                            //File.Delete(_editorButtons[i].TiedObject.FileLocation);
                        }
                        AssetDatabase.Refresh();
                        CloseFinal();
                        break;
                    }
                    else
                    {
                        _editorButtons[i].MarkedForDeletion = false;
                    }
                }
            }

            GUILayout.EndScrollView();

            Rect backBtn = EditorGUILayout.BeginVertical("Button", GUILayout.Height(50));

            if (ProVersion)
            {
                GUI.color = ShadedBlue;
            }
            if (GUI.Button(backBtn, GUIContent.none))
            {
                //CloseFinal();
                Close();
                _instance = null;
                return;
            }
            EditorGUILayout.Space();
            EditorGUILayout.BeginHorizontal();
            GUI.color = Color.white;
            GUILayout.FlexibleSpace();
            GUIStyle boldStyle = new GUIStyle(GUI.skin.GetStyle("boldLabel"));

            boldStyle.alignment = TextAnchor.UpperCenter;
            GUILayout.Label("Close", boldStyle);
            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndVertical();
        }
        /// <summary>
        /// Setup all the variables to be used within the editor
        /// </summary>
        public void Initialize()
        {
            titleContent = new GUIContent("Forge Wizard");
            ProVersion   = EditorGUIUtility.isProSkin;

            ForgeClassObject.IDENTITIES = 0;
            _referenceBitWise           = new List <string>();
            _referenceBitWise.Add("0x1");
            _referenceBitWise.Add("0x2");
            _referenceBitWise.Add("0x4");
            _referenceBitWise.Add("0x8");
            _referenceBitWise.Add("0x10");
            _referenceBitWise.Add("0x20");
            _referenceBitWise.Add("0x40");
            _referenceBitWise.Add("0x80");

            _referenceVariables = new Dictionary <object, string>();
            _referenceVariables.Add(typeof(bool).Name, "bool");
            _referenceVariables.Add(typeof(byte).Name, "byte");
            _referenceVariables.Add(typeof(char).Name, "char");
            _referenceVariables.Add(typeof(short).Name, "short");
            _referenceVariables.Add(typeof(ushort).Name, "ushort");
            _referenceVariables.Add(typeof(int).Name, "int");
            _referenceVariables.Add(typeof(uint).Name, "uint");
            _referenceVariables.Add(typeof(float).Name, "float");
            _referenceVariables.Add(typeof(long).Name, "long");
            _referenceVariables.Add(typeof(ulong).Name, "ulong");
            _referenceVariables.Add(typeof(double).Name, "double");
            _referenceVariables.Add(typeof(string).Name, "string");
            _referenceVariables.Add(typeof(Vector2).Name, "Vector2");
            _referenceVariables.Add(typeof(Vector3).Name, "Vector3");
            _referenceVariables.Add(typeof(Vector4).Name, "Vector4");
            _referenceVariables.Add(typeof(Quaternion).Name, "Quaternion");
            _referenceVariables.Add(typeof(Color).Name, "Color");
            _referenceVariables.Add(typeof(object).Name, "object");
            _referenceVariables.Add(typeof(object[]).Name, "object[]");
            _referenceVariables.Add(typeof(byte[]).Name, "byte[]");

            _scrollView    = Vector2.zero;
            _editorButtons = new List <ForgeEditorButton>();
            _instance      = this;

            _storingPath     = Path.Combine(Application.dataPath, GENERATED_FOLDER_PATH);
            _userStoringPath = Path.Combine(Application.dataPath, USER_GENERATED_FOLDER_PATH);

            if (!Directory.Exists(_storingPath))
            {
                Directory.CreateDirectory(_storingPath);
            }

            if (!Directory.Exists(_userStoringPath))
            {
                Directory.CreateDirectory(_userStoringPath);
            }

            string[] files     = Directory.GetFiles(_storingPath, "*.cs", SearchOption.TopDirectoryOnly);
            string[] userFiles = Directory.GetFiles(_userStoringPath, "*.cs", SearchOption.TopDirectoryOnly);

            //if (File.Exists(Path.Combine(Application.persistentDataPath, FN_WIZARD_DATA))) //Check for our temp file, this will make it so that we can load this data from memory regaurdless of errors
            //{
            //	IFormatter bFormatter = new BinaryFormatter();
            //	bool updateColors = false;
            //	using (Stream s = new FileStream(Path.Combine(Application.persistentDataPath, FN_WIZARD_DATA), FileMode.Open, FileAccess.Read, FileShare.Read))
            //	{
            //		try
            //		{
            //			object deserializedObject = bFormatter.Deserialize(s);
            //			if (deserializedObject != null)
            //			{
            //				_editorButtons = (List<ForgeEditorButton>)deserializedObject;
            //				bool cleared = true;
            //				for (int i = 0; i < _editorButtons.Count; ++i)
            //				{
            //					_editorButtons[i].SetupLists();
            //					if (_editorButtons[i].TiedObject == null)
            //					{
            //						cleared = false;
            //						break;
            //					}
            //				}

            //				if (cleared)
            //					updateColors = true;
            //				else
            //				{
            //					_editorButtons = new List<ForgeEditorButton>();
            //					ReloadScripts(files, userFiles);
            //				}
            //			}
            //			else
            //				ReloadScripts(files, userFiles);
            //		}
            //		catch
            //		{
            //			ReloadScripts(files, userFiles);
            //		}
            //	}

            //	if (updateColors)
            //	{
            //		for (int i = 0; i < _editorButtons.Count; ++i)
            //		{
            //			_editorButtons[i].UpdateButtonColor();
            //			if (_editorButtons[i].IsNetworkObject)
            //				ForgeClassObject.IDENTITIES++;
            //		}
            //	}
            //}
            //else
            ReloadScripts(files, userFiles);

            #region Texture Loading
            Arrow             = Resources.Load <Texture2D>("Arrow");
            SideArrow         = Resources.Load <Texture2D>("SideArrow");
            SideArrowInverse  = FlipTexture(SideArrow);
            Star              = Resources.Load <Texture2D>("Star");
            TrashIcon         = Resources.Load <Texture2D>("Trash");
            SubtractIcon      = Resources.Load <Texture2D>("Subtract");
            AddIcon           = Resources.Load <Texture2D>("Add");
            SaveIcon          = Resources.Load <Texture2D>("Save");
            LightbulbIcon     = Resources.Load <Texture2D>("Lightbulb");
            BackgroundTexture = new Texture2D(1, 1);
            BackgroundTexture.SetPixel(0, 0, LightsOffBackgroundColor);
            BackgroundTexture.Apply();
            #endregion

            _createUndo = () =>
            {
                if (ActiveButton.IsDirty)
                {
                    if (EditorUtility.DisplayDialog("Confirmation", "Are you sure? This will trash the current object", "Yes", "No"))
                    {
                        ActiveButton = null;
                        ChangeMenu(ForgeEditorActiveMenu.Main);
                    }
                }
                else
                {
                    //We don't care because they didn't do anything
                    ActiveButton = null;
                    ChangeMenu(ForgeEditorActiveMenu.Main);
                }
            };

            _modifyUndo = () =>
            {
                bool isDirty = ActiveButton.IsDirty;

                if (isDirty)
                {
                    if (EditorUtility.DisplayDialog("Confirmation", "Are you sure? This will undo the current changes", "Yes", "No"))
                    {
                        ActiveButton.ResetToDefaults();
                        ActiveButton = null;
                        ChangeMenu(ForgeEditorActiveMenu.Main);
                    }
                }
                else
                {
                    ActiveButton.ResetToDefaults();
                    ActiveButton = null;
                    ChangeMenu(ForgeEditorActiveMenu.Main);
                }
            };

            AssetDatabase.Refresh();
        }
        /// <summary>
        /// Compiles our generated code for the user
        /// </summary>
        public void Compile()
        {
            if (ActiveButton == null)
            {
                Debug.LogError("WHAT?! LOL");
                return;
            }

            if (string.IsNullOrEmpty(ActiveButton.ButtonName))
            {
                Debug.LogError("Can't have an empty class name");
                return;
            }

            EditorApplication.LockReloadAssemblies();

            int identity = 1;

            for (int i = 0; i < _editorButtons.Count; ++i)
            {
                if (_editorButtons[i].IsCreated)
                {
                    //Brand new class being added!
                    string networkObjectData   = SourceCodeNetworkObject(null, _editorButtons[i], identity);
                    string networkBehaviorData = SourceCodeNetworkBehavior(null, _editorButtons[i]);
                    if (!string.IsNullOrEmpty(networkObjectData))
                    {
                        using (StreamWriter sw = File.CreateText(Path.Combine(_userStoringPath, string.Format("{0}{1}.cs", _editorButtons[i].StrippedSearchName, "NetworkObject"))))
                        {
                            sw.Write(networkObjectData);
                        }

                        using (StreamWriter sw = File.CreateText(Path.Combine(_userStoringPath, string.Format("{0}{1}.cs", _editorButtons[i].StrippedSearchName, "Behavior"))))
                        {
                            sw.Write(networkBehaviorData);
                        }
                        identity++;

                        string strippedName = _editorButtons[i].StrippedSearchName;
                        _editorButtons[i].ButtonName = strippedName + "NetworkObject";
                    }
                }
                else
                {
                    if (_editorButtons[i].TiedObject != null)
                    {
                        if (_editorButtons[i].TiedObject.IsNetworkBehavior)
                        {
                            string networkBehaviorData = SourceCodeNetworkBehavior(null, _editorButtons[i]);

                            using (StreamWriter sw = File.CreateText(Path.Combine(_userStoringPath, _editorButtons[i].TiedObject.Filename)))
                            {
                                sw.Write(networkBehaviorData);
                            }
                        }
                        else if (_editorButtons[i].TiedObject.IsNetworkObject)
                        {
                            string networkObjectData = SourceCodeNetworkObject(null, _editorButtons[i], identity);
                            using (StreamWriter sw = File.CreateText(Path.Combine(_userStoringPath, _editorButtons[i].TiedObject.Filename)))
                            {
                                sw.Write(networkObjectData);
                            }
                            identity++;
                        }
                    }
                }
            }

            string factoryData = SourceCodeFactory();

            using (StreamWriter sw = File.CreateText(Path.Combine(_storingPath, "NetworkObjectFactory.cs")))
            {
                sw.Write(factoryData);
            }

            string networkManagerData = SourceCodeNetworkManager();

            using (StreamWriter sw = File.CreateText(Path.Combine(_storingPath, "NetworkManager.cs")))
            {
                sw.Write(networkManagerData);
            }

            //IFormatter previousSavedState = new BinaryFormatter();
            //using (Stream s = new FileStream(Path.Combine(Application.persistentDataPath, FN_WIZARD_DATA), FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
            //{
            //    previousSavedState.Serialize(s, _editorButtons);
            //}

            EditorApplication.UnlockReloadAssemblies();

            AssetDatabase.Refresh();

            //_editorButtons.Remove(ActiveButton);
            ActiveButton = null;
            CloseFinal();
        }
Exemplo n.º 9
0
        /// <summary>
        /// This will render the main menu
        /// </summary>
        private void RenderMainMenu()
        {
            if (_editorButtons == null)
            {
                Initialize();
                return;                 //Editor is getting refreshed
            }

            GUILayout.BeginHorizontal();
            GUILayout.Label("Search", GUILayout.Width(50));
            _searchField = GUILayout.TextField(_searchField);
            Rect verticleButton = EditorGUILayout.BeginVertical("Button", GUILayout.Width(100), GUILayout.Height(15));

            if (ProVersion)
            {
                GUI.color = TealBlue;
            }
            if (GUI.Button(verticleButton, GUIContent.none))
            {
                ActiveButton           = new ForgeEditorButton("");
                ActiveButton.IsCreated = true;
                ChangeMenu(ForgeEditorActiveMenu.Create);
            }
            GUI.color = Color.white;
            GUILayout.BeginHorizontal();
            GUILayout.Label(Star);
            GUILayout.Label("Create", EditorStyles.boldLabel);
            GUILayout.EndHorizontal();
            GUILayout.EndVertical();

            GUILayout.EndHorizontal();

            _scrollView = GUILayout.BeginScrollView(_scrollView);

            for (int i = 0; i < _editorButtons.Count; ++i)
            {
                if (_editorButtons[i].IsNetworkBehavior)
                {
                    continue;
                }

                if (string.IsNullOrEmpty(_searchField) || _editorButtons[i].PossiblyMatches(_searchField))
                {
                    _editorButtons[i].Render();
                }

                if (_editorButtons[i].MarkedForDeletion)
                {
                    if (EditorUtility.DisplayDialog("Confirmation", "Are you sure? This will delete the class", "Yes", "No"))
                    {
                        if (_editorButtons[i].TiedObject.IsNetworkObject || _editorButtons[i].TiedObject.IsNetworkBehavior)
                        {
                            //Then we will need to remove this from the factory and destroy the other object as well
                            string searchName           = _editorButtons[i].TiedObject.StrippedSearchName;
                            string folderPath           = _editorButtons[i].TiedObject.FileLocation.Substring(0, _editorButtons[i].TiedObject.FileLocation.Length - _editorButtons[i].TiedObject.Filename.Length);
                            string filePathBehavior     = Path.Combine(folderPath, searchName + "Behavior.cs");
                            string filePathNetworkedObj = Path.Combine(folderPath, searchName + "NetworkObject.cs");

                            if (File.Exists(filePathBehavior))                             //Delete the behavior
                            {
                                File.Delete(filePathBehavior);
                            }
                            if (File.Exists(filePathNetworkedObj))                             //Delete the object
                            {
                                File.Delete(filePathNetworkedObj);
                            }
                            _editorButtons.RemoveAt(i);

                            string factoryData = SourceCodeFactory();
                            using (StreamWriter sw = File.CreateText(Path.Combine(_storingPath, "NetworkObjectFactory.cs")))
                            {
                                sw.Write(factoryData);
                            }

                            string networkManagerData = SourceCodeNetworkManager();
                            using (StreamWriter sw = File.CreateText(Path.Combine(_storingPath, "NetworkManager.cs")))
                            {
                                sw.Write(networkManagerData);
                            }
                        }
                        else
                        {
                            //Random object
                            //File.Delete(_editorButtons[i].TiedObject.FileLocation);
                        }
                        AssetDatabase.Refresh();
                        CloseFinal();
                        break;
                    }
                    else
                    {
                        _editorButtons[i].MarkedForDeletion = false;
                    }
                }
            }

            GUILayout.EndScrollView();

            Rect backBtn = EditorGUILayout.BeginVertical("Button", GUILayout.Height(50));

            if (ProVersion)
            {
                GUI.color = ShadedBlue;
            }
            if (GUI.Button(backBtn, GUIContent.none))
            {
                //CloseFinal();
                Close();
                _instance = null;
                return;
            }
            EditorGUILayout.Space();
            EditorGUILayout.BeginHorizontal();
            GUI.color = Color.white;
            GUILayout.FlexibleSpace();
            GUIStyle boldStyle = new GUIStyle(GUI.skin.GetStyle("boldLabel"));

            boldStyle.alignment = TextAnchor.UpperCenter;
            GUILayout.Label("Close", boldStyle);
            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndVertical();
        }
Exemplo n.º 10
0
        /// <summary>
        /// Setup all the variables to be used within the editor
        /// </summary>
        public void Initialize()
        {
            titleContent = new GUIContent("Forge Wizard");
            ProVersion   = EditorGUIUtility.isProSkin;

            ForgeClassObject.IDENTITIES = 0;
            _referenceBitWise           = new List <string>();
            _referenceBitWise.Add("0x1");
            _referenceBitWise.Add("0x2");
            _referenceBitWise.Add("0x4");
            _referenceBitWise.Add("0x8");
            _referenceBitWise.Add("0x10");
            _referenceBitWise.Add("0x20");
            _referenceBitWise.Add("0x40");
            _referenceBitWise.Add("0x80");

            _referenceVariables = new Dictionary <object, string>();
            _referenceVariables.Add(typeof(bool).Name, "bool");
            _referenceVariables.Add(typeof(byte).Name, "byte");
            _referenceVariables.Add(typeof(char).Name, "char");
            _referenceVariables.Add(typeof(short).Name, "short");
            _referenceVariables.Add(typeof(ushort).Name, "ushort");
            _referenceVariables.Add(typeof(int).Name, "int");
            _referenceVariables.Add(typeof(uint).Name, "uint");
            _referenceVariables.Add(typeof(float).Name, "float");
            _referenceVariables.Add(typeof(long).Name, "long");
            _referenceVariables.Add(typeof(ulong).Name, "ulong");
            _referenceVariables.Add(typeof(double).Name, "double");
            _referenceVariables.Add(typeof(string).Name, "string");
            _referenceVariables.Add(typeof(Vector2).Name, "Vector2");
            _referenceVariables.Add(typeof(Vector3).Name, "Vector3");
            _referenceVariables.Add(typeof(Vector4).Name, "Vector4");
            _referenceVariables.Add(typeof(Quaternion).Name, "Quaternion");
            _referenceVariables.Add(typeof(Color).Name, "Color");
            _referenceVariables.Add(typeof(object).Name, "object");
            _referenceVariables.Add(typeof(object[]).Name, "object[]");
            _referenceVariables.Add(typeof(byte[]).Name, "byte[]");

            _scrollView    = Vector2.zero;
            _editorButtons = new List <ForgeEditorButton>();
            _instance      = this;

            _storingPath     = Path.Combine(Application.dataPath, GENERATED_FOLDER_PATH);
            _userStoringPath = Path.Combine(Application.dataPath, USER_GENERATED_FOLDER_PATH);

            if (!Directory.Exists(_storingPath))
            {
                Directory.CreateDirectory(_storingPath);
            }

            if (!Directory.Exists(_userStoringPath))
            {
                Directory.CreateDirectory(_userStoringPath);
            }

            string[] files     = Directory.GetFiles(_storingPath, "*", SearchOption.TopDirectoryOnly);
            string[] userFiles = Directory.GetFiles(_userStoringPath, "*", SearchOption.TopDirectoryOnly);
            List <ForgeClassObject> correctFiles = new List <ForgeClassObject>();

            for (int i = 0; i < files.Length; ++i)
            {
                if (!files[i].EndsWith(".meta"))                 //Ignore all meta files
                {
                    correctFiles.Add(new ForgeClassObject(files[i]));
                }
            }

            for (int i = 0; i < userFiles.Length; ++i)
            {
                if (!userFiles[i].EndsWith(".meta"))                 //Ignore all meta files
                {
                    correctFiles.Add(new ForgeClassObject(userFiles[i]));
                }
            }

            if (!ForgeClassObject.HasExactFilename(correctFiles, "NetworkObjectFactory"))
            {
                MakeForgeFactory();                 //We do not have the Forge Factory, we need to make this!
            }
            for (int i = 0; i < correctFiles.Count; ++i)
            {
                var btn = new ForgeEditorButton(correctFiles[i]);

                if (btn.IsNetworkObject || btn.IsNetworkBehavior)
                {
                    _editorButtons.Add(btn);
                }
            }

            #region Texture Loading
            Arrow             = Resources.Load <Texture2D>("Arrow");
            SideArrow         = Resources.Load <Texture2D>("SideArrow");
            SideArrowInverse  = FlipTexture(SideArrow);
            Star              = Resources.Load <Texture2D>("Star");
            TrashIcon         = Resources.Load <Texture2D>("Trash");
            SubtractIcon      = Resources.Load <Texture2D>("Subtract");
            AddIcon           = Resources.Load <Texture2D>("Add");
            SaveIcon          = Resources.Load <Texture2D>("Save");
            LightbulbIcon     = Resources.Load <Texture2D>("Lightbulb");
            BackgroundTexture = new Texture2D(1, 1);
            BackgroundTexture.SetPixel(0, 0, LightsOffBackgroundColor);
            BackgroundTexture.Apply();
            #endregion

            _createUndo = () =>
            {
                if (ActiveButton.IsDirty)
                {
                    if (EditorUtility.DisplayDialog("Confirmation", "Are you sure? This will trash the current object", "Yes", "No"))
                    {
                        ActiveButton = null;
                        ChangeMenu(ForgeEditorActiveMenu.Main);
                    }
                }
                else
                {
                    //We don't care because they didn't do anything
                    ActiveButton = null;
                    ChangeMenu(ForgeEditorActiveMenu.Main);
                }
            };

            _modifyUndo = () =>
            {
                bool isDirty = ActiveButton.IsDirty;

                if (isDirty)
                {
                    if (EditorUtility.DisplayDialog("Confirmation", "Are you sure? This will undo the current changes", "Yes", "No"))
                    {
                        ActiveButton.ResetToDefaults();
                        ActiveButton = null;
                        ChangeMenu(ForgeEditorActiveMenu.Main);
                    }
                }
                else
                {
                    ActiveButton.ResetToDefaults();
                    ActiveButton = null;
                    ChangeMenu(ForgeEditorActiveMenu.Main);
                }
            };

            AssetDatabase.Refresh();
        }