def main(args): original_pak = set() addon_info = {} # parse addon info if args.addon_list: with open(args.addon_list) as f: addon_info = json.load(f) with vpk.open(args.base_package) as pak01: original_pak = set(filter(lambda f: args.name_match in f, pak01)) if not len(original_pak): raise AssertionError("base package is empty") addons = args.PACKAGE if args.mod_directory: workshop_dir = os.path.join(args.mod_directory, 'addons') for path, name, files in os.walk(workshop_dir): for file in files: _, ext = os.path.splitext(file) if ext == '.vpk': addons.append(os.path.join(path, file)) num_skipped = 0 num_conflicting = 0 for addon in addons: workshop_id, _ = os.path.splitext(os.path.basename(addon)) addon_package = vpk.open(addon) file_desc = workshop_id if addon_info: file_info = addon_info.get('plugins').get(workshop_id) file_desc = '{id} ({name})'.format(id=workshop_id, name=file_info.get('title')) try: conflicting_items = original_pak & set(addon_package) if len(conflicting_items): safe_print('Conflicting files in', file_desc) safe_print(*('\t' + str(s) for s in conflicting_items), sep='\n') print() num_conflicting += 1 except BaseException as e: print('Skipping addon', file_desc, '({e.__class__.__name__}: {e})'.format(e=e)) print() num_skipped += 1 safe_print( len(addons), "plugin(s) checked ({} skipped, {} conflicts).".format( num_skipped, num_conflicting))
def __init__(self, vpk_file, parent): """ Args: """ self.parent = parent self.vpk_file = vpk_file self.vpk_obj = vpk.open(vpk_file)
def open_vpk(self, vpk_path): if self.vpk_loaded: # if we already have a file open, close it. self.close_vpk() self.status_bar.showMessage(MSG_OPEN_VPK) if not os.path.exists(vpk_path): print( "Attempted to open {}, which doesn't exist.".format(vpk_path)) return self.opened_file = vpk_path try: self.opened_vpk = vpk.open(vpk_path) except Exception as e: print("Ran into an error from the VPK Library.") sys.stdout.write(str(e)) self.error_box(str(e)) return self.vpk_loaded = True self.status_bar.showMessage(MSG_UNDERSTAND_VPK) # Now we attempt to understand the vpk self.internal_directory_understanding = self.understand_directories( self.opened_vpk) self.status_bar.showMessage(MSG_UPDATE_UI) self.update_interface() self.status_bar.clearMessage()
def add(self, path): if isfile(path): if not path.endswith(".vpk"): print(f"\"{path}\" is not a valid file.") exit() self.paks.append(vpk.open(path)) elif isdir(path): self.dirs.append(path) else: print(f"\"{path}\" is an invalid path.")
def __init__(self, path): self.vpk = vpklib.open(path) self.path = path self.name = os.path.splitext(path)[0].split("\\")[-1] self.selectedTypes = None self.files = None types = [] for file in self.vpk.items(): #file[0] is the name fileName, fileExtension = os.path.splitext(file[0]) if not (fileExtension in types): types.append(fileExtension) self.types = types
def workItHarderDoItBetter(path): global TaskSuccessful config["DEFAULT"]["PreviousSpawnlistDirectory"] = os.path.dirname(path) files = [ f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f)) ] files = sorted(files) lastFile = files[-1] strid = lastFile[0:3] id = int(strid) + 1 spawnlist.Spawnlist.ID = id if dialog.ok_cancel_dialog( "Select the _dir.vpk file to make a spawnlist from.", caption=CAPTION): vpkpath = dialog.open_dialog( caption=CAPTION, wildcard="Valve Pak _dir File (*_dir.vpk)|*_dir.vpk", defaultDir=config.get("DEFAULT", "PreviousVPKDirectory", fallback="")) if vpkpath: config["DEFAULT"]["PreviousVPKDirectory"] = os.path.dirname( vpkpath) name = dialog.text_entry_dialog(message="Name your spawnlist.", caption=CAPTION) if name and (not name == ""): name = name.replace("\"", "''") pak = vpk.open(vpkpath) sl = spawnlist.Spawnlist(name) structure = modelpath.ModelPath("root") for pakfile in pak: if pakfile.endswith(".mdl"): structure.addModel(pakfile) populateSpawnlist(sl, structure.getSubPath("models")) saveSpawnlist(sl, path) if TaskSuccessful: dialog.ok_dialog("Successfully saved spawnlist!", caption=CAPTION) else: dialog.ok_dialog("Could not successfully save spawnlist!", caption=CAPTION)
def LoadVPK(self, file): print('Opening {}'.format(file)) self.DirectoryModel.clear() self.ExportItems = [] self.VPK = None try: self.VPK = vpk.open(file) except FileNotFoundError as E: self.ErrorBox(str(E), 'File Doesn\'t Exist.') return except ValueError as E: self.ErrorBox(str(E)) return self.VPKDir = file self.HandleVPK(self.VPK)
def run(args): if args.create: create_vpk(args) return pak = vpk.open(args.file, path_enc=args.path_enc) path_filter = make_filter_func(args.filter, args.filter_name, args.regex, args.invert_match) if args.list or args.listall: print_file_list(pak, path_filter, args.listall) elif args.pipe_output: pipe_files(pak, path_filter) elif args.test: print_verifcation(pak) elif args.out_location: extract_files(pak, path_filter, args.out_location, args.makedir) else: print_header(pak)
def main(): parser = make_argparser() args = parser.parse_args() if not sys.argv or not args.file: parser.print_help() return if args.file == '-': print("Reading from/writing to a pipe is not supported") return try: if args.create: create_vpk(args) return pak = vpk.open(args.file, path_enc=args.path_enc) path_filter = make_filter_func(args.filter, args.filter_name, args.regex) if args.list or args.listall: print_file_list(pak, path_filter, args.listall) elif args.pipe_output: pipe_files(pak, path_filter) elif args.test: print_verifcation(pak) elif args.out_location: extract_files(pak, path_filter, args.out_location, args.makedir) else: print_header(pak) except ValueError as e: print("Error:", str(e)) except IOError as e: print("IOError:", str(e)) except KeyboardInterrupt: pass
def RebuildHammerRoot(): if not (HammerRoot() / 'garrysmod' / 'garrysmod_dir.vpk').exists(): print("missing hammer copy, copying") (HammerRoot() / 'garrysmod' / 'cfg').mkdir(parents=True, exist_ok=True) def mov(s, d): if (GetGModPath() / s).is_dir(): distutils.dir_util.copy_tree(str(GetGModPath() / s), str(HammerRoot() / d)) else: shutil.copy(str(GetGModPath() / s), str(HammerRoot() / d)) link_files("garrysmod/garrysmod_000.vpk", HammerRoot()) link_files("garrysmod/garrysmod_001.vpk", HammerRoot()) link_files("garrysmod/garrysmod_002.vpk", HammerRoot()) link_files("garrysmod/garrysmod_dir.vpk", HammerRoot()) mov("platform/platform_misc_000.vpk", 'garrysmod/') mov("platform/platform_misc_dir.vpk", 'garrysmod/') mov("garrysmod/steam.inf", 'garrysmod/') with (HammerRoot() / 'garrysmod/steam_appid.txt').open('wb') as f: f.write(b"4000\n\0") mov("bin/", 'bin/') mov("platform/", 'platform/') mov("garrysmod/resource/", 'garrysmod/resource/') # hammer needs shaders with vpk.open(str(GetGModPath() / "sourceengine/hl2_misc_dir.vpk")) as hl2misc: for fpath in hl2misc: if fpath.startswith("shaders/"): (HammerRoot() / 'garrysmod' / Path(fpath).parents[0]).mkdir(parents=True, exist_ok=True) with hl2misc.get_file(fpath) as input, ( HammerRoot() / 'garrysmod' / Path(fpath)).open('wb') as output: copyfileobj(input, output)
def main(): parser = make_argparser() args = parser.parse_args() if not sys.argv or not args.file: parser.print_help() return if args.file == '-': print("Reading from/writing to a pipe is not supported") return try: if args.create: create_vpk(args.create, args.file) return pak = vpk.open(args.file) path_filter = make_filter_func(args.filter, args.filter_name, args.regex) if args.list or args.listall: print_file_list(pak, path_filter, args.listall) elif args.pipe_output: pipe_files(pak, path_filter) elif args.test: print_verifcation(pak) elif args.out_location: extract_files(pak, path_filter, args.out_location, args.makedir) else: print_header(pak) except ValueError as e: print("Error:", str(e)) except IOError as e: print("IOError:", str(e)) except KeyboardInterrupt: pass
dirpath = os.path.join(*os.path.split(path)[:-1]) try: os.makedirs(dirpath) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(dirpath): pass return path # clear output directory if os.path.exists("./out"): shutil.rmtree("./out") LOG.info("Reading VPK from %s" % repr(vpk_path)) # load game asset index pak1 = vpk.open(vpk_path) LOG.info("Reading items.txt") # load items.txt schema and save a local copy to track in repo with pak1.get_file("scripts/npc/items.txt") as vpkfile: vpkfile.save(os.path.join(src_root, 'items.txt')) items = vdf.load(vpkfile)['DOTAAbilities'] pt_names = ['power_treads_str.png', 'power_treads_agi.png', 'power_treads_int.png'] def get_file(filename): prerendered_path = os.path.join(src_preimages_root, filename) if os.path.exists(prerendered_path): return open(prerendered_path, 'rb')
def setUp(self): self.pak = vpk.open('./tests/test_dir.vpk')
def setUp(self): self.pak = vpk.open('./tests/test_dir.vpk') self.temp_path = "./tempout"
def setUp(self): self.pak = vpk.open('./tests/test_dir.vpk', path_enc=None)
def setUp(self): self.pak = vpk.open('./tests/test_dir.vpk')
from collections import OrderedDict import vpk import vdf from PIL import Image # Path to the bin that decompiles vtex_c into png # https://github.com/SteamDatabase/ValveResourceFormat decompiler = './decompiler/Decompiler.exe' destination = './resources' temp = './temp' # Path to vpk, which contains all the emoticons # windows d:/steam/SteamApps/common/dota 2 beta/game/dota/pak01_dir.vpk # wsl /mnt/d/steam/SteamApps/common/dota 2 beta/game/dota/pak01_dir.vpk pak = vpk.open( '/mnt/d/steam/SteamApps/common/dota 2 beta/game/dota/pak01_dir.vpk') emoticons = vdf.loads(pak['scripts/emoticons.txt'].read().decode('utf-16le'), mapper=OrderedDict)['emoticons'] destination_gif = destination + '/images/emoticons' destination_json = destination + '/json' with open(destination_json + '/emoticons.json', 'w') as f: f.write(json.dumps(emoticons, indent=4)) print('> Emoticons data saved in %s' % destination_json) if not os.path.isdir(temp): os.mkdir(temp) existing = os.listdir(destination_gif)
def iter_pak(self, pak_file: str) -> Iterator[Tuple[PurePosixPath, FileInfo]]: pak = vpk.open(pak_file) for pak_path, metadata in pak.read_index_iter(): path = vmf_path(pak_path) yield (path, FileInfo(pak_path, (pak, metadata)))
import argparse parser = argparse.ArgumentParser() parser.add_argument('inputPath') parser.add_argument('outPath') parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() inputPath = args.inputPath outputPath = args.outPath try: pak1 = vpk.open(inputPath) except: print("Can't find file at path: " + inputPath) sys.exit(0) for filepath in pak1: if args.verbose: print("extracting: " + filepath) pakfile = pak1.get_file(filepath) pakfile = pak1[filepath] newFile = outputPath + filepath
def main(): def main_version(): head = 'ClientVersion=' with open(DOTA2_CLIENT + 'game/dota/steam.inf', 'r') as inf: while True: line = inf.readline().strip() if line: if line.startswith(head): with open('./version', 'w') as version: version.write(line[len(head):]) return else: raise Exception( 'Not found ClientVersion in steam.inf file.') main_version() os.makedirs('localization', exist_ok=True) with vpk.open(DOTA2_CLIENT + 'game/dota/pak01_dir.vpk') as pak01: for rule in l10ns: with pak01.get_file(rule.get_pak_path('english')) as input: data = rule.pull(vdf.loads(input.read().decode('utf-8'))) remove_special_key(data) out_name = f'main/resource/localization/{rule.name}_english.txt.json' with open(out_name, 'w', encoding='utf-8') as out: json.dump(data, out, indent=4, ensure_ascii=False) print(f'Wrote "{out_name}" done!!') with open('vo.txt', 'r') as vof: for vo in vof.readlines(): vo = vo.strip() if len(vo) == 0: continue with pak01.get_file( f'resource/subtitles/subtitles_{vo}_english.dat' ) as dat: keys = [] for fn in pak01: if not fn.startswith(f'sounds/vo/{vo}/'): continue fn = fn.removeprefix('sounds/vo/').removesuffix( '.vsnd_c').replace('/', '_') keys.append(fn) data = vccd.load(dat.read(), keys=keys).captions out_name = f'main/resource/subtitles/subtitles_{vo}_english.dat.json' with open(out_name, 'w', encoding='utf-8') as out: json.dump(data, out, indent=4, ensure_ascii=False) print(f'Wrote "{out_name}" done!!') with open('addons.txt', 'r') as addons: for addon in addons.readlines(): addon = addon.strip() if len(addon) == 0: continue with open(DOTA2_CLIENT + f'game/dota_addons/{addon}/resource/addon_english.txt', 'r', encoding='utf-8') as input: data = vdf.loads(input.read())['lang']['Tokens'] os.makedirs(f'addons/{addon}/resource', exist_ok=True) out_name = f'addons/{addon}/resource/addon_english.txt.json' with open(out_name, 'w', encoding='utf-8') as out: json.dump(data, out, indent=4, ensure_ascii=False) print(f'Wrote "{out_name}" done!!')
def set_vpk_path(path): globals["vpk"] = vpk.open(path)
required_materials = input( "Please specify the location of a file containing the list of needed material files: " ) required_materials_file = open(required_materials, "r") required_materials = required_materials_file.read().strip().split("\n") required_materials_file.close() required_models = input( "Please specify the location of a file containing the list of needed model files: " ) required_models_file = open(required_models, "r") required_models = required_models_file.read().strip().split("\n") required_models_file.close() vpk_game = vpk.open(vpk_location) vpk_hl2 = vpk.open(hl2_vpk_location) fetched_files = 0 def write_output_file(path, data): if not os.path.exists(path): try: os.makedirs(os.path.dirname(path)) except OSError as e: if e.errno != errno.EEXIST: raise output_file = open(path, "wb") output_file.write(data)
def setUp(self): self.pak = vpk.open('./tests/test_dir.vpk') self.temp_path = "./tempout"