Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import bpy, sys, os, json
- ### USER DEFINED VARIABLES ###
- # tip: uses forward slashes for paths!
- mappath = r'VMF_FILE_PATH'
- materials = r'PATH/_materials.blend'
- props = r'PATH/_props.blend'
- filesavepath = r'FILE/SAVE/PATH.blend'
- bpy.ops.import_scene.plumber_vmf(filepath=mappath, light_factor=10, game='0', scale=0.1)
- bpy.ops.wm.save_as_mainfile(filepath=filesavepath)
- for i in bpy.data.actions:
- i.use_fake_user = True
- def link(a):
- blendfile = materials
- section = "\\Material\\"
- object = a
- filepath = blendfile + section + object
- directory = blendfile + section
- filename = object
- bpy.ops.wm.link(
- filepath=filepath,
- filename=filename,
- directory=directory)
- def name(a):
- return a.lower()
- global rl
- rl = [] #removelist
- mesh = []
- mats = {}
- skip = []
- def add(a, b):
- if not a in b:
- b.append(a)
- lookfor = ""
- for i in [*bpy.data.collections['brushes'].objects, *bpy.data.collections['overlays'].objects]:
- for m in i.material_slots:
- if m.material.name.startswith('materials/'):
- if bpy.data.materials.get(m.material.name.replace('materials/', '')) != None:
- m.material = bpy.data.materials[m.material.name.replace('materials/', '')]
- if i.type != "MESH":
- continue
- for m in i.material_slots:
- if m.material == None:
- continue
- if m.material.library != None:
- continue
- m.material.name = m.material.name.upper()
- if m.material.name not in mats:
- mats[m.material.name] = f'{name(m.material.name)}'
- if mats[m.material.name] in skip:
- continue
- try:
- bpy.data.materials[mats[m.material.name]]
- m.material = bpy.data.materials[mats[m.material.name]]
- continue
- except:
- link(mats[m.material.name])
- try:
- bpy.data.materials[mats[m.material.name]]
- print(f"successfully linked {mats[m.material.name]}")
- add(m.material.name, rl)
- m.material = bpy.data.materials[mats[m.material.name]]
- except:
- #raise
- print(f'Material {mats[m.material.name]} not found!')
- skip.append(mats[m.material.name])
- m.material.name = m.material.name.lower()
- continue
- print(len(rl))
- for i in rl:
- bpy.data.materials.remove(bpy.data.materials[i])
- bpy.ops.outliner.orphans_purge(do_recursive=True)
- import math
- import mathutils
- def link(a):
- blendfile = props
- section = "\\Mesh\\"
- object = a
- filepath = blendfile + section + object
- directory = blendfile + section
- filename = object
- bpy.ops.wm.link(
- filepath=filepath,
- filename=filename,
- directory=directory)
- def name(a):
- return a.lower()
- PATH = mappath
- breaking = 0
- VMF = open(PATH, 'r')
- FOUND = False
- mesh = []
- msh = {}
- skip = []
- def add(a, b):
- if not a in b:
- b.append(a)
- lookfor = ""
- for obj in bpy.data.collections['props'].objects:
- if obj.type != 'EMPTY':
- continue
- NAME = obj.name.split('_')[-1]
- bak = obj.name
- obj.name = 'EMPTY'
- VMF = open(PATH, "r")
- FOUND = False
- for i in VMF:
- if f'"id" "{NAME}"' in i:
- FOUND = True
- continue
- if FOUND and "}" in i:
- #VMF.close()
- break
- if FOUND and '"model"' in i:
- #print(i)
- LINE = i.replace('\t', '').replace('\n', '')
- MODEL = LINE.replace('"', '').split(' ')[1]
- print
- MODEL = MODEL.replace("models/", '').replace('.mdl', '')
- if bpy.data.meshes.get(MODEL) == None:
- link(MODEL)
- if bpy.data.meshes.get(MODEL) == None:
- print(f'nothing found for {bak}, {MODEL}')
- VMF.close()
- obj.name = bak
- break
- NEW = bpy.data.objects.new(bak, bpy.data.meshes[MODEL])
- NEW.location = obj.location
- NEW.rotation_euler = obj.rotation_euler
- NEW.scale = obj.scale
- bpy.data.collections['props'].objects.link(NEW)
- bpy.data.objects.remove(obj)
- #VMF.close()
- continue
- for i in bpy.data.collections["props"].objects:
- #print(mesh)
- if i.type != 'MESH':
- continue
- if i.data.library != None:
- continue
- if i.data.name.endswith('_ref'):
- i.data.name = i.data.name[:i.data.name.rfind('/')]
- i.data.name = i.data.name.upper()
- if not i.data.name in msh:
- msh[i.data.name] = f"{name(i.data.name)}"
- if msh[i.data.name] in skip:
- continue
- try:
- bpy.data.meshes[msh[i.data.name]]
- except:
- link(msh[i.data.name])
- try:
- bpy.data.meshes[msh[i.data.name]]
- print(f"Mesh {msh[i.data.name]} found in file!\n---------")
- i.data = bpy.data.meshes[msh[i.data.name]]
- print(f"{i.name}'s mesh is now {i.data.name}\n---------")
- i.scale[0] = i.scale[0]*10
- i.scale[1] = i.scale[1]*10
- i.scale[2] = i.scale[2]*10
- obj = i
- if obj.data.get('skin_groups') == None:
- continue
- for mod in [mod for mod in obj.modifiers if mod.type == 'NODES']:
- if mod.node_group.name == 'SETSKIN':
- obj.modifiers.remove(mod)
- FOUND = False
- NAME = obj.name.split('_')[-1]
- VMF = open(PATH, 'r')
- for i in VMF:
- if f'"id" "{NAME}"' in i:
- FOUND = True
- if FOUND == True and "}" in i:
- print(f'Nothing found for {obj.name}!')
- break
- if "skin" in i and FOUND == True:
- LINE = i.replace('\t', '').replace('\n', '')
- SKIN = int(LINE.replace('"', '').split(' ')[1])
- if SKIN == 0:
- continue
- GROUPS = obj.data.get('skin_groups')
- obj.select_set(True)
- #print(obj.data.get('skin_groups')[str(SKIN)])
- for mod in obj.modifiers:
- if 'REPLACEMAT' in mod.name:
- obj.modifiers.remove(mod)
- print(obj.name)
- try:
- for MAT in GROUPS[str(SKIN)]:
- if bpy.data.materials.get(MAT) == None:
- print(f'No matching skin found for {obj.name}!')
- VMF.close()
- breaking = 1
- break
- except:
- break
- if breaking == 1:
- breaking = 0
- break
- for num in range(len(GROUPS['0'])):
- MOD = obj.modifiers.new('REPLACEMAT', 'NODES')
- MOD.node_group = bpy.data.node_groups['REPLACEMAT']
- MOD["Input_2"] = bpy.data.materials[GROUPS['0'][num]]
- MOD["Input_3"] = bpy.data.materials[GROUPS[str(SKIN)][num]]
- if GROUPS[str(SKIN)][num] not in obj.material_slots:
- print(f'{GROUPS[str(SKIN)][num]} not in {obj.name}!')
- VMF.close()
- break
- except:
- print(f"Mesh {msh[i.data.name]} not found in file!\nObject {i.name}'s mesh is still {i.data.name}")
- skip.append(msh[i.data.name])
- i.data.name = i.data.name.lower()
- continue
- bpy.ops.outliner.orphans_purge(do_recursive=True)
- for obj in bpy.data.collections['Collection'].objects:
- bpy.data.objects.remove(obj)
- from pathlib import Path
- import shutil
- WITH_ALPHA = True
- def save():
- bpy.ops.wm.save_mainfile(compress=True)
- def pack():
- try:
- bpy.ops.file.pack_all()
- except:
- pass
- # Disable
- unpk = Path(bpy.path.abspath('//unpack//'))
- if not os.path.exists(unpk):
- os.mkdir(unpk)
- oldtext = Path(bpy.path.abspath('//textures//'))
- counter = 0
- #blockPrint()
- for mat in bpy.data.materials:
- if mat.library != None:
- continue
- if mat.use_nodes == False:
- continue
- for NODE in mat.node_tree.nodes:
- if NODE.type != 'TEX_IMAGE':
- continue
- if NODE.image.get('optimized') == True:
- continue
- try:
- png = NODE.image
- oldname = NODE.image.name
- newname = png.name.replace('/', '--')
- png.name = newname
- savepath = os.path.join(unpk, (png.name + '.png'))
- png.file_format = 'PNG'
- png.filepath_raw = savepath
- png.save(filepath=savepath)
- try:
- png.unpack()
- try:
- shutil.rmtree(oldtext)
- except:
- pass
- png.filepath_raw = savepath
- png.reload()
- png.name = oldname
- counter +=1
- except:
- continue
- except:
- print(mat.name)
- print(NODE.name)
- print('fart')
- continue
- print(f'OPTIMIZED {counter} IMAGES')
- if counter != 0:
- print('PACKING')
- pack()
- print('SAVING')
- save()
- print('REMOVING UNPACKS')
- try:
- shutil.rmtree(unpk)
- except:
- pass
- print('REMOVING ORIGINALS')
- try:
- shutil.rmtree(oldtext)
- except:
- pass
- #logfile.writelines(f'{bpy.path.basename(bpy.data.filepath)}: {oldsize}MB to {newsize}MB\n\n')
- #logfile.close()
- os.remove(bpy.data.filepath + '1')
- else:
- print('NOTHING TO DO!')
- VMF = open(PATH, 'r')
- LINES = VMF.readlines()
- START = LINES.index("}\n")
- VMFlines = LINES[START:]
- FOUND = False
- VMF.close()
- for x, i in enumerate(bpy.data.collections["brushes"].objects):
- #print(x, i)
- ID = i.name.split("_")
- if len(ID) != 3:
- continue
- ID = ID[-1]
- FOUND = False
- PAST = True
- BAD = True
- for LINE in VMFlines:
- LINE = LINE.strip()
- if f'"id" "{ID}"' in LINE:
- FOUND = True
- continue
- if "}" in LINE and FOUND:
- Bad = True
- break
- if '"rendermode" "10"' in LINE and FOUND:
- print(i.name, 'deleted')
- bpy.data.objects.remove(i)
- Bad = False
- break
- else:
- print(i.name, ' None')
- if Bad == False:
- pass
- else:
- print(i.name, ' None')
- suns = list(filter(lambda a: a.data.type == 'SUN', filter(lambda a: a.type == 'LIGHT', bpy.data.objects)))
- for sun in suns:
- sun.data.shadow_cascade_max_distance = 1000
- sunID = suns[0].name.split('_')[2]
- map_file = open(mappath, 'r')
- found = False
- for line in map_file.readlines():
- if f'"id" "{sunID}"' in line:
- found = True
- continue
- if '}' in line and found == True:
- break
- #bpy.ops.wm.quit_blender()
- if '"_ambient"' in line and not "_ambientHDR" in line:
- data = line.strip()
- line = data.split('" "')
- line = line[1].replace('"', '')
- line = line.split(' ')
- color = list(map(lambda a: float(a)/255, line))[:-1] + [1]
- #print(list(line))
- break
- #print(color)
- worldmat = bpy.context.scene.world
- AMBY = worldmat.node_tree.nodes.new('ShaderNodeGroup')
- AMBY.node_tree = bpy.data.node_groups['TF2 Ambient']
- OUTPUT = worldmat.node_tree.nodes['World Output'].inputs[0]
- BG = OUTPUT.links[0].from_socket
- worldmat.node_tree.links.new(BG, AMBY.inputs[0])
- worldmat.node_tree.links.new(AMBY.outputs[0], OUTPUT)
- AMBY.inputs[1].default_value = color
- bpy.context.scene.eevee.use_gtao = True
- bpy.context.scene.eevee.gtao_distance = 10
- ENV = worldmat.node_tree.nodes["Environment Texture"]
- ENV.image.unpack()
- fp = ENV.image.filepath_raw
- tpath = os.path.join(Path(bpy.path.abspath(fp)).parents[0], 'skybox.exr')
- #os.remove(bpy.path.abspath(fp))
- bak = [bpy.context.scene.render.image_settings.file_format, bpy.context.scene.render.image_settings.color_mode, bpy.context.scene.render.image_settings.exr_codec]
- bpy.context.scene.render.image_settings.file_format = 'OPEN_EXR'
- bpy.context.scene.render.image_settings.color_mode = 'RGB'
- bpy.context.scene.render.image_settings.exr_codec = 'DWAA'
- ENV.image.save_render(filepath=tpath, scene=bpy.context.scene)
- ENV.image.filepath = tpath
- ENV.image.filepath_raw = tpath
- ENV.image.reload()
- ENV.image.pack()
- os.remove(bpy.path.abspath(fp))
- bpy.context.scene.render.image_settings.file_format = bak[0]
- bpy.context.scene.render.image_settings.color_mode = bak[1]
- bpy.context.scene.render.image_settings.exr_codec = bak[2]
- del bak
- '''
- imgname = os.path.basename(ENV.image.name).replace('.exr', '.png')
- print('---file---')
- print(imgname)
- newfilepath = os.path.join(skyboxes, imgname)
- print(newfilepath)
- if os.path.exists(newfilepath):
- print('------')
- ENV.image.unpack()
- filepath = ENV.image.filepath
- os.remove(bpy.path.abspath(filepath))
- ENV.image.filepath = newfilepath
- ENV.image.pack()
- else:
- ENV.image.save_render(newfilepath)
- ENV.image.unpack()
- filepath = ENV.image.filepath
- os.remove(bpy.path.abspath(filepath))
- ENV.image.filepath = newfilepath
- ENV.image.pack()'''
- try:
- for i in bpy.data.objects:
- if i.type != 'MESH':
- continue
- if i.data.library != None:
- continue
- for m in i.material_slots:
- if m.material == None: continue
- if m.material.name.startswith(''):
- #print(m.material.name)
- NAME = m.material.name.replace('materials/', '')
- NAME = NAME[:None if "." not in NAME else NAME.find(".")]
- #print(NAME)
- if bpy.data.materials.get(NAME) != None:
- print(NAME)
- print(i.name)
- m.material = bpy.data.materials.get(NAME)
- except:
- pass
- save()
- try:
- os.remove(bpy.data.filepath + '1')
- except:
- pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement