Beispiel #1
0
        protected void PaintSnapVisualisation()
        {
            if (visualSnappedEdges != null)
            {
                PaintUtility.DrawLines(visualSnappedEdges.ToArray(), ToolConstants.oldThickLineScale, ColorSettings.SnappedEdges);
            }

            var _origMatrix = Handles.matrix;

            Handles.matrix = MathConstants.identityMatrix;
            if (visualSnappedGrid != null)
            {
                PaintUtility.DrawDottedLines(visualSnappedGrid.ToArray(), ColorSettings.SnappedEdges);
            }

            if (visualSnappedBrush != null)
            {
                var brush_cache = InternalCSGModelManager.GetBrushCache(visualSnappedBrush);
                if (brush_cache != null &&
                    brush_cache.compareTransformation != null &&
                    brush_cache.childData != null &&
                    brush_cache.childData.ModelTransform != null &&
                    brush_cache.childData.ModelTransform)
                {
                    var color             = ColorSettings.HoverOutlines;
                    var brush_translation = brush_cache.compareTransformation.modelLocalPosition + brush_cache.childData.ModelTransform.position;
                    CSGRenderer.DrawOutlines(visualSnappedBrush.brushID, brush_translation,
                                             color, color, color, color, ToolConstants.oldThickLineScale);
                }
            }
            Handles.matrix = _origMatrix;
        }
Beispiel #2
0
        public UndoGroup(SelectedBrushSurface[] selectedBrushSurfaces, string name, bool reregisterMaterials = false, bool ignoreGroup = false)
        {
            if (selectedBrushSurfaces == null)
            {
                return;
            }

            this._reregisterMaterials = reregisterMaterials;
            var uniqueBrushes = new HashSet <CSGBrush>();
            var uniqueModels  = new HashSet <CSGModel>();

            for (int i = 0; i < selectedBrushSurfaces.Length; i++)
            {
                if (!selectedBrushSurfaces[i].brush)
                {
                    continue;
                }

                var brush = selectedBrushSurfaces[i].brush;
//				var surface_index = selectedBrushSurfaces[i].surfaceIndex;
                if (uniqueBrushes.Add(brush))
                {
                    CSGBrushCache brushCache = InternalCSGModelManager.GetBrushCache(brush);
                    if (brushCache != null)
                    {
                        uniqueModels.Add(brushCache.childData.Model);
                    }
                }
            }

            _undoGroupIndex = -1;

            _brushes = uniqueBrushes.ToArray();
            _models  = uniqueModels.ToArray();
            if (_brushes.Length > 0)
            {
                if (!ignoreGroup)
                {
                    _undoGroupIndex = Undo.GetCurrentGroup();
                    Undo.IncrementCurrentGroup();
                }
                Undo.RegisterCompleteObjectUndo(_brushes, name);
                for (int i = 0; i < _brushes.Length; i++)
                {
                    if (!_brushes[i])
                    {
                        continue;
                    }
                    UnityEditor.EditorUtility.SetDirty(_brushes[i]);
                    if (reregisterMaterials)
                    {
                        CSGBrushCache brushCache = InternalCSGModelManager.GetBrushCache(_brushes[i]);
                        if (brushCache != null)
                        {
                            InternalCSGModelManager.UnregisterMaterials(brushCache.childData.Model, _brushes[i].Shape, false);
                        }
                    }
                }
            }
        }
Beispiel #3
0
        public override void OnPaint()
        {
            RealtimeCSG.Grid.RenderGrid();
            if (hoverBrushSurface == null)
            {
                return;
            }

            var brush       = hoverBrushSurface.brush;
            var brush_cache = InternalCSGModelManager.GetBrushCache(brush);

            if (brush_cache == null ||
                brush_cache.childData == null ||
                brush_cache.childData.ModelTransform == null)
            {
                return;
            }

            var highlight_surface = hoverBrushSurface.surfaceIndex;
            var highlight_texGen  = brush.Shape.Surfaces[highlight_surface].TexGenIndex;
            var model_translation = brush_cache.childData.Model.transform.position;
            var brush_translation = brush_cache.compareTransformation.modelLocalPosition + model_translation;

            CSGRenderer.DrawSelectedBrush(brush.brushID, brush.Shape,
                                          brush_translation, ColorSettings.WireframeOutline,
                                          highlight_texGen,
                                          false, ToolConstants.oldLineScale);
        }
        public void OnPaint()
        {
            if (!hoverOnSelectedSurfaces)
            {
                var activetool = EditModeManager.ActiveTool as EditModeSurface;
                if (activetool != null)
                {
                    var selectedBrushSurfaces = activetool.GetSelectedSurfaces();
                    for (int i = 0; i < selectedBrushSurfaces.Length; i++)
                    {
                        var brush       = selectedBrushSurfaces[i].brush;
                        var brush_cache = InternalCSGModelManager.GetBrushCache(brush);
                        if (brush_cache == null)
                        {
                            return;
                        }

                        var highlight_surface = selectedBrushSurfaces[i].surfaceIndex;
                        var highlight_texGen  = brush.Shape.Surfaces[highlight_surface].TexGenIndex;
                        var brush_translation = brush_cache.compareTransformation.modelLocalPosition + brush_cache.childData.ModelTransform.position;

                        CSGRenderer.DrawTexGenOutlines(brush.brushID, brush.Shape,
                                                       brush_translation, highlight_texGen,
                                                       ColorSettings.SurfaceInnerStateColor[2],
                                                       ColorSettings.SurfaceOuterStateColor[2],
                                                       //ColorSettings.SurfaceTriangleStateColor[2],
                                                       ToolConstants.oldThinLineScale);
                    }
                }
            }

            if (hoverBrushSurfaces != null)
            {
                for (int i = 0; i < hoverBrushSurfaces.Length; i++)
                {
                    var brush       = hoverBrushSurfaces[i].brush;
                    var brush_cache = InternalCSGModelManager.GetBrushCache(brush);
                    if (brush_cache == null)
                    {
                        return;
                    }

                    var brush_translation = brush_cache.compareTransformation.modelLocalPosition + brush_cache.childData.ModelTransform.position;

                    var highlight_surface = hoverBrushSurfaces[i].surfaceIndex;
                    if (highlight_surface == -1 || selectAllSurfaces)
                    {
                        CSGRenderer.DrawSelectedBrush(brush.brushID, brush.Shape, brush_translation, ColorSettings.WireframeOutline, 0, selectAllSurfaces, ToolConstants.oldLineScale);
                    }
                    else
                    {
                        var highlight_texGen = brush.Shape.Surfaces[highlight_surface].TexGenIndex;
                        CSGRenderer.DrawSelectedBrush(brush.brushID, brush.Shape, brush_translation, ColorSettings.WireframeOutline, highlight_texGen, selectAllSurfaces, ToolConstants.oldLineScale);
                    }
                }
            }
        }
Beispiel #5
0
        internal static void OnPaint(SceneView sceneView)
        {
            SceneDragToolManager.OnPaint();

            if (sceneView == null ||
                Event.current.type != EventType.Repaint)
            {
                return;
            }

            if (RealtimeCSG.CSGSettings.GridVisible)
            {
                RealtimeCSG.CSGGrid.RenderGrid();
            }

            if (RealtimeCSG.CSGSettings.IsWireframeShown(sceneView))
            {
                if (forceOutlineUpdate || meshGeneration != InternalCSGModelManager.MeshGeneration)
                {
                    forceOutlineUpdate = false;
                    meshGeneration     = InternalCSGModelManager.MeshGeneration;
                    lineMeshManager.Begin();
                    for (int i = 0; i < InternalCSGModelManager.Brushes.Length; i++)
                    {
                        var brush = InternalCSGModelManager.Brushes[i];
                        if (!brush)
                        {
                            continue;
                        }

                        var brush_cache = InternalCSGModelManager.GetBrushCache(brush);
                        if (brush_cache == null)
                        {
                            continue;
                        }

                        if (!brush.outlineColor.HasValue)
                        {
                            brush.outlineColor = ColorSettings.GetBrushOutlineColor(brush);
                        }

                        var brush_translation = brush_cache.compareTransformation.modelLocalPosition +
                                                brush_cache.childData.ModelTransform.position;
                        CSGRenderer.DrawSimpleOutlines(lineMeshManager, brush.brushID, brush_translation, brush.outlineColor.Value);
                    }
                    lineMeshManager.End();
                }

                MaterialUtility.LineDashMultiplier      = 1.0f;
                MaterialUtility.LineThicknessMultiplier = 1.0f;
                MaterialUtility.LineAlphaMultiplier     = 1.0f;
                lineMeshManager.Render(MaterialUtility.NoZTestGenericLine);
            }
        }
 void UpdateBrushMeshes(HashSet <CSGBrush> brushes, HashSet <CSGModel> models)
 {
     foreach (var brush in brushes)
     {
         brush.EnsureInitialized();
         ShapeUtility.CheckMaterials(brush.Shape);
         var brush_cache = InternalCSGModelManager.GetBrushCache(brush);
         InternalCSGModelManager.RegisterMaterials(brush_cache.childData.Model, brush.Shape, false);
     }
     foreach (var model in models)
     {
         InternalCSGModelManager.UpdateMaterialCount(model);
     }
     foreach (var brush in brushes)
     {
         InternalCSGModelManager.CheckSurfaceModifications(brush, true);
         InternalCSGModelManager.ValidateBrush(brush);
     }
     MeshInstanceManager.UpdateHelperSurfaceVisibility();
 }
        void RestoreMaterials(SelectedBrushSurface[] hoverBrushSurfaces)
        {
            if (hoverBrushSurfaces == null)
            {
                return;
            }

            var updateModels  = new HashSet <CSGModel>();
            var updateBrushes = new HashSet <CSGBrush>();

            for (int i = 0; i < hoverBrushSurfaces.Length; i++)
            {
                var brush       = hoverBrushSurfaces[i].brush;
                var brush_cache = InternalCSGModelManager.GetBrushCache(brush);
                if (brush_cache == null ||
                    brush_cache.childData == null ||
                    brush_cache.childData.Model == null)
                {
                    continue;
                }

                try
                {
                    var model = brush_cache.childData.Model;
                    updateModels.Add(model);
                    if (updateBrushes.Add(brush))
                    {
                        var shape = brush.Shape;
                        for (int t = 0; t < shape.TexGens.Length; t++)
                        {
                            shape.TexGens[t].RenderMaterial = previousMaterials[i][t];
                        }
                    }
                }
                finally { }
            }
            UpdateBrushMeshes(updateBrushes, updateModels);
        }
        void RestoreMaterials(SelectedBrushSurface[] hoverBrushSurfaces)
        {
            if (hoverBrushSurfaces == null)
            {
                return;
            }

            var updateModels  = new HashSet <CSGModel>();
            var updateBrushes = new HashSet <CSGBrush>();

            for (int i = 0; i < hoverBrushSurfaces.Length; i++)
            {
                var brush       = hoverBrushSurfaces[i].brush;
                var brush_cache = InternalCSGModelManager.GetBrushCache(brush);
                if (brush_cache == null ||
                    brush_cache.childData == null ||
                    brush_cache.childData.Model == null)
                {
                    continue;
                }

                try
                {
                    var model = brush_cache.childData.Model;
                    updateModels.Add(model);
                    if (updateBrushes.Add(brush))
                    {
                        InternalCSGModelManager.UnregisterMaterials(model, brush.Shape, false);

                        System.Array.Copy(previousMaterials[i], brush.Shape.Materials, brush.Shape.Materials.Length);
                    }
                }
                finally { }
            }
            UpdateBrushMeshes(updateBrushes, updateModels);
        }
        //void OnSceneGUI() <- paints -everything- again for every selected brush
        public static void OnSceneGUI(SceneView sceneView)
        {
            if (EditorApplication.isPlayingOrWillChangePlaymode)
            {
                return;
            }


            /*
             * int prevHotControl		= GUIUtility.hotControl;
             * int prevKeyboardControl = GUIUtility.keyboardControl;
             *
             * // make it impossible for the tool to click in the bottom bar area
             * int bottomBarId	 = GUIUtility.GetControlID (BottomBarInputHash, FocusType.Passive);
             * bool forceRevert = false;
             * //if (GUIUtility.hotControl == 0)
             * {
             *      var bottomBarRect = sceneView.position;
             *      var min = bottomBarRect.min;
             *      var max = bottomBarRect.max;
             *
             *      min.y = max.y - (GUIStyleUtility.BottomToolBarHeight + 18);
             *
             *      bottomBarRect.min = min;
             *      bottomBarRect.max = max;
             *
             *      if (bottomBarRect.Contains(Event.current.mousePosition))
             *      {
             *              GUIUtility.hotControl	   = bottomBarId;
             *              GUIUtility.keyboardControl = bottomBarId;
             *              forceRevert = true;
             *      }
             * }
             */
            SelectionUtility.HandleEvents();
            InitTools();

            HandleBuilderEvents();
            //HandleYMode();
            {
                UpdateTool();

                if (instance.activeTool != null)
                {
                    if (RealtimeCSG.CSGSettings.EnableRealtimeCSG)
                    {
                        // handle the tool
                        var sceneSize = sceneView.position.size;
                        var sceneRect = new Rect(0, 0, sceneSize.x, sceneSize.y - ((GUIStyleUtility.BottomToolBarHeight + 4) + 17));
                        //var originalEventType = Event.current.type;
                        //if (originalEventType == EventType.MouseMove ||
                        //	originalEventType == EventType.MouseUp)
                        //	holdingDownMouse = false;

                        //var mousePos = Event.current.mousePosition;
                        //if (originalEventType == EventType.Layout ||
                        //	originalEventType == EventType.Repaint ||
                        //	sceneRect.Contains(mousePos) ||
                        //	holdingDownMouse)
                        instance.activeTool.HandleEvents(sceneRect);

                        //if (originalEventType == EventType.MouseDown ||
                        //	originalEventType == EventType.MouseDrag)
                        //	holdingDownMouse = true;
                    }
                    else
                    {
                        if (Event.current.type == EventType.Repaint)
                        {
                            var brushes      = instance.filteredSelection.BrushTargets;
                            var wireframes   = new List <GeometryWireframe>(brushes.Length);
                            var translations = new List <Vector3>(brushes.Length);
                            for (int i = 0; i < brushes.Length; i++)
                            {
                                var brush = brushes[i];
                                if (!brush)
                                {
                                    continue;
                                }

                                var brushCache = InternalCSGModelManager.GetBrushCache(brush);
                                if (brushCache == null ||
                                    brushCache.childData == null ||
                                    !brushCache.childData.Model)
                                {
                                    continue;
                                }

                                var brushTranslation = brushCache.compareTransformation.modelLocalPosition + brushCache.childData.ModelTransform.position;

                                wireframes.Add(BrushOutlineManager.GetBrushOutline(brushes[i].brushID));
                                translations.Add(brushTranslation);
                            }
                            if (wireframes.Count > 0)
                            {
                                CSGRenderer.DrawSelectedBrushes(instance.zTestLineMeshManager, instance.noZTestLineMeshManager,
                                                                wireframes.ToArray(), translations.ToArray(),
                                                                ColorSettings.SelectedOutlines, ToolConstants.thickLineScale);
                            }
                            MaterialUtility.LineDashMultiplier      = 1.0f;
                            MaterialUtility.LineThicknessMultiplier = 1.0f;
                            MaterialUtility.LineAlphaMultiplier     = 1.0f;
                            instance.zTestLineMeshManager.Render(MaterialUtility.ZTestGenericLine);
                            instance.zTestLineMeshManager.Render(MaterialUtility.ZTestGenericLine);
                        }
                    }
                }
            }

            /*
             * // reset the control so the bottom bar can take over
             * if (forceRevert)
             * {
             *      GUIUtility.hotControl		= prevHotControl;
             *      GUIUtility.keyboardControl	= prevKeyboardControl;
             * }
             */

            int sceneWindowId   = GUIUtility.GetControlID(SceneWindowHash, FocusType.Passive);
            var sceneWindowType = Event.current.GetTypeForControl(sceneWindowId);

            if (sceneWindowType == EventType.Repaint)
            {
                if (currentEditorWindows.Count > 0)
                {
                    for (int i = 0; i < currentEditorWindows.Count; i++)
                    {
                        currentEditorWindows[i].Repaint();
                    }
                    return;
                }
            }

            if (sceneWindowType == EventType.MouseMove)
            {
                SceneTools.IsDraggingObjectInScene = false;
            }

            if (RealtimeCSG.CSGSettings.EnableRealtimeCSG)
            {
                if (sceneView != null && sceneWindowType != EventType.Used && !SceneTools.IsDraggingObjectInScene)
                {
                    if (currentEditorWindows.Count == 0)
                    {
                        try
                        {
                            Handles.BeginGUI();
                            Rect windowRect = new Rect(Vector2.zero, sceneView.position.size);
                            CSGBrushEditorGUI.HandleWindowGUI(windowRect);
                        }
                        finally
                        {
                            Handles.EndGUI();
                        }
                    }
                }
            }
        }
