def optimize_bam(path): path = core.Filename.from_os_specific(path) loader = core.Loader.get_global_ptr() node = loader.load_sync(path) model = core.NodePath(node) print("Before:") analyze_node(node) any_changed = False for child in model.find_all_matches('**/+GeomNode'): gnode = child.node() for i in range(gnode.get_num_geoms()): if optimize_geom(gnode, i): any_changed = True for tex in model.find_all_textures(): if tex.name and not tex.filename: rel_path = 'layers/' + tex.name + '.png' dir = core.Filename(path.get_dirname()) fn = core.Filename(dir, rel_path) if tex.write(fn): print(f"{tex.name}: wrote to {fn}") tex.filename = 'assets/' + dir.get_basename() + '/' + rel_path tex.fullpath = fn any_changed = True if any_changed: model.write_bam_file(path) print("After:") analyze_node(node) else: print("File is already optimized, no changes needed.")
def __init__(self, filename, parent = None): self.filename = filename self.absFilename = core.Filename(self.filename) self.absFilename.makeAbsolute() self.parent = parent self.assetFiles = [] self.children = [] self.item = None if parent: self.parentRelativeFilename = core.Filename(self.absFilename) self.parentRelativeFilename.makeRelativeTo(parent.absFilename) else: self.parentRelativeFilename = None
def init(_base): assetdir_rel = p3d.Filename('assets') config = None if not pman.is_frozen(): config = pman.get_config() if config['run']['auto_build']: pman.build(config) assetdir_rel = p3d.Filename.from_os_specific( config['build']['export_dir']) # Add assets directory to model path assetdir = p3d.Filename(p3d.Filename.expand_from('$MAIN_DIR'), assetdir_rel) p3d.get_model_path().prepend_directory(assetdir)
def __resolve_vfs_relative_path(self, file_path, okMissing=False, file_type=''): """ Resolves a file path to a VFS relative Filename object for use in resource loading """ if not isinstance(file_path, core.Filename): file_name = core.Filename(file_path) else: file_name = file_path vfs = core.VirtualFileSystem.get_global_ptr() search_path = core.get_model_path().get_value() # Verify the file exists found = vfs.resolve_filename(file_name, search_path) if not found: # Notify the user message = 'Failed to load %s file: %s' % (file_type, file_name.c_str()) sprite_notify.warning('Search Path: %s' % str(search_path.get_directories())) if not okMissing: sprite_notify.error(message) else: sprite_notify.warning(message) return None return file_name
def create_runtime(appname, mainscript, use_console): freezer = FreezeTool.Freezer(platform=platform, path=path) freezer.addModule('__main__', filename=mainscript) for incmod in self.include_modules.get(appname, []) + self.include_modules.get('*', []): freezer.addModule(incmod) for exmod in self.exclude_modules.get(appname, []) + self.exclude_modules.get('*', []): freezer.excludeModule(exmod) freezer.done(addStartupModules=True) stub_name = 'deploy-stub' if platform.startswith('win'): if not use_console: stub_name = 'deploy-stubw' stub_name += '.exe' if use_wheels: stub_file = p3dwhl.open('panda3d_tools/{0}'.format(stub_name)) else: dtool_path = p3d.Filename(p3d.ExecutionEnvironment.get_dtool_name()).to_os_specific() stub_path = os.path.join(os.path.dirname(dtool_path), '..', 'bin', stub_name) stub_file = open(stub_path, 'rb') freezer.generateRuntimeFromStub(os.path.join(builddir, appname), stub_file) stub_file.close() freezer_extras.update(freezer.extras) freezer_modules.update(freezer.getAllModuleNames())
def _get_save_path(self): if not __file__.endswith('.py'): save_file = core.Filename(core.Filename.get_user_appdata_directory(), 'hexima/save.json') save_file.make_dir() return save_file.to_os_specific() else: return os.path.join(self.mainDir, 'save.json')
def new_load_model(self, model_path, **kwargs): fname = p3d.Filename(model_path) if fname.get_extension() in 'gltf, glb': return load_model(self, model_path, gltf_settings=gltf_settings, **kwargs) else: return _load_model(model_path, **kwargs)
def __init__(self, filename, parent=None): self.filename = filename self.absFilename = core.Filename(self.filename) self.absFilename.makeAbsolute() self.parent = parent self.assetFiles = [] self.children = [] self.item = None # Custom name for the folder. Used for the top-level folder of a tree, # like $DMODELS. self.alias = None if parent: self.parentRelativeFilename = core.Filename(self.absFilename) self.parentRelativeFilename.makeRelativeTo(parent.absFilename) else: self.parentRelativeFilename = None
def export(self, scene_root, filepath): '''Export the given scene root to the given filepath''' filepath = p3d.Filename().from_os_specific(filepath) ext = filepath.get_extension() if ext == 'bam': scene_root.write_bam_file(filepath) else: raise Exception(f'Unsupported export format: {ext}')
def import_file(self, filepath): '''Import the given filepath as a library''' filepath = p3d.Filename().from_os_specific(filepath) lib = self._loader.load_sync(filepath, self._loader_opts) if not lib: raise Exception(f'Failed to load {filepath}') self.libraries.append(lib)
def init_music(self, entity): music = entity[Music] music._songs = {} music._prev_songs = set() for song in music.songs: music._songs[song] = loader.load_music( core.Filename('music', song + '.ogg')) music._songs[song].set_loop(True) music._songs[song].set_volume(0)
def parse_path(path): path = str(path) path_parts = path.split('/') path_parts = [ _PATH_VARS.get(i, i) for i in path_parts ] return p3d.Filename('/'.join(path_parts))
def get_bounds(need_reload, key, np): h = sha384(f'{key}-road-{np.name}'.encode()).hexdigest() fname = core.Filename(base.main_dir, f'assets/cache/{h}') if need_reload: bounds = pp.get_model_bounds(np) with open(fname.to_os_specific(), 'wb') as f: pickle.dump(bounds, f) else: with open(fname.to_os_specific(), 'rb') as f: bounds = pickle.load(f) return bounds
def chk_timestamp(key, base_type): h = sha384(f'{key}-{base_type}'.encode()).hexdigest() lvl_fname = core.Filename(base.main_dir, f'assets/cache/{h}') bam_fname = core.Filename(base.main_dir, f'assets/models/{key}.bam') timestamp = 0 need_reload = True if lvl_fname.exists(): with open(lvl_fname.to_os_specific(), 'r') as f: try: timestamp = int(f.read()) except ValueError: pass else: lvl_fname.make_dir() need_reload = True bts = bam_fname.get_timestamp() if bts == timestamp: need_reload = False with open(lvl_fname.to_os_specific(), 'w') as f: f.write(str(bts)) return need_reload, lvl_fname
def new_load_model(self, model_path, **kwargs): if not isinstance(model_path, (tuple, list, set)): model_path = [model_path] for model in model_path: fname = p3d.Filename(model) if fname.get_extension() in ('gltf', 'glb'): return load_model(self, model, gltf_settings=gltf_settings, **kwargs) else: return _load_model(model_path, **kwargs)
def createNextAsset(self): if self.isPaused: return if len(self.files) > 0: filename = core.Filename(self.files.pop(0)) self.createAssetItem(filename) else: if not self.dlg.PreloadItems: self.addQueuedItems() self.done = True if self.callback: self.callback() self.cleanup()
def init_sfx(self, entity): player = entity[SfxPlayer] player._sfx = {} if TerrainObject in entity: root = entity[TerrainObject]._root else: root = None for sound in player.sounds: path = core.Filename('sfx', sound + '.ogg') sfx = self.audio3d.audio_manager.get_sound( path, positional=(root is not None)) if player.loop: sfx.set_loop(True) player._sfx[sound] = sfx player._root = root
def setup(self, showbase): self.viewport_widgets.reparent_to(showbase.render) self.scene_root.reparent_to(showbase.render) # Add a better starting camera position self.camera = showbase.cam self.camera.set_pos(10, -10, 10) self.camera.look_at(0, 0, 0) # Try to load a model modelpath = None if len(sys.argv) > 1: modelpath = sys.argv[1] self.assetlib.import_file(modelpath) model_root = self.assetlib.libraries[0] self.scene_root.attach_new_node(model_root) if modelpath is not None: exportpath = p3d.Filename().from_os_specific(modelpath) exportpath = exportpath.get_fullpath_wo_extension() + '.bam' self.accept('x', self.save_scene_to_bam, [exportpath])
def createAssets(self): # First, create all of the items up front with temporary icons. # This is so all of the assets are available for selecting even before # we create the thumbnails. if self.dlg.PreloadItems: text = self.dlg.ui.leFileFilter.text().lower() tempThumb = QtGui.QIcon(getNotFoundImage()) for filename in self.files: fn = core.Filename(filename) itemText = fn.getBasename() item = QtWidgets.QListWidgetItem(tempThumb, itemText) item.setSizeHint(QtCore.QSize(128, 128)) item.setToolTip(itemText) item.filename = fn self.listView.addItem(item) if self.canFilter and len(text) > 0 and text not in item.text().lower(): self.listView.setRowHidden(self.listView.row(item), True) self.items[fn] = item # Now load actual thumbnails self.createNextAsset()
def __init__(self): main_dir = core.ExecutionEnvironment.get_environment_variable( "MAIN_DIR") main_dir = core.Filename.from_os_specific(main_dir) core.load_prc_file(core.Filename(main_dir, "settings.prc")) ShowBase.__init__(self) self.disable_mouse() # Workaround for failure to load simplepbr shaders on macOS if getattr(sys, 'frozen', False) and sys.platform == 'darwin': simplepbr.__file__ = self.main_dir + '/' self.assume_gamepad = False DGG.setDefaultRolloverSound(loader.load_sfx('sfx/ui-a.ogg')) DGG.setDefaultClickSound(loader.load_sfx('sfx/ui-b.ogg')) base.setBackgroundColor((0, 0, 0, 1)) self.quality_menu = Menu('quality.', [ ('high.', self.setup_high), ('medium.', self.setup_medium), ('low.', self.setup_low), ('none.', self.setup_potato), ]) self.quality_menu.show() self.gamepads = set() for dev in self.devices.get_devices( core.InputDevice.DeviceClass.gamepad): self._device_connected(dev) self.assume_gamepad = False self.accept('connect-device', self._device_connected) self.accept('disconnect-device', self._device_disconnected)
def setup_terrain(self): self.heightfield = self.noise.terrain() f = sdf.circle((30, 30), 15) avg = np.max(self.heightfield[713:743, 713:743]) self.heightfield[713:743, 713:743][f] = avg # self.heightfield[self.__bounds] -= 0.1 # self.heightfield = np.clip(self.heightfield, 0, 1) hf = (self.heightfield * 255).astype(np.uint8) f = core.TemporaryFile(core.Filename('assets', 'terrain.png')) im = Image.fromarray(hf) im.save(f.get_filename().get_fullpath()) self.terrain = core.GeoMipTerrain('terrain') self.terrain.set_heightfield(f.get_filename()) self.terrain.set_block_size(32) self.terrain.set_near(2) self.terrain.set_far(100) self.terrain.set_focal_point(self.camera) self.terrain_root = self.terrain.get_root() self.terrain_root.reparent_to(self.render) self.terrain_root.set_scale(common.T_XY_SCALE, common.T_XY_SCALE, common.T_Z_SCALE) offset = common.T_XY * common.T_XY_SCALE / 2 self.terrain_offset = core.Vec3(-offset, -offset, 0) self.terrain_root.set_pos(self.terrain_offset) tex = self.loader.load_texture('grass.jpg') tex.set_minfilter(core.SamplerState.FT_linear_mipmap_linear) tex.set_anisotropic_degree(2) self.terrain_root.set_texture(tex, 1) self.terrain_root.set_tex_scale(core.TextureStage.get_default(), 50) self.terrain.generate() # Stones where the tower is... rot = self.render.attach_new_node('rot') d = rot.attach_new_node('d') for i in range(40): d.set_y(random.uniform(common.T_ST_Y_MIN, common.T_ST_Y_MAX)) rot.set_h(360 / 40 * (i + random.random() - 0.5)) node_path = modelgen.stone( core.Vec2( random.uniform(common.T_ST_MIN_SIZE, common.T_ST_MAX_SIZE), random.uniform(common.T_ST_MIN_SIZE, common.T_ST_MAX_SIZE))) node_path.reparent_to(self.render) node_path.set_pos(d.get_pos(self.render)) node_path.set_hpr(random.uniform(0, 360), random.uniform(0, 360), random.uniform(0, 360)) node_path.set_z( self.sample_terrain_z(*tuple(node_path.get_pos().xy)) - 1) # Obelisks mat = core.Material('mat') mat.set_emission(core.Vec4(0.2, 0.4, 0.1, 1)) for i, (x, y) in enumerate(self.ob_coords): stone_circle = modelgen.stone_circle(20, 30) node_path = modelgen.obelisk() node_path.reparent_to(stone_circle) stone_circle.reparent_to(self.render) node_path.set_material(mat) hs = common.T_XY * common.T_XY_SCALE / 2 wx = x * common.T_XY_SCALE - hs stone_circle.set_x(wx) wy = y * common.T_XY_SCALE - hs stone_circle.set_y(wy) stone_circle.set_z(self.sample_terrain_z(wx, wy)) self.collision.add( collision.CollisionCircle( core.Vec2(wx, wy), 2, )) self.collision.add( collision.CollisionCircle(core.Vec2(wx, wy), 30, (self.__obelisk_found_event, (i, )), ghost=True)) self.collision.add( collision.CollisionCircle(core.Vec2(wx, wy), 12, (self.__toggle_nonogram, (i, )), ghost=True)) self.task_mgr.add(self.__update_terrain, 'update_task')
def open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True): if sys.version_info >= (3, 0): # Python 3 is much stricter than Python 2, which lets # unknown flags fall through. for ch in mode: if ch not in 'rwxabt+U': raise ValueError("invalid mode: '%s'" % (mode)) creating = 'x' in mode writing = 'w' in mode appending = 'a' in mode updating = '+' in mode binary = 'b' in mode universal = 'U' in mode reading = universal or 'r' in mode if binary and 't' in mode: raise ValueError("can't have text and binary mode at once") if creating + reading + writing + appending > 1: raise ValueError("must have exactly one of create/read/write/append mode") if binary: if encoding: raise ValueError("binary mode doesn't take an encoding argument") if errors: raise ValueError("binary mode doesn't take an errors argument") if newline: raise ValueError("binary mode doesn't take a newline argument") if isinstance(file, core.Istream) or isinstance(file, core.Ostream): # If we were given a stream instead of a filename, assign # it directly. raw = StreamIOWrapper(file) raw.mode = mode else: vfile = None if isinstance(file, core.VirtualFile): # We can also "open" a VirtualFile object for reading. vfile = file filename = vfile.getFilename() elif isinstance(file, unicodeType): # If a raw string is given, assume it's an os-specific # filename. filename = core.Filename.fromOsSpecificW(file) elif isinstance(file, strType): filename = core.Filename.fromOsSpecific(file) else: # It's either a Filename object or an os.PathLike. # If a Filename is given, make a writable copy anyway. filename = core.Filename(file) if binary or sys.version_info >= (3, 0): filename.setBinary() else: filename.setText() if not vfile: vfile = _vfs.getFile(filename) if not vfile: if reading: raise FileNotFoundError("No such file or directory: '%s'" % (filename)) vfile = _vfs.createFile(filename) if not vfile: raise IOError("Failed to create file: '%s'" % (filename)) elif creating: # In 'creating' mode, we have to raise FileExistsError # if the file already exists. Otherwise, it's the same # as 'writing' mode. raise FileExistsError("File exists: '%s'" % (filename)) elif vfile.isDirectory(): raise IsADirectoryError("Is a directory: '%s'" % (filename)) # Actually open the streams. if reading: if updating: stream = vfile.openReadWriteFile(False) else: stream = vfile.openReadFile(False) if not stream: raise IOError("Could not open %s for reading" % (filename)) elif writing or creating: if updating: stream = vfile.openReadWriteFile(True) else: stream = vfile.openWriteFile(False, True) if not stream: raise IOError("Could not open %s for writing" % (filename)) elif appending: if updating: stream = vfile.openReadAppendFile() else: stream = vfile.openAppendFile() if not stream: raise IOError("Could not open %s for appending" % (filename)) else: raise ValueError("Must have exactly one of create/read/write/append mode and at most one plus") raw = StreamIOWrapper(stream, needsVfsClose=True) raw.mode = mode raw.name = vfile.getFilename().toOsSpecific() # If a binary stream was requested, return the stream we've created. if binary: return raw # If we're in Python 2, we don't decode unicode strings by default. if not encoding and sys.version_info < (3, 0): return raw line_buffering = False if buffering == 1: line_buffering = True elif buffering == 0: raise ValueError("can't have unbuffered text I/O") # Otherwise, create a TextIOWrapper object to wrap it. wrapper = io.TextIOWrapper(raw, encoding, errors, newline, line_buffering) wrapper.mode = mode return wrapper
def load_file(self, filepath): filepath = p3d.Filename(filepath) filepath.make_absolute() filepath = filepath.to_os_specific() url = f'file://{filepath}' self.load_url(url)
def generateAssetTree(self): self.rootFilename = core.Filename("resources") self.rootFilenameAbs = core.Filename(self.rootFilename) self.rootFilenameAbs.makeAbsolute() self.rootFolder = self.r_generateAssets(self.rootFilename, None)[0]
def create_nsis(command, basename, build_dir): platform = command.get_current_platform() if not platform.startswith('win'): command.announce( '\tNSIS installer not supported for platform: {}'.format(platform), distutils.log.ERROR) return try: subprocess.call(['makensis', '--version']) except OSError: command.announce( '\tCould not find makensis tool that is required to build NSIS installers', distutils.log.ERROR) return is_64bit = platform == 'win_amd64' # Get a list of build applications build_cmd = command.get_finalized_command('build_apps') apps = build_cmd.gui_apps.copy() apps.update(build_cmd.console_apps) apps = ['{}.exe'.format(i) for i in apps] shortname = command.distribution.get_name() # Create the .nsi installer script nsifile = p3d.Filename(build_cmd.build_base, shortname + ".nsi") nsifile.unlink() nsi = open(nsifile.to_os_specific(), "w") # Some global info nsi.write('Name "%s"\n' % shortname) nsi.write('OutFile "%s"\n' % os.path.join(command.dist_dir, basename + '.exe')) if is_64bit: nsi.write('InstallDir "$PROGRAMFILES64\\%s"\n' % shortname) else: nsi.write('InstallDir "$PROGRAMFILES\\%s"\n' % shortname) nsi.write('SetCompress auto\n') nsi.write('SetCompressor lzma\n') nsi.write('ShowInstDetails nevershow\n') nsi.write('ShowUninstDetails nevershow\n') nsi.write('InstType "Typical"\n') # Tell Vista that we require admin rights nsi.write('RequestExecutionLevel admin\n') nsi.write('\n') # TODO offer run and desktop shortcut after we figure out how to deal # with multiple apps nsi.write('!include "MUI2.nsh"\n') nsi.write('!define MUI_ABORTWARNING\n') nsi.write('\n') nsi.write('Var StartMenuFolder\n') nsi.write('!insertmacro MUI_PAGE_WELCOME\n') # TODO license file nsi.write('!insertmacro MUI_PAGE_DIRECTORY\n') nsi.write('!insertmacro MUI_PAGE_STARTMENU Application $StartMenuFolder\n') nsi.write('!insertmacro MUI_PAGE_INSTFILES\n') nsi.write('!insertmacro MUI_PAGE_FINISH\n') nsi.write('!insertmacro MUI_UNPAGE_WELCOME\n') nsi.write('!insertmacro MUI_UNPAGE_CONFIRM\n') nsi.write('!insertmacro MUI_UNPAGE_INSTFILES\n') nsi.write('!insertmacro MUI_UNPAGE_FINISH\n') nsi.write('!insertmacro MUI_LANGUAGE "English"\n') # This section defines the installer. nsi.write('Section "" SecCore\n') nsi.write(' SetOutPath "$INSTDIR"\n') curdir = "" nsi_dir = p3d.Filename.fromOsSpecific(build_cmd.build_base) build_root_dir = p3d.Filename.fromOsSpecific(build_dir) for root, dirs, files in os.walk(build_dir): dirs.sort() for name in files: basefile = p3d.Filename.fromOsSpecific(os.path.join(root, name)) file = p3d.Filename(basefile) file.makeAbsolute() file.makeRelativeTo(nsi_dir) outdir = p3d.Filename(basefile) outdir.makeAbsolute() outdir.makeRelativeTo(build_root_dir) outdir = outdir.getDirname().replace('/', '\\') if curdir != outdir: nsi.write(' SetOutPath "$INSTDIR\\%s"\n' % outdir) curdir = outdir nsi.write(' File "%s"\n' % (file.toOsSpecific())) nsi.write(' SetOutPath "$INSTDIR"\n') nsi.write(' WriteUninstaller "$INSTDIR\\Uninstall.exe"\n') nsi.write(' ; Start menu items\n') nsi.write(' !insertmacro MUI_STARTMENU_WRITE_BEGIN Application\n') nsi.write(' CreateDirectory "$SMPROGRAMS\\$StartMenuFolder"\n') for app in apps: nsi.write( ' CreateShortCut "$SMPROGRAMS\\$StartMenuFolder\\%s.lnk" "$INSTDIR\\%s"\n' % (shortname, app)) nsi.write( ' CreateShortCut "$SMPROGRAMS\\$StartMenuFolder\\Uninstall.lnk" "$INSTDIR\\Uninstall.exe"\n' ) nsi.write(' !insertmacro MUI_STARTMENU_WRITE_END\n') nsi.write('SectionEnd\n') # This section defines the uninstaller. nsi.write('Section Uninstall\n') nsi.write(' RMDir /r "$INSTDIR"\n') nsi.write(' ; Desktop icon\n') nsi.write(' Delete "$DESKTOP\\%s.lnk"\n' % shortname) nsi.write(' ; Start menu items\n') nsi.write( ' !insertmacro MUI_STARTMENU_GETFOLDER Application $StartMenuFolder\n' ) nsi.write(' RMDir /r "$SMPROGRAMS\\$StartMenuFolder"\n') nsi.write('SectionEnd\n') nsi.close() cmd = ['makensis'] for flag in ["V2"]: cmd.append('{}{}'.format( '/' if sys.platform.startswith('win') else '-', flag)) cmd.append(nsifile.to_os_specific()) subprocess.check_call(cmd)
def test_cg_from_file(gsg): """Test compiling Cg shaders from files""" shader_path = core.Filename(SHADERS_DIR, 'cg_simple.sha') run_cg_compile_check(gsg, shader_path)
def test_load_sdr_lut(): filepath = p3d.Filename(os.path.dirname(__file__), 'lut.png') simplepbr.load_sdr_lut(filepath)
import appdirs import panda3d.core as p3d _APPNAME = 'mercury' _APPAUTHOR = False _APPDIRS = appdirs.AppDirs(appname=_APPNAME, appauthor=_APPAUTHOR, roaming=True) APP_ROOT_DIR = p3d.Filename.expand_from('$MAIN_DIR') CONFIG_DIR = p3d.Filename(APP_ROOT_DIR, 'config') USER_CONFIG_DIR = p3d.Filename.from_os_specific(_APPDIRS.user_config_dir) _PATH_VARS = { '$USER_APPDATA': _APPDIRS.user_data_dir, '$MAIN_DIR': str(APP_ROOT_DIR), } def parse_path(path): path = str(path) path_parts = path.split('/') path_parts = [ _PATH_VARS.get(i, i) for i in path_parts ] return p3d.Filename('/'.join(path_parts))
def write(filename: str, egg_data: egg.EggData) -> None: """write egg data to a file""" egg_data.writeEgg(core.Filename(filename))
def test_cg_compile_error(gsg): """Test getting compile errors from bad Cg shaders""" shader_path = core.Filename(SHADERS_DIR, 'cg_bad.sha') run_cg_compile_check(gsg, shader_path, expect_fail=True)