def _import_compiled_module(self, fullname): """ Loads the compiled C/C++ shared object as a Python module, and returns it. """ vfile = vfs.getFile(self.filename, False) # We can only import a compiled module if it already exists on # disk. This means if it's a truly virtual file that has no # on-disk equivalent, we have to write it to a temporary file # first. if hasattr(vfile, 'getMount') and \ isinstance(vfile.getMount(), VirtualFileMountSystem): # It's a real file. filename = self.filename else: # It's a virtual file. Dump it. filename = Filename.temporary( '', self.filename.getBasenameWoExtension(), '.' + self.filename.getExtension(), type=Filename.TDso) filename.setExtension(self.filename.getExtension()) fin = open(vfile, 'rb') fout = open(filename, 'wb') data = fin.read(4096) while data: fout.write(data) data = fin.read(4096) fin.close() fout.close() module = imp.load_module(fullname, None, filename.toOsSpecific(), self.desc) module.__file__ = self.filename.cStr() return module
def SaveScene(file, quad_tree, extra_data=None): export_data = [] if extra_data: for item in extra_data: export_data.append(item) for node in quad_tree: for child in node.getChildren(): temp = {} if child.hasPythonTag("actor_files"): temp["actor"] = unicode(child.getPythonTag("actor_files")[0]) temp["actor_anims"] = child.getPythonTag("actor_files")[1] temp["actor_collision"] = child.getPythonTag("actor_files")[2] elif child.hasPythonTag("model_file"): temp["model"] = unicode(child.getPythonTag("model_file")) if child.hasPythonTag("light_color"): c = child.getPythonTag("light_color") temp["color_r"] = c[0] temp["color_g"] = c[1] temp["color_b"] = c[2] temp["rotation_h"] = child.getH(render) temp["rotation_p"] = child.getP(render) temp["rotation_r"] = child.getR(render) temp["position_x"] = child.getX(render) temp["position_y"] = child.getY(render) temp["position_z"] = child.getZ(render) temp["scale"] = child.getScale()[0] temp["parent_name"] = node.getName() temp["parent_index"] = quad_tree.index(node) temp["props"] = unicode(child.getPythonTag("props")) export_data.append(temp) with open(file, "w") as outfile: json.dump(export_data, outfile, indent=4, separators=(",", ": "), sort_keys=True)
def load_yaml_file(filename): """ This method is a wrapper arround yaml_load, and provides error checking """ import time start = time.clock() try: with open(filename, "r") as handle: parsed_yaml = yaml_load(handle, Loader=SafeLoader) except IOError as msg: RPObject.global_error("YAMLLoader", "Could not find or open file:", filename) RPObject.global_error("YAMLLoader", msg) raise Exception("Failed to load YAML file: File not found") except YAMLError as msg: RPObject.global_error("YAMLLoader", "Invalid yaml-syntax in file:", filename) RPObject.global_error("YAMLLoader", msg) raise Exception("Failed to load YAML file: Invalid syntax") duration = (time.clock() - start) * 1000.0 # Optionally print out profiling information # print("Took", round(duration, 2), "ms to load", filename) return parsed_yaml
def write_configuration(self): """ Writes the time of day configuration """ yaml = "\n\n" yaml += "# This file was autogenerated by the Time of Day Editor\n" yaml += "# Please avoid editing this file manually, instead use the\n" yaml += "# Time of Day Editor located at Toolkit/DayTimeEditor/.\n" yaml += "# Any comments and formattings in this file will be lost!\n" yaml += "\n\n" yaml += "control_points:\n" for plugin in self._interface.get_plugin_instances(): mod_str = "" for setting_id, handle in iteritems(plugin.get_config().get_daytime_settings()): if handle.was_modified(): mod_str += " " + setting_id + ": " + handle.serialize() + "\n" if mod_str: yaml += " " + plugin.get_id() + ":\n" yaml += mod_str yaml += "\n\n" cfg_file = "$$Config/daytime.yaml" try: with open(cfg_file, "w") as handle: handle.write(yaml) except IOError as msg: self.debug("Failed to write config file:", msg)
def _compile(self, filename, source): """ Compiles the Python source code to a code object and attempts to write it to an appropriate .pyc file. """ if source and source[-1] != '\n': source = source + '\n' code = __builtin__.compile(source, filename.cStr(), 'exec') # try to cache the compiled code pycFilename = Filename(filename) pycFilename.setExtension(pycExtension) try: f = open(pycFilename, 'wb') except IOError: pass else: f.write('\0\0\0\0') f.write(struct.pack('<I', self.timestamp)) f.write(marshal.dumps(code)) f.flush() f.seek(0, 0) f.write(imp.get_magic()) f.close() return code
def _compile(self, filename, source): """ Compiles the Python source code to a code object and attempts to write it to an appropriate .pyc file. May raise SyntaxError or other errors generated by the compiler. """ if source and source[-1] != '\n': source = source + '\n' code = compile(source, filename.toOsSpecific(), 'exec') # try to cache the compiled code pycFilename = Filename(filename) pycFilename.setExtension(compiledExtensions[0]) try: f = open(pycFilename.toOsSpecific(), 'wb') except IOError: pass else: f.write(imp.get_magic()) if sys.version_info >= (3, 0): f.write((self.timestamp & 0xffffffff).to_bytes(4, 'little')) f.write(b'\0\0\0\0') else: f.write( chr(self.timestamp & 0xff) + chr((self.timestamp >> 8) & 0xff) + chr((self.timestamp >> 16) & 0xff) + chr((self.timestamp >> 24) & 0xff)) f.write(marshal.dumps(code)) f.close() return code
def reload_shaders(self): """ This method augo-generates a shader which copies all textures specified as "from-tex" to the textures specified as "to-tex". """ uniforms = [] lines = [] # Collect all samplers and generate the required uniforms and copy code for i, (from_tex, to_tex) in enumerate(self._transfers): index = str(i) uniforms.append(self.get_sampler_type(from_tex) + " SrcTex" + index) uniforms.append(self.get_sampler_type(to_tex, True) + " DestTex" + index) lines.append("\n // Copying " + from_tex.get_name() + " to " + to_tex.get_name()) lines.append(self.get_sampler_lookup(from_tex, "data" + index, "SrcTex" + index, "coord_2d_int")) lines.append(self.get_store_code(to_tex, "DestTex" + index, "coord_2d_int", "data" + index)) lines.append("\n") # Actually create the shader fragment = "#version 430\n" fragment += "\n// Autogenerated, do not edit! Your changes will be lost.\n\n" for uniform in uniforms: fragment += "uniform " + uniform + ";\n" fragment += "\nvoid main() {\n" fragment += " ivec2 coord_2d_int = ivec2(gl_FragCoord.xy);\n" for line in lines: fragment += " " + line + "\n" fragment += "}\n" # Write the shader shader_dest = "/$$rptemp/$$update_previous_pipes.frag.glsl" with open(shader_dest, "w") as handle: handle.write(fragment) # Load it back again self._target.shader = self.load_shader(shader_dest)
def reload(self): if self.__always_enable: self.__button['state'] = DGG.NORMAL else: self.__button['state'] = DGG.DISABLED datafile = game_settings[ 'save_folder'] + self.__fileName + game_settings['save_type'] infofile = game_settings[ 'save_folder'] + self.__fileName + game_settings['save_infotype'] if exists(datafile) and exists(infofile): infostream = open( game_settings['save_folder'] + self.__fileName + game_settings['save_infotype'], 'rb') info = pickle.load(infostream) infostream.close() temp = info.text.splitlines() if temp: text = temp[0] else: text = '' if len(text) > 15: text = text[0:13] + '...' self.__text.setText(self.__head + '\n' + info.time.strftime('%Y-%m-%d %H:%M') + '\n' + ' ' + text) self.__button['state'] = DGG.NORMAL self.__exists = True else: self.__text.setText(self.__head + '\n NO DATA') self.__exists = False
def GenerateNavmeshCSV(map, output): #check the map size map_size = map.getReadXSize() #make it square if map.getReadYSize() != map_size: new_map = PNMImage(map_size, map_size) new_map.boxFilterFrom(0.0, map) map = new_map #generate data nods = [] for y in range(0, map_size): for x in range(0, map_size): nods += GetNeighbors((x, y), map, map_size) #write data with open(output, 'w') as output_file: #header output_file.write('Grid Size,' + str(map_size) + '\n') output_file.write( 'NULL,NodeType,GridX,GridY,Length,Width,Height,PosX,PosY,PosZ\n') #data... for nod in nods: output_file.write( '{NULL},{NodeType},{GridX},{GridY},{Length},{Width},{Height},{PosX},{PosY},{PosZ}\n' .format(**nod))
def loadMultifilePrcFiles(self, mf, root): """ Loads any prc files in the root of the indicated Multifile, which is presumed to have been mounted already under root. """ # We have to load these prc files explicitly, since the # ConfigPageManager can't directly look inside the vfs. Use # the Multifile interface to find the prc files, rather than # vfs.scanDirectory(), so we only pick up the files in this # particular multifile. cpMgr = ConfigPageManager.getGlobalPtr() for f in mf.getSubfileNames(): fn = Filename(f) if fn.getDirname() == '' and fn.getExtension() == 'prc': pathname = '%s/%s' % (root, f) alreadyLoaded = False for cpi in range(cpMgr.getNumImplicitPages()): if cpMgr.getImplicitPage(cpi).getName() == pathname: # No need to load this file twice. alreadyLoaded = True break if not alreadyLoaded: data = file.open(Filename(pathname), 'r').read() cp = loadPrcFileData(pathname, data) # Set it to sort value 20, behind the implicit pages. cp.setSort(20)
def _compile(self, filename, source): """ Compiles the Python source code to a code object and attempts to write it to an appropriate .pyc file. May raise SyntaxError or other errors generated by the compiler. """ if source and source[-1] != "\n": source = source + "\n" code = compile(source, filename.toOsSpecific(), "exec") # try to cache the compiled code pycFilename = Filename(filename) pycFilename.setExtension(compiledExtensions[0]) try: f = open(pycFilename.toOsSpecific(), "wb") except IOError: pass else: f.write(imp.get_magic()) if sys.version_info >= (3, 0): f.write((self.timestamp & 0xFFFFFFFF).to_bytes(4, "little")) f.write(b"\0\0\0\0") else: f.write( chr(self.timestamp & 0xFF) + chr((self.timestamp >> 8) & 0xFF) + chr((self.timestamp >> 16) & 0xFF) + chr((self.timestamp >> 24) & 0xFF) ) f.write(marshal.dumps(code)) f.close() return code
def write_configuration(self): """ Writes the plugin configuration """ yaml = "\n\n" yaml += "# This file was autogenerated by the Plugin Configurator\n" yaml += "# Please avoid editing this file manually, instead use \n" yaml += "# the Plugin Configurator located at Toolkit/PluginConfigurator/.\n" yaml += "# Any comments and formattings in this file will be lost!\n" yaml += "\n\n" # Write enabled plugins yaml += "enabled: \n" for plugin in self._enabled_plugins: yaml += " - " + plugin + "\n" yaml += "\n" # Write overrides yaml += "overrides: \n" for override in sorted(self._overrides): new_value = self._overrides[override] yaml += " " + override + ": " + str(new_value) + "\n" yaml += "\n" plugin_dest = "$$Config/plugins.yaml" with open(plugin_dest, "w") as handle: handle.write(yaml)
def loadDNA(self, filename): filename = '/' + filename with open(filename, 'r') as f: tree = DNAParser.parse(f) return tree
def load(self, filename): """ Loads the effect from a given filename """ self.debug("Load effect from", filename) self.defines = {} self.source = filename self.shaderParts = { "Default": {}, "Shadows": {}, "Voxelize": {}, "EarlyZ": {} } self.shaderObjs = { "Default": None, "Shadows": None, "Voxelize": None, "EarlyZ": None } self._handleProperties() self.name = filename.replace("\\", "/").split("/")[-1].split(".")[0] self._rename("Effect-" + self.name) with open(filename, "r") as handle: content = handle.readlines() self._parse(content) self._createShaderObjects()
def __init__(self): self.frameMain = DirectFrame(frameSize=(base.a2dLeft, base.a2dRight, base.a2dBottom, base.a2dTop), frameColor=(0.05, 0.05, 0.05, 1)) self.frameMain.setTransparency(1) tpBig = TextProperties() tpBig.setTextScale(1.5) tpSmall = TextProperties() tpSmall.setTextScale(0.75) tpUs = TextProperties() tpUs.setUnderscore(True) tpMgr = TextPropertiesManager.getGlobalPtr() tpMgr.setProperties("big", tpBig) tpMgr.setProperties("small", tpSmall) tpMgr.setProperties("us", tpUs) creditsText = "" with open("credits.txt") as f: creditsText = f.read() self.lblCredits = DirectLabel(text=creditsText, text_fg=(1, 1, 1, 1), text_bg=(0, 0, 0, 0), frameColor=(0, 0, 0, 0), text_align=TextNode.ACenter, scale=0.1, pos=(0, 0, base.a2dTop - 0.2)) self.lblCredits.setTransparency(1) self.lblCredits.reparentTo(self.frameMain) self.creditsScroll = LerpPosInterval(self.lblCredits, 12.0, (0, 0, base.a2dTop + 3.5), startPos=(0, 0, base.a2dBottom), name="CreditsScroll") self.btnBack = DirectButton(text="BACK", text_fg=(1, 1, 1, 1), text_align=TextNode.ALeft, scale=0.1, pad=(0.15, 0.15), pos=(base.a2dLeft + 0.08, 0, base.a2dBottom + 0.05), frameColor=( (0.2, 0.2, 0.2, 0.8), (0.4, 0.4, 0.4, 0.8), (0.4, 0.4, 0.4, 0.8), (0.1, 0.1, 0.1, 0.8), ), relief=1, command=base.messenger.send, extraArgs=["Credits-Back"], pressEffect=False, rolloverSound=None, clickSound=None) self.btnBack.setTransparency(1) self.btnBack.reparentTo(self.frameMain) self.hide()
def loadModel(self, model): self.currentScale=1.0 self.currentHPR=[0, 0, 0] self.currentZ=0.0 self.isLocked=False if self.currentObject!=None: self.currentObject.removeNode() self.currentObject=loader.loadModel(model) self.currentObject.reparentTo(render) self.currentObject.setPythonTag('props', '') self.currentObject.setHpr(self.currentHPR[0],self.currentHPR[1],self.currentHPR[2]) self.currentObject.setZ(self.currentZ) self.currentObject.setScale(self.currentScale) for geom in self.currentObject.findAllMatches('**/+GeomNode'): if geom.hasTag('light'): self.currentLight=self.lightManager.addLight(pos=self.currentObject.getPos(), color=(1.0, 1.0, 1.0), radius=10.0) self.currentObject.setPythonTag('hasLight', self.currentLight) self.currentHPR=[255.0, 255.0, 255.0] if geom.hasTag('particle'): file='particle/'+geom.getTag('particle') if exists(file): with open(file) as f: values=json.load(f) p=createEffect(values) self.currentObject.setPythonTag('particle', p) p.start(parent=self.currentObject, renderParent=render) if geom.hasTag('glsl_shader'): glsl_shader=geom.getTag('glsl_shader') self.currentObject.setShader(Shader.load(Shader.SLGLSL, "shaders/{0}_v.glsl".format(glsl_shader),"shaders/{0}_f.glsl".format(glsl_shader))) else: self.currentObject.setShader(Shader.load(Shader.SLGLSL, "shaders/default_v.glsl","shaders/default_f.glsl")) if self.currentObject.find('**/navmesh_terrain'): self.isLocked=True self.currentObject.find('**/navmesh_terrain').hide() if self.currentObject.find('**/navmesh_tile'): self.isLocked=True self.currentObject.find('**/navmesh_tile').hide() if self.currentObject.find('**/collision'): self.currentObject.find('**/collision').hide() for tex_stage in self.currentObject.findAllTextureStages(): tex=self.currentObject.findTexture(tex_stage) if tex: file_name=tex.getFilename() tex_format=tex.getFormat() #print tex_stage, file_name, tex_format newTex=loader.loadTexture(str(file_name)[:-3]+'dds') if tex_stage.getMode()==TextureStage.M_normal: tex_stage.setMode(TextureStage.M_normal_gloss) if tex_stage.getMode()!=TextureStage.M_normal_gloss: if tex_format==Texture.F_rgb: tex_format=Texture.F_srgb elif tex_format==Texture.F_rgba: tex_format=Texture.F_srgb_alpha newTex.setFormat(tex_format) self.currentObject.setTexture(tex_stage, newTex, 1)
def write_config(self): """ Generates the shader configuration for the common inputs """ content = self._input_ubo.generate_shader_code() try: # Try to write the temporary file with open("/$$rptemp/$$main_scene_data.inc.glsl", "w") as handle: handle.write(content) except IOError as msg: self.error("Failed to write common resources shader configuration!", msg)
def _loadPyc(self, vfile, timestamp): """ Reads and returns the marshal data from a .pyc file. """ code = None f = open(vfile, 'rb') if f.read(4) == imp.get_magic(): t = struct.unpack('<I', f.read(4))[0] if not timestamp or t == timestamp: code = marshal.loads(f.read()) f.close() return code
def _generate_shader_config(self): """ Generates the shader configuration """ content = self._ubo.generate_shader_code() # Try to write the temporary file try: with open("$$PipelineTemp/$$DayTimeConfig.inc.glsl", "w") as handle: handle.write(content) except IOError as msg: self.error("Failed to write daytime autoconfig!", msg)
def save_data(file_name, data, mode = 2): _savingloadinglock.acquire() try: f = open(file_name,'wb') pickle.dump(data, f, mode) f.close() except Exception as exp: raise exp finally: _savingloadinglock.release()
def _createShaderFile(self, stage, part, code): """ Writes the shader code to a temporary file and returns the path to that file """ filename = "PipelineTemp/Effect" + str(self.getEffectID()) + "_" + self.name + "_" + stage + "_" + part + "_" + self.getSerializedSettings() + ".tmp.glsl" with open(filename, "w") as handle: handle.write(code) return filename
def save_data(file_name, data, mode=2): _savingloadinglock.acquire() try: f = open(file_name, 'wb') pickle.dump(data, f, mode) f.close() except Exception as exp: raise exp finally: _savingloadinglock.release()
def write_config(self): """ Generates the shader configuration for the common inputs """ content = self._input_ubo.generate_shader_code() try: # Try to write the temporary file with open("/$$rptemp/$$main_scene_data.inc.glsl", "w") as handle: handle.write(content) except IOError as msg: self.error( "Failed to write common resources shader configuration!", msg)
def save(self, dest): """ Writes the default property file to a given location """ output = "# Autogenerated by Time of Day Manager\n" output += "# Do not edit! Your changes will be lost.\n" for propid, prop in self.properties.items(): output += propid + \ " [" + ";".join([str(i) for i in prop.values]) + "]\n" with open(dest, "w") as handle: handle.write(output)
def _read_source(self): """ Returns the Python source for this file, if it is available, or None if it is not. May raise IOError. """ if self.desc[2] == imp.PY_COMPILED or \ self.desc[2] == imp.C_EXTENSION: return None filename = Filename(self.filename) filename.setExtension('py') filename.setText() if sys.version_info >= (3, 0): # Use the tokenize module to detect the encoding. import tokenize fh = open(self.filename, 'rb') encoding, lines = tokenize.detect_encoding(fh.readline) return (b''.join(lines) + fh.read()).decode(encoding) else: return open(self.filename, self.desc[1]).read()
def _read_source(self): """ Returns the Python source for this file, if it is available, or None if it is not. May raise IOError. """ if self.desc[2] == imp.PY_COMPILED or self.desc[2] == imp.C_EXTENSION: return None filename = Filename(self.filename) filename.setExtension("py") filename.setText() return open(self.filename, self.desc[1]).read()
def _read_source(self): """ Returns the Python source for this file, if it is available, or None if it is not. May raise IOError. """ if self.desc[2] == imp.PY_COMPILED or \ self.desc[2] == imp.C_EXTENSION: return None filename = Filename(self.filename) filename.setExtension('py') filename.setText() return open(self.filename, self.desc[1]).read()
def load_data(file_name): _savingloadinglock.acquire() try: f = open(file_name,'rb') loaded = pickle.load(f) f.close() except Exception as exp: raise exp finally: _savingloadinglock.release() return loaded
def load(self, filename): """ Loads the effect from a given filename """ self.debug("Load effect from", filename) self._handleProperties() self.name = filename.replace("\\", "/").split("/")[-1].split(".")[0] with open(filename, "r") as handle: content = handle.readlines() self._parse(content) self._createShaderObjects()
def load_data(file_name): _savingloadinglock.acquire() try: f = open(file_name, 'rb') loaded = pickle.load(f) f.close() except Exception as exp: raise exp finally: _savingloadinglock.release() return loaded
def _handleIncludes(self, source): """ Internal (recursive) method to parse #include's """ with open(source, "r") as handle: content = handle.readlines() newContent = "" includeIdentifier = "#include " # Iterate through lines for line_idx, line in enumerate(content): lineStrip = line.strip() if lineStrip.startswith(includeIdentifier): includePart = lineStrip[len(includeIdentifier):].strip() # Filename is surrounded by braces # Todo: maybe also support ->'<- additionally to ->"<- if includePart.startswith('"') and includePart.endswith('"'): # Special case if includePart == '"%ShaderAutoConfig%"': properIncludePart = "PipelineTemp/ShaderAutoConfig.include" else: # Extract include part properIncludePart = Filename.fromOsSpecific(join( self._GlobalShaderPath, includePart[1:-1])).toOsGeneric() # And check if file exists if isfile(properIncludePart): # Check for recursive includes if properIncludePart in self._GlobalIncludeStack: # print "BetterShader: Ignoring recursive # include:",properIncludePart pass else: self._GlobalIncludeStack.append(properIncludePart) newContent += "\n// FILE: '" + \ str(properIncludePart) + "' \n" newContent += self._handleIncludes( properIncludePart).strip() + "\n" else: print "BetterShader: Failed to load '" + str(properIncludePart) + "'!" else: print "BetterShader: Invalid include:", includePart continue newContent += line.rstrip() + "\n" return newContent
def loadDefaultSettings(fileName='config/default.sconf'): '''Load default unserialized settings''' global game_settings try: fileHandle = open(fileName) for line in fileHandle: spaceCutter = re.compile(ur'\s+', re.UNICODE) splited = spaceCutter.split(line, 1) game_settings[splited[0]] = eval(splited[1].strip()) fileHandle.close() except: #raise LoadSettingsException('No such file: ' + fileName) pass
def loadDefaultSettings(fileName = 'config/default.sconf'): '''Load default unserialized settings''' global game_settings try: fileHandle = open(fileName) for line in fileHandle: spaceCutter = re.compile(ur'\s+',re.UNICODE) splited = spaceCutter.split(line,1) game_settings[splited[0]] = eval(splited[1].strip()) fileHandle.close() except: #raise LoadSettingsException('No such file: ' + fileName) pass
def _createShaderFile(self, stage, part, code): """ Writes the shader code to a temporary file and returns the path to that file """ filename = "PipelineTemp/$$-Effect" + str( self.getEffectID() ) + "_" + self.name + "_" + stage + "_" + part + "_" + self.getSerializedSettings( ) + ".tmp.glsl" with open(filename, "w") as handle: handle.write(code) return filename
def _parseTemplate(self, filename): """ Parses a shader template file and returns its content """ with open(filename, "r") as handle: content = handle.readlines() parsedLines = [] for line in content: line = line.rstrip() parsedLines.append(line) return parsedLines
def save_daytime_overrides(self, override_file): """ Saves all time of day overrides to the given file """ output = "\n# Render Pipeline Time Of Day Configuration\n" output += "# Instead of editing this file, prefer to use the Time Of Day Editor\n" output += "# Any formatting and comments will be lost\n\n" output += "control_points:\n" for plugin_id, settings in iteritems(self.day_settings): if settings: output += " " * 4 + plugin_id + ":\n" for setting_id, setting_handle in iteritems(settings): output += " " * 8 + setting_id + ": " output += setting_handle.serialize() + "\n" with open(override_file, "w") as handle: handle.write(output)
def runScriptFile(self,fileName): #'''note that would ignore panda virtual pathes''' pathes = runtime_data.game_settings['pscriptpathes'] types = runtime_data.game_settings['pscripttypes'] for ft in ((folder,type) for folder in pathes for type in types): if exists(ft[0] + fileName + ft[1]): handle = open(ft[0] + fileName + ft[1]) script = handle.read() handle.close() break if script: self.runScript(script) else: safeprint("file not find: "+ fileName)
def load_settings(self): """ Loads all day time settings from the plugin manager and registers them to the used input buffer """ for plugin_id, settings in iteritems(self._pipeline.plugin_mgr.day_settings): for setting, handle in iteritems(settings): setting_id = "{}.{}".format(plugin_id, setting) self._input_ubo.register_pta(setting_id, handle.glsl_type) self._setting_handles[setting_id] = handle self._pipeline.stage_mgr.input_blocks.append(self._input_ubo) # Generate UBO shader code shader_code = self._input_ubo.generate_shader_code() with open("/$$rptemp/$$daytime_config.inc.glsl", "w") as handle: handle.write(shader_code)
def _read_source(self): """ Returns the Python source for this file, if it is available, or None if it is not. """ if self.fileType == FTPythonCompiled or \ self.fileType == FTCompiledModule: return None filename = Filename(self.filename) filename.setExtension('py') try: file = open(filename, 'rU') except IOError: return None return file.read()
def load_settings(self): """ Loads all day time settings from the plugin manager and registers them to the used input buffer """ for plugin_id, settings in iteritems( self._pipeline.plugin_mgr.day_settings): for setting, handle in iteritems(settings): setting_id = "{}.{}".format(plugin_id, setting) self._input_ubo.register_pta(setting_id, handle.glsl_type) self._setting_handles[setting_id] = handle self._pipeline.stage_mgr.input_blocks.append(self._input_ubo) # Generate UBO shader code shader_code = self._input_ubo.generate_shader_code() with open("/$$rptemp/$$daytime_config.inc.glsl", "w") as handle: handle.write(shader_code)
def loadMultifilePrcFiles(self, mf, root): """ Loads any prc files in the root of the indicated Multifile, which is presumed to have been mounted already under root. """ # We have to load these prc files explicitly, since the # ConfigPageManager can't directly look inside the vfs. Use # the Multifile interface to find the prc files, rather than # vfs.scanDirectory(), so we only pick up the files in this # particular multifile. for f in mf.getSubfileNames(): fn = Filename(f) if fn.getDirname() == '' and fn.getExtension() == 'prc': pathname = '%s/%s' % (root, f) data = file.open(Filename(pathname), 'r').read() loadPrcFileData(pathname, data)
def _writeDebugShader(self, name, content): """ Internal method to dump shader for debugging """ if not self._DumpShaders: return cachePath = "PipelineTemp" if not isdir(cachePath): print "Cache path does not exist!:", cachePath print "Disabling shader dump" self._DumpShaders = False return writeName = name.strip().replace("/", "-").replace(".", "_") + ".bin" with open(join(cachePath, writeName), "w") as handle: handle.write(str(content))
def saveGlslInclude(self, dest): """ Writes the GLSL structure representation to a given location """ output = "// Autogenerated by Time of Day Manager\n" output += "// Do not edit! Your changes will be lost.\n\n\n" output += "struct TimeOfDay {\n\n" for propid, prop in self.properties.items(): name = propid.replace(".", "_") output += " // " + prop.description + "\n" output += " " + \ prop.propType.getGlslType() + " " + name + ";\n\n" output += "};\n\n\n" with open(dest, "w") as handle: handle.write(output)
def loadFromFile(self, filename): """ Attempts to load settings from a given file. When the file does not exist, nothing happens, and an error is printed """ self.debug("Loading ini-file from", filename) if not isfile(filename): self.error("File not found:", filename) return handle = open(filename, "r") content = handle.readlines() handle.close() # Set to default settings for name, setting in self.settings.iteritems(): setting.setValue(setting.default) setattr(self, name, setting.default) # Read new settings for line in content: line = line.strip() # Empty line, comment, or section if len(line) < 1 or line[0] in ["//", "#", "["]: continue # No assignment if "=" not in line: self.warn("Ignoring invalid line:", line) continue parts = line.split("=") settingName = parts[0].strip() settingValue = "" if len(parts) > 1: settingValue = parts[1].strip() if settingName not in self.settings: self.warn("Unrecognized setting:", settingName) continue self.settings[settingName].setValue(settingValue) setattr(self, settingName, self.settings[settingName].getValue())
def load(self, filename): """ Loads the effect from a given filename """ self.debug("Load effect from", filename) self.defines = {} self.source = filename self.shaderParts = {"Default": {}, "Shadows": {}, "Voxelize": {}} self.shaderObjs = {"Default": None, "Shadows": None, "Voxelize": None} self._handleProperties() self.name = filename.replace("\\", "/").split("/")[-1].split(".")[0] self._rename("Effect-" + self.name) with open(filename, "r") as handle: content = handle.readlines() self._parse(content) self._createShaderObjects()
def save_overrides(self, override_file): """ Saves all overrides to the given file """ output = "\n# Render Pipeline Plugin Configuration\n" output += "# Instead of editing this file, prefer to use the Plugin Configurator\n" output += "# Any formatting and comments will be lost\n\n" output += "enabled:\n" sort_criteria = lambda pid: ("A" if self.is_plugin_enabled(pid) else "B") + pid for plugin_id in sorted(self.settings, key=sort_criteria): output += " {}- {}\n".format( " # " if plugin_id not in self.enabled_plugins else " ", plugin_id) output += "\n\noverrides:\n" for plugin_id, pluginsettings in sorted(iteritems(self.settings)): output += " " * 4 + plugin_id + ":\n" for setting_id, setting_handle in iteritems(pluginsettings): output += " " * 8 + "{}: {}\n".format(setting_id, setting_handle.value) output += "\n" with open(override_file, "w") as handle: handle.write(output)
def YAMLEasyLoad(filename): """ This method is a wrapper arround YAMLLoad, and provides error checking """ from direct.stdpy.file import open from ...Util.DebugObject import DebugObject try: with open(filename, "r") as handle: parsed_yaml = YAMLLoad(handle, Loader=SafeLoader) except IOError as msg: DebugObject.global_error("YAMLLoader", "Could not find or open file:", filename) DebugObject.global_error("YAMLLoader", msg) raise Exception("Failed to load YAML file: File not found") except YAMLError as msg: DebugObject.global_error("YAMLLoader", "Invalid yaml-syntax in file:", filename) DebugObject.global_error("YAMLLoader", msg) raise Exception("Failed to load YAML file: Invalid syntax") return parsed_yaml
def load(self, filename): """ Loads the property values from <filename> """ self.debug("Loading from", filename) if not isfile(filename): self.error("Could not load", filename) return False with open(filename, "r") as handle: content = handle.readlines() for line in content: line = line.strip() if len(line) < 1 or line.startswith("#"): continue parts = line.split() if len(parts) != 2: self.warn("Invalid line:", line) continue propId = parts[0] propData = parts[1] if propId not in self.properties: self.warn("Invalid ID:", propId) continue prop = self.properties[propId] if not (propData.startswith("[") and propData.endswith("]")): self.warn("Invalid data:", propData) propData = propData[1:-1].split(";") propData = [prop.propType.convertString(i) for i in propData] if len(propData) != 8: self.warn("Data count does not match for", propId) continue prop.values = propData prop.recompute()
def reload_shaders(self): """ This method augo-generates a shader which copies all textures specified as "from-tex" to the textures specified as "to-tex". """ uniforms = [] lines = [] # Collect all samplers and generate the required uniforms and copy code for i, (from_tex, to_tex) in enumerate(self._transfers): index = str(i) uniforms.append( self.get_sampler_type(from_tex) + " SrcTex" + index) uniforms.append( self.get_sampler_type(to_tex, True) + " DestTex" + index) lines.append("\n // Copying " + from_tex.get_name() + " to " + to_tex.get_name()) lines.append( self.get_sampler_lookup(from_tex, "data" + index, "SrcTex" + index, "coord_2d_int")) lines.append( self.get_store_code(to_tex, "DestTex" + index, "coord_2d_int", "data" + index)) lines.append("\n") # Actually create the shader fragment = "#version 430\n" fragment += "\n// Autogenerated, do not edit! Your changes will be lost.\n\n" for uniform in uniforms: fragment += "uniform " + uniform + ";\n" fragment += "\nvoid main() {\n" fragment += " ivec2 coord_2d_int = ivec2(gl_FragCoord.xy);\n" for line in lines: fragment += " " + line + "\n" fragment += "}\n" # Write the shader shader_dest = "/$$rptemp/$$update_previous_pipes.frag.glsl" with open(shader_dest, "w") as handle: handle.write(fragment) # Load it back again self._target.shader = self.load_shader(shader_dest)