Beispiel #10
0
        /*
         * static void OnGUIContentsMaterialInspector(Material material, bool mixedValues)
         * {
         *      //if (materialEditor == null || prevMaterial != material)
         *      {
         *              var editor = materialEditor as Editor;
         *              Editor.CreateCachedEditor(material, typeof(MaterialEditor), ref editor);
         *              materialEditor = editor as MaterialEditor;
         *      }
         *
         *      if (materialEditor != null)
         *      {
         *              EditorGUI.showMixedValue = mixedValues;
         *              try
         *              {
         *                      materialEditor.DrawHeader();
         *                      if (materialEditor.PropertiesGUI())
         *                      {
         *                              materialEditor.PropertiesChanged();
         *                      }
         *              }
         *              catch
         *              {}
         *              EditorGUI.showMixedValue = false;
         *      }
         * }
         */

        private static void OnGUIContents(bool isSceneGUI, EditModeSurface tool)
        {
            EditModeCommonGUI.StartToolGUI();

            var selectedBrushSurfaces = (tool == null) ? new SelectedBrushSurface[0] : tool.GetSelectedSurfaces();
            var enabled = selectedBrushSurfaces.Length > 0;

            EditorGUI.BeginDisabledGroup(!enabled);
            {
                Material material      = null;
                var      currentTexGen = new TexGen();

                var  haveTexgen            = false;
                var  multipleColors        = !enabled;
                var  multipleTranslationX  = !enabled;
                var  multipleTranslationY  = !enabled;
                var  multipleScaleX        = !enabled;
                var  multipleScaleY        = !enabled;
                var  multipleRotationAngle = !enabled;
                var  multipleMaterials     = !enabled;
                bool?textureLocked         = null;

                bool foundHelperMaterial = false;
                RenderSurfaceType?firstRenderSurfaceType = null;
                Material          firstMaterial          = null;
                if (selectedBrushSurfaces.Length > 0)
                {
                    for (var i = 0; i < selectedBrushSurfaces.Length; i++)
                    {
                        var brush = selectedBrushSurfaces[i].brush;
                        if (!brush)
                        {
                            continue;
                        }
                        var surfaceIndex = selectedBrushSurfaces[i].surfaceIndex;
                        if (surfaceIndex >= brush.Shape.Surfaces.Length)
                        {
                            Debug.LogWarning("surface_index >= brush.Shape.Surfaces.Length");
                            continue;
                        }
                        var texGenIndex = brush.Shape.Surfaces[surfaceIndex].TexGenIndex;
                        if (texGenIndex >= brush.Shape.TexGens.Length)
                        {
                            Debug.LogWarning("texGen_index >= brush.Shape.TexGens.Length");
                            continue;
                        }
                        var      brushCache = InternalCSGModelManager.GetBrushCache(brush);
                        var      model      = (brushCache != null) ? brushCache.childData.Model : null;
                        Material foundMaterial;
                        var      texGenFlags = brush.Shape.TexGenFlags[texGenIndex];
                        if (model && (!model.IsRenderable || model.ShadowsOnly))
                        {
                            foundHelperMaterial = true;
                            if (!firstRenderSurfaceType.HasValue)
                            {
                                firstRenderSurfaceType = ModelTraits.GetModelSurfaceType(model);
                            }
                            foundMaterial = null;
                        }
                        else
                        if ((texGenFlags & TexGenFlags.NoRender) == TexGenFlags.NoRender)
                        {
                            foundHelperMaterial = true;
                            if (!firstRenderSurfaceType.HasValue)
                            {
                                if ((texGenFlags & TexGenFlags.NoCastShadows) != TexGenFlags.NoCastShadows)
                                {
                                    firstRenderSurfaceType = RenderSurfaceType.ShadowOnly;
                                }
                                else
                                if ((texGenFlags & TexGenFlags.NoCollision) != TexGenFlags.NoCollision)
                                {
                                    firstRenderSurfaceType = RenderSurfaceType.Collider;
                                }
                                else
                                {
                                    firstRenderSurfaceType = RenderSurfaceType.Hidden;
                                }
                            }
                            foundMaterial = null;
                        }
                        else
                        {
                            var surfaceMaterial = brush.Shape.TexGens[texGenIndex].RenderMaterial;
                            if (!foundHelperMaterial)
                            {
                                var surfaceType = MaterialUtility.GetMaterialSurfaceType(surfaceMaterial);
                                if (!firstRenderSurfaceType.HasValue)
                                {
                                    firstRenderSurfaceType = surfaceType;
                                }
                                foundHelperMaterial = surfaceType != RenderSurfaceType.Normal;
                            }
                            foundMaterial = surfaceMaterial;
                        }
                        if ((texGenFlags & TexGenFlags.WorldSpaceTexture) == TexGenFlags.WorldSpaceTexture)
                        {
                            if (i == 0)
                            {
                                textureLocked = false;
                            }
                            else if (textureLocked.HasValue && textureLocked.Value)
                            {
                                textureLocked = null;
                            }
                        }
                        else
                        {
                            if (i == 0)
                            {
                                textureLocked = true;
                            }
                            else if (textureLocked.HasValue && !textureLocked.Value)
                            {
                                textureLocked = null;
                            }
                        }
                        if (foundMaterial != material)
                        {
                            if (!material)
                            {
                                firstMaterial = foundMaterial;
                                material      = foundMaterial;
                            }
                            else
                            {
                                multipleMaterials = true;
                            }
                        }
                        if (!haveTexgen)
                        {
                            currentTexGen = brush.Shape.TexGens[texGenIndex];
                            haveTexgen    = true;
                        }
                        else
                        {
                            if (!multipleColors)
                            {
                                var color = brush.Shape.TexGens[texGenIndex].Color;
                                multipleColors = currentTexGen.Color.a != color.a ||
                                                 currentTexGen.Color.b != color.b ||
                                                 currentTexGen.Color.g != color.g ||
                                                 currentTexGen.Color.r != color.r;
                            }
                            if (!multipleScaleX || !multipleScaleY)
                            {
                                var scale = brush.Shape.TexGens[texGenIndex].Scale;
                                multipleScaleX = multipleScaleX || currentTexGen.Scale.x != scale.x;
                                multipleScaleY = multipleScaleY || currentTexGen.Scale.y != scale.y;
                            }

                            if (!multipleTranslationX || !multipleTranslationY)
                            {
                                var translation = brush.Shape.TexGens[texGenIndex].Translation;
                                multipleTranslationX = multipleTranslationX || currentTexGen.Translation.x != translation.x;
                                multipleTranslationY = multipleTranslationY || currentTexGen.Translation.y != translation.y;
                            }

                            if (!multipleRotationAngle)
                            {
                                var rotationAngle = brush.Shape.TexGens[texGenIndex].RotationAngle;
                                multipleRotationAngle = currentTexGen.RotationAngle != rotationAngle;
                            }
                        }
                    }
                    if (foundHelperMaterial && !firstMaterial)
                    {
                        if (firstRenderSurfaceType.HasValue)
                        {
                            firstMaterial = MaterialUtility.GetSurfaceMaterial(firstRenderSurfaceType.Value);
                        }
                        else
                        {
                            firstMaterial = MaterialUtility.HiddenMaterial;
                        }
                    }
                }

                GUILayout.BeginVertical(isSceneGUI ? materialDoubleWidth : CSG_GUIStyleUtility.ContentEmpty);
                {
                    GUILayout.BeginVertical(isSceneGUI ? GUI.skin.box : GUIStyle.none);
                    {
                        /*
                         * Color new_color;
                         * EditorGUI.BeginChangeCheck();
                         * {
                         *      EditorGUI.showMixedValue = multipleColors;
                         *      // why doesn't the colorfield return a modified color?
                         *      try
                         *      {
                         *              new_color = EditorGUILayout.ColorField(GUIContent.none, currentTexGen.Color);
                         *      }
                         *      catch
                         *      {
                         *              new_color = currentTexGen.Color;
                         *      }
                         * }
                         * if (EditorGUI.EndChangeCheck() || currentTexGen.Color != new_color)
                         * {
                         *      SurfaceUtility.SetColors(selectedBrushSurfaces, new_color);
                         * }
                         */
                        if (isSceneGUI)
                        {
                            GUILayout.BeginHorizontal(CSG_GUIStyleUtility.ContentEmpty);
                            {
                                EditorGUI.BeginDisabledGroup(material == null);
                                {
                                    GUILayout.BeginVertical(CSG_GUIStyleUtility.ContentEmpty);
                                    {
                                        GUILayout.Space(1);

                                        /*
                                         * Color new_color;
                                         * EditorGUI.BeginChangeCheck();
                                         * {
                                         *      EditorGUI.showMixedValue = multipleColors;
                                         *      // why doesn't the colorfield return a modified color?
                                         *      try
                                         *      {
                                         *              new_color = EditorGUILayout.ColorField(GUIContent.none, currentTexGen.Color);
                                         *      }
                                         *      catch
                                         *      {
                                         *              new_color = currentTexGen.Color;
                                         *      }
                                         * }
                                         * if (EditorGUI.EndChangeCheck() || currentTexGen.Color != new_color)
                                         * {
                                         *      SurfaceUtility.SetColors(selectedBrushSurfaces, new_color);
                                         * }
                                         *
                                         * GUILayout.Space(1);
                                         */
                                        Material newMaterial;
                                        EditorGUI.BeginChangeCheck();
                                        {
                                            EditorGUI.showMixedValue = multipleMaterials;
                                            newMaterial = EditorGUILayout.ObjectField(material, typeof(Material), true) as Material;
                                            EditorGUI.showMixedValue = false;
                                        }
                                        if (EditorGUI.EndChangeCheck())
                                        {
                                            if (newMaterial)
                                            {
                                                SurfaceUtility.SetMaterials(selectedBrushSurfaces, newMaterial);
                                                CSGSettings.DefaultMaterial = newMaterial;
                                                CSGSettings.Save();
                                            }
                                        }
                                    }
                                    GUILayout.EndVertical();
                                    GUILayout.Space(1);
                                }
                                EditorGUI.EndDisabledGroup();
                            }
                            GUILayout.EndHorizontal();
                            GUILayout.Space(4);
                            GUILayout.BeginHorizontal(CSG_GUIStyleUtility.ContentEmpty);
                            {
                                GUILayout.Space(2);
                                OnGUIContentsMaterialImage(isSceneGUI, firstMaterial, multipleMaterials, selectedBrushSurfaces);
                                GUILayout.BeginHorizontal(materialWidth);
                                {
                                    GUILayout.FlexibleSpace();
                                    GUILayout.BeginVertical(materialHeight);
                                    {
                                        OnGUIContentsJustify(isSceneGUI, selectedBrushSurfaces);
                                        GUILayout.FlexibleSpace();
                                    }
                                    GUILayout.EndVertical();
                                }
                                GUILayout.EndHorizontal();
                                GUILayout.FlexibleSpace();
                            }
                            GUILayout.EndHorizontal();
                        }
                    }
                    GUILayout.EndVertical();

                    if (!isSceneGUI)
                    {
                        EditorGUILayout.Space();
                    }

                    if (currentTexGen.Scale.x == 0.0f)
                    {
                        currentTexGen.Scale.x = 1.0f;
                    }
                    if (currentTexGen.Scale.y == 0.0f)
                    {
                        currentTexGen.Scale.y = 1.0f;
                    }

                    const float scale_round = 10000.0f;
                    currentTexGen.Scale.x       = Mathf.RoundToInt(currentTexGen.Scale.x * scale_round) / scale_round;
                    currentTexGen.Scale.y       = Mathf.RoundToInt(currentTexGen.Scale.y * scale_round) / scale_round;
                    currentTexGen.Translation.x = Mathf.RoundToInt(currentTexGen.Translation.x * scale_round) / scale_round;
                    currentTexGen.Translation.y = Mathf.RoundToInt(currentTexGen.Translation.y * scale_round) / scale_round;
                    currentTexGen.RotationAngle = Mathf.RoundToInt(currentTexGen.RotationAngle * scale_round) / scale_round;

                    var leftStyle   = isSceneGUI ? EditorStyles.miniButtonLeft  : GUI.skin.button;
                    var middleStyle = isSceneGUI ? EditorStyles.miniButtonMid   : GUI.skin.button;
                    var rightStyle  = isSceneGUI ? EditorStyles.miniButtonRight : GUI.skin.button;

                    GUILayout.BeginVertical(isSceneGUI ? GUI.skin.box : GUIStyle.none);
                    {
                        EditorGUI.BeginChangeCheck();
                        {
                            EditorGUI.showMixedValue = !textureLocked.HasValue;
                            textureLocked            = EditorGUILayout.ToggleLeft(ContentLockTexture, textureLocked.HasValue ? textureLocked.Value : false);
                            TooltipUtility.SetToolTip(ToolTipLockTexture);
                        }
                        if (EditorGUI.EndChangeCheck())
                        {
                            SurfaceUtility.SetTextureLock(selectedBrushSurfaces, textureLocked.Value);
                        }
                    }
                    GUILayout.EndVertical();

                    GUILayout.BeginVertical(isSceneGUI ? GUI.skin.box : GUIStyle.none);
                    {
                        GUILayout.BeginHorizontal(CSG_GUIStyleUtility.ContentEmpty);
                        {
                            if (isSceneGUI)
                            {
                                EditorGUILayout.LabelField(ContentUVScale, EditorStyles.miniLabel, labelWidth);
                            }
                            else
                            {
                                EditorGUILayout.LabelField(ContentUVScale, largeLabelWidth);
                            }
                            TooltipUtility.SetToolTip(ToolTipScaleUV);

                            GUILayout.BeginHorizontal(CSG_GUIStyleUtility.ContentEmpty);
                            {
                                if (!isSceneGUI)
                                {
                                    EditorGUILayout.LabelField(ContentUSymbol, unitWidth);
                                }
                                EditorGUI.BeginChangeCheck();
                                {
                                    EditorGUI.showMixedValue = multipleScaleX;
                                    currentTexGen.Scale.x    = EditorGUILayout.FloatField(currentTexGen.Scale.x, minFloatFieldWidth);
                                }
                                if (EditorGUI.EndChangeCheck())
                                {
                                    SurfaceUtility.SetScaleX(selectedBrushSurfaces, currentTexGen.Scale.x);
                                }
                                if (!isSceneGUI)
                                {
                                    EditorGUILayout.LabelField(ContentVSymbol, unitWidth);
                                }
                                EditorGUI.BeginChangeCheck();
                                {
                                    EditorGUI.showMixedValue = multipleScaleY;
                                    currentTexGen.Scale.y    = EditorGUILayout.FloatField(currentTexGen.Scale.y, minFloatFieldWidth);
                                }
                                if (EditorGUI.EndChangeCheck())
                                {
                                    SurfaceUtility.SetScaleY(selectedBrushSurfaces, currentTexGen.Scale.y);
                                }
                            }
                            GUILayout.EndHorizontal();
                        }
                        GUILayout.EndHorizontal();
                        GUILayout.BeginHorizontal(CSG_GUIStyleUtility.ContentEmpty);
                        {
                            if (isSceneGUI)
                            {
                                EditorGUILayout.LabelField(ContentOffset, EditorStyles.miniLabel, labelWidth);
                            }
                            else
                            {
                                EditorGUILayout.LabelField(ContentOffset, largeLabelWidth);
                            }
                            TooltipUtility.SetToolTip(ToolTipOffsetUV);

                            GUILayout.BeginHorizontal(CSG_GUIStyleUtility.ContentEmpty);
                            {
                                if (!isSceneGUI)
                                {
                                    EditorGUILayout.LabelField(ContentUSymbol, unitWidth);
                                }
                                EditorGUI.BeginChangeCheck();
                                {
                                    EditorGUI.showMixedValue    = multipleTranslationX;
                                    currentTexGen.Translation.x = EditorGUILayout.FloatField(currentTexGen.Translation.x, minFloatFieldWidth);
                                }
                                if (EditorGUI.EndChangeCheck())
                                {
                                    SurfaceUtility.SetTranslationX(selectedBrushSurfaces, currentTexGen.Translation.x);
                                }

                                if (!isSceneGUI)
                                {
                                    EditorGUILayout.LabelField(ContentVSymbol, unitWidth);
                                }
                                EditorGUI.BeginChangeCheck();
                                {
                                    EditorGUI.showMixedValue    = multipleTranslationY;
                                    currentTexGen.Translation.y = EditorGUILayout.FloatField(currentTexGen.Translation.y, minFloatFieldWidth);
                                }
                                if (EditorGUI.EndChangeCheck())
                                {
                                    SurfaceUtility.SetTranslationY(selectedBrushSurfaces, currentTexGen.Translation.y);
                                }
                            }
                            GUILayout.EndHorizontal();
                        }
                        GUILayout.EndHorizontal();
                        GUILayout.BeginHorizontal(CSG_GUIStyleUtility.ContentEmpty);
                        {
                            if (isSceneGUI)
                            {
                                EditorGUILayout.LabelField(ContentRotate, EditorStyles.miniLabel, labelWidth);
                            }
                            else
                            {
                                EditorGUILayout.LabelField(ContentRotate, largeLabelWidth);
                            }
                            TooltipUtility.SetToolTip(ToolTipRotation);

                            if (!isSceneGUI)
                            {
                                GUILayout.BeginVertical(CSG_GUIStyleUtility.ContentEmpty);
                            }

                            GUILayout.BeginHorizontal(CSG_GUIStyleUtility.ContentEmpty);
                            {
                                EditorGUI.BeginChangeCheck();
                                {
                                    EditorGUI.showMixedValue    = multipleRotationAngle;
                                    currentTexGen.RotationAngle = EditorGUILayout.FloatField(currentTexGen.RotationAngle, minFloatFieldWidth);
                                    if (!isSceneGUI)
                                    {
                                        EditorGUILayout.LabelField(ContentAngleSymbol, unitWidth);
                                    }
                                }
                                if (EditorGUI.EndChangeCheck())
                                {
                                    SurfaceUtility.SetRotationAngle(selectedBrushSurfaces, currentTexGen.RotationAngle);
                                }
                            }
                            GUILayout.EndHorizontal();

                            var buttonWidth = isSceneGUI ? new GUILayoutOption[] { angleButtonWidth } : new GUILayoutOption[0];
                            GUILayout.BeginHorizontal(CSG_GUIStyleUtility.ContentEmpty);
                            {
                                if (GUILayout.Button(ContentRotate90Negative, leftStyle, buttonWidth))
                                {
                                    SurfaceUtility.AddRotationAngle(selectedBrushSurfaces, -90.0f);
                                }
                                TooltipUtility.SetToolTip(ToolTipRotate90Negative);
                                if (GUILayout.Button(ContentRotate90Positive, rightStyle, buttonWidth))
                                {
                                    SurfaceUtility.AddRotationAngle(selectedBrushSurfaces, +90.0f);
                                }
                                TooltipUtility.SetToolTip(ToolTipRotate90Positive);
                            }
                            GUILayout.EndHorizontal();
                            if (!isSceneGUI)
                            {
                                GUILayout.EndVertical();
                            }
                        }
                        GUILayout.EndHorizontal();
                    }
                    GUILayout.EndVertical();

                    if (!isSceneGUI)
                    {
                        EditorGUILayout.Space();
                    }

                    GUILayout.BeginVertical(isSceneGUI ? GUI.skin.box : GUIStyle.none);
                    {
                        GUILayout.BeginHorizontal(CSG_GUIStyleUtility.ContentEmpty);
                        {
                            if (!isSceneGUI)
                            {
                                GUILayout.Label(ContentFit, largeLabelWidth);
                            }
                            else
                            {
                                GUILayout.Label(ContentFit, EditorStyles.miniLabel, smallLabelWidth);
                            }
                            if (GUILayout.Button(ContentFitX, leftStyle))
                            {
                                SurfaceUtility.FitSurfaceX(selectedBrushSurfaces);
                            }
                            TooltipUtility.SetToolTip(ToolTipFitX);
                            if (GUILayout.Button(ContentFitXY, middleStyle))
                            {
                                SurfaceUtility.FitSurface(selectedBrushSurfaces);
                            }
                            TooltipUtility.SetToolTip(ToolTipFitXY);
                            if (GUILayout.Button(ContentFitY, rightStyle))
                            {
                                SurfaceUtility.FitSurfaceY(selectedBrushSurfaces);
                            }
                            TooltipUtility.SetToolTip(ToolTipFitY);
                        }
                        GUILayout.EndHorizontal();
                        GUILayout.BeginHorizontal(CSG_GUIStyleUtility.ContentEmpty);
                        {
                            if (!isSceneGUI)
                            {
                                GUILayout.Label(ContentReset, largeLabelWidth);
                            }
                            else
                            {
                                GUILayout.Label(ContentReset, EditorStyles.miniLabel, smallLabelWidth);
                            }
                            if (GUILayout.Button(ContentResetX, leftStyle))
                            {
                                SurfaceUtility.ResetSurfaceX(selectedBrushSurfaces);
                            }
                            TooltipUtility.SetToolTip(ToolTipResetX);
                            if (GUILayout.Button(ContentResetXY, middleStyle))
                            {
                                SurfaceUtility.ResetSurface(selectedBrushSurfaces);
                            }
                            TooltipUtility.SetToolTip(ToolTipResetXY);
                            if (GUILayout.Button(ContentResetY, rightStyle))
                            {
                                SurfaceUtility.ResetSurfaceY(selectedBrushSurfaces);
                            }
                            TooltipUtility.SetToolTip(ToolTipResetY);
                        }
                        GUILayout.EndHorizontal();
                        GUILayout.BeginHorizontal(CSG_GUIStyleUtility.ContentEmpty);
                        {
                            if (!isSceneGUI)
                            {
                                GUILayout.Label(ContentFlip, largeLabelWidth);
                            }
                            else
                            {
                                GUILayout.Label(ContentFlip, EditorStyles.miniLabel, smallLabelWidth);
                            }
                            if (GUILayout.Button(ContentFlipX, leftStyle))
                            {
                                SurfaceUtility.FlipX(selectedBrushSurfaces);
                            }
                            TooltipUtility.SetToolTip(ToolTipFlipX);
                            if (GUILayout.Button(ContentFlipXY, middleStyle))
                            {
                                SurfaceUtility.FlipXY(selectedBrushSurfaces);
                            }
                            TooltipUtility.SetToolTip(ToolTipFlipXY);
                            if (GUILayout.Button(ContentFlipY, rightStyle))
                            {
                                SurfaceUtility.FlipY(selectedBrushSurfaces);
                            }
                            TooltipUtility.SetToolTip(ToolTipFlipY);
                        }
                        GUILayout.EndHorizontal();
                        GUILayout.BeginHorizontal(CSG_GUIStyleUtility.ContentEmpty);
                        {
                            if (!isSceneGUI)
                            {
                                GUILayout.Label(ContentScale, largeLabelWidth);
                            }
                            else
                            {
                                GUILayout.Label(ContentScale, EditorStyles.miniLabel, smallLabelWidth);
                            }
                            if (GUILayout.Button(ContentDoubleScale, leftStyle))
                            {
                                SurfaceUtility.MultiplyScale(selectedBrushSurfaces, 2.0f);
                            }
                            TooltipUtility.SetToolTip(ToolTipDoubleScale);
                            if (GUILayout.Button(ContentHalfScale, rightStyle))
                            {
                                SurfaceUtility.MultiplyScale(selectedBrushSurfaces, 0.5f);
                            }
                            TooltipUtility.SetToolTip(ToolTipHalfScale);
                        }
                        GUILayout.EndHorizontal();
                    }
                    GUILayout.EndVertical();

                    if (!isSceneGUI)
                    {
                        EditorGUILayout.Space();
                    }

                    if (!isSceneGUI)
                    {
                        OnGUIContentsJustify(isSceneGUI, selectedBrushSurfaces);
                    }

                    if (!isSceneGUI)
                    {
                        EditorGUILayout.Space();
                    }

                    GUILayout.BeginVertical(isSceneGUI ? GUI.skin.box : GUIStyle.none);
                    {
                        EditModeCommonGUI.OnSurfaceFlagButtons(selectedBrushSurfaces, isSceneGUI);
                        GUILayout.BeginHorizontal(CSG_GUIStyleUtility.ContentEmpty);
                        {
                            EditorGUI.BeginDisabledGroup(!SurfaceUtility.CanSmooth(selectedBrushSurfaces));
                            {
                                if (GUILayout.Button(ContentSmoothSurfaces, leftStyle))
                                {
                                    SurfaceUtility.Smooth(selectedBrushSurfaces);
                                }
                                TooltipUtility.SetToolTip(ToolTipSmoothSurfaces);
                            }
                            EditorGUI.EndDisabledGroup();
                            EditorGUI.BeginDisabledGroup(!SurfaceUtility.CanUnSmooth(selectedBrushSurfaces));
                            {
                                if (GUILayout.Button(ContentUnSmoothSurfaces, rightStyle))
                                {
                                    SurfaceUtility.UnSmooth(selectedBrushSurfaces);
                                }
                                TooltipUtility.SetToolTip(ToolTipUnSmoothSurfaces);
                            }
                            EditorGUI.EndDisabledGroup();
                        }
                        GUILayout.EndHorizontal();
                    }
                    GUILayout.EndVertical();

                    if (!isSceneGUI)
                    {
                        EditorGUILayout.Space();
                        Material new_material;
                        GUILayout.BeginHorizontal(CSG_GUIStyleUtility.ContentEmpty);
                        {
                            EditorGUILayout.LabelField(ContentMaterial, largeLabelWidth);
                            GUILayout.BeginVertical(CSG_GUIStyleUtility.ContentEmpty);
                            {
                                EditorGUI.BeginChangeCheck();
                                {
                                    EditorGUI.showMixedValue = multipleMaterials;
                                    new_material             = EditorGUILayout.ObjectField(material, typeof(Material), true) as Material;
                                    EditorGUI.showMixedValue = false;
                                }
                                if (EditorGUI.EndChangeCheck())
                                {
                                    if (!new_material)
                                    {
                                        new_material = MaterialUtility.MissingMaterial;
                                    }
                                    SurfaceUtility.SetMaterials(selectedBrushSurfaces, new_material);
                                }
                            }
                            GUILayout.Space(2);
                            GUILayout.BeginHorizontal(CSG_GUIStyleUtility.ContentEmpty);
                            {
                                GUILayout.Space(5);
                                OnGUIContentsMaterialImage(isSceneGUI, firstMaterial, multipleMaterials, selectedBrushSurfaces);
                            }
                            GUILayout.EndHorizontal();
                            GUILayout.EndVertical();
                        }
                        GUILayout.EndHorizontal();
                        // Unity won't let us do this
                        //GUILayout.BeginVertical(GUIStyleUtility.ContentEmpty);
                        //OnGUIContentsMaterialInspector(first_material, multiple_materials);
                        //GUILayout.EndVertical();
                    }
                }
                GUILayout.EndVertical();
            }
            EditorGUI.EndDisabledGroup();
            EditorGUI.showMixedValue = false;
        }
        void ApplyMaterial(SelectedBrushSurface[] hoverBrushSurfaces)
        {
            if (hoverBrushSurfaces == null)
            {
                return;
            }
            var updateModels  = new HashSet <CSGModel>();
            var updateBrushes = new HashSet <CSGBrush>();

            for (int i = 0; i < hoverBrushSurfaces.Length; i++)
            {
                var brush       = hoverBrushSurfaces[i].brush;
                var brush_cache = InternalCSGModelManager.GetBrushCache(brush);
                if (brush_cache == null ||
                    brush_cache.childData == null ||
                    brush_cache.childData.Model == null)
                {
                    continue;
                }
                try
                {
                    var model = brush_cache.childData.Model;
                    updateModels.Add(model);
                    if (updateBrushes.Add(brush))
                    {
                        // per brush
                        if (!selectAllSurfaces)
                        {
                            var shape = brush.Shape;
                            for (int t = 0; t < shape.TexGens.Length; t++)
                            {
                                shape.TexGens[t].RenderMaterial = previousMaterials[i][t];
                            }
                        }
                        else
                        {
                            var shape          = brush.Shape;
                            var surfaceTexGens = shape.TexGens.ToArray();
                            if (dragMaterials.Count > 1)
                            {
                                for (int m = 0; m < surfaceTexGens.Length; m++)
                                {
                                    surfaceTexGens[m].RenderMaterial = dragMaterials[Random.Range(0, dragMaterials.Count)];
                                }
                            }
                            else
                            {
                                var materialInstance = dragMaterials[0];
                                for (int m = 0; m < surfaceTexGens.Length; m++)
                                {
                                    surfaceTexGens[m].RenderMaterial = materialInstance;
                                }
                            }
                            shape.TexGens = surfaceTexGens;
                        }
                    }

                    // per surface
                    if (!selectAllSurfaces)
                    {
                        var highlight_surface = hoverBrushSurfaces[i].surfaceIndex;
                        if (highlight_surface >= 0)
                        {
                            var highlight_texGen = brush.Shape.Surfaces[highlight_surface].TexGenIndex;

                            Material dragMaterial;
                            if (dragMaterials.Count > 1)
                            {
                                dragMaterial = dragMaterials[Random.Range(0, dragMaterials.Count)];
                            }
                            else
                            {
                                dragMaterial = dragMaterials[0];
                            }

                            brush.Shape.TexGens[highlight_texGen].RenderMaterial = dragMaterial;
                        }
                    }
                }
                finally {}
            }
            UpdateBrushMeshes(updateBrushes, updateModels);
        }
