Skip to content
Snippets Groups Projects
space_view3d_materials_utils.py 20.2 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
    #(c) 2010 Michael Williamson (michaelw)
    #ported from original by Michael Williamsn
    #
    #tested r28370
    #
    #
    # ##### 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 #####
    
    bl_addon_info = {
        'name': '3D View: Material Utils',
        'author': 'michaelw',
        'version': '0.9',
        'blender': (2, 5, 3),
        'location': 'View3D > Q key',
        'description': 'Menu of material tools (assign, select by etc)  in the 3D View',
        'url':
        'http://wiki.blender.org/index.php/Extensions:2.5/Py/' \
            'Scripts',  # @todo Create wiki page and fix this link.
        'category': '3D View'}
    "a menu of material tools"
    
    """
    Name: 'Master Material Menu'
    Blender: 253
    """
    
    __author__ = ["michaelW"]
    __version__ = '1.3'
    __url__ = [""]
    __bpydoc__ = """
    this script has several functions and operators... grouped for convenience
    * assign material:
        offers the user a list of ALL the materials in the blend file and an additional "new" entry
        the chosen material will be assigned to all the selected objects in object mode.
        
        in edit mode the selected faces get the selected material applied.
    
        if the user chose "new" the new material can be renamed using the "last operator" section of the toolbox
        After assigning the material "clean material slots" and "material to texface" are auto run to keep things tidy (see description bellow)
    
    
    *select by material
        in object mode this offers the user a menu of all materials in the blend file
        any objects using the selected material will become selected, any objects without the material will be removed from selection.
        
        in edit mode:  the menu offers only the materials attached to the current object. It will select the faces that use the material and deselect those that do not.
    
    *clean material slots
        for all selected objects any empty material slots or material slots with materials that are not used by the mesh faces will be removed.
    
    *
    
    
     Any un-used materials and slots will be removed 
    """
    
    
    
    import bpy
    from bpy.props import*
    
    
    def replace_material(m1 , m2, all_objects = False):
        #replace material named m1 with material named m2
        #m1 is the name of original material
        #m2 is the name of the material to replace it with
        #'all' will replace throughout the blend file
        try:
            matorg = bpy.data.materials[m1]
            matrep = bpy.data.materials[m2]
            
            
            #store active object
            scn = bpy.context.scene
            ob_active = bpy.context.active_object
            
            if all_objects:
                objs = bpy.data.objects
            
            else:
                objs = bpy.context.selected_editable_objects
            
            for ob in objs:
                if ob.type == 'MESH':
                    scn.objects.active = ob
                    print(ob.name)   
                    ms = ob.material_slots.values()
                
                    for m in ms:
                        if m.material == matorg:
                            m.material = matrep
                            #don't break the loop as the material can be 
                            # ref'd more than once
            
            #restore active object
            scn.objects.active = ob_active
        except:
            print('no match to replace')
    
    def select_material_by_name(find_mat):
        #in object mode selects all objects with material find_mat
        #in edit mode selects all faces with material find_mat
        
        #check for editmode
        editmode = False
    
        scn = bpy.context.scene
        actob = bpy.context.active_object
        if actob.mode == 'EDIT':
            editmode =True
            bpy.ops.object.mode_set()
        
        
        if not editmode:
            objs = bpy.data.objects 
            for ob in objs:
                if ob.type == 'MESH':
                    ms = ob.material_slots.values()
                    for m in ms:
                        if m.material.name == find_mat:
                            ob.selected = True
                            #the active object may not have the mat!
                            #set it to one that does!
                            scn.objects.active = ob
                            break
                        else:
                            ob.selected = False
                                
                #deselect non-meshes                
                else:
                    ob.selected = False
        
        else:
            #it's editmode, so select the faces
            ob = actob
            ms = ob.material_slots.values()
        
            #same material can be on multiple slots
            slot_indeces =[]
            i = 0
            found = False
            for m in ms:
                if m.material.name == find_mat:
                    slot_indeces.append(i)
                    found = True
            me = ob.data
            for f in me.faces:
                if f.material_index in slot_indeces:
                    f.selected = True
                else:
                    f.selected = False
            me.update   
        if editmode:
            bpy.ops.object.mode_set(mode = 'EDIT')
    
    def mat_to_texface():
        #assigns the first image in each material to the faces in the active uvlayer
        #for all selected objects
        
        #check for editmode
        editmode = False
        
        actob = bpy.context.active_object
        if actob.mode == 'EDIT':
            editmode =True
            bpy.ops.object.mode_set()
        
        for ob in bpy.context.selected_editable_objects:
            #get the materials from slots
            ms = ob.material_slots.values()
            
            #build a list of images, one per material
            images=[]
            #get the textures from the mats
            for m in ms:
                gotimage = False
                textures = m.material.texture_slots.values()
                if len(textures) >= 1:
                    for t in textures:
                        if t != None:
                            tex = t.texture
                            if tex.type == 'IMAGE':
                                img = tex.image
                                images.append(img)
                                gotimage =True
                                break
        
                if not gotimage:
                    print('noimage on', m.name)
                    images.append(None)
        
            #now we have the images
            #applythem to the uvlayer
        
            
            me = ob.data
            #got uvs?
            if not me.uv_textures:
                scn = bpy.context.scene
                scn.objects.active = ob
                bpy.ops.mesh.uv_texture_add()
                scn.objects.active = actob
            
            #get active uvlayer
            for t in  me.uv_textures:
                if t.active:
                    uvtex = t.data.values()
                    for f in me.faces:
                        #check that material had an image!
                        if images[f.material_index] != None:
                            uvtex[f.index].image = images[f.material_index]
                            uvtex[f.index].tex =True
                        else:
                            uvtex[f.index].tex =False
        
            me.update
            
        
        if editmode:
            bpy.ops.object.mode_set(mode = 'EDIT')
                        
            
    
    def assignmatslots(ob, matlist):
        #given an object and a list of material names
        #removes all material slots form the object
        #adds new ones for each material in matlist
        #adds the materials to the slots as well.
    
        scn = bpy.context.scene
        ob_active = bpy.context.active_object
        scn.objects.active = ob
    
        for s in ob.material_slots:
            bpy.ops.object.material_slot_remove()
    
    
        #re-add them and assign material
        i = 0
        for m in matlist:
            mat = bpy.data.materials[m]
            bpy.ops.object.material_slot_add()
            ob.material_slots.values()[i].material = mat
            i += 1
    
        #restore active object:
        scn.objects.active = ob_active
    
    
    def cleanmatslots():
        #check for edit mode
        editmode = False
        actob = bpy.context.active_object
        if actob.mode == 'EDIT':
            editmode =True
            bpy.ops.object.mode_set()
    
    
        objs = bpy.context.selected_editable_objects
        
        for ob in objs:
            print(ob.name)    
            mats = ob.material_slots.keys()
        
            #check the faces on the mesh to build a list of used materials
            usedMatIndex =[]        #we'll store used materials indices here
            faceMats =[]    
            me = ob.data
            for f in me.faces:
                #get the material index for this face...
                faceindex = f.material_index
                        
                #indices will be lost: Store face mat use by name
                currentfacemat = mats[faceindex]
                faceMats.append(currentfacemat)
                        
                        
                #check if index is already listed as used or not
                found = 0
                for m in usedMatIndex:
                    if m == faceindex:
                        found = 1
                        #break
                            
                if found == 0:
                #add this index to the list     
                    usedMatIndex.append(faceindex)
        
            #re-assign the used mats to the mesh and leave out the unused
            ml = []
            mnames = []
            for u in usedMatIndex:
                ml.append( mats[u] )
                #we'll need a list of names to get the face indices...
                mnames.append(mats[u])
                        
            assignmatslots(ob, ml)
            
                    
            #restore face indices:
            i = 0
            for f in me.faces:
                matindex = mnames.index(faceMats[i])
                f.material_index = matindex
                i += 1
            print('Done')
        if editmode:
            bpy.ops.object.mode_set(mode = 'EDIT')
    
    
    
    
    
    def assign_mat(matname="Default"): 
        #get active object so we can restore it later
        actob = bpy.context.active_object
        
        #check if material exists, if it doesn't then create it
        mats =bpy.data.materials
        found = False
        for m in mats:
            if m.name == matname:
                target = m
                found = True
                break
        if not found:
            target = bpy.data.materials.new(matname)
        
        
        #if objectmodeset all faces
        editmode = False
        allfaces = True
        if actob.mode == 'EDIT':
            editmode =True
            allfaces = False    
            bpy.ops.object.mode_set()
        
        objs = bpy.context.selected_editable_objects
        
        for ob in objs:    
            #set the active object to our object
            scn = bpy.context.scene
            scn.objects.active = ob
            
        
            #check if the material is on the object already
            if ob.type =='MESH':
                #check material slots for matname material
                found=False
                i = 0
                mats = ob.material_slots
                for m in mats:
                    if m.name == matname:
                        found =True
                        index = i
                        #make slot active
                        ob.active_material_index = i
                        break
                    i += 1
                
                if not found:
                    index=i
                    #the material is not attached to the object 
                    #so attach it!
        
                    #add a material slot
                    bpy.ops.object.material_slot_add()
        
                    #make  slot active
                    ob.active_material_index = i
        
                    #and assign material to slot
                    ob.material_slots.values()[i].material = target
                #now assign the material:
                me =ob.data
                if allfaces:
                    for f in me.faces:
                        f.material_index = index
                elif allfaces == False:
                    for f in me.faces:
                        if f.selected:
                            f.material_index = index
                me.update
    
        #restore the active object
        bpy.context.scene.objects.active = actob
        if editmode:
            bpy.ops.object.mode_set(mode = 'EDIT')
    
    def texface_to_mat():
        
        for ob in bpy.context.selected_editable_objects:
            img = 0
            m = 0
            #get Image from active_uv_texture
            if (ob.data.uv_textures
            and ob.data.active_uv_texture.data[0].image):
                img = ob.data.active_uv_texture.data[0].image
            #if not look in other uv_textures, take first one
            else:
                for uv_tex in ob.data.uv_textures:
                    if uv_tex.data[0].image:
                        img = uv_tex.data[0].image
                        break
            
            #get material to assign image to if object has an image in uv_textures
            if img:
                #get active material
                if ob.active_material:
                    m = ob.active_material
                #if not look if there are others, take first one
                if not m and ob.material_slots:
                    ms = ob.material_slots.values()
                    for matslot in ms:
                        if matslot.material:
                            m = matslot.material
                            break
            
            #if ob has no material but we have an image create a material
            if not m and img:
                m = bpy.data.materials.new(name=img.name)
                ob.data.add_material(m)
    
            #if image is there create texture and apply to material
            if img:
                tex = bpy.data.textures.new(name=img.name)
                tex.type = 'IMAGE'
                tex = tex.recast_type()
                tex.image = img
                m.add_texture(tex, texture_coordinates='UV', map_to='COLOR')
    
    #operator classes:
    #---------------------------------------------------------------------
    
    class VIEW3D_OT_texface_to_material(bpy.types.Operator):
        ''''''
        bl_idname = "texface_to_material"
        bl_label = "MW Texface Images to Material/Texture"
        bl_options = {'REGISTER', 'UNDO'}
    
        def poll(self, context):
            return context.active_object != None
    
        def execute(self, context):
            texface_to_mat()
            return {'FINISHED'}
    
    class VIEW3D_OT_assign_material(bpy.types.Operator):
        '''assign a material to the selection'''
        bl_idname = "assign_material"
        bl_label = "MW Assign Material"
        bl_options = {'REGISTER', 'UNDO'}
    
        matname = StringProperty(name = 'Material Name', 
            description = 'Name of Material to Assign', 
            default = "", maxlen = 21)
        
        def poll(self, context):
            return context.active_object != None
    
        def execute(self, context):
            mn = self.properties.matname
            print(mn)
            assign_mat(mn)
            cleanmatslots()
            mat_to_texface()
            return {'FINISHED'}
    
    class VIEW3D_OT_clean_material_slots(bpy.types.Operator):
        '''removes any material slots from the 
        selected objects that are not used by the mesh'''
        bl_idname = "clean_material_slots"
        bl_label = "MW Clean Material Slots"
        bl_options = {'REGISTER', 'UNDO'}
    
        def poll(self, context):
            return context.active_object != None
    
        def execute(self, context):
            cleanmatslots()
            return {'FINISHED'}
    
    class VIEW3D_OT_material_to_texface(bpy.types.Operator):
        ''''''
        bl_idname = "material_to_texface"
        bl_label = "MW Material Images to Texface"
        bl_options = {'REGISTER', 'UNDO'}
    
        def poll(self, context):
            return context.active_object != None
    
        def execute(self, context):
            mat_to_texface()
            return {'FINISHED'}
    
    class VIEW3D_OT_select_material_by_name(bpy.types.Operator):
        ''''''
        bl_idname = "select_material_by_name"
        bl_label = "MW Select Material By Name"
        bl_options = {'REGISTER', 'UNDO'}
        matname = StringProperty(name = 'Material Name', 
            description = 'Name of Material to Select', 
            default = "", maxlen = 21)
    
        def poll(self, context):
            return context.active_object != None
    
        def execute(self, context):
            mn = self.properties.matname
            select_material_by_name(mn)
            return {'FINISHED'}
    
    
    class VIEW3D_OT_replace_material(bpy.types.Operator):
        '''assign a material to the selection'''
        bl_idname = "replace_material"
        bl_label = "MW Replace Material"
        bl_options = {'REGISTER', 'UNDO'}
    
        matorg = StringProperty(name = 'Material to Replace', 
            description = 'Name of Material to Assign', 
            default = "", maxlen = 21)
    
        matrep = StringProperty(name = 'Replacement material', 
            description = 'Name of Material to Assign', 
            default = "", maxlen = 21)
    
        all_objects = BoolProperty(name ='all_objects',
            description="replace for all objects in this blend file",
            default = True)
        
        def poll(self, context):
            return context.active_object != None
    
        def execute(self, context):
            m1 = self.properties.matorg
            m2 = self.properties.matrep
            all = self.properties.all_objects
            replace_material(m1,m2,all)
            return {'FINISHED'}
    
    #menu classes
    #-------------------------------------------------------------------------------
    class VIEW3D_MT_master_material(bpy.types.Menu):
        bl_label = "Master Material Menu"
    
        def draw(self, context):
            layout = self.layout
            layout.operator_context = 'INVOKE_REGION_WIN'
    
            layout.menu("VIEW3D_MT_assign_material", icon='ZOOMIN')
            layout.menu("VIEW3D_MT_select_material", icon='HAND')
            layout.separator()
            layout.operator("clean_material_slots", 
                text = 'Clean Material Slots', icon='CANCEL')
            layout.operator("material_to_texface",
                text = 'Material to Texface',icon='FACESEL_HLT')
            layout.operator("texface_to_material",
                text = 'Texface to Material',icon='FACESEL_HLT')
    
            layout.separator()
            layout.operator("replace_material", 
                text = 'Replace Material', icon='ARROW_LEFTRIGHT')
           
    
    
    class VIEW3D_MT_assign_material(bpy.types.Menu):
        bl_label = "Assign Material"
    
        def draw(self, context):
            layout = self.layout
            layout.operator_context = 'INVOKE_REGION_WIN'
    
            ob = context
            layout.label
            for i in range (len(bpy.data.materials)):
        
                layout.operator("assign_material",
                    text=bpy.data.materials[i].name, 
                    icon='MATERIAL_DATA').matname = bpy.data.materials[i].name
    
            layout.operator("assign_material",text="Add New", 
                    icon='ZOOMIN')
    
    class VIEW3D_MT_select_material(bpy.types.Menu):
        bl_label = "Select by Material"
    
        def draw(self, context):
            layout = self.layout
            layout.operator_context = 'INVOKE_REGION_WIN'
    
            ob = context.object
            layout.label
            if ob.mode == 'OBJECT':
                #show all materials in entire blend file
                for i in range (len(bpy.data.materials)):
            
                    layout.operator("select_material_by_name",
                        text=bpy.data.materials[i].name, 
                        icon='MATERIAL_DATA').matname = bpy.data.materials[i].name
    
    
            elif ob.mode == 'EDIT':
                #show only the materials on this object
                mats = ob.material_slots.keys()
                for m in mats:
                    layout.operator("select_material_by_name",
                        text=m, 
                        icon='MATERIAL_DATA').matname = m
    
    
    
    
           
    
    classes = [
    VIEW3D_OT_assign_material,
    VIEW3D_OT_clean_material_slots,
    VIEW3D_OT_material_to_texface,
    VIEW3D_OT_select_material_by_name,
    VIEW3D_OT_replace_material,
    VIEW3D_OT_texface_to_material,
    VIEW3D_MT_master_material,
    VIEW3D_MT_assign_material,
    VIEW3D_MT_select_material]
    
    def register():
        register = bpy.types.register
        for cls in classes:
            register(cls)
    
        km = bpy.context.manager.active_keyconfig.keymaps['3D View']
        kmi = km.items.add('wm.call_menu', 'Q', 'PRESS')
        kmi.properties.name = "VIEW3D_MT_master_material"
    
    def unregister():
        unregister = bpy.types.unregister
        for cls in classes:
            unregister(cls)
    
        km = bpy.context.manager.active_keyconfig.keymaps['3D View']
        for kmi in km.items:
            if kmi.idname == 'wm.call_menu':
                if kmi.properties.name ==  "VIEW3D_MT_master_material":
                    km.remove_item(kmi)
                    break
    
    if __name__ == "__main__":
        register()