Skip to content

Commit

Permalink
Add IBlockyScenePreprocessor interface
Browse files Browse the repository at this point in the history
  • Loading branch information
bgk- committed Feb 8, 2022
1 parent 5c178fa commit 28e0947
Show file tree
Hide file tree
Showing 28 changed files with 213 additions and 100 deletions.
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#### 0.1.3 (2022-01-23)

- Fix default parent setter scene reference
- Update README
- Implement random rotation and placement visualization

#### 0.1.2 (2022-01-16)

- Add README
- Fix ParentSetter editor
- Refactor out parentSetter

#### 0.1.1 (2021-12-30)
- Video Part 3 end
- Initial commit
7 changes: 7 additions & 0 deletions CHANGELOG.md.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Editor/Attributes.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions Editor/Attributes/BlockyButtonAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;

namespace PeartreeGames.BlockyWorldEditor.Editor
{
[AttributeUsage(AttributeTargets.Method)]
public class BlockyButtonAttribute : Attribute
{
public readonly string label;

public BlockyButtonAttribute() {}

public BlockyButtonAttribute(string label)
{
this.label = label;
}
}
}
3 changes: 3 additions & 0 deletions Editor/Attributes/BlockyButtonAttribute.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
using System;
using UnityEngine;
using UnityEngine;