Beispiel #12
0
        protected override void HandleEditShapeEvents(Rect sceneRect)
        {
            if (settings.vertices.Length < 2)
            {
                if (editMode == EditMode.ExtrudeShape ||
                    editMode == EditMode.EditShape)
                {
                    editMode = EditMode.CreatePlane;
                }
            }

            if (!SceneDragToolManager.IsDraggingObjectInScene &&
                Event.current.type == EventType.Repaint)
            {
                if (visualSnappedEdges != null)
                {
                    PaintUtility.DrawLines(visualSnappedEdges.ToArray(), ToolConstants.oldThickLineScale, ColorSettings.SnappedEdges);
                }

                if (visualSnappedGrid != null)
                {
                    var _origMatrix = Handles.matrix;
                    Handles.matrix = MathConstants.identityMatrix;
                    PaintUtility.DrawDottedLines(visualSnappedGrid.ToArray(), ColorSettings.SnappedEdges);
                    Handles.matrix = _origMatrix;
                }

                if (visualSnappedBrush != null)
                {
                    var brush_cache = InternalCSGModelManager.GetBrushCache(visualSnappedBrush);
                    if (brush_cache != null &&
                        brush_cache.compareTransformation != null &&
                        brush_cache.childData != null &&
                        brush_cache.childData.ModelTransform != null &&
                        brush_cache.childData.ModelTransform)
                    {
                        var brush_translation = brush_cache.compareTransformation.modelLocalPosition + brush_cache.childData.ModelTransform.position;
                        CSGRenderer.DrawOutlines(visualSnappedBrush.brushID, brush_translation, ColorSettings.SelectedOutlines, ColorSettings.SelectedOutlines, ColorSettings.SelectedOutlines, ColorSettings.SelectedOutlines);
                    }
                }

                var origMatrix = Handles.matrix;
                Handles.matrix = MathConstants.identityMatrix;
                PaintBounds();
                Handles.matrix = origMatrix;
            }

            HandleHeightHandles(sceneRect, false);

            for (int i = 0; i < settings.vertices.Length; i++)
            {
                var id         = settings.vertexIDs[i];
                var point_type = Event.current.GetTypeForControl(id);
                switch (point_type)
                {
                case EventType.Repaint:
                {
                    if (SceneDragToolManager.IsDraggingObjectInScene)
                    {
                        break;
                    }

                    bool isSelected = id == GUIUtility.keyboardControl;
                    var  temp       = Handles.color;
                    var  origMatrix = Handles.matrix;

                    Handles.matrix = MathConstants.identityMatrix;
                    var rotation = Camera.current.transform.rotation;


                    if (isSelected)
                    {
                        Handles.color = ColorSettings.PointInnerStateColor[3];
                    }
                    else
                    if (HandleUtility.nearestControl == id)
                    {
                        Handles.color = ColorSettings.PointInnerStateColor[1];
                    }
                    else
                    {
                        Handles.color = ColorSettings.PointInnerStateColor[0];
                    }

                    float handleSize       = CSG_HandleUtility.GetHandleSize(settings.vertices[i]);
                    float scaledHandleSize = handleSize * ToolConstants.handleScale;
                    PaintUtility.SquareDotCap(id, settings.vertices[i], rotation, scaledHandleSize);

                    Handles.matrix = origMatrix;
                    Handles.color  = temp;
                    break;
                }

                case EventType.Layout:
                {
                    if ((Tools.viewTool != ViewTool.None && Tools.viewTool != ViewTool.Pan))
                    {
                        break;
                    }

                    var origMatrix = Handles.matrix;
                    Handles.matrix = MathConstants.identityMatrix;
                    float handleSize       = CSG_HandleUtility.GetHandleSize(settings.vertices[i]);
                    float scaledHandleSize = handleSize * ToolConstants.handleScale;
                    HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(settings.vertices[i], scaledHandleSize));
                    Handles.matrix = origMatrix;

                    break;
                }

                case EventType.ValidateCommand:
                case EventType.KeyDown:
                {
                    if (GUIUtility.hotControl == id)
                    {
                        if (Keys.CancelActionKey.IsKeyPressed())
                        {
                            Event.current.Use();
                            break;
                        }
                    }
                    break;
                }

                case EventType.KeyUp:
                {
                    if (GUIUtility.hotControl == id)
                    {
                        if (Keys.CancelActionKey.IsKeyPressed())
                        {
                            GUIUtility.hotControl             = 0;
                            GUIUtility.keyboardControl        = 0;
                            EditorGUIUtility.editingTextField = false;
                            Event.current.Use();
                            break;
                        }
                    }
                    break;
                }

                case EventType.MouseDown:
                {
                    if (!sceneRect.Contains(Event.current.mousePosition))
                    {
                        break;
                    }
                    if (Tools.viewTool != ViewTool.None && Tools.viewTool != ViewTool.Pan)
                    {
                        break;
                    }
                    if (GUIUtility.hotControl == 0 && HandleUtility.nearestControl == id && Event.current.button == 0)
                    {
                        GUIUtility.hotControl             = id;
                        GUIUtility.keyboardControl        = id;
                        EditorGUIUtility.editingTextField = false;
                        EditorGUIUtility.SetWantsMouseJumping(1);
                        Event.current.Use();
                        break;
                    }
                    break;
                }

                case EventType.MouseDrag:
                {
                    if (Tools.viewTool != ViewTool.None && Tools.viewTool != ViewTool.Pan)
                    {
                        break;
                    }
                    if (GUIUtility.hotControl == id && Event.current.button == 0)
                    {
                        Undo.RecordObject(this, "Modify shape");

                        var mouseRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
                        RealtimeCSG.CSGGrid.SetForcedGrid(buildPlane);
                        var alignedPlane  = new CSGPlane(RealtimeCSG.CSGGrid.CurrentWorkGridPlane.normal, settings.vertices[0]);
                        var worldPosition = buildPlane.Project(alignedPlane.Intersection(mouseRay));
                        if (float.IsInfinity(worldPosition.x) || float.IsNaN(worldPosition.x) ||
                            float.IsInfinity(worldPosition.y) || float.IsNaN(worldPosition.y) ||
                            float.IsInfinity(worldPosition.z) || float.IsNaN(worldPosition.z))
                        {
                            worldPosition = settings.vertices[i];
                        }

                        ResetVisuals();
                        if (snapFunction != null)
                        {
                            CSGBrush snappedOnBrush;
                            worldPosition = snapFunction(worldPosition, buildPlane, ref base.visualSnappedEdges, out snappedOnBrush, generatedBrushes);
                        }

                        base.visualSnappedGrid = RealtimeCSG.CSGGrid.FindAllGridEdgesThatTouchPoint(worldPosition);

                        settings.vertices[i] = worldPosition;

                        CenterExtrusionPoints(buildPlane);
                        UpdateBaseShape();

                        if (editMode == EditMode.ExtrudeShape)
                        {
                            StartExtrudeMode();
                            UpdateBaseShape();
                        }
                        UpdateExtrudedShape();

                        GUI.changed = true;
                        Event.current.Use();
                        break;
                    }
                    break;
                }

                case EventType.MouseUp:
                {
                    if (GUIUtility.hotControl != id)
                    {
                        break;
                    }
                    if (Tools.viewTool != ViewTool.None && Tools.viewTool != ViewTool.Pan)
                    {
                        break;
                    }
                    if (Event.current.button == 0)
                    {
                        GUIUtility.hotControl             = 0;
                        GUIUtility.keyboardControl        = 0;
                        EditorGUIUtility.editingTextField = false;
                        EditorGUIUtility.SetWantsMouseJumping(0);
                        Event.current.Use();

                        ResetVisuals();
                        //if (Length == 0 || Width == 0)
                        //{
                        //	Cancel();
                        //}
                        break;
                    }
                    break;
                }
                }
            }
        }
