class Starter: def __init__(self, log_prefix="coginvasion-", log_extension=".log", path="logs/"): log_suffix = time.strftime("%d-%m-%Y-%H-%M-%S") if not os.path.exists(path): os.mkdir(path) logfile = os.path.join(path, log_prefix + log_suffix + log_extension) self.logfile = logfile log = open(logfile, "a") logOut = Logger(sys.stdout, log) logErr = Logger(sys.stderr, log) sys.stdout = logOut sys.stderr = logErr def startNotifyLogging(self): self.nout = MultiplexStream() Notify.ptr().setOstreamPtr(self.nout, 0) self.nout.addFile(Filename(self.logfile)) self.nout.addStandardOutput() sys.stdout.console = True sys.stderr.console = True
from utils import Object, directions from terrain.terrain import Terrain from towers import Tower from tiles import Floor, Empty from selection import Selection import config loadPrcFileData("", "framebuffer-stencil #t") # loadPrcFileData("", "want-pstats 1") # loadPrcFileData('', 'notify-level spam\ndefault-directnotify-level info') # sys.setrecursionlimit(1000000) nout = MultiplexStream() Notify.ptr().setOstreamPtr(nout, 0) nout.addFile(Filename("out.txt")) class MyApp: """The main class.""" def __init__(self): """Start the app.""" self.base = ShowBase() self.base.disableMouse() filters = CommonFilters(self.base.win, self.base.cam) filters.setBloom(blend=(0, 0, 0, 1)) self.base.render.setShaderAuto( BitMask32.allOn() & ~BitMask32.bit(Shader.BitAutoShaderGlow)) ts = TextureStage('ts') ts.setMode(TextureStage.MGlow)
# LOGGING # # setup Logging logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s: %(message)s", filename=os.path.join(__builtin__.basedir, "game.log"), datefmt="%d-%m-%Y %H:%M:%S", filemode="w") # First log entry, the program version logging.info("Version %s" % __builtin__.versionstring) # redirect the notify output to a log file nout = MultiplexStream() Notify.ptr().setOstreamPtr(nout, 0) nout.addFile(Filename(os.path.join(__builtin__.basedir, "game_p3d.log"))) # # LOGGING END # class Main(ShowBase, FSM): """Main function of the application initialise the engine (ShowBase)""" def __init__(self): """initialise the engine""" ShowBase.__init__(self) FSM.__init__(self, "FSM-Game") # # BASIC APPLICATION CONFIGURATIONS
# # LOGGING # # setup Logging logging.basicConfig( level=logging.DEBUG, format="%(asctime)s %(levelname)s: %(message)s", filename=os.path.join(__builtin__.basedir, "game.log"), datefmt="%d-%m-%Y %H:%M:%S", filemode="w") # First log entry, the program version logging.info("Version %s" % versionstring) # redirect the notify output to a log file nout = MultiplexStream() Notify.ptr().setOstreamPtr(nout, 0) nout.addFile(Filename(os.path.join(__builtin__.basedir, "game_p3d.log"))) # # LOGGING END # from world import World from gui.mainmenu import Menu from gui.optionsmenu import OptionsMenu import helper class Main(ShowBase, FSM): def __init__(self): ShowBase.__init__(self) FSM.__init__(self, "FSM-Game") #
# log ######################################################################## from os.path import exists, join from panda3d.core import MultiplexStream, Notify, Filename from yorg.yorg import Yorg import sys import direct.particles.ParticleManagerGlobal # for deploy-ng if sys.platform != 'darwin' and not exists('main.py'): # (on osx it shows an error window on exit) # is it the deployed version? log_path = '' if sys.platform == 'win32' and not exists('main.py'): log_path = join(str(Filename.get_user_appdata_directory()), 'Yorg') if not exists(log_path): Filename.mkdir(Filename(log_path)) sys.stdout = open( join(log_path, 'yorg_output.txt') if log_path else 'yorg_output.txt', 'w') sys.stderr = open( join(log_path, 'yorg_error.txt') if log_path else 'yorg_error.txt', 'w') nout = MultiplexStream() Notify.ptr().setOstreamPtr(nout, 0) nout.addFile( join(log_path, 'yorg_log.txt') if log_path else 'yorg_log.txt') # main ####################################################################### if __name__ == '__main__' or exists('main.pyo'): Yorg()
# (on osx it shows an error window on exit) log_path = '' # is it the deployed windows version? if sys.platform == 'win32' and not exists('main.py'): log_path = join(str(Filename.get_user_appdata_directory()), 'Yorg') if not exists(log_path): Filename.mkdir(Filename(log_path)) ofile = 'yorg_output.txt' opath = join(log_path, ofile) if log_path else ofile sys.stdout = open(opath, 'w') epath = join(log_path, 'yorg_error.txt') if log_path else 'yorg_error.txt' sys.stderr = open(epath, 'w') nout = MultiplexStream() Notify.ptr().setOstreamPtr(nout, 0) lpath = join(log_path, 'yorg_log.txt') if log_path else 'yorg_log.txt' nout.addFile(lpath) # main ####################################################################### if __name__ == '__main__' or exists('main.pyo'): yorg = Yorg() try: yorg.run() except Exception as e: import traceback traceback.print_exc() # for windows: log_path = '' # is it the deployed windows version? if sys.platform == 'win32' and not exists('main.py'): log_path = join(str(Filename.get_user_appdata_directory()), 'Yorg') if not exists(log_path):
def getPmPerceptualError(mesh, pm_filebuf, mipmap_tarfilebuf): perceptualdiff = which('perceptualdiff') if perceptualdiff is None: raise Exception("perceptualdiff exectuable not found on path") pm_chunks = [] if pm_filebuf is not None: data = pm_filebuf.read(PM_CHUNK_SIZE) refinements_read = 0 num_refinements = None while len(data) > 0: (refinements_read, num_refinements, pm_refinements, data_left) = pdae_utils.readPDAEPartial(data, refinements_read, num_refinements) pm_chunks.append(pm_refinements) data = data_left + pm_filebuf.read(PM_CHUNK_SIZE) tar = tarfile.TarFile(fileobj=mipmap_tarfilebuf) texsizes = [] largest_tarinfo = (0, None) for tarinfo in tar: tarinfo.xsize = int(tarinfo.name.split('x')[0]) if tarinfo.xsize > largest_tarinfo[0]: largest_tarinfo = (tarinfo.xsize, tarinfo) if tarinfo.xsize >= 128: texsizes.append(tarinfo) if len(texsizes) == 0: texsizes.append(largest_tarinfo[1]) texsizes = sorted(texsizes, key=lambda t: t.xsize) texims = [] first_image_data = None for tarinfo in texsizes: f = tar.extractfile(tarinfo) texdata = f.read() if first_image_data is None: first_image_data = texdata texpnm = PNMImage() texpnm.read(StringStream(texdata), 'something.jpg') newtex = Texture() newtex.load(texpnm) texims.append(newtex) mesh.images[0].setData(first_image_data) scene_members = getSceneMembers(mesh) # turn off panda3d printing to stdout nout = MultiplexStream() Notify.ptr().setOstreamPtr(nout, 0) nout.addFile(Filename(os.devnull)) base = ShowBase() rotateNode = GeomNode("rotater") rotatePath = base.render.attachNewNode(rotateNode) matrix = numpy.identity(4) if mesh.assetInfo.upaxis == collada.asset.UP_AXIS.X_UP: r = collada.scene.RotateTransform(0, 1, 0, 90) matrix = r.matrix elif mesh.assetInfo.upaxis == collada.asset.UP_AXIS.Y_UP: r = collada.scene.RotateTransform(1, 0, 0, 90) matrix = r.matrix rotatePath.setMat(Mat4(*matrix.T.flatten().tolist())) geom, renderstate, mat4 = scene_members[0] node = GeomNode("primitive") node.addGeom(geom) if renderstate is not None: node.setGeomState(0, renderstate) geomPath = rotatePath.attachNewNode(node) geomPath.setMat(mat4) wrappedNode = ensureCameraAt(geomPath, base.camera) base.disableMouse() attachLights(base.render) base.render.setShaderAuto() base.render.setTransparency(TransparencyAttrib.MNone) base.render.setColorScaleOff(9999) controls.KeyboardMovement() controls.MouseDrag(wrappedNode) controls.MouseScaleZoom(wrappedNode) controls.ButtonUtils(wrappedNode) controls.MouseCamera() error_data = [] try: tempdir = tempfile.mkdtemp(prefix='meshtool-print-pm-perceptual-error') triangleCounts = [] hprs = [(0, 0, 0), (0, 90, 0), (0, 180, 0), (0, 270, 0), (90, 0, 0), (-90, 0, 0)] for texim in texims: np = base.render.find("**/rotater/collada") np.setTextureOff(1) np.setTexture(texim, 1) for angle, hpr in enumerate(hprs): wrappedNode.setHpr(*hpr) takeScreenshot(tempdir, base, geomPath, texim, angle) triangleCounts.append(getNumTriangles(geomPath)) for pm_chunk in pm_chunks: pdae_panda.add_refinements(geomPath, pm_chunk) for texim in texims: np = base.render.find("**/rotater/collada") np.setTextureOff(1) np.setTexture(texim, 1) for angle, hpr in enumerate(hprs): wrappedNode.setHpr(*hpr) takeScreenshot(tempdir, base, geomPath, texim, angle) triangleCounts.append(getNumTriangles(geomPath)) full_tris = triangleCounts[-1] full_tex = texims[-1] for numtris in triangleCounts: for texim in texims: pixel_diff = 0 for angle, hpr in enumerate(hprs): curFile = '%d_%d_%d_%d.png' % (numtris, texim.getXSize(), texim.getYSize(), angle) curFile = os.path.join(tempdir, curFile) fullFile = '%d_%d_%d_%d.png' % (full_tris, full_tex.getXSize(), full_tex.getYSize(), angle) fullFile = os.path.join(tempdir, fullFile) try: output = subprocess.check_output([ perceptualdiff, '-threshold', '1', fullFile, curFile ]) except subprocess.CalledProcessError as ex: output = ex.output output = output.strip() if len(output) > 0: pixel_diff = max(pixel_diff, int(output.split('\n')[1].split()[0])) error_data.append({ 'triangles': numtris, 'width': texim.getXSize(), 'height': texim.getYSize(), 'pixel_error': pixel_diff }) finally: shutil.rmtree(tempdir, ignore_errors=True) return error_data
def getPmPerceptualError(mesh, pm_filebuf, mipmap_tarfilebuf): perceptualdiff = which('perceptualdiff') if perceptualdiff is None: raise Exception("perceptualdiff exectuable not found on path") pm_chunks = [] if pm_filebuf is not None: data = pm_filebuf.read(PM_CHUNK_SIZE) refinements_read = 0 num_refinements = None while len(data) > 0: (refinements_read, num_refinements, pm_refinements, data_left) = pdae_utils.readPDAEPartial(data, refinements_read, num_refinements) pm_chunks.append(pm_refinements) data = data_left + pm_filebuf.read(PM_CHUNK_SIZE) tar = tarfile.TarFile(fileobj=mipmap_tarfilebuf) texsizes = [] largest_tarinfo = (0, None) for tarinfo in tar: tarinfo.xsize = int(tarinfo.name.split('x')[0]) if tarinfo.xsize > largest_tarinfo[0]: largest_tarinfo = (tarinfo.xsize, tarinfo) if tarinfo.xsize >= 128: texsizes.append(tarinfo) if len(texsizes) == 0: texsizes.append(largest_tarinfo[1]) texsizes = sorted(texsizes, key=lambda t: t.xsize) texims = [] first_image_data = None for tarinfo in texsizes: f = tar.extractfile(tarinfo) texdata = f.read() if first_image_data is None: first_image_data = texdata texpnm = PNMImage() texpnm.read(StringStream(texdata), 'something.jpg') newtex = Texture() newtex.load(texpnm) texims.append(newtex) mesh.images[0].setData(first_image_data) scene_members = getSceneMembers(mesh) # turn off panda3d printing to stdout nout = MultiplexStream() Notify.ptr().setOstreamPtr(nout, 0) nout.addFile(Filename(os.devnull)) base = ShowBase() rotateNode = GeomNode("rotater") rotatePath = base.render.attachNewNode(rotateNode) matrix = numpy.identity(4) if mesh.assetInfo.upaxis == collada.asset.UP_AXIS.X_UP: r = collada.scene.RotateTransform(0,1,0,90) matrix = r.matrix elif mesh.assetInfo.upaxis == collada.asset.UP_AXIS.Y_UP: r = collada.scene.RotateTransform(1,0,0,90) matrix = r.matrix rotatePath.setMat(Mat4(*matrix.T.flatten().tolist())) geom, renderstate, mat4 = scene_members[0] node = GeomNode("primitive") node.addGeom(geom) if renderstate is not None: node.setGeomState(0, renderstate) geomPath = rotatePath.attachNewNode(node) geomPath.setMat(mat4) wrappedNode = ensureCameraAt(geomPath, base.camera) base.disableMouse() attachLights(base.render) base.render.setShaderAuto() base.render.setTransparency(TransparencyAttrib.MNone) base.render.setColorScaleOff(9999) controls.KeyboardMovement() controls.MouseDrag(wrappedNode) controls.MouseScaleZoom(wrappedNode) controls.ButtonUtils(wrappedNode) controls.MouseCamera() error_data = [] try: tempdir = tempfile.mkdtemp(prefix='meshtool-print-pm-perceptual-error') triangleCounts = [] hprs = [(0, 0, 0), (0, 90, 0), (0, 180, 0), (0, 270, 0), (90, 0, 0), (-90, 0, 0)] for texim in texims: np = base.render.find("**/rotater/collada") np.setTextureOff(1) np.setTexture(texim, 1) for angle, hpr in enumerate(hprs): wrappedNode.setHpr(*hpr) takeScreenshot(tempdir, base, geomPath, texim, angle) triangleCounts.append(getNumTriangles(geomPath)) for pm_chunk in pm_chunks: pdae_panda.add_refinements(geomPath, pm_chunk) for texim in texims: np = base.render.find("**/rotater/collada") np.setTextureOff(1) np.setTexture(texim, 1) for angle, hpr in enumerate(hprs): wrappedNode.setHpr(*hpr) takeScreenshot(tempdir, base, geomPath, texim, angle) triangleCounts.append(getNumTriangles(geomPath)) full_tris = triangleCounts[-1] full_tex = texims[-1] for numtris in triangleCounts: for texim in texims: pixel_diff = 0 for angle, hpr in enumerate(hprs): curFile = '%d_%d_%d_%d.png' % (numtris, texim.getXSize(), texim.getYSize(), angle) curFile = os.path.join(tempdir, curFile) fullFile = '%d_%d_%d_%d.png' % (full_tris, full_tex.getXSize(), full_tex.getYSize(), angle) fullFile = os.path.join(tempdir, fullFile) try: output = subprocess.check_output([perceptualdiff, '-threshold', '1', fullFile, curFile]) except subprocess.CalledProcessError as ex: output = ex.output output = output.strip() if len(output) > 0: pixel_diff = max(pixel_diff, int(output.split('\n')[1].split()[0])) error_data.append({'triangles': numtris, 'width': texim.getXSize(), 'height': texim.getYSize(), 'pixel_error': pixel_diff}) finally: shutil.rmtree(tempdir, ignore_errors=True) return error_data
# # setup Logging logging.basicConfig( level=logging.DEBUG, format="%(asctime)s %(levelname)s: %(message)s", filename=os.path.join(basedir, "game.log"), datefmt="%d-%m-%Y %H:%M:%S", filemode="w") # First log entry, the program version logging.info("Version {}".format(versionstring)) # redirect the notify output to a log file nout = MultiplexStream() Notify.ptr().setOstreamPtr(nout, 0) nout.addFile(Filename(os.path.join(basedir, "game_p3d.log"))) # # LOGGING END # class Main(ShowBase, FSM): """Main function of the application initialise the engine (ShowBase)""" def __init__(self): """initialise the engine""" ShowBase.__init__(self) FSM.__init__(self, "FSM-Game") # # BASIC APPLICATION CONFIGURATIONS
# LOGGING # # setup Logging logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s: %(message)s", filename=os.path.join(basedir, "game.log"), datefmt="%d-%m-%Y %H:%M:%S", filemode="w") # First log entry, the program version logging.info("Version {}".format(versionstring)) # redirect the notify output to a log file nout = MultiplexStream() Notify.ptr().setOstreamPtr(nout, 0) nout.addFile(Filename(os.path.join(basedir, "game_p3d.log"))) # # LOGGING END # class Main(ShowBase, FSM): """Main function of the application initialise the engine (ShowBase)""" def __init__(self): """initialise the engine""" ShowBase.__init__(self) FSM.__init__(self, "FSM-Game") # # BASIC APPLICATION CONFIGURATIONS