namespace PeartreeGames.BlockyWorldEditor.Editor
{
public class SceneObjectAttribute : PropertyAttribute
public class BlockySceneObjectAttribute : PropertyAttribute
{
public readonly string backingPropertyName;

public SceneObjectAttribute(string backingPropertyName)
public BlockySceneObjectAttribute(string backingPropertyName)
{
this.backingPropertyName = backingPropertyName;
}
Expand Down
17 changes: 2 additions & 15 deletions Editor/BlockyUtilities.cs → Editor/BlockyEditorUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,14 @@

namespace PeartreeGames.BlockyWorldEditor.Editor
{
public static class BlockyUtilities
public static class BlockyEditorUtilities
{
public static float ClampAngle(float rotationY) => rotationY < 0 ? 360 - Mathf.Abs(rotationY) % 360 :
rotationY > 360 ? rotationY % 360 : rotationY;

public static Vector3Int SnapToGrid(Vector3 hit, int gridHeight, int gridSize = 1) =>
new(Mathf.RoundToInt(hit.x / gridSize) * gridSize, gridHeight,
Mathf.RoundToInt(hit.z / gridSize) * gridSize);

public static void SetTargetVisualization(Vector3Int target, BlockyEditMode mode, int brushSize,
bool isSquareDragging, List<Vector3Int> squareDraggingList, Vector3Int squareDragStart)
{
var originalColor = Handles.color;
Handles.color = Event.current.control ? Color.red : Color.cyan;
var gridSize = Vector3.one;
if (mode == BlockyEditMode.Paint)
{
// render placement prefab
}

var offset = new Vector3(0, -0.5f, 0);

if (isSquareDragging)
Expand All @@ -33,7 +21,6 @@ public static void SetTargetVisualization(Vector3Int target, BlockyEditMode mode
{
Handles.DrawWireCube(pos + offset, gridSize);
}

Handles.color = originalColor;
return;
}
Expand Down Expand Up @@ -81,7 +68,7 @@ public static bool TryGetTargetPoint(Vector2 currentMousePosition, int gridHeigh
var hPlane = new Plane(Vector3.up, Vector3.up * gridHeight);
if (!hPlane.Raycast(ray, out var enter)) return false;
var hit = ray.GetPoint(enter);
targetHit = SnapToGrid(hit, gridHeight);
targetHit = BlockyUtilities.SnapToGrid(hit, gridHeight);
return true;
}

Expand Down
File renamed without changes.
73 changes: 57 additions & 16 deletions Editor/BlockyEditorWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UIElements;
using Random = UnityEngine.Random;

Expand All @@ -20,16 +21,13 @@ public class BlockyEditorWindow : EditorWindow
private bool _isSquareDragging;
private readonly List<Vector3Int> _draggingSquareList = new();
private Vector3Int _dragStartPosition;

public static readonly Vector3 GridOffset = new(0.5f, 0, 0.5f);
private IBlockyPiece CurrentBlocky => _settings == null ? null : _settings.Selected;
public Action<BlockyEditMode> onBlockyModeChange;

private GameObject _placementObject;
private Shader _placementShader;


[MenuItem("Window/BlockyEditor")]
[MenuItem("Tools/BlockyEditor")]
private static void ShowWindow()
{
var window = GetWindow<BlockyEditorWindow>();
Expand All @@ -39,8 +37,7 @@ private static void ShowWindow()

private void OnEnable()
{
onBlockyModeChange = delegate { };
onBlockyModeChange += OnBlockyModeChange;
EditorSceneManager.sceneClosing += OnSceneClosing;
_placementShader = Shader.Find("Blocky/Placement");
PopulateMap();
if (_settings == null)
Expand Down Expand Up @@ -70,25 +67,69 @@ private void OnEnable()
.First(a => a is BlockyParentSetter) as BlockyParentSetter;

}
if (_serializedSettings == null) _serializedSettings = new SerializedObject(_settings);

_settings.editMode = BlockyEditMode.None;
_serializedSettings ??= new SerializedObject(_settings);
_serializedSettings.ApplyModifiedProperties();
rootVisualElement.styleSheets.Add(Resources.Load<StyleSheet>("BlockyEditor"));
var settingsView = new BlockySettingsElement(this, _serializedSettings);
rootVisualElement.Add(settingsView);

RefreshPalette();
Repaint();
RefreshPalette();
Repaint();
}

private void OnBlockyModeChange(BlockyEditMode mode)
private void OnDisable()
{
EditorSceneManager.sceneClosing -= OnSceneClosing;
}

private void OnSceneClosing(Scene scene, bool removingScene)
{
if (_settings.editMode == BlockyEditMode.None) return;
// In Painting/Selection mode while scene is closing, process the scenes beforehand
var preprocessors = GetScenePreprocessors();
foreach(var preprocessor in preprocessors) preprocessor.ProcessScene(this, scene);
EditorSceneManager.MarkSceneDirty(scene);
EditorSceneManager.SaveScene(scene);
}

public void OnBlockyModeChange(BlockyEditMode mode)
{
if (mode != BlockyEditMode.Paint && _placementObject != null)
var preprocessors = GetScenePreprocessors();
var openSceneCount = SceneManager.sceneCount;
if (mode == BlockyEditMode.None)
{
DestroyImmediate(_placementObject);
if (_placementObject != null) DestroyImmediate(_placementObject);
for (var i = 0; i < openSceneCount; i++)
{
var scene = SceneManager.GetSceneAt(i);
foreach(var preprocessor in preprocessors) preprocessor.ProcessScene(this, scene);
}
EditorSceneManager.MarkAllScenesDirty();
EditorSceneManager.SaveOpenScenes();
}
else
{
for (var i = 0; i < openSceneCount; i++)
{
var scene = SceneManager.GetSceneAt(i);
foreach (var preprocessor in preprocessors) preprocessor.RevertScene(this, scene);
}
}
}

private static List<IBlockyScenePreprocessor> GetScenePreprocessors()
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var results = new List<IBlockyScenePreprocessor>();
foreach (var assembly in assemblies)
{
var preprocessors = assembly.GetTypes()
.Where(t => !t.IsAbstract && t.GetInterfaces().Contains(typeof(IBlockyScenePreprocessor))).Select(t => (IBlockyScenePreprocessor) Activator.CreateInstance(t)).ToList();
results.AddRange(preprocessors);
}
return results;
}


Expand Down Expand Up @@ -120,12 +161,12 @@ private void OnLostFocus()
private void OnSceneGUI(SceneView sceneView)
{
if (_settings.editMode == BlockyEditMode.None) return;
if (!BlockyUtilities.TryGetTargetPoint(Event.current.mousePosition, _settings.gridHeight,
if (!BlockyEditorUtilities.TryGetTargetPoint(Event.current.mousePosition, _settings.gridHeight,
out _settings.target)) return;
BlockyUtilities.SetTargetVisualization(_settings.target, _settings.editMode, _settings.brushSize,
BlockyEditorUtilities.SetTargetVisualization(_settings.target, _settings.editMode, _settings.brushSize,
_isSquareDragging, _draggingSquareList, _dragStartPosition);
BlockyUtilities.SetPlacementVisualization(_settings.target, _settings.rotation, _settings.editMode, CurrentBlocky, _placementShader, ref _placementObject);
_settings.parentSetter.SetBoundsVisualization(_settings.target, _settings.gridHeight);
BlockyEditorUtilities.SetPlacementVisualization(_settings.target, _settings.rotation, _settings.editMode, CurrentBlocky, _placementShader, ref _placementObject);
_settings.parentSetter.SetVisualization(_settings.target, _settings.gridHeight);

HandleInput(_settings.target);
HandleUtility.Repaint();
Expand Down
2 changes: 1 addition & 1 deletion Editor/BlockyParentSetter/BlockyDefaultParentSetter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace PeartreeGames.BlockyWorldEditor.Editor
public class BlockyDefaultParentSetter : BlockyParentSetter
{
[SerializeField]
[SceneObject("Parent")]
[BlockySceneObject("Parent")]
private GameObject parent;

public GameObject Parent { get; set; }
Expand Down
5 changes: 1 addition & 4 deletions Editor/BlockyParentSetter/BlockyParentSetter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ namespace PeartreeGames.BlockyWorldEditor.Editor
{
public abstract class BlockyParentSetter : ScriptableObject
{
public virtual void Init(BlockyEditorWindow window) {}
public abstract Transform GetParent(BlockyObject block);
public virtual void SetBoundsVisualization(Vector3Int target, int gridHeight) {}


public virtual void SetVisualization(Vector3Int target, int gridHeight) {}
}
}
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@

namespace PeartreeGames.BlockyWorldEditor.Editor
{
[CustomPropertyDrawer(typeof(SceneObjectAttribute))]
public class SceneObjectDrawer : PropertyDrawer
[CustomPropertyDrawer(typeof(BlockySceneObjectAttribute))]
public class BlockySceneObjectDrawer : PropertyDrawer
{

public override VisualElement CreatePropertyGUI(SerializedProperty property)
{
var elem = new ObjectField(property.name) { allowSceneObjects = true, objectType = typeof(GameObject) };
var sceneObject = attribute as SceneObjectAttribute;
var sceneObject = attribute as BlockySceneObjectAttribute;
elem.RegisterValueChangedCallback(changed =>
{
var type = property.serializedObject.targetObject.GetType();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ public BlockySettingsElement(BlockyEditorWindow window, SerializedObject seriali
{
serializedParentSetterProperty.objectReferenceValue =
parentSetters.Find(p => p.GetType().Name == change.newValue);
((BlockyParentSetter)serializedParentSetterProperty.objectReferenceValue).Init(window);
serializedSettings.ApplyModifiedProperties();
serializedParentSetterProperty = serializedSettings.FindProperty("parentSetter");
var prev = placement.Q("ParentSetter");
Expand Down Expand Up @@ -103,16 +102,15 @@ public BlockySettingsElement(BlockyEditorWindow window, SerializedObject seriali
paintButton.RegisterValueChangedCallback(c =>
{
settings.editMode = c.newValue ? BlockyEditMode.Paint : BlockyEditMode.None;
((BlockyParentSetter)serializedParentSetterProperty.objectReferenceValue).Init(window);
window.onBlockyModeChange?.Invoke(settings.editMode);
window.PopulateMap();
window.OnBlockyModeChange(settings.editMode);
selectButton.SetValueWithoutNotify(false);
});
selectButton.RegisterValueChangedCallback(c =>
{
settings.editMode = c.newValue ? BlockyEditMode.Select : BlockyEditMode.None;
window.onBlockyModeChange?.Invoke(settings.editMode);
window.PopulateMap();
window.OnBlockyModeChange(settings.editMode);
paintButton.SetValueWithoutNotify(false);
});
modes.Add(paintButton);
Expand All @@ -134,30 +132,34 @@ private static GroupBox CreateParentSetterBox(SerializedProperty prop)
var obj = new SerializedObject(prop.objectReferenceValue);
box.AddToClassList("parent-setter");

// if (prop.objectReferenceValue is BlockyDefaultParentSetter defaultParentSetter)
// {
// defaultParentSetter.Parent = null;
// var parentField = new ObjectField("Parent") { allowSceneObjects = true, objectType = typeof(GameObject) };
// parentField.RegisterValueChangedCallback(changed =>
// {
// defaultParentSetter.Parent = changed.newValue as GameObject;
// });
// box.Add(parentField);
// }
// else
// {
var itr = obj.GetIterator();
if (itr.NextVisible(true))
var itr = obj.GetIterator();
if (itr.NextVisible(true))
{
do
{
if (itr.name == "m_Script") continue;
var field = new PropertyField(itr);
field.Bind(obj);
box.Add(field);
} while (itr.NextVisible(false));
}

var methods = prop.objectReferenceValue.GetType().GetMethods().Where(m => m.GetCustomAttributes(typeof(BlockyButtonAttribute), true).Length > 0).ToList();
foreach (var method in methods)
{
if (method.GetParameters().Length > 0) continue;
var label =
((BlockyButtonAttribute) method.GetCustomAttributes(typeof(BlockyButtonAttribute), false)[0]).label;
var button = new Button(() =>
{
method.Invoke(prop.objectReferenceValue, null);
})
{
do
{
if (itr.name == "m_Script") continue;
var field = new PropertyField(itr);
field.Bind(obj);
box.Add(field);
} while (itr.NextVisible(false));
}
// }
text = label ?? method.Name
};

box.Add(button);
}

return box;
}
Expand All @@ -179,7 +181,6 @@ private static List<BlockyParentSetter> GetParentSetters(SerializedObject obj, B
var subAssets = AssetDatabase.LoadAllAssetsAtPath(path);
foreach (var result in parentSetterClasses)
{
result.Init(window);
if (Array.Exists(subAssets, sub => sub.GetType().Name == result.GetType().Name)) continue;
result.name = result.GetType().Name;
AssetDatabase.AddObjectToAsset(result, obj.targetObject);
Expand Down
10 changes: 10 additions & 0 deletions Editor/IBlockyScenePreprocessor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using UnityEngine.SceneManagement;

namespace PeartreeGames.BlockyWorldEditor.Editor
{
public interface IBlockyScenePreprocessor
{
public void ProcessScene(BlockyEditorWindow window, Scene scene);
public void RevertScene(BlockyEditorWindow window, Scene scene);
}
}
Loading

0 comments on commit 28e0947

Please sign in to comment.