Beispiel #13
0
        public void HandleEvents(Rect sceneRect)
        {
            if (CurrentGenerator == null)
            {
                return;
            }

            CurrentGenerator.HandleEvents(sceneRect);
            switch (Event.current.type)
            {
            case EventType.ValidateCommand:
            {
                if (!EditorGUIUtility.editingTextField && Keys.MakeSelectedAdditiveKey.IsKeyPressed())
                {
                    Event.current.Use(); break;
                }
                if (!EditorGUIUtility.editingTextField && Keys.MakeSelectedSubtractiveKey.IsKeyPressed())
                {
                    Event.current.Use(); break;
                }
                if (!EditorGUIUtility.editingTextField && Keys.MakeSelectedIntersectingKey.IsKeyPressed())
                {
                    Event.current.Use(); break;
                }
                if (!EditorGUIUtility.editingTextField && Keys.CancelActionKey.IsKeyPressed())
                {
                    Event.current.Use(); break;
                }
                if (Keys.HandleSceneValidate(CSGBrushEditorManager.CurrentTool, false))
                {
                    Event.current.Use(); HandleUtility.Repaint(); break;
                }
                break;
            }

            case EventType.KeyDown:
            {
                if (!EditorGUIUtility.editingTextField && Keys.MakeSelectedAdditiveKey.IsKeyPressed())
                {
                    Event.current.Use(); break;
                }
                if (!EditorGUIUtility.editingTextField && Keys.MakeSelectedSubtractiveKey.IsKeyPressed())
                {
                    Event.current.Use(); break;
                }
                if (!EditorGUIUtility.editingTextField && Keys.MakeSelectedIntersectingKey.IsKeyPressed())
                {
                    Event.current.Use(); break;
                }
                if (!EditorGUIUtility.editingTextField && Keys.CancelActionKey.IsKeyPressed())
                {
                    Event.current.Use(); break;
                }
                if (Keys.HandleSceneKeyDown(CSGBrushEditorManager.CurrentTool, false))
                {
                    Event.current.Use(); HandleUtility.Repaint(); break;
                }
                break;
            }

            case EventType.KeyUp:
            {
                if (!EditorGUIUtility.editingTextField && Keys.MakeSelectedAdditiveKey.IsKeyPressed())
                {
                    SetOperationType(CSGOperationType.Additive);     Event.current.Use(); break;
                }
                if (!EditorGUIUtility.editingTextField && Keys.MakeSelectedSubtractiveKey.IsKeyPressed())
                {
                    SetOperationType(CSGOperationType.Subtractive);  Event.current.Use(); break;
                }
                if (!EditorGUIUtility.editingTextField && Keys.MakeSelectedIntersectingKey.IsKeyPressed())
                {
                    SetOperationType(CSGOperationType.Intersecting); Event.current.Use(); break;
                }
                if (!EditorGUIUtility.editingTextField && Keys.CancelActionKey.IsKeyPressed())
                {
                    CurrentGenerator.PerformDeselectAll(); Event.current.Use(); break;
                }
                if (Keys.HandleSceneKeyUp(CSGBrushEditorManager.CurrentTool, false))
                {
                    Event.current.Use(); HandleUtility.Repaint(); break;
                }
                break;
            }

            case EventType.Repaint:
            {
                if (lastLineMeshGeneration != InternalCSGModelManager.MeshGeneration)
                {
                    lastLineMeshGeneration = InternalCSGModelManager.MeshGeneration;

                    var brush_translations = new Vector3[brushes.Length];
                    var brush_ids          = new Int32[brushes.Length];
                    for (int i = brushes.Length - 1; i >= 0; i--)
                    {
                        var brush       = brushes[i];
                        var brush_cache = InternalCSGModelManager.GetBrushCache(brush);
                        if (brush.brushID == -1 ||                                      // could be a prefab
                            brush_cache == null ||
                            brush_cache.compareTransformation == null ||
                            brush_cache.childData == null ||
                            brush_cache.childData.ModelTransform == null ||
                            !brush_cache.childData.ModelTransform)
                        {
                            ArrayUtility.RemoveAt(ref brush_translations, i);
                            ArrayUtility.RemoveAt(ref brush_ids, i);
                            continue;
                        }
                        brush_translations[i] = brush_cache.compareTransformation.modelLocalPosition + brush_cache.childData.ModelTransform.position;
                        brush_ids[i]          = brush.brushID;
                    }
                    CSGRenderer.DrawSelectedBrushes(zTestLineMeshManager, noZTestLineMeshManager, brush_ids, brush_translations,
                                                    ColorSettings.SelectedOutlines, ToolConstants.lineScale);
                }

                MaterialUtility.LineAlphaMultiplier     = 1.0f;
                MaterialUtility.LineDashMultiplier      = 2.0f;
                MaterialUtility.LineThicknessMultiplier = 2.0f;
                noZTestLineMeshManager.Render(MaterialUtility.NoZTestGenericLine);
                MaterialUtility.LineThicknessMultiplier = 1.0f;
                zTestLineMeshManager.Render(MaterialUtility.ZTestGenericLine);

                break;
            }
            }
        }
