Skip to content
Snippets Groups Projects
object_boolean_tools.py 45 KiB
Newer Older
  • Learn to ignore specific revisions
  • 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
    # ##### BEGIN GPL LICENSE BLOCK #####
    #
    #  This program is free software; you can redistribute it and/or
    #  modify it under the terms of the GNU General Public License
    #  as published by the Free Software Foundation; either version 2
    #  of the License, or (at your option) any later version.
    #
    #  This program is distributed in the hope that it will be useful,
    #  but WITHOUT ANY WARRANTY; without even the implied warranty of
    #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    #  GNU General Public License for more details.
    #
    #  You should have received a copy of the GNU General Public License
    #  along with this program; if not, write to the Free Software Foundation,
    #  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
    #
    # ##### END GPL LICENSE BLOCK #####
    
    # <pep8 compliant>
    
    bl_info = {
        "name": "Bool Tool",
        "author": "Vitor Balbio, Mikhail Rachinskiy, TynkaTopi, Meta-Androcto",
        "version": (0, 3, 3),
        "blender": (2, 77, 0),
        "location": "View3D > Toolshelf > BoolTool",
        "description": "Bool Tools Hotkey: Ctrl Shift B",
        "wiki_url": "http://wiki.blender.org/index.php/Extensions:2.6/Py/Scripts/Object/BoolTool",
        "tracker_url": "https://developer.blender.org/maniphest/task/edit/form/2/",
        "category": "Object",
        }
    
    import bpy
    from bpy.app.handlers import persistent
    from bpy.types import (
            Operator,
            Panel,
            )
    
    
    # -------------------  Bool Tool FUNCTIONS------------------------------
    # Utils:
    
    # Hide boolean objects
    def update_BoolHide(self, context):
        ao = context.scene.objects.active
        objs = [i.object for i in ao.modifiers if i.type == 'BOOLEAN']
        hide_state = context.scene.BoolHide
    
        for o in objs:
            o.hide = hide_state
    
    # Object is a Canvas
    
    
    def isCanvas(_obj):
        try:
            if _obj["BoolToolRoot"]:
                return True
        except:
            return False
    
    
    # Object is a Brush Tool Bool
    def isBrush(_obj):
        try:
            if _obj["BoolToolBrush"]:
                return True
        except:
            return False
    
    
    # Object is a Poly Brush Tool Bool collection
    def isPolyBrush(_obj):
        try:
            if _obj["BoolToolPolyBrush"]:
                return True
        except:
            return False
    
    
    def BT_ObjectByName(obj):
        for ob in bpy.context.scene.objects:
            if isCanvas(ob) or isBrush(ob):
                if ob.name == obj:
                    return ob
    
    
    def FindCanvas(obj):
        for ob in bpy.context.scene.objects:
            if isCanvas(ob):
                for mod in ob.modifiers:
                    if ("BTool_" in mod.name):
                        if (obj.name in mod.name):
                            return ob
    
    
    def isFTransf():
        user_preferences = bpy.context.user_preferences
        addons = user_preferences.addons
        addon_prefs = addons[__name__].preferences
        if addon_prefs.fast_transform:
            return True
        else:
            return False
    
    
    """
    # EXPERIMENTAL FEATURES
    def isMakeVertexGroup():
        user_preferences = bpy.context.user_preferences
        addon_prefs = user_preferences.addons[__name__].preferences
        if addon_prefs.make_vertex_groups:
            return True
        else:
            return False
    
    def isMakeBoundary():
        user_preferences = bpy.context.user_preferences
        addon_prefs = user_preferences.addons[__name__].preferences
        if addon_prefs.make_boundary:
            return True
        else:
            return False
    """
    
    
    def ConvertToMesh(obj):
        act = bpy.context.scene.objects.active
        bpy.context.scene.objects.active = obj
        bpy.ops.object.convert(target="MESH")
        bpy.context.scene.objects.active = act
    
    
    # Do the Union, Difference and Intersection Operations with a Brush
    def Operation(context, _operation):
    
        useWire = bpy.context.user_preferences.addons[__name__].preferences.use_wire
    
        for selObj in bpy.context.selected_objects:
            if selObj != context.active_object and (selObj.type == "MESH" or selObj.type == "CURVE"):
                if selObj.type == "CURVE":
                    ConvertToMesh(selObj)
                actObj = context.active_object
                selObj.hide_render = True
                cyclesVis = selObj.cycles_visibility
                # for obj in bpy.context.scene.objects:
                #   if isCanvas(obj):
                #      for mod in obj.modifiers:
                #         if(mod.name == "BTool_" + selObj.name):
                #            obj.modifiers.remove(mod)
    
                if useWire:
                    selObj.draw_type = "WIRE"
                else:
                    selObj.draw_type = "BOUNDS"
    
                cyclesVis.camera = False
                cyclesVis.diffuse = False
                cyclesVis.glossy = False
                cyclesVis.shadow = False
                cyclesVis.transmission = False
                if _operation == "SLICE":
                    # copies dupli_group property(empty), but group property is empty (users_group = None)
                    clone = context.active_object.copy()
                    # clone.select=True
                    context.scene.objects.link(clone)
                    sliceMod = clone.modifiers.new("BTool_" + selObj.name, "BOOLEAN")  # add mod to clone obj
                    sliceMod.object = selObj
                    sliceMod.operation = "DIFFERENCE"
                    clone["BoolToolRoot"] = True
                newMod = actObj.modifiers.new("BTool_" + selObj.name, "BOOLEAN")
                newMod.object = selObj
                if _operation == "SLICE":
                    newMod.operation = "INTERSECT"
                else:
                    newMod.operation = _operation
    
                actObj["BoolToolRoot"] = True
                selObj["BoolToolBrush"] = _operation
                selObj["BoolTool_FTransform"] = "False"
    
    
    # Do Direct Union, Difference and Intersection Operations
    def Operation_Direct(context, _operation):
        actObj = context.active_object
    
        useWire = bpy.context.user_preferences.addons[__name__].preferences.use_wire
        for selObj in bpy.context.selected_objects:
            if selObj != context.active_object and (selObj.type == "MESH" or selObj.type == "CURVE"):
                if selObj.type == "CURVE":
                    ConvertToMesh(selObj)
                actObj = context.active_object
                if useWire:
                    selObj.draw_type = "WIRE"
                else:
                    selObj.draw_type = "BOUNDS"
                if _operation == "SLICE":
                    # copies dupli_group property(empty), but group property is empty (users_group = None)
                    clone = context.active_object.copy()
                    # clone.select=True
                    clone.data = context.active_object.data.copy()
                    context.scene.objects.link(clone)
                    sliceMod = clone.modifiers.new("BTool_" + selObj.name, "BOOLEAN")  # add mod to clone obj
                    sliceMod.object = selObj
                    sliceMod.operation = "DIFFERENCE"
    
                    bpy.ops.object.modifier_apply(modifier=sliceMod.name)
    
                newMod = actObj.modifiers.new("BTool_" + selObj.name, "BOOLEAN")
                if _operation == "SLICE":
                    newMod.operation = "INTERSECT"
                else:
                    newMod.operation = _operation
                newMod.object = selObj
                bpy.ops.object.modifier_apply(modifier=newMod.name)
                bpy.ops.object.select_all(action='DESELECT')
                # selObj.select = True
                # bpy.ops.object.delete()
    
    
    # Remove Obejcts form the BoolTool System
    def Remove(context, thisObj_name, Prop):
        # Find the Brush pointed in the Tree View and Restore it, active is the Canvas
        actObj = context.active_object
    
        # Restore the Brush
        def RemoveThis(_thisObj_name):
            for obj in bpy.context.scene.objects:
                # if it's the brush object
                if obj.name == _thisObj_name:
                    cyclesVis = obj.cycles_visibility
                    obj.draw_type = "TEXTURED"
                    del obj["BoolToolBrush"]
                    del obj["BoolTool_FTransform"]
                    cyclesVis.camera = True
                    cyclesVis.diffuse = True
                    cyclesVis.glossy = True
                    cyclesVis.shadow = True
                    cyclesVis.transmission = True
    
                    # Remove it from the Canvas
                    for mod in actObj.modifiers:
                        if ("BTool_" in mod.name):
                            if (_thisObj_name in mod.name):
                                actObj.modifiers.remove(mod)
    
        if Prop == "THIS":
            RemoveThis(thisObj_name)
    
        # If the remove was called from the Properties:
        else:
            # Remove the Brush Property
            if Prop == "BRUSH":
                Canvas = FindCanvas(actObj)
                for mod in Canvas.modifiers:
                    if ("BTool_" in mod.name):
                        if (actObj.name in mod.name):
                            Canvas.modifiers.remove(mod)
                            cyclesVis = actObj.cycles_visibility
                            actObj.draw_type = "TEXTURED"
                            del actObj["BoolToolBrush"]
                            del actObj["BoolTool_FTransform"]
                            cyclesVis.camera = True
                            cyclesVis.diffuse = True
                            cyclesVis.glossy = True
                            cyclesVis.shadow = True
                            cyclesVis.transmission = True
    
            if Prop == "CANVAS":
                for mod in actObj.modifiers:
                    if ("BTool_" in mod.name):
                        RemoveThis(mod.object.name)
    
    
    # Tooble the Enable the Brush Object Propertie
    def EnableBrush(context, objList, canvas):
        for obj in objList:
            for mod in canvas.modifiers:
                if ("BTool_" in mod.name and mod.object.name == obj):
    
                    if (mod.show_viewport):
                        mod.show_viewport = False
                        mod.show_render = False
                    else:
                        mod.show_viewport = True
                        mod.show_render = True
    
    
    # Find the Canvas and Enable this Brush
    def EnableThisBrush(context, set):
        canvas = None
        for obj in bpy.context.scene.objects:
            if obj != bpy.context.active_object:
                if isCanvas(obj):
                    for mod in obj.modifiers:
                        if ("BTool_" in mod.name):
                            if mod.object == bpy.context.active_object:
                                canvas = obj
    
        for mod in canvas.modifiers:
            if ("BTool_" in mod.name):
                if mod.object == bpy.context.active_object:
                    if set == "None":
                        if (mod.show_viewport):
                            mod.show_viewport = False
                            mod.show_render = False
                        else:
                            mod.show_viewport = True
                            mod.show_render = True
                    else:
                        if (set == "True"):
                            mod.show_viewport = True
                        else:
                            mod.show_viewport = False
                    return
    
    
    # Tooble the Fast Transform Propertie of the Active Brush
    def EnableFTransf(context):
        actObj = bpy.context.active_object
    
        if actObj["BoolTool_FTransform"] == "True":
            actObj["BoolTool_FTransform"] = "False"
        else:
            actObj["BoolTool_FTransform"] = "True"
        return
    
    
    # Apply All Brushes to the Canvas
    def ApplyAll(context, list):
        objDeleteList = []
        for selObj in list:
            if isCanvas(selObj) and selObj == context.active_object:
                for mod in selObj.modifiers:
                    if ("BTool_" in mod.name):
                        objDeleteList.append(mod.object)
                    try:
                        bpy.ops.object.modifier_apply(modifier=mod.name)
                    except:  # if fails the means it is multiuser data
                        context.active_object.data = context.active_object.data.copy()  # so just make data unique
                        bpy.ops.object.modifier_apply(modifier=mod.name)
    
                # bpy.ops.object.select_all(action='TOGGLE')
                # bpy.ops.object.select_all(action='DESELECT')
                # for obj in deleteList:
                #     obj.select = True
                # bpy.ops.object.delete()
        for obj in context.scene.objects:
            if isCanvas(obj):
                for mod in obj.modifiers:
                    if mod.type == 'BOOLEAN':
                        if mod.object in objDeleteList:  # do not delete brush that is used by another canvas
                            objDeleteList.remove(mod.object)  # remove it from deletion
        bpy.ops.object.select_all(action='DESELECT')
        # for obj in objDeleteList:
        #     obj.select = True
        #     bpy.ops.object.delete()
    
    
    # Apply This Brush to the Canvas
    def ApplyThisBrush(context, brush):
        for obj in context.scene.objects:
            if isCanvas(obj):
                for mod in obj.modifiers:
                    if ("BTool_" + brush.name in mod.name):
                        """
                        # EXPERIMENTAL
                        if isMakeVertexGroup():
                            # Turn all faces of the Brush selected
                            bpy.context.scene.objects.active = brush
                            bpy.ops.object.mode_set(mode='EDIT')
                            bpy.ops.mesh.select_all(action='SELECT')
                            bpy.ops.object.mode_set(mode='OBJECT')
    
                            #Turn off al faces of the Canvas selected
                            bpy.context.scene.objects.active = canvas
                            bpy.ops.object.mode_set(mode='EDIT')
                            bpy.ops.mesh.select_all(action='DESELECT')
                            bpy.ops.object.mode_set(mode='OBJECT')
                        """
    
                        # Apply This Brush
                        context.scene.objects.active = obj
                        try:
                            bpy.ops.object.modifier_apply(modifier=mod.name)
                        except:  # if fails the means it is multiuser data
                            context.active_object.data = context.active_object.data.copy()  # so just make data unique
                            bpy.ops.object.modifier_apply(modifier=mod.name)
                        bpy.ops.object.select_all(action='TOGGLE')
                        bpy.ops.object.select_all(action='DESELECT')
    
                        """
                        # EXPERIMENTAL
                        if isMakeVertexGroup():
                            # Make Vertex Group
                            bpy.ops.object.mode_set(mode='EDIT')
                            bpy.ops.object.vertex_group_assign_new()
                            bpy.ops.mesh.select_all(action='DESELECT')
                            bpy.ops.object.mode_set(mode='OBJECT')
    
                            canvas.vertex_groups.active.name = "BTool_" + brush.name
                        """
    
                    # Garbage Colletor
        brush.select = True
        # bpy.ops.object.delete()
    
    
    def GCollector(_obj):
        if isCanvas(_obj):
            BTRoot = False
            for mod in _obj.modifiers:
                if ("BTool_" in mod.name):
                    BTRoot = True
                    if mod.object is None:
                        _obj.modifiers.remove(mod)
            if not BTRoot:
                del _obj["BoolToolRoot"]
    
    
    # Handle the callbacks when modifing things in the scene
    @persistent
    def HandleScene(scene):
        if bpy.data.objects.is_updated:
            for ob in bpy.data.objects:
                if ob.is_updated:
                    GCollector(ob)
    
    
    # ------------------ Bool Tool OPERATORS-----------------------------------------------------
    class BTool_DrawPolyBrush(Operator):
        """Draw Polygonal Mask, can be applyied to Canvas > Brush or Directly. ESC to Exit"""
        bl_idname = "btool.draw_polybrush"
        bl_label = "Draw Poly Brush"
    
        count = 0
    
        @classmethod
        def poll(cls, context):
            return context.active_object is not None
    
        def modal(self, context, event):
            self.count += 1
            actObj = bpy.context.active_object
            if self.count == 1:
                actObj.select = True
                bpy.ops.gpencil.draw('INVOKE_DEFAULT', mode="DRAW_POLY")
    
            if event.type in {'RET', 'NUMPAD_ENTER'}:
    
                bpy.ops.gpencil.convert(type='POLY')
                for obj in context.selected_objects:
                    if obj.type == "CURVE":
                        obj.name = "PolyDraw"
                        bpy.context.scene.objects.active = obj
                        bpy.ops.object.select_all(action='DESELECT')
                        obj.select = True
                        bpy.ops.object.convert(target="MESH")
                        bpy.ops.object.mode_set(mode='EDIT')
                        bpy.ops.mesh.select_all(action='SELECT')
                        bpy.ops.mesh.edge_face_add()
                        bpy.ops.mesh.flip_normals()
                        bpy.ops.object.mode_set(mode='OBJECT')
                        bpy.ops.object.origin_set(type='ORIGIN_CENTER_OF_MASS')
                        bpy.ops.object.modifier_add(type="SOLIDIFY")
                        for mod in obj.modifiers:
                            if mod.name == "Solidify":
                                mod.name = "BTool_PolyBrush"
                                mod.thickness = 1
                                mod.offset = 0
                        obj["BoolToolPolyBrush"] = True
    
                        bpy.ops.object.select_all(action='DESELECT')
                        bpy.context.scene.objects.active = actObj
                        bpy.context.scene.update()
                        actObj.select = True
                        obj.select = True
                        # try:
                        bpy.context.scene.grease_pencil.clear()
                        bpy.ops.gpencil.data_unlink()
    
                return {'FINISHED'}
    
            if event.type in {'ESC'}:
                bpy.ops.ed.undo()  # remove o Grease Pencil
                return {'CANCELLED'}
    
            return {'RUNNING_MODAL'}
    
        def invoke(self, context, event):
            if context.object:
                context.window_manager.modal_handler_add(self)
                return {'RUNNING_MODAL'}
            else:
                self.report({'WARNING'}, "No active object, could not finish")
                return {'CANCELLED'}
    
    
    # Fast Transform
    class BTool_FastTransform(Operator):
        """Enable Fast Transform"""
        bl_idname = "btool.fast_transform"
        bl_label = "Fast Transform"
    
        operator = bpy.props.StringProperty("")
    
        count = 0
    
        def modal(self, context, event):
            self.count += 1
            actObj = bpy.context.active_object
            useWire = bpy.context.user_preferences.addons[__name__].preferences.use_wire
            if self.count == 1:
    
                if isBrush(actObj) and actObj["BoolTool_FTransform"] == "True":
                    EnableThisBrush(bpy.context, "False")
                    if useWire:
                        actObj.draw_type = "WIRE"
                    else:
                        actObj.draw_type = "BOUNDS"
    
                if self.operator == "Translate":
                    bpy.ops.transform.translate('INVOKE_DEFAULT')
                if self.operator == "Rotate":
                    bpy.ops.transform.rotate('INVOKE_DEFAULT')
                if self.operator == "Scale":
                    bpy.ops.transform.resize('INVOKE_DEFAULT')
    
            if event.type == 'LEFTMOUSE':
                if isBrush(actObj):
                    EnableThisBrush(bpy.context, "True")
                    actObj.draw_type = "WIRE"
                return {'FINISHED'}
    
            if event.type in {'RIGHTMOUSE', 'ESC'}:
                if isBrush(actObj):
                    EnableThisBrush(bpy.context, "True")
                    actObj.draw_type = "WIRE"
                return {'CANCELLED'}
    
            return {'RUNNING_MODAL'}
    
        def invoke(self, context, event):
            if context.object:
                context.window_manager.modal_handler_add(self)
                return {'RUNNING_MODAL'}
            else:
                self.report({'WARNING'}, "No active object, could not finish")
                return {'CANCELLED'}
    
    
    # -------------------  Bool Tool OPERATOR CLASSES --------------------------------------------------------
    
    # Brush Operators --------------------------------------------
    
    # Boolean Union Operator
    class BTool_Union(Operator):
        """This operator add a union brush to a canvas"""
        bl_idname = "btool.boolean_union"
        bl_label = "Brush Union"
    
        @classmethod
        def poll(cls, context):
            return context.active_object is not None
    
        def execute(self, context):
            Operation(context, "UNION")
            return {'FINISHED'}
    
    
    # Boolean Intersection Operator
    class BTool_Inters(Operator):
        """This operator add a intersect brush to a canvas"""
        bl_idname = "btool.boolean_inters"
        bl_label = "Brush Intersection"
    
        @classmethod
        def poll(cls, context):
            return context.active_object is not None
    
        def execute(self, context):
            Operation(context, "INTERSECT")
            return {'FINISHED'}
    
    
    # Boolean Difference Operator
    class BTool_Diff(Operator):
        """This operator add a difference brush to a canvas"""
        bl_idname = "btool.boolean_diff"
        bl_label = "Brush Difference"
    
        @classmethod
        def poll(cls, context):
            return context.active_object is not None
    
        def execute(self, context):
            Operation(context, "DIFFERENCE")
            return {'FINISHED'}
    
    # Boolean Slices Operator
    
    
    class BTool_Slice(Operator):
        """This operator add a intersect brush to a canvas"""
        bl_idname = "btool.boolean_slice"
        bl_label = "Brush Slice"
    
        @classmethod
        def poll(cls, context):
            return context.active_object is not None
    
        def execute(self, context):
            Operation(context, "SLICE")
            return {'FINISHED'}
    
    # Booltron Direct FUNCTIONS ---------------------------------------------------
    
    
    def mesh_selection(ob, select_action):
        context = bpy.context
        scene = context.scene
        obj = context.active_object
        ops_me = bpy.ops.mesh
        ops_ob = bpy.ops.object
    
        scene.objects.active = ob
        ops_ob.mode_set(mode="EDIT")
        ops_me.select_all(action=select_action)
        ops_ob.mode_set(mode="OBJECT")
        scene.objects.active = obj
    
    
    def modifier_boolean(obj, ob, mode, delete_not=False):
        md = obj.modifiers.new("BoolTool Direct", 'BOOLEAN')
        md.show_viewport = False
        md.show_render = False
        md.operation = mode
        md.object = ob
    
        bpy.ops.object.modifier_apply(modifier="BoolTool Direct")
        if delete_not is True:
            return
        bpy.context.scene.objects.unlink(ob)
        bpy.data.objects.remove(ob)
    
    
    def boolean_each(mode):
        context = bpy.context
        obj = context.active_object
    
        obj.select = False
        obs = context.selected_objects
    
        mesh_selection(obj, 'DESELECT')
        for ob in obs:
            mesh_selection(ob, 'SELECT')
            modifier_boolean(obj, ob, mode)
        obj.select = True
    
    
    def objects_get():
        context = bpy.context
        obj = context.active_object
    
        obj.select = False
        ob = context.selected_objects[0]
    
        mesh_selection(obj, 'DESELECT')
        mesh_selection(ob, 'SELECT')
    
        return obj, ob
    
    # Booltron Direct Operators ---------------------------------------------------
    
    
    class Direct_Union(Operator):
        """Combine selected objects"""
        bl_idname = "btool.direct_union"
        bl_label = "Union"
        bl_options = {'REGISTER', 'UNDO'}
    
        def execute(self, context):
            boolean_each('UNION')
            return {'FINISHED'}
    
    
    class Direct_Difference(Operator):
        """Subtract selected objects from active object"""
        bl_idname = "btool.direct_difference"
        bl_label = "Difference"
        bl_options = {'REGISTER', 'UNDO'}
    
        def execute(self, context):
            boolean_each('DIFFERENCE')
            return {'FINISHED'}
    
    
    class Direct_Intersect(Operator):
        """Keep only intersecting geometry"""
        bl_idname = "btool.direct_intersect"
        bl_label = "Intersect"
        bl_options = {'REGISTER', 'UNDO'}
    
        def execute(self, context):
            boolean_each('INTERSECT')
            return {'FINISHED'}
    
    
    class Direct_Slice(Operator):
        """Slice active object along the selected object (can handle only two objects at a time)"""
        bl_idname = "btool.direct_slice"
        bl_label = "Slice"
        bl_options = {'REGISTER', 'UNDO'}
    
        @classmethod
        def poll(cls, context):
            return len(context.selected_objects) == 2
    
        def execute(self, context):
            scene = context.scene
            obj, ob = objects_get()
    
            def object_duplicate(ob):
                ops_ob = bpy.ops.object
                ops_ob.select_all(action="DESELECT")
                ops_ob.select_pattern(pattern=ob.name)
                ops_ob.duplicate()
                scene.objects.active = obj
                return context.selected_objects[0]
    
            obj_copy = object_duplicate(obj)
            modifier_boolean(obj, ob, 'DIFFERENCE', delete_not=True)
            scene.objects.active = obj_copy
            modifier_boolean(obj_copy, ob, 'INTERSECT')
            return {'FINISHED'}
    
    
    class Direct_Subtract(Operator):
        """Subtract selected object from active object, """ \
        """subtracted object not removed (can handle only two objects at a time))"""
        bl_idname = "btool.direct_subtract"
        bl_label = "Subtract"
        bl_options = {'REGISTER', 'UNDO'}
    
        @classmethod
        def poll(cls, context):
            return len(context.selected_objects) == 2
    
        def execute(self, context):
            obj, ob = objects_get()
            modifier_boolean(obj, ob, 'DIFFERENCE', delete_not=True)
            return {'FINISHED'}
    
    # Utils Class ---------------------------------------------------------------
    
    # Find the Brush Selected in Three View
    
    
    class BTool_FindBrush(Operator):
        """Find the this brush"""
        bl_idname = "btool.find_brush"
        bl_label = ""
        obj = bpy.props.StringProperty("")
    
        @classmethod
        def poll(cls, context):
            return context.active_object is not None
    
        def execute(self, context):
            for ob in bpy.context.scene.objects:
                if (ob.name == self.obj):
                    bpy.ops.object.select_all(action='TOGGLE')
                    bpy.ops.object.select_all(action='DESELECT')
                    bpy.context.scene.objects.active = ob
                    ob.select = True
            return {'FINISHED'}
    
    
    # Mode The Modifier in The Stack Up or Down
    class BTool_MoveStack(Operator):
        """Move this Brush Up/Down in the Stack"""
        bl_idname = "btool.move_stack"
        bl_label = ""
        modif = bpy.props.StringProperty("")
        direction = bpy.props.StringProperty("")
    
        @classmethod
        def poll(cls, context):
            return context.active_object is not None
    
        def execute(self, context):
            if (self.direction == "UP"):
                bpy.ops.object.modifier_move_up(modifier=self.modif)
            if (self.direction == "DOWN"):
                bpy.ops.object.modifier_move_down(modifier=self.modif)
            return {'FINISHED'}
    
    
    # Enable or Disable a Brush in th Three View
    class BTool_EnableBrush(Operator):
        """Removes all BoolTool config assigned to it"""
        bl_idname = "btool.enable_brush"
        bl_label = ""
    
        thisObj = bpy.props.StringProperty("")
    
        @classmethod
        def poll(cls, context):
            return context.active_object is not None
    
        def execute(self, context):
            # in this case is just one object but the function accept more than one at once
            EnableBrush(context, [self.thisObj], context.active_object)
            return {'FINISHED'}
    
    
    # Enable or Disabel a Brush Directly
    class BTool_EnableThisBrush(Operator):
        """ Toggles this brush"""
        bl_idname = "btool.enable_this_brush"
        bl_label = ""
    
        @classmethod
        def poll(cls, context):
            return context.active_object is not None
    
        def execute(self, context):
            EnableThisBrush(context, "None")
            return {'FINISHED'}
    
    
    # Enable or Disabel a Brush Directly
    class BTool_EnableFTransform(Operator):
        """Use Fast Transformations to improve speed"""
        bl_idname = "btool.enable_ftransf"
        bl_label = ""
    
        @classmethod
        def poll(cls, context):
            return context.active_object is not None
    
        def execute(self, context):
            EnableFTransf(context)
            return {'FINISHED'}
    
    
    # Other Operations -------------------------------------------------------
    
    # Remove a Brush or a Canvas
    class BTool_Remove(Operator):
        """Removes all BoolTool config assigned to it"""
        bl_idname = "btool.remove"
        bl_label = ""
        bl_options = {'UNDO'}
        thisObj = bpy.props.StringProperty("")
        Prop = bpy.props.StringProperty("")
    
        @classmethod
        def poll(cls, context):
            return context.active_object is not None
    
        def execute(self, context):
            Remove(context, self.thisObj, self.Prop)
            return {'FINISHED'}
    
    
    # Apply All to Canvas
    class BTool_AllBrushToMesh(Operator):
        """Apply all brushes of this canvas"""
        bl_idname = "btool.to_mesh"
        bl_label = "Apply All Canvas"
        bl_options = {'UNDO'}
    
        @classmethod
        def poll(cls, context):
            return context.active_object is not None
    
        def execute(self, context):
            list = bpy.context.selected_objects
            ApplyAll(context, list)
            return {'FINISHED'}
    
    
    # Apply This Brush to the Canvas
    class BTool_BrushToMesh(Operator):
        """Apply this brush to the canvas"""
        bl_idname = "btool.brush_to_mesh"
        bl_label = "Apply this Brush to Canvas"
        bl_options = {'UNDO'}
    
        @classmethod
        def poll(cls, context):
    
            if isBrush(context.active_object):
                return True
            else:
                return False
    
        def execute(self, context):
            ApplyThisBrush(context, bpy.context.active_object)
            return {'FINISHED'}
    
    
    # TODO
    # Apply This Brush To Mesh
    
    
    # ------------------- MENU CLASSES ------------------------------
    # 3Dview Header Menu
    class BoolTool_Menu(bpy.types.Menu):
        bl_label = "BoolTool Operators"
        bl_idname = "OBJECT_MT_BoolTool_Menu"
    
        def draw(self, context):
            layout = self.layout
    
            layout.label("Auto Boolean:")
            layout.operator(Direct_Difference.bl_idname, icon="ROTACTIVE")
            layout.operator(Direct_Union.bl_idname, icon="ROTATECOLLECTION")
            layout.operator(Direct_Intersect.bl_idname, icon="ROTATECENTER")
            layout.operator(Direct_Slice.bl_idname, icon="ROTATECENTER")
            layout.operator(Direct_Subtract.bl_idname, icon="ROTACTIVE")
            layout.separator()
    
            layout.label("Brush Boolean:")
            layout.operator(BTool_Diff.bl_idname, icon="ROTACTIVE")
            layout.operator(BTool_Union.bl_idname, icon="ROTATECOLLECTION")
            layout.operator(BTool_Inters.bl_idname, icon="ROTATECENTER")
            layout.operator(BTool_Slice.bl_idname, icon="ROTATECENTER")
            layout.separator()
    
            if (isCanvas(context.active_object)):
                layout.separator()
                layout.operator(BTool_AllBrushToMesh.bl_idname, icon="MOD_LATTICE", text="Apply All")
                Rem = layout.operator(BTool_Remove.bl_idname, icon="CANCEL", text="Remove All")
                Rem.thisObj = ""
                Rem.Prop = "CANVAS"
    
            if (isBrush(context.active_object)):
                layout.separator()
                layout.operator(BTool_BrushToMesh.bl_idname, icon="MOD_LATTICE", text="Apply Brush")
                Rem = layout.operator(BTool_Remove.bl_idname, icon="CANCEL", text="Remove Brush")
                Rem.thisObj = ""
                Rem.Prop = "BRUSH"
    
    
    def VIEW3D_BoolTool_Menu(self, context):
        self.layout.menu(BoolTool_Menu.bl_idname)
    
    # ---------------- Bool Tools ---------------------
    
    
    class BoolTool_Tools(Panel):
        bl_label = "Tools"
        bl_idname = "BoolTool_Tools"
        bl_space_type = "VIEW_3D"
        bl_region_type = "TOOLS"
        bl_category = "Bool Tool"
        bl_context = "objectmode"
    
        def draw(self, context):
            layout = self.layout
    
            row = layout.row(True)
            col = row.column(True)
            col.label("Auto Boolean:", icon="MODIFIER")
            col.separator()
            col.operator(Direct_Difference.bl_idname, icon="ROTACTIVE")
            col.operator(Direct_Union.bl_idname, icon="ROTATECOLLECTION")
            col.operator(Direct_Intersect.bl_idname, icon="ROTATECENTER")
            col.separator()
            col.operator(Direct_Slice.bl_idname, icon="ROTATECENTER")
            col.operator(Direct_Subtract.bl_idname, icon="ROTACTIVE")
    
            layout.separator()
            row = layout.row(True)
            col = row.column(True)
            col.label("Brush Boolean:", icon="MODIFIER")
            col.separator()
            col.operator(BTool_Diff.bl_idname, text="Difference", icon="ROTACTIVE")
            col.operator(BTool_Union.bl_idname, text="Union", icon="ROTATECOLLECTION")
            col.operator(BTool_Inters.bl_idname, text="Intersect", icon="ROTATECENTER")
            col.operator(BTool_Slice.bl_idname, text="Slice", icon="ROTATECENTER")
    
            layout.separator()
            row = layout.row(True)
            col = row.column(True)
            col.label("Draw:", icon="MESH_CUBE")
            col.separator()
            col.operator(BTool_DrawPolyBrush.bl_idname, icon="LINE_DATA")
            col.separator()
    
    
    # ---------- Properties --------------------------------------------------------
    class BoolTool_Config(Panel):
        bl_label = "Properties"
        bl_idname = "BoolTool_BConfig"
        bl_space_type = "VIEW_3D"
        bl_region_type = "TOOLS"