コード例 #1
0
    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
コード例 #2
0
 def runcode(self, code):
     # Empty buffers
     self.stringio.truncate(0)
     self.stringio.seek(0)
     self.stream.clearData()
     try:
         # Swap buffers
         notify = Notify.ptr()
         old_notify = notify.get_ostream_ptr()
         notify.set_ostream_ptr(self.stream, False)
         with redirect_stdout(self.stringio):
             # Exec, writing output to buffers
             exec(code, self.locals)
         # Write buffers to output string.
         io_data = self.stringio.getvalue()
         stream_data = self.stream.getData().decode("utf-8")
         self.write(io_data + stream_data)
         # Restore buffers
         notify.set_ostream_ptr(old_notify, False)
     except:
         self.showtraceback()
コード例 #3
0
ファイル: main.py プロジェクト: erdOne/TowerDefence
from minimap import Minimap
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')
コード例 #4
0
 def _init_notify(self):
     """ Internal method to init the stream to catch all notify messages """
     self._notify_stream = LineStream()
     Notify.ptr().set_ostream_ptr(self._notify_stream, False)
コード例 #5
0
 def getPandaCategories(self):
     from panda3d.core import Notify
     topCategory = Notify.ptr().getTopCategory()
     return self._getPandaCategories(topCategory)
コード例 #6
0
ファイル: urwidOnly.py プロジェクト: croxis/sandbox
#Output
logOutput = urwid.SimpleListWalker([])
logOutputWindow = urwid.ListBox(logOutput)

pythonOutput = urwid.SimpleListWalker([])
pythonOutputWindow = urwid.ListBox(pythonOutput)

commandOutput = urwid.SimpleListWalker([])
commandOutputWindow = urwid.ListBox(commandOutput)

fill = urwid.Frame(logOutputWindow, header=menu, footer=None, focus_part='body')


# Here we hook panda3d's logging into our system
line_stream = LineStream()
Notify.ptr().setOstreamPtr(line_stream, 0)


def get_logs(task):
    '''Yanks Panda3D's log pipe and pumps it to logOutput'''
    #if line_stream.hasNewline():
    while line_stream.isTextAvailable():
        logOutput.contents.append(urwid.Text(line_stream.getLine()))
        logOutput.set_focus(len(logOutput) - 1)
    return task.cont


if __name__ == '__main__':
    from direct.showbase.ShowBase import ShowBase
    from math import pi, sin, cos
    from direct.task import Task
コード例 #7
0
ファイル: main.py プロジェクト: grimfang/owp_ajaw
#
# 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")
コード例 #8
0
 def _init_notify(self):
     """ Internal method to init the stream to catch all notify messages """
     self._notify_stream = LineStream()
     Notify.ptr().set_ostream_ptr(self._notify_stream, False)
コード例 #9
0
ファイル: NotifyPanel.py プロジェクト: Oldtiger5/panda3d
 def getPandaCategories(self):
     from panda3d.core import Notify
     topCategory = Notify.ptr().getTopCategory()
     return self._getPandaCategories(topCategory)
コード例 #10
0
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
コード例 #11
0
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