Beispiel #14
0
        public static void OnSceneGUI(SceneView sceneView)
        {
            if (EditorApplication.isPlayingOrWillChangePlaymode)
            {
                return;
            }

            CameraUtility.InitDistanceChecks(sceneView);
            SelectionUtility.HandleEvents();
            InitTools();

            HandleBuilderEvents();
            {
                UpdateTool();

                if (instance.activeTool != null)
                {
                    if (RealtimeCSG.CSGSettings.EnableRealtimeCSG)
                    {
                        // handle the tool
                        var sceneSize = sceneView.position.size;
                        var sceneRect = new Rect(0, 0, sceneSize.x, sceneSize.y - ((CSG_GUIStyleUtility.BottomToolBarHeight + 4) + 17));

                        instance.activeTool.HandleEvents(sceneRect);
                    }
                    else
                    {
                        if (Event.current.type == EventType.Repaint)
                        {
                            var brushes      = instance.filteredSelection.BrushTargets;
                            var wireframes   = new List <GeometryWireframe>(brushes.Length);
                            var translations = new List <Vector3>(brushes.Length);
                            for (int i = 0; i < brushes.Length; i++)
                            {
                                var brush = brushes[i];
                                if (!brush)
                                {
                                    continue;
                                }

                                var brushCache = InternalCSGModelManager.GetBrushCache(brush);
                                if (brushCache == null ||
                                    brushCache.childData == null ||
                                    !brushCache.childData.Model)
                                {
                                    continue;
                                }

                                var brushTranslation = brushCache.compareTransformation.modelLocalPosition + brushCache.childData.ModelTransform.position;

                                wireframes.Add(BrushOutlineManager.GetBrushOutline(brushes[i].brushID));
                                translations.Add(brushTranslation);
                            }
                            if (wireframes.Count > 0)
                            {
                                CSGRenderer.DrawSelectedBrushes(instance.zTestLineMeshManager, instance.noZTestLineMeshManager,
                                                                wireframes.ToArray(), translations.ToArray(),
                                                                ColorSettings.SelectedOutlines, ToolConstants.thickLineScale);
                            }
                            MaterialUtility.LineDashMultiplier      = 1.0f;
                            MaterialUtility.LineThicknessMultiplier = 1.0f;
                            MaterialUtility.LineAlphaMultiplier     = 1.0f;
                            instance.zTestLineMeshManager.Render(MaterialUtility.ZTestGenericLine);
                            instance.zTestLineMeshManager.Render(MaterialUtility.ZTestGenericLine);
                        }
                    }
                }
            }

            int sceneWindowId   = GUIUtility.GetControlID(SceneWindowHash, FocusType.Passive);
            var sceneWindowType = Event.current.GetTypeForControl(sceneWindowId);

            if (sceneWindowType == EventType.Repaint)
            {
                if (currentEditorWindows.Count > 0)
                {
                    for (int i = 0; i < currentEditorWindows.Count; i++)
                    {
                        currentEditorWindows[i].Repaint();
                    }
                    return;
                }
            }

            if (sceneWindowType == EventType.MouseMove)
            {
                SceneDragToolManager.IsDraggingObjectInScene = false;
            }

            if (RealtimeCSG.CSGSettings.EnableRealtimeCSG)
            {
                if (sceneView && sceneWindowType != EventType.Used && !SceneDragToolManager.IsDraggingObjectInScene)
                {
                    if (currentEditorWindows.Count == 0)
                    {
                        try
                        {
                            Handles.BeginGUI();
                            Rect windowRect = new Rect(Vector2.zero, sceneView.position.size);
                            EditModeSelectionGUI.HandleWindowGUI(windowRect);
                        }
                        finally
                        {
                            Handles.EndGUI();
                        }
                    }
                }
            }
        }
        protected override void HandleCreateShapeEvents(Rect sceneRect)
        {
            bool     pointOnEdge      = false;
            bool     havePlane        = false;
            bool     vertexOnGeometry = false;
            CSGBrush vertexOnBrush    = null;

            CSGPlane hoverBuildPlane = buildPlane;
            var      sceneView       = SceneView.currentDrawingSceneView; //(SceneView.currentDrawingSceneView != null) ? SceneView.currentDrawingSceneView : SceneView.lastActiveSceneView;
            var      camera          = (sceneView == null) ? null : sceneView.camera;
            var      assume2DView    = CSGSettings.Assume2DView(sceneView);

            if (camera != null &&
                camera.pixelRect.Contains(Event.current.mousePosition))
            {
                if (!hoverDefaultPlane.HasValue ||
                    settings.vertices.Length == 0)
                {
                    bool forceGrid = RealtimeCSG.Grid.ForceGrid;
                    RealtimeCSG.Grid.ForceGrid = false;
                    hoverDefaultPlane          = RealtimeCSG.Grid.CurrentGridPlane;
                    RealtimeCSG.Grid.ForceGrid = forceGrid;
                    firstSnappedEdges          = null;
                    firstSnappedBrush          = null;
                    firstSnappedPlanes         = null;
                    base.geometryModel         = null;
                }
                if (editMode == EditMode.CreatePlane)
                {
                    BrushIntersection intersection;
                    if (!assume2DView && !havePlane &&
                        SceneQueryUtility.FindWorldIntersection(Event.current.mousePosition, out intersection, MathConstants.GrowBrushFactor))
                    {
                        worldPosition = intersection.worldIntersection;
                        if (intersection.surfaceInverted)
                        {
                            hoverBuildPlane = intersection.plane.Negated();
                        }
                        else
                        {
                            hoverBuildPlane = intersection.plane;
                        }
                        vertexOnBrush = intersection.brush;

                        vertexOnGeometry = true;
                    }
                    else
                    {
                        hoverBuildPlane = hoverDefaultPlane.Value;
                        vertexOnBrush   = null;

                        var mouseRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
                        worldPosition    = hoverBuildPlane.Intersection(mouseRay);
                        vertexOnGeometry = false;
                    }
                    ResetVisuals();
                    if (snapFunction != null)
                    {
                        CSGBrush snappedOnBrush;
                        worldPosition = snapFunction(worldPosition, hoverBuildPlane, ref visualSnappedEdges, out snappedOnBrush, generatedBrushes, ignoreAllBrushes: true);
                        if (snappedOnBrush != null)
                        {
                            pointOnEdge = (visualSnappedEdges != null &&
                                           visualSnappedEdges.Count > 0);
                            vertexOnBrush    = snappedOnBrush;
                            vertexOnGeometry = true;
                        }
                    }

                    if (settings.vertices.Length == 1)
                    {
                        if (hoverBuildPlane.normal != MathConstants.zeroVector3)
                        {
                            editMode  = EditMode.CreateShape;
                            havePlane = true;
                        }
                    }
                }
                else
                {
                    var mouseRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
                    if (settings.vertices.Length == 2)
                    {
                        var startPoint = settings.vertices[1];

                        var forward = camera.transform.forward;
                        if (Vector3.Dot(forward, gridBinormal) < Vector3.Dot(forward, gridTangent))
                        {
                            hoverBuildPlane = new CSGPlane(gridBinormal, startPoint);
                        }
                        else
                        {
                            hoverBuildPlane = new CSGPlane(gridTangent, startPoint);
                        }
                        worldPosition = hoverBuildPlane.Intersection(mouseRay);

                        // the third point is always straight up from the second point
                        //worldPosition = startPoint + (Vector3.Dot(worldPosition - startPoint, gridNormal) * gridNormal);

                        RealtimeCSG.Grid.SetForcedGrid(hoverBuildPlane);
                        ResetVisuals();
                        if (raySnapFunction != null)
                        {
                            Ray      ray = new Ray(startPoint, gridNormal);
                            CSGBrush snappedOnBrush;
                            worldPosition = raySnapFunction(worldPosition, ray, ref visualSnappedEdges, out snappedOnBrush);
                            if (snappedOnBrush != null)
                            {
                                pointOnEdge = (visualSnappedEdges != null &&
                                               visualSnappedEdges.Count > 0);
                                vertexOnBrush = snappedOnBrush;
                            }
                        }

                        worldPosition = GeometryUtility.ProjectPointOnInfiniteLine(worldPosition, startPoint, gridNormal);
                    }
                    else
                    {
                        worldPosition = hoverBuildPlane.Intersection(mouseRay);

                        RealtimeCSG.Grid.SetForcedGrid(hoverBuildPlane);
                        ResetVisuals();
                        if (snapFunction != null)
                        {
                            CSGBrush snappedOnBrush;
                            worldPosition = snapFunction(worldPosition, hoverBuildPlane, ref visualSnappedEdges, out snappedOnBrush, generatedBrushes, ignoreAllBrushes: true);
                            if (snappedOnBrush != null)
                            {
                                pointOnEdge = (visualSnappedEdges != null &&
                                               visualSnappedEdges.Count > 0);
                                vertexOnBrush = snappedOnBrush;
                            }
                        }
                    }
                }

                if (geometryModel == null && vertexOnBrush != null)
                {
                    var brush_cache = InternalCSGModelManager.GetBrushCache(vertexOnBrush);
                    if (brush_cache != null && brush_cache.childData != null && brush_cache.childData.Model)
                    {
                        geometryModel = brush_cache.childData.Model;
                    }
                }

                if (worldPosition != prevWorldPosition)
                {
                    prevWorldPosition = worldPosition;
                    if (settings.vertices.Length > 0)
                    {
                        if ((settings.vertices[0] - worldPosition).sqrMagnitude > MathConstants.EqualityEpsilon)
                        {
                            UpdateSizes();
                            UpdateBaseShape(true);
                        }
                    }
                    if (Event.current.type != EventType.Repaint)
                    {
                        SceneView.RepaintAll();
                    }
                }

                visualSnappedGrid  = RealtimeCSG.Grid.FindAllGridEdgesThatTouchPoint(worldPosition);
                visualSnappedBrush = vertexOnBrush;
            }
            RealtimeCSG.Grid.SetForcedGrid(hoverBuildPlane);



            if (!SceneTools.IsDraggingObjectInScene &&
                Event.current.type == EventType.Repaint)
            {
                PaintSnapVisualisation();
                PaintShape(base.shapeId);
            }


            var type = Event.current.GetTypeForControl(base.shapeId);

            switch (type)
            {
            case EventType.Layout:
            {
                return;
            }

            case EventType.ValidateCommand:
            case EventType.KeyDown:
            {
                if (GUIUtility.hotControl == base.shapeId)
                {
                    if (Keys.PerformActionKey.IsKeyPressed() ||
                        Keys.DeleteSelectionKey.IsKeyPressed() ||
                        Keys.CancelActionKey.IsKeyPressed())
                    {
                        Event.current.Use();
                    }
                }
                return;
            }

            case EventType.KeyUp:
            {
                if (GUIUtility.hotControl == base.shapeId)
                {
                    if (Keys.CylinderBuilderMode.IsKeyPressed() ||
                        Keys.PerformActionKey.IsKeyPressed())
                    {
                        HotKeyReleased();
                        Event.current.Use();
                        return;
                    }
                    if (Keys.DeleteSelectionKey.IsKeyPressed() ||
                        Keys.CancelActionKey.IsKeyPressed())
                    {
                        Cancel();
                        Event.current.Use();
                        return;
                    }
                }
                return;
            }

            case EventType.MouseDown:
            {
                if (!sceneRect.Contains(Event.current.mousePosition))
                {
                    break;
                }
                if (Tools.viewTool != ViewTool.None && Tools.viewTool != ViewTool.Pan)
                {
                    return;
                }
                if ((GUIUtility.hotControl != 0 && GUIUtility.hotControl != shapeEditId && GUIUtility.hotControl != base.shapeId) ||
                    Event.current.button != 0)
                {
                    return;
                }

                Event.current.Use();
                if (settings.vertices.Length == 0)
                {
                    if ((GUIUtility.hotControl == 0 ||
                         GUIUtility.hotControl == base.shapeEditId) && base.shapeId != -1)
                    {
                        base.CalculateWorldSpaceTangents();
                        GUIUtility.hotControl             = base.shapeId;
                        GUIUtility.keyboardControl        = base.shapeId;
                        EditorGUIUtility.editingTextField = false;
                    }
                }

                if (GUIUtility.hotControl == base.shapeId &&
                    settings.vertices.Length < kMaxPoints)
                {
                    if (!float.IsNaN(worldPosition.x) && !float.IsInfinity(worldPosition.x) &&
                        !float.IsNaN(worldPosition.y) && !float.IsInfinity(worldPosition.y) &&
                        !float.IsNaN(worldPosition.z) && !float.IsInfinity(worldPosition.z))
                    {
                        if (settings.vertices.Length < 2 &&
                            hoverBuildPlane.normal.sqrMagnitude != 0)
                        {
                            buildPlane = hoverBuildPlane;
                        }
                        CalculateWorldSpaceTangents();

                        if (settings.vertices.Length == 0)
                        {
                            if (pointOnEdge)
                            {
                                firstSnappedEdges  = visualSnappedEdges.ToArray();
                                firstSnappedBrush  = visualSnappedBrush;
                                firstSnappedPlanes = null;
                            }
                            else
                            {
                                firstSnappedBrush  = null;
                                firstSnappedEdges  = null;
                                firstSnappedPlanes = null;
                            }
                            planeOnGeometry = vertexOnGeometry;
                        }
                        else
                        {
                            if (firstSnappedEdges != null)
                            {
                                if (firstSnappedPlanes == null)
                                {
                                    CreateSnappedPlanes();
                                }

                                bool outside = true;
                                for (int i = 0; i < firstSnappedPlanes.Length; i++)
                                {
                                    if (firstSnappedPlanes[i].Distance(worldPosition) <= MathConstants.DistanceEpsilon)
                                    {
                                        outside = false;
                                        break;
                                    }
                                }

                                planeOnGeometry = !outside;
                            }

                            if (vertexOnGeometry)
                            {
                                var plane    = hoverDefaultPlane.Value;
                                var distance = plane.Distance(worldPosition);
                                plane.d          += distance;
                                hoverDefaultPlane = plane;

                                for (int i = 0; i < settings.vertices.Length; i++)
                                {
                                    if (!settings.onGeometryVertices[i])
                                    {
                                        settings.SetPoint(i, GeometryUtility.ProjectPointOnPlane(plane, settings.vertices[i]));
                                        settings.onGeometryVertices[i] = true;
                                    }
                                }
                            }
                        }
                        ArrayUtility.Add(ref settings.onGeometryVertices, vertexOnGeometry);
                        settings.AddPoint(worldPosition);

                        UpdateSizes();
                        SceneView.RepaintAll();
                        if (settings.vertices.Length == kMaxPoints)
                        {
                            HotKeyReleased();
                        }
                    }
                }
                return;
            }

            case EventType.MouseDrag:
            {
                if (Tools.viewTool != ViewTool.None && Tools.viewTool != ViewTool.Pan)
                {
                    break;
                }
                if (GUIUtility.hotControl == base.shapeId && Event.current.button == 0)
                {
                    Event.current.Use();
                }
                return;
            }

            case EventType.MouseUp:
            {
                if (GUIUtility.hotControl != base.shapeId)
                {
                    return;
                }
                if (Tools.viewTool != ViewTool.None && Tools.viewTool != ViewTool.Pan)
                {
                    return;
                }
                if (Event.current.button == 0)
                {
                    Event.current.Use();

                    ResetVisuals();
                    if (settings.vertices.Length == kMaxPoints)
                    {
                        GUIUtility.hotControl             = 0;
                        GUIUtility.keyboardControl        = 0;
                        EditorGUIUtility.editingTextField = false;

                        editMode = EditMode.CreateShape;
                        HotKeyReleased();
                    }
                }
                return;
            }
            }
        }
        void ApplyMaterial(SelectedBrushSurface[] hoverBrushSurfaces)
        {
            if (hoverBrushSurfaces == null)
            {
                return;
            }
            var updateModels  = new HashSet <CSGModel>();
            var updateBrushes = new HashSet <CSGBrush>();

            for (int i = 0; i < hoverBrushSurfaces.Length; i++)
            {
                var brush       = hoverBrushSurfaces[i].brush;
                var brush_cache = InternalCSGModelManager.GetBrushCache(brush);
                if (brush_cache == null ||
                    brush_cache.childData == null ||
                    brush_cache.childData.Model == null)
                {
                    continue;
                }
                try
                {
                    var model = brush_cache.childData.Model;
                    updateModels.Add(model);
                    if (updateBrushes.Add(brush))
                    {
                        InternalCSGModelManager.UnregisterMaterials(model, brush.Shape, false);

                        // per brush
                        if (!selectAllSurfaces)
                        {
                            System.Array.Copy(previousMaterials[i], brush.Shape.Materials, brush.Shape.Materials.Length);
                        }
                        else
                        {
                            var surfaceMaterials = brush.Shape.Materials.ToArray();
                            if (dragMaterials.Count > 1)
                            {
                                for (int m = 0; m < surfaceMaterials.Length; m++)
                                {
                                    surfaceMaterials[m] = dragMaterials[Random.Range(0, dragMaterials.Count)];
                                }
                            }
                            else
                            {
                                for (int m = 0; m < surfaceMaterials.Length; m++)
                                {
                                    surfaceMaterials[m] = dragMaterials[0];
                                }
                            }
                            System.Array.Copy(surfaceMaterials, brush.Shape.Materials, brush.Shape.Materials.Length);
                        }
                    }

                    // per surface
                    if (!selectAllSurfaces)
                    {
                        var highlight_surface = hoverBrushSurfaces[i].surfaceIndex;
                        if (highlight_surface >= 0)
                        {
                            var highlight_texGen = brush.Shape.Surfaces[highlight_surface].TexGenIndex;

                            Material dragMaterial;
                            if (dragMaterials.Count > 1)
                            {
                                dragMaterial = dragMaterials[Random.Range(0, dragMaterials.Count)];
                            }
                            else
                            {
                                dragMaterial = dragMaterials[0];
                            }

                            brush.Shape.Materials[highlight_texGen] = dragMaterial;
                        }
                    }
                }
                finally {}
            }
            UpdateBrushMeshes(updateBrushes, updateModels);
        }
        public bool UpdateSelection(HashSet <CSGNode> newTargetNodes, HashSet <Transform> newTargetOthers)
        {
            if (newTargetNodes == null)
            {
                newTargetNodes = new HashSet <CSGNode>();
            }
            if (newTargetOthers == null)
            {
                newTargetOthers = new HashSet <Transform>();
            }

            this.RemovedNodes  = null;
            this.RemovedOthers = null;

            this.AddedNodes  = null;
            this.AddedOthers = null;

            var foundRemovedNodes = new List <CSGNode>();

            if (this.NodeTargets != null &&
                this.NodeTargets.Length > 0)
            {
                if (newTargetNodes.Count == 0)
                {
                    foundRemovedNodes.AddRange(this.NodeTargets);
                }
                else
                {
                    for (int i = 0; i < this.NodeTargets.Length; i++)
                    {
                        if (!this.NodeTargets[i] ||
                            !newTargetNodes.Contains(this.NodeTargets[i]))
                        {
                            foundRemovedNodes.Add(this.NodeTargets[i]);
                        }
                    }
                }
            }

            var foundRemovedOthers = new List <Transform>();

            if (this.OtherTargets != null &&
                this.OtherTargets.Length > 0)
            {
                if (newTargetOthers.Count == 0)
                {
                    foundRemovedOthers.AddRange(this.OtherTargets);
                }
                else
                {
                    for (int i = 0; i < this.OtherTargets.Length; i++)
                    {
                        if (!this.OtherTargets[i] ||
                            !newTargetOthers.Contains(this.OtherTargets[i]))
                        {
                            foundRemovedOthers.Add(this.OtherTargets[i]);
                        }
                    }
                }
            }

            var originalTargetNodeCount  = (this.NodeTargets == null) ? 0 : this.NodeTargets.Length;
            var originalTargetOtherCount = (this.OtherTargets == null) ? 0 : this.OtherTargets.Length;

            // If our counts are the same and nothing is removed (and nothing could've been added), nothing has changed.
            if (newTargetNodes.Count == originalTargetNodeCount &&
                newTargetOthers.Count == originalTargetOtherCount &&
                foundRemovedNodes.Count == 0 &&
                foundRemovedOthers.Count == 0)
            {
                //Debug.Log(originalTargetNodeCount + " " + originalTargetOtherCount + " " + newTargetNodes .Count + " " + newTargetOthers .Count);
                return(false);
            }

            Validate();

            foreach (var node in foundRemovedNodes)
            {
                ArrayUtility.Remove(ref this.NodeTargets, node);

                var brush = node as CSGBrush;
                if (brush != null)
                {
                    ArrayUtility.Remove(ref this.BrushTargets, brush);
                    continue;
                }
                var operation = node as CSGOperation;
                if (node is CSGOperation)
                {
                    ArrayUtility.Remove(ref this.OperationTargets, operation);
                    continue;
                }
                var model = node as CSGModel;
                if (node is CSGModel)
                {
                    ArrayUtility.Remove(ref this.ModelTargets, model);
                    continue;
                }
            }

            foreach (var other in foundRemovedOthers)
            {
                ArrayUtility.Remove(ref this.OtherTargets, other);
            }

            var foundAddedNodes = new List <CSGNode>();

            foreach (var node in newTargetNodes)
            {
                if (this.NodeTargets != null &&
                    ArrayUtility.Contains(this.NodeTargets, node))
                {
                    continue;
                }

                if (this.NodeTargets == null)
                {
                    this.NodeTargets = new CSGNode[] { node };
                }
                else
                {
                    ArrayUtility.Add(ref this.NodeTargets, node);
                }

                foundAddedNodes.Add(node);

                if (SelectionUtility.IsPrefab(node.gameObject))
                {
                    continue;
                }

                var brush = node as CSGBrush;
                if (brush != null)
                {
                    if (this.BrushTargets == null)
                    {
                        this.BrushTargets = new CSGBrush[] { brush }
                    }
                    ;
                    else
                    {
                        ArrayUtility.Add(ref this.BrushTargets, brush);
                    }
                    continue;
                }
                var operation = node as CSGOperation;
                if (node is CSGOperation)
                {
                    if (this.OperationTargets == null)
                    {
                        this.OperationTargets = new CSGOperation[] { operation }
                    }
                    ;
                    else
                    {
                        ArrayUtility.Add(ref this.OperationTargets, operation);
                    }
                    continue;
                }
                var model = node as CSGModel;
                if (node is CSGModel)
                {
                    if (this.ModelTargets == null)
                    {
                        this.ModelTargets = new CSGModel[] { model }
                    }
                    ;
                    else
                    {
                        ArrayUtility.Add(ref this.ModelTargets, model);
                    }
                    continue;
                }
            }

            var foundAddedOthers = new List <Transform>();

            foreach (var other in newTargetOthers)
            {
                if (this.OtherTargets != null &&
                    ArrayUtility.Contains(this.OtherTargets, other))
                {
                    continue;
                }

                if (this.OtherTargets == null)
                {
                    this.OtherTargets = new Transform[] { other }
                }
                ;
                else
                {
                    ArrayUtility.Add(ref this.OtherTargets, other);
                }
                foundAddedOthers.Add(other);
            }

            for (int i = foundAddedNodes.Count - 1; i >= 0; i--)
            {
                var node  = foundAddedNodes[i];
                var brush = node as CSGBrush;
                if (brush != null)
                {
                    var brush_cache = InternalCSGModelManager.GetBrushCache(brush);
                    if (brush_cache == null ||
                        brush_cache.childData == null ||
                        brush_cache.childData.Model == null)
                    {
                        continue;
                    }

                    var childModel = brush_cache.childData.Model;
                    if (childModel &&
                        childModel.isActiveAndEnabled)
                    {
                        SelectionUtility.LastUsedModel = childModel;
                    }
                    break;
                }
                var operation = node as CSGOperation;
                if (operation != null)
                {
                    var operation_cache = InternalCSGModelManager.GetOperationCache(operation);
                    if (operation_cache == null ||
                        operation_cache.ChildData == null ||
                        operation_cache.ChildData.Model == null)
                    {
                        continue;
                    }

                    SelectionUtility.LastUsedModel = operation_cache.ChildData.Model;
                    break;
                }
                var model = node as CSGModel;
                if (model &&
                    model.isActiveAndEnabled)
                {
                    SelectionUtility.LastUsedModel = model;
                    break;
                }
            }

            this.RemovedNodes  = foundRemovedNodes.ToArray();
            this.RemovedOthers = foundRemovedOthers.ToArray();

            this.AddedNodes  = foundAddedNodes.ToArray();
            this.AddedOthers = foundAddedOthers.ToArray();

            return(foundAddedNodes.Count > 0 || foundRemovedNodes.Count > 0 || foundAddedOthers.Count > 0 || foundRemovedOthers.Count > 0);
        }
