SHARE
TWEET

Untitled

a guest Dec 11th, 2019 84 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. using System.IO;
  4.  
  5. public class MapEditor : MonoBehaviour
  6. {
  7.     #region Singleton
  8.     public static MapEditor Instance;
  9.     private void Awake()
  10.     {
  11.         Instance = this;
  12.     }
  13.     #endregion
  14.  
  15.     private static byte MaxConsoleMessages = 9;
  16.  
  17.     public enum ToolMode { None, Placement, Move, Rotate, Scale };
  18.     public enum ConsoleMessageType { Normal, Warning, Error };
  19.  
  20.     [Header("References")]
  21.     public MapEditorCamera editorCamera;
  22.     public Material ghostMaterial;
  23.     public GameObject nodeGenericVisualRepresentationPrefab;
  24.  
  25.     [Header("References/Tools")]
  26.     public Transform cursorSelectionHolder;
  27.     public Color placementColor;
  28.  
  29.     [Header("References/UI")]
  30.     public GameObject ui_escapeMenu;
  31.  
  32.     [Header("Information")]
  33.     [SerializeField] private Vector3 cursorWorldPosition = Vector3.zero;
  34.     [SerializeField] private Vector3 nearestGridPoint = Vector3.zero;
  35.     [SerializeField] private ToolMode toolMode = ToolMode.Placement;
  36.     public AssetDirectories selectedDirectory;
  37.     public AssetGroup selectedGroup;
  38.     public List<string> consoleMessages = new List<string>();
  39.     [SerializeField] private MapEditorAsset selectedAssetForPlacement;
  40.     [SerializeField] private PlacedNode.NodeType selectedNodeTypeForPlacement;
  41.     [SerializeField] private PlacedObject selectedObject;
  42.     [SerializeField] private bool snapToGrid = false;
  43.     [SerializeField] private float realTime;
  44.     [SerializeField] private List<string> consoleMessagesSentThisSession = new List<string>();
  45.  
  46.     private void Start()
  47.     {
  48.         WriteToConsole(System.DateTime.Now.ToString());
  49.         StartNewProject();
  50.     }
  51.  
  52.     private void OnDisable()
  53.     {
  54.         // Unselect whatever selection has been selected to undo any potential changes
  55.         if (selectedObject != null)
  56.             UnSelectCurrentSelection();
  57.     }
  58.  
  59.     private void OnApplicationQuit()
  60.     {
  61.         // Write all the map editor logs to a file
  62.         WriteToConsole("Closing Application...");
  63.         WriteToConsole(System.DateTime.Now.ToString());
  64.         File.WriteAllLines(UGI.LogsPath + "/LastLog_MapEditor.txt", consoleMessagesSentThisSession.ToArray());
  65.     }
  66.  
  67.     private void StartNewProject ()
  68.     {
  69.         // Inform the data handler to scrub/delete existing data
  70.         MapEditorDataHandler.Instance.ClearAllData();
  71.  
  72.         // Default the map editor to having nothing selected
  73.         SetTool(ToolMode.None);
  74.  
  75.         // Default us to having the "GW" group selected
  76.         SetGroup(AssetGroup.GW);
  77.         // Default us to having the "All" directory selected which will make all assets display
  78.         SetDirectory(AssetDirectories.All);
  79.  
  80.         // Update the nodes to display all available nodes
  81.         UI_MapEditor.Instance.UpdateNodesUI();
  82.  
  83.         // And then select to display the assets menu
  84.         UI_MapEditor.Instance.OnClick_Menu_Assets();
  85.  
  86.         // Then write to the console
  87.         WriteToConsole("Started new project");
  88.     }
  89.  
  90.     private void Update()
  91.     {
  92.         realTime = Time.realtimeSinceStartup;
  93.  
  94.         // Toggle the escape menu
  95.         if (Input.GetKeyDown(KeyCode.Escape))
  96.         {
  97.             ui_escapeMenu.SetActive(!ui_escapeMenu.activeInHierarchy);
  98.         }
  99.  
  100.         // Find the closest point to the cursor and cache it
  101.         cursorWorldPosition = GameCursor.GetClosestPoint(editorCamera.gameObject, true, GameCursor.IgnoreMapEditorTags);
  102.         // Then round it to find the nearest grid point
  103.         nearestGridPoint = Vector3Int.RoundToInt(cursorWorldPosition);
  104.  
  105.         // If we're snapping to grid
  106.         snapToGrid = Input.GetKey(KeyCode.LeftControl);
  107.  
  108.         // Do null checks
  109.         OnUpdate_CheckForNullReferences();
  110.  
  111.         // Handle logic of tools differently
  112.         switch (toolMode)
  113.         {
  114.             case ToolMode.None:
  115.                 OnUpdate_NoneTool();
  116.                 break;
  117.             case ToolMode.Placement:
  118.                 OnUpdate_PlacementTool();
  119.                 break;
  120.         }
  121.  
  122.     }
  123.  
  124.     private void OnUpdate_CheckForNullReferences ()
  125.     {
  126.         // If the object we had selected becomes null, unselect it
  127.         if (selectedObject == null)
  128.             UnSelectCurrentSelection();
  129.     }
  130.  
  131.     private void OnUpdate_NoneTool ()
  132.     {
  133.         // If our cursor is over any UI, don't do anything
  134.         if (GameCursor.IsCursorOverUI())
  135.             return;
  136.  
  137.         // If we left click
  138.         if (Input.GetMouseButtonDown(0))
  139.         {
  140.             // Find the closest object we hit
  141.             GameObject hitObject = GameCursor.FindClosestObject(editorCamera.gameObject, true, GameCursor.IgnoreMapEditorTags);
  142.  
  143.             // If we hit nothing
  144.             if(hitObject == null)
  145.             {
  146.                 UnSelectCurrentSelection();
  147.                 return;
  148.             }
  149.  
  150.             // If it has a selectable component, then select it
  151.             PlacedObject placedObject = hitObject.GetComponent<PlacedObject>();
  152.             if(placedObject != null)
  153.             {
  154.                 SelectObject(placedObject);
  155.                 return;
  156.             }
  157.             else
  158.             {
  159.                 // If what we clicked on is not selectable, then we've selected nothing
  160.                 // and should unselect whatever we do have selected
  161.                 UnSelectCurrentSelection();
  162.             }
  163.         }
  164.     }
  165.  
  166.     private void OnUpdate_PlacementTool ()
  167.     {
  168.         if (snapToGrid)
  169.         {
  170.             SetCursorSelectionVisualToNearestGridPoint();
  171.         } else
  172.         {
  173.             SetCursorSelectVisualToCursor();
  174.         }
  175.  
  176.         // If we don't have an asset selected for placement,
  177.         // AKA we're not placing anything, then we can't be
  178.         // in placement mode
  179.         if (selectedAssetForPlacement == null && selectedNodeTypeForPlacement == PlacedNode.NodeType.None)
  180.         {
  181.             WriteToConsole("Nothing selected yet tool was caught in placement mode - Switching to none", ConsoleMessageType.Warning);
  182.             SetTool(ToolMode.None);
  183.             return;
  184.         }
  185.  
  186.         // If our cursor isn't over any UI
  187.         if(GameCursor.IsCursorOverUI() == false)
  188.         {
  189.             // If we left click
  190.             if (Input.GetMouseButtonDown(0))
  191.             {
  192.                 if(selectedAssetForPlacement != null)
  193.                 {
  194.                     // Place the asset we're holding, keep placing if we're holding shift
  195.                     PlaceAssetAtCursor(Input.GetKey(KeyCode.LeftShift));
  196.                 }
  197.                 else if (selectedNodeTypeForPlacement != PlacedNode.NodeType.None)
  198.                 {
  199.                     // Place the node we're holding, keep placing if we're holding shift
  200.                     PlaceNodeAtCursor(Input.GetKey(KeyCode.LeftShift));
  201.                 }
  202.             }
  203.             else if (Input.GetMouseButtonDown(1))
  204.             { // If we right click
  205.                 if (selectedAssetForPlacement != null)
  206.                 {
  207.                     // Cancel what we were doing
  208.                     CancelPlacingAsset();
  209.                 }
  210.                 else if (selectedNodeTypeForPlacement != PlacedNode.NodeType.None)
  211.                 {
  212.                     // Cancel what we were doing
  213.                     CancelPlacingNode();
  214.                 }
  215.             }
  216.         }
  217.  
  218.     }
  219.  
  220.     private void PlaceAssetAtCursor (bool isHoldingToPlaceMultiple)
  221.     {
  222.         MEObjectSpawner.Instance.PlaceAsset
  223.             (
  224.             selectedAssetForPlacement,
  225.             snapToGrid ? nearestGridPoint : cursorWorldPosition,
  226.             Vector3.zero,
  227.             Vector3.one
  228.             );
  229.  
  230.         if(isHoldingToPlaceMultiple == false)
  231.         {
  232.             CancelPlacingAsset();
  233.         }
  234.     }
  235.     private void PlaceNodeAtCursor (bool isHoldingToPlaceMultiple)
  236.     {
  237.         MEObjectSpawner.Instance.PlaceNode
  238.             (
  239.             selectedNodeTypeForPlacement,
  240.             snapToGrid ? nearestGridPoint : cursorWorldPosition,
  241.             Vector3.zero,
  242.             Vector3.one
  243.             );
  244.  
  245.         if (isHoldingToPlaceMultiple == false)
  246.             CancelPlacingNode();
  247.     }
  248.  
  249.     private void CancelPlacingAsset ()
  250.     {
  251.         SetTool(ToolMode.None);
  252.         selectedAssetForPlacement = null;
  253.     }
  254.     private void CancelPlacingNode ()
  255.     {
  256.         SetTool(ToolMode.None);
  257.         selectedNodeTypeForPlacement = PlacedNode.NodeType.None;
  258.     }
  259.  
  260.     private void SetCursorSelectVisualToCursor ()
  261.     {
  262.         // Set the position of the cursor selection to the cursor
  263.         cursorSelectionHolder.position = cursorWorldPosition;
  264.     }
  265.     private void SetCursorSelectionVisualToNearestGridPoint ()
  266.     {
  267.         // Set the position of the cursor selection to the nearest grid point
  268.         cursorSelectionHolder.position = nearestGridPoint;
  269.     }
  270.  
  271.     public void SelectAssetFromAssetBrowser(MapEditorAsset asset)
  272.     {
  273.         // Set the tool to none in case we had something else selected
  274.         SetTool(ToolMode.None);
  275.  
  276.         // Cache the selected asset
  277.         selectedAssetForPlacement = asset;
  278.  
  279.         // Instantiate a copy of the asset to the cursor selection holder so the player
  280.         // can see what they're placing down
  281.         GameObject visualAsset = Instantiate(asset.prefab, cursorSelectionHolder);
  282.  
  283.         // Then iterate through it and make it look like a ghost
  284.         foreach(MeshRenderer renderer in visualAsset.GetComponentsInChildren<MeshRenderer>())
  285.         {
  286.             renderer.material = ghostMaterial;
  287.         }
  288.  
  289.         // And iterate through it and get rid of any colliders so while placing it can't
  290.         // collide with raycasts or other objects
  291.         foreach(Collider col in visualAsset.GetComponentsInChildren<Collider>())
  292.         {
  293.             Destroy(col);
  294.         }
  295.  
  296.         // Finally, set the map editor tool to placement
  297.         SetTool(ToolMode.Placement);
  298.     }
  299.  
  300.     public void SelectNodeFromNodeBrowser (PlacedNode.NodeType type)
  301.     {
  302.         // Set the tool to none in case we had something else selected
  303.         SetTool(ToolMode.None);
  304.  
  305.         // Then cache the selected node
  306.         selectedNodeTypeForPlacement = type;
  307.  
  308.         // Create a visual to represent where the node will go & parent it to the cursor
  309.         Instantiate(nodeGenericVisualRepresentationPrefab, cursorSelectionHolder);
  310.  
  311.         // Then set the map editor tool to placement
  312.         SetTool(ToolMode.Placement);
  313.     }
  314.  
  315.     public void SetTool(ToolMode tool)
  316.     {
  317.         toolMode = tool;
  318.  
  319.         // Change the placement visual depending on the selected tool
  320.         switch (tool)
  321.         {
  322.             case ToolMode.None:
  323.                 // Get rid of any references to things we may have been placing
  324.                 selectedAssetForPlacement = null;
  325.                 selectedNodeTypeForPlacement = PlacedNode.NodeType.None;
  326.  
  327.                 // Make the object no longer visible
  328.                 cursorSelectionHolder.gameObject.SetActive(false);
  329.  
  330.                 // Set it to a position the player will never see
  331.                 cursorSelectionHolder.position = new Vector3(-999f, -999f, -999f);
  332.  
  333.                 // And get rid of any children since they're likely ghosts of whatever object
  334.                 // the player was placing
  335.                 foreach(Transform child in cursorSelectionHolder)
  336.                 {
  337.                     Destroy(child.gameObject);
  338.                 }
  339.                 break;
  340.             case ToolMode.Placement:
  341.                 cursorSelectionHolder.gameObject.SetActive(true);
  342.                 break;
  343.         }
  344.     }
  345.  
  346.     public void SetGroup (AssetGroup group)
  347.     {
  348.         selectedGroup = group;
  349.         UI_MapEditor.Instance.UpdateGroupsUI();
  350.         UI_MapEditor.Instance.UpdateAssetsUI();
  351.     }
  352.     public void SetDirectory (AssetDirectories directory)
  353.     {
  354.         selectedDirectory = directory;
  355.         UI_MapEditor.Instance.UpdateDirectoriesUI();
  356.         UI_MapEditor.Instance.UpdateAssetsUI();
  357.     }
  358.  
  359.     public void WriteToConsole (string text, ConsoleMessageType messageType = ConsoleMessageType.Normal)
  360.     {
  361.         string changedText = "";
  362.  
  363.         switch(messageType)
  364.         {
  365.             case ConsoleMessageType.Warning:
  366.                 changedText = "> <color=yellow>(Warning) " + text + "</color>";
  367.                 Debug.LogWarning("(Map Editor) " + text);
  368.                 break;
  369.             case ConsoleMessageType.Error:
  370.                 changedText = "> <color=red>(Error) " + text + "</color>";
  371.                 Debug.LogError("(Map Editor) " + text);
  372.                 break;
  373.             default:
  374.                 changedText = "> (Message) " + text;
  375.                 Debug.Log("(Map Editor) " + text);
  376.                 break;
  377.         }
  378.  
  379.         consoleMessages.Add(changedText);
  380.         consoleMessagesSentThisSession.Add("[" + realTime.ToString("N3") + "] " + changedText);
  381.         if (consoleMessages.Count > MaxConsoleMessages)
  382.             consoleMessages.RemoveAt(0);
  383.  
  384.         UI_MapEditor.Instance.UpdateConsoleText();
  385.     }
  386.  
  387.     public void SelectObject (PlacedObject placedObject)
  388.     {
  389.         // Unselect whatever we currently have selected
  390.         UnSelectCurrentSelection();
  391.         Debug.Log("Selected: " + placedObject.name);
  392.  
  393.         // Cache our selection
  394.         selectedObject = placedObject;
  395.  
  396.         // Update the inspector
  397.         UI_MapEditor.Instance.UpdateInspectorUI(selectedObject);
  398.     }
  399.  
  400.     public void UnSelectCurrentSelection ()
  401.     {
  402.         // Make the reference null
  403.         selectedObject = null;
  404.         // Then update the inspector
  405.         UI_MapEditor.Instance.UpdateInspectorUI(null);
  406.     }
  407.  
  408.     /*
  409.      * On Value Changed Functions
  410.      */
  411.     #region Inspector Transform Changes
  412.     public void OnValueChanged_Inspector_PositionX()
  413.     {
  414.         // Get the value the player entered
  415.         string text = UI_MapEditor.Instance.inspector_transform_positionDisplay_x.text;
  416.         // Then convert it to a float
  417.         float value = text == "" ? 0f : float.Parse(text);
  418.  
  419.         // Cache the object's relative transform
  420.         Vector3 position = selectedObject.transform.position;
  421.  
  422.         // And update the object's transform accordingly
  423.         position.x = value;
  424.         selectedObject.transform.position = position;
  425.     }
  426.     public void OnValueChanged_Inspector_PositionY()
  427.     {
  428.         // Get the value the player entered
  429.         string text = UI_MapEditor.Instance.inspector_transform_positionDisplay_y.text;
  430.         // Then convert it to a float
  431.         float value = text == "" ? 0f : float.Parse(text);
  432.  
  433.         // Cache the object's relative transform
  434.         Vector3 position = selectedObject.transform.position;
  435.  
  436.         // And update the object's transform accordingly
  437.         position.y = value;
  438.         selectedObject.transform.position = position;
  439.     }
  440.     public void OnValueChanged_Inspector_PositionZ()
  441.     {
  442.         // Get the value the player entered
  443.         string text = UI_MapEditor.Instance.inspector_transform_positionDisplay_z.text;
  444.         // Then convert it to a float
  445.         float value = text == "" ? 0f : float.Parse(text);
  446.  
  447.         // Cache the object's relative transform
  448.         Vector3 position = selectedObject.transform.position;
  449.  
  450.         // And update the object's transform accordingly
  451.         position.z = value;
  452.         selectedObject.transform.position = position;
  453.     }
  454.     public void OnValueChanged_Inspector_RotationX()
  455.     {
  456.         // Get the value the player entered
  457.         string text = UI_MapEditor.Instance.inspector_transform_rotationDisplay_x.text;
  458.         // Then convert it to a float
  459.         float value = text == "" ? 0f : float.Parse(text);
  460.  
  461.         // Cache the object's relative transform
  462.         Vector3 rotation = selectedObject.transform.eulerAngles;
  463.  
  464.         // And update the object's transform accordingly
  465.         rotation.x = value;
  466.         selectedObject.transform.eulerAngles = rotation;
  467.     }
  468.     public void OnValueChanged_Inspector_RotationY()
  469.     {
  470.         // Get the value the player entered
  471.         string text = UI_MapEditor.Instance.inspector_transform_rotationDisplay_y.text;
  472.         // Then convert it to a float
  473.         float value = text == "" ? 0f : float.Parse(text);
  474.  
  475.         // Cache the object's relative transform
  476.         Vector3 rotation = selectedObject.transform.eulerAngles;
  477.  
  478.         // And update the object's transform accordingly
  479.         rotation.y = value;
  480.         selectedObject.transform.eulerAngles = rotation;
  481.     }
  482.     public void OnValueChanged_Inspector_RotationZ()
  483.     {
  484.         // Get the value the player entered
  485.         string text = UI_MapEditor.Instance.inspector_transform_rotationDisplay_z.text;
  486.         // Then convert it to a float
  487.         float value = text == "" ? 0f : float.Parse(text);
  488.  
  489.         // Cache the object's relative transform
  490.         Vector3 rotation = selectedObject.transform.eulerAngles;
  491.  
  492.         // And update the object's transform accordingly
  493.         rotation.z = value;
  494.         selectedObject.transform.eulerAngles = rotation;
  495.     }
  496.     public void OnValueChanged_Inspector_ScaleX()
  497.     {
  498.         // Get the value the player entered
  499.         string text = UI_MapEditor.Instance.inspector_transform_scaleDisplay_x.text;
  500.         // Then convert it to a float
  501.         float value = text == "" ? 0f : float.Parse(text);
  502.  
  503.         // Cache the object's relative transform
  504.         Vector3 scale = selectedObject.transform.localScale;
  505.  
  506.         // And update the object's transform accordingly
  507.         scale.x = value;
  508.         selectedObject.transform.localScale = scale;
  509.     }
  510.     public void OnValueChanged_Inspector_ScaleY()
  511.     {
  512.         // Get the value the player entered
  513.         string text = UI_MapEditor.Instance.inspector_transform_scaleDisplay_y.text;
  514.         // Then convert it to a float
  515.         float value = text == "" ? 0f : float.Parse(text);
  516.  
  517.         // Cache the object's relative transform
  518.         Vector3 scale = selectedObject.transform.localScale;
  519.  
  520.         // And update the object's transform accordingly
  521.         scale.y = value;
  522.         selectedObject.transform.localScale = scale;
  523.     }
  524.     public void OnValueChanged_Inspector_ScaleZ()
  525.     {
  526.         // Get the value the player entered
  527.         string text = UI_MapEditor.Instance.inspector_transform_scaleDisplay_z.text;
  528.         // Then convert it to a float
  529.         float value = text == "" ? 0f : float.Parse(text);
  530.  
  531.         // Cache the object's relative transform
  532.         Vector3 scale = selectedObject.transform.localScale;
  533.  
  534.         // And update the object's transform accordingly
  535.         scale.z = value;
  536.         selectedObject.transform.localScale = scale;
  537.     }
  538.     #endregion
  539.     /*
  540.      * On Click Functions
  541.      */
  542.     public void OnClick_DeleteSelectedObject ()
  543.     {
  544.         MEObjectSpawner.Instance.DestroyPlacedObject(selectedObject);
  545.         UnSelectCurrentSelection();
  546.     }
  547.     public void OnClick_Save ()
  548.     {
  549.         UI_MapEditor.Instance.OpenSaveMenu();
  550.     }
  551.  
  552.     public void OnClick_Load ()
  553.     {
  554.         UI_MapEditor.Instance.OpenLoadMenu();
  555.     }
  556.  
  557.     public void OnClick_AssetInHierarchy (PlacedAsset asset)
  558.     {
  559.         SelectObject(asset);
  560.     }
  561. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top