Beispiel #18
0
        protected override void HandleCreateShapeEvents(Rect sceneRect)
        {
            if (settings.vertices.Length < 2)
            {
                if (editMode == EditMode.ExtrudeShape ||
                    editMode == EditMode.EditShape)
                {
                    editMode = EditMode.CreatePlane;
                }
            }

            bool     pointOnEdge      = false;
            bool     havePlane        = false;
            bool     vertexOnGeometry = false;
            CSGBrush vertexOnBrush    = null;

            CSGPlane hoverBuildPlane = buildPlane;
            var      sceneView       = SceneView.currentDrawingSceneView; //(SceneView.currentDrawingSceneView != null) ? SceneView.currentDrawingSceneView : SceneView.lastActiveSceneView;
            var      camera          = (sceneView == null) ? null : sceneView.camera;

            if (camera != null &&
                camera.pixelRect.Contains(Event.current.mousePosition))
            {
                if (!hoverDefaultPlane.HasValue ||
                    settings.vertices.Length == 0)
                {
                    bool forceGrid = RealtimeCSG.CSGGrid.ForceGrid;
                    RealtimeCSG.CSGGrid.ForceGrid = false;
                    hoverDefaultPlane             = RealtimeCSG.CSGGrid.CurrentGridPlane;
                    RealtimeCSG.CSGGrid.ForceGrid = forceGrid;
                    firstSnappedEdges             = null;
                    firstSnappedBrush             = null;
                    firstSnappedPlanes            = null;
                    base.geometryModel            = null;
                }
                if (editMode == EditMode.CreatePlane)
                {
                    BrushIntersection intersection;
                    if (!IgnoreDepthForRayCasts(sceneView) && !havePlane &&
                        SceneQueryUtility.FindWorldIntersection(Event.current.mousePosition, out intersection))
                    {
                        worldPosition = intersection.worldIntersection;
                        if (intersection.surfaceInverted)
                        {
                            hoverBuildPlane = intersection.plane.Negated();
                        }
                        else
                        {
                            hoverBuildPlane = intersection.plane;
                        }
                        vertexOnBrush = intersection.brush;

                        vertexOnGeometry = true;
                    }
                    else
                    {
                        hoverBuildPlane = hoverDefaultPlane.Value;
                        vertexOnBrush   = null;

                        var mouseRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
                        worldPosition    = hoverBuildPlane.Intersection(mouseRay);
                        vertexOnGeometry = false;
                    }

                    ResetVisuals();
                    if (snapFunction != null)
                    {
                        CSGBrush snappedOnBrush;
                        worldPosition = snapFunction(worldPosition, hoverBuildPlane, ref visualSnappedEdges, out snappedOnBrush, generatedBrushes);
                        if (snappedOnBrush != null)
                        {
                            pointOnEdge = (visualSnappedEdges != null &&
                                           visualSnappedEdges.Count > 0);
                            vertexOnBrush    = snappedOnBrush;
                            vertexOnGeometry = true;
                        }
                    }

                    if (settings.vertices.Length == 1)
                    {
                        if (hoverBuildPlane.normal != MathConstants.zeroVector3)
                        {
                            editMode  = EditMode.CreateShape;
                            havePlane = true;
                        }
                    }
                    else
                    if (settings.vertices.Length == 2)
                    {
                        onLastPoint = true;
                    }
                }
                else
                {
                    var mouseRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
                    worldPosition = hoverBuildPlane.Intersection(mouseRay);

                    ResetVisuals();
                    if (snapFunction != null)
                    {
                        CSGBrush snappedOnBrush;
                        worldPosition = snapFunction(worldPosition, hoverBuildPlane, ref visualSnappedEdges, out snappedOnBrush, generatedBrushes);
                        if (snappedOnBrush != null)
                        {
                            pointOnEdge = (visualSnappedEdges != null &&
                                           visualSnappedEdges.Count > 0);
                            vertexOnBrush = snappedOnBrush;
                        }
                    }
                }

                if (geometryModel == null && vertexOnBrush != null)
                {
                    var brush_cache = InternalCSGModelManager.GetBrushCache(vertexOnBrush);
                    if (brush_cache != null && brush_cache.childData != null && brush_cache.childData.Model)
                    {
                        geometryModel = brush_cache.childData.Model;
                    }
                }

                if (worldPosition != prevWorldPosition)
                {
                    prevWorldPosition = worldPosition;
                    if (Event.current.type != EventType.Repaint)
                    {
                        SceneView.RepaintAll();
                    }
                }

                visualSnappedGrid  = RealtimeCSG.CSGGrid.FindAllGridEdgesThatTouchPoint(worldPosition);
                visualSnappedBrush = vertexOnBrush;
            }

            RealtimeCSG.CSGGrid.SetForcedGrid(hoverBuildPlane);


            if (!SceneDragToolManager.IsDraggingObjectInScene &&
                Event.current.type == EventType.Repaint)
            {
                PaintSnapVisualisation();
                PaintShape(base.shapeId);
            }


            var type = Event.current.GetTypeForControl(base.shapeId);

            switch (type)
            {
            case EventType.Layout:
            {
                return;
            }

            case EventType.ValidateCommand:
            case EventType.KeyDown:
            {
                if (GUIUtility.hotControl == base.shapeId)
                {
                    if (Keys.PerformActionKey.IsKeyPressed() ||
                        Keys.DeleteSelectionKey.IsKeyPressed() ||
                        Keys.CancelActionKey.IsKeyPressed())
                    {
                        Event.current.Use();
                    }
                }
                return;
            }

            case EventType.KeyUp:
            {
                if (GUIUtility.hotControl == base.shapeId)
                {
                    if (Keys.BoxBuilderMode.IsKeyPressed() ||
                        Keys.PerformActionKey.IsKeyPressed())
                    {
                        HotKeyReleased();
                        Event.current.Use();
                        return;
                    }
                    if (Keys.DeleteSelectionKey.IsKeyPressed() ||
                        Keys.CancelActionKey.IsKeyPressed())
                    {
                        Cancel();
                        Event.current.Use();
                        return;
                    }
                }
                return;
            }

            case EventType.MouseDown:
            {
                if (!sceneRect.Contains(Event.current.mousePosition))
                {
                    break;
                }
                if (Tools.viewTool != ViewTool.None && Tools.viewTool != ViewTool.Pan)
                {
                    return;
                }
                if ((GUIUtility.hotControl != 0 && GUIUtility.hotControl != shapeEditId && GUIUtility.hotControl != base.shapeId) ||
                    Event.current.button != 0)
                {
                    return;
                }

                Event.current.Use();
                if (settings.vertices.Length == 0)
                {
                    if ((GUIUtility.hotControl == 0 ||
                         GUIUtility.hotControl == base.shapeEditId) && base.shapeId != -1)
                    {
                        base.CalculateWorldSpaceTangents();
                        GUIUtility.hotControl             = base.shapeId;
                        GUIUtility.keyboardControl        = base.shapeId;
                        EditorGUIUtility.editingTextField = false;
                    }
                }

                if (GUIUtility.hotControl == base.shapeId && settings.vertices.Length < 2)
                {
                    if (!float.IsNaN(worldPosition.x) && !float.IsInfinity(worldPosition.x) &&
                        !float.IsNaN(worldPosition.y) && !float.IsInfinity(worldPosition.y) &&
                        !float.IsNaN(worldPosition.z) && !float.IsInfinity(worldPosition.z))
                    {
                        if (hoverBuildPlane.normal.sqrMagnitude != 0)
                        {
                            buildPlane = hoverBuildPlane;
                        }
                        CalculateWorldSpaceTangents();

                        if (settings.vertices.Length == 0)
                        {
                            if (pointOnEdge)
                            {
                                firstSnappedEdges  = visualSnappedEdges.ToArray();
                                firstSnappedBrush  = visualSnappedBrush;
                                firstSnappedPlanes = null;
                            }
                            else
                            {
                                firstSnappedBrush  = null;
                                firstSnappedEdges  = null;
                                firstSnappedPlanes = null;
                            }
                            geometryPlane   = buildPlane;
                            planeOnGeometry = vertexOnGeometry;
                        }
                        else
                        {
                            if (firstSnappedEdges != null)
                            {
                                if (firstSnappedPlanes == null)
                                {
                                    CreateSnappedPlanes();
                                }

                                bool outside = true;
                                for (int i = 0; i < firstSnappedPlanes.Length; i++)
                                {
                                    if (firstSnappedPlanes[i].Distance(worldPosition) <= MathConstants.DistanceEpsilon)
                                    {
                                        outside = false;
                                        break;
                                    }
                                }

                                planeOnGeometry = !outside;
                            }

                            if (vertexOnGeometry)
                            {
                                var plane    = hoverDefaultPlane.Value;
                                var distance = plane.Distance(worldPosition);
                                if (float.IsInfinity(distance) || float.IsNaN(distance))
                                {
                                    distance = 1.0f;
                                }
                                plane.d          += distance;
                                hoverDefaultPlane = plane;

                                for (int i = 0; i < settings.vertices.Length; i++)
                                {
                                    if (!settings.onGeometryVertices[i])
                                    {
                                        settings.vertices[i]           = GeometryUtility.ProjectPointOnPlane(plane, settings.vertices[i]);
                                        settings.onGeometryVertices[i] = true;
                                    }
                                }
                            }
                        }
                        ArrayUtility.Add(ref settings.onGeometryVertices, vertexOnGeometry);
                        settings.AddPoint(worldPosition);
                        SceneView.RepaintAll();
                        if (settings.vertices.Length == 2)
                        {
                            HotKeyReleased();
                        }
                    }
                }
                return;
            }

            case EventType.MouseDrag:
            {
                if (Tools.viewTool != ViewTool.None && Tools.viewTool != ViewTool.Pan)
                {
                    break;
                }
                if (GUIUtility.hotControl == base.shapeId && Event.current.button == 0)
                {
                    Event.current.Use();
                }
                return;
            }

            case EventType.MouseUp:
            {
                if (GUIUtility.hotControl != base.shapeId)
                {
                    return;
                }
                if (Tools.viewTool != ViewTool.None && Tools.viewTool != ViewTool.Pan)
                {
                    return;
                }
                if (Event.current.button == 0)
                {
                    Event.current.Use();

                    ResetVisuals();
                    if (onLastPoint)
                    {
                        GUIUtility.hotControl             = 0;
                        GUIUtility.keyboardControl        = 0;
                        EditorGUIUtility.editingTextField = false;

                        editMode = EditMode.CreateShape;
                        HotKeyReleased();
                    }
                }
                return;
            }
            }
            return;
        }
Beispiel #19
0
        public void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    if (_brushes == null)
                    {
                        return;
                    }

                    if (_brushes.Length > 0)
                    {
                        for (int i = 0; i < _brushes.Length; i++)
                        {
                            if (!_brushes[i])
                            {
                                continue;
                            }
                            _brushes[i].EnsureInitialized();
                            ShapeUtility.CheckMaterials(_brushes[i].Shape);
                            if (_reregisterMaterials)
                            {
                                CSGBrushCache brushCache = InternalCSGModelManager.GetBrushCache(_brushes[i]);
                                if (brushCache != null)
                                {
                                    InternalCSGModelManager.RegisterMaterials(brushCache.childData.Model, _brushes[i].Shape, false);
                                }
                            }
                        }
                        if (_reregisterMaterials)
                        {
                            for (int i = 0; i < _models.Length; i++)
                            {
                                if (!_models[i])
                                {
                                    continue;
                                }
                                InternalCSGModelManager.UpdateMaterialCount(_models[i]);
                            }
                        }
                        for (int i = 0; i < _brushes.Length; i++)
                        {
                            if (!_brushes[i])
                            {
                                continue;
                            }
                            InternalCSGModelManager.CheckSurfaceModifications(_brushes[i], true);
                        }
                        if (_undoGroupIndex != -1)
                        {
                            Undo.CollapseUndoOperations(_undoGroupIndex);
                            Undo.FlushUndoRecordObjects();
                        }
                    }
                }
                _brushes      = null;
                _models       = null;
                disposedValue = true;
            }
        }
Beispiel #20
0
        public static void DoSelectionClick()
        {
            GameObject gameobject;

            SceneQueryUtility.FindClickWorldIntersection(Event.current.mousePosition, out gameobject);

            gameobject = SceneQueryUtility.GetGroupGameObjectIfObjectIsPartOfGroup(gameobject);

            var  selectedObjectsOnClick = new List <int>(Selection.instanceIDs);
            bool addedSelection         = false;

            if (EditorGUI.actionKey)
            {
                if (gameobject != null)
                {
                    var instanceID = gameobject.GetInstanceID();
                    if (selectedObjectsOnClick.Contains(instanceID))
                    {
                        selectedObjectsOnClick.Remove(instanceID);
                    }
                    else
                    {
                        selectedObjectsOnClick.Add(instanceID);
                        addedSelection = true;
                    }

                    if (selectedObjectsOnClick.Count == 0)
                    {
                        Selection.activeTransform = null;
                    }
                    else
                    {
                        Selection.instanceIDs = selectedObjectsOnClick.ToArray();
                    }
                }
            }
            else
            if (Event.current.shift)
            {
                if (gameobject != null)
                {
                    var instanceID = gameobject.GetInstanceID();
                    selectedObjectsOnClick.Add(instanceID);
                    Selection.instanceIDs = selectedObjectsOnClick.ToArray();
                    addedSelection        = true;
                }
            }
            else
            if (Event.current.alt)
            {
                if (gameobject != null)
                {
                    var instanceID = gameobject.GetInstanceID();
                    selectedObjectsOnClick.Remove(instanceID);
                    Selection.instanceIDs = selectedObjectsOnClick.ToArray();
                    return;
                }
            }
            else
            {
                Selection.activeGameObject = gameobject;
                addedSelection             = true;
            }

            if (!addedSelection)
            {
                foreach (var item in Selection.GetFiltered(typeof(CSGBrush), SelectionMode.Deep))
                {
                    var brush       = item as CSGBrush;
                    var brush_cache = InternalCSGModelManager.GetBrushCache(brush);
                    if (brush_cache == null ||
                        brush_cache.childData == null ||
                        !brush_cache.childData.Model ||
                        !brush_cache.childData.Model.isActiveAndEnabled)
                    {
                        continue;
                    }
                    SelectionUtility.LastUsedModel = brush_cache.childData.Model;
                    break;
                }
            }
            else
            if (gameobject != null)
            {
                var brush = gameobject.GetComponent <CSGBrush>();
                if (brush != null)
                {
                    var brush_cache = InternalCSGModelManager.GetBrushCache(brush);
                    if (brush_cache == null ||
                        brush_cache.childData == null ||
                        !brush_cache.childData.Model ||
                        !brush_cache.childData.Model.isActiveAndEnabled)
                    {
                        return;
                    }
                    SelectionUtility.LastUsedModel = brush_cache.childData.Model;
                }
            }
        }
Beispiel #21
0
        protected bool GenerateBrushObjects(int brushObjectCount, bool inGridSpace = true)
        {
            Undo.IncrementCurrentGroup();
            undoGroupIndex = Undo.GetCurrentGroup();

            var lastUsedModel          = SelectionUtility.LastUsedModel;
            var lastUsedModelTransform = !lastUsedModel ? null : lastUsedModel.transform;

            if (!lastUsedModelTransform ||
                !lastUsedModel.isActiveAndEnabled)
            {
                if (prevSelection != null && prevSelection.Length > 0)
                {
                    for (int i = 0; i < prevSelection.Length; i++)
                    {
                        UnityEngine.Object obj   = prevSelection[i];
                        CSGBrush           brush = obj as CSGBrush;
                        MonoBehaviour      mono  = obj as MonoBehaviour;
                        GameObject         go    = obj as GameObject;
                        if (!brush)
                        {
                            if (mono)
                            {
                                brush = mono.GetComponentInChildren <CSGBrush>();
                            }
                            if (go)
                            {
                                brush = go.GetComponentInChildren <CSGBrush>();
                            }
                        }

                        if (!brush)
                        {
                            continue;
                        }

                        if ((brush.gameObject.hideFlags & (HideFlags.HideInHierarchy | HideFlags.NotEditable | HideFlags.DontSaveInBuild)) != 0)
                        {
                            continue;
                        }

                        var brush_cache = InternalCSGModelManager.GetBrushCache(brush);
                        if (brush_cache == null ||
                            brush_cache.childData == null ||
                            brush_cache.childData.ModelTransform == null)
                        {
                            continue;
                        }

                        var model = brush_cache.childData.Model;
                        if (!model ||
                            !model.isActiveAndEnabled)
                        {
                            continue;
                        }

                        lastUsedModelTransform = brush_cache.childData.ModelTransform;
                        break;
                    }
                }
            }

            if (generatedBrushes != null && generatedBrushes.Length > 0)
            {
                for (int i = generatedBrushes.Length - 1; i >= 0; i--)
                {
                    if (generatedBrushes[i])
                    {
                        continue;
                    }
                    ArrayUtility.RemoveAt(ref generatedBrushes, i);
                }
                for (int i = generatedGameObjects.Length - 1; i >= 0; i--)
                {
                    if (generatedGameObjects[i])
                    {
                        var brush = generatedGameObjects[i].GetComponentInChildren <CSGBrush>();
                        if (brush && ArrayUtility.Contains(generatedBrushes, brush))
                        {
                            continue;
                        }
                    }
                    ArrayUtility.RemoveAt(ref generatedGameObjects, i);
                }
            }

            if (generatedGameObjects == null ||
                generatedGameObjects.Length != brushObjectCount)
            {
                if (generatedBrushes != null && generatedBrushes.Length > 0)
                {
                    for (int i = 0; i < generatedBrushes.Length; i++)
                    {
                        InternalCSGModelManager.OnDestroyed(generatedBrushes[i]);
                        GameObject.DestroyImmediate(generatedBrushes[i]);
                    }
                }
                if (generatedGameObjects != null && generatedGameObjects.Length > 0)
                {
                    for (int i = 0; i < generatedGameObjects.Length; i++)
                    {
                        GameObject.DestroyImmediate(generatedGameObjects[i]);
                    }
                }

                if (parentGameObject != null)
                {
                    GameObject.DestroyImmediate(parentGameObject);
                }

                //DebugEditorWindow.PrintDebugInfo();

#if DEMO
                if (CSGBindings.BrushesAvailable() < brushObjectCount)
                {
                    Debug.Log("Demo brush limit hit (" + CSGBindings.BrushesAvailable() + " available, " + brushObjectCount + " required), for the ability to create more brushes please purchase Realtime-CSG");
                    return(false);
                }
#endif
                if (lastUsedModelTransform == null)
                {
                    parentGameObject = OperationsUtility.CreateGameObject(lastUsedModelTransform, "Model", true);
                    InternalCSGModelManager.CreateCSGModel(parentGameObject);
                    parentModel = parentGameObject.GetComponent <CSGModel>();
                    Undo.RegisterCreatedObjectUndo(parentGameObject, "Created model");

                    if (brushObjectCount > 1)
                    {
                        operationGameObject = OperationsUtility.CreateGameObject(parentGameObject.transform, "Operation", true);
                        var transform = operationGameObject.transform;
                        SetBrushTransformation(transform);

                        var operation = operationGameObject.AddComponent <CSGOperation>();
                        if (CurrentCSGOperationType != invalidCSGOperationType)
                        {
                            operation.OperationType = CurrentCSGOperationType;
                        }
                        operation.HandleAsOne = true;
                        Undo.RegisterCreatedObjectUndo(operationGameObject, "Created operation");
                        parentTransform = operationGameObject.transform;
                    }
                    else
                    {
                        parentTransform = parentGameObject.transform;
                    }
                }
                else
                if (brushObjectCount > 1)
                {
                    parentModel      = lastUsedModelTransform.GetComponent <CSGModel>();
                    parentGameObject = OperationsUtility.CreateGameObject(lastUsedModelTransform, "Brushes", true);
                    var transform = parentGameObject.transform;
                    SetBrushTransformation(transform);

                    operationGameObject = parentGameObject;
                    var operation = operationGameObject.AddComponent <CSGOperation>();
                    if (CurrentCSGOperationType != invalidCSGOperationType)
                    {
                        operation.OperationType = CurrentCSGOperationType;
                    }
                    operation.HandleAsOne = true;
                    parentTransform       = operationGameObject.transform;
                    Undo.RegisterCreatedObjectUndo(parentGameObject, "Created brush");
                }
                else
                {
                    parentGameObject    = null;
                    operationGameObject = null;
                    parentTransform     = lastUsedModelTransform;
                    parentModel         = lastUsedModelTransform.GetComponent <CSGModel>();
                }


                generatedGameObjects = new GameObject[brushObjectCount];
                generatedBrushes     = new CSGBrush[brushObjectCount];
                for (int p = 0; p < brushObjectCount; p++)
                {
                    string name;
                    if (brushObjectCount == 1)
                    {
                        name = "Brush";
                    }
                    else
                    {
                        name = "Brush (" + p + ")";
                    }
                    var gameObject = OperationsUtility.CreateGameObject(parentTransform, name, false);
                    gameObject.SetActive(false);

                    var brushComponent = gameObject.AddComponent <CSGBrush>();

                    if (operationGameObject == null)
                    {
                        if (CurrentCSGOperationType != invalidCSGOperationType)
                        {
                            brushComponent.OperationType = CurrentCSGOperationType;
                        }
                        operationGameObject = gameObject;
                        var transform = gameObject.transform;
                        SetBrushTransformation(transform);
                    }

                    generatedBrushes[p]             = brushComponent;
                    generatedBrushes[p].ControlMesh = new ControlMesh();
                    generatedBrushes[p].Shape       = new Shape();
                    Undo.RegisterCreatedObjectUndo(gameObject, "Created brush");
                    generatedGameObjects[p] = gameObject;
                }
                //InternalCSGModelManager.Refresh(forceHierarchyUpdate: true);
                // brushes not registered at this point!??


                //DebugEditorWindow.PrintDebugInfo();
                //Selection.objects = generatedGameObjects;
            }
            else
            {
                UpdateBrushPosition();
            }

            return(generatedBrushes != null && generatedBrushes.Length > 0 && generatedBrushes.Length == brushObjectCount);
        }