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
 def __init__(self):
     self.config = getConfigShowbase()
     vfs = VirtualFileSystem.getGlobalPtr()
     self.eventMgr = eventMgr
     self.messenger = messenger
     self.bboard = bulletinBoard
     self.taskMgr = taskMgr
     self.AISleep = self.config.GetFloat('ai-sleep', 0.04)
     Task.TaskManager.taskTimerVerbose = self.config.GetBool(
         'task-timer-verbose', 0)
     Task.TaskManager.extendedExceptions = self.config.GetBool(
         'extended-exceptions', 0)
     self.sfxManagerList = None
     self.musicManager = None
     self.jobMgr = jobMgr
     self.hidden = NodePath('hidden')
     self.graphicsEngine = GraphicsEngine.getGlobalPtr()
     globalClock = ClockObject.getGlobalClock()
     self.trueClock = TrueClock.getGlobalPtr()
     globalClock.setRealTime(self.trueClock.getShortTime())
     globalClock.setAverageFrameRateInterval(30.0)
     globalClock.tick()
     taskMgr.globalClock = globalClock
     __builtins__['ostream'] = Notify.out()
     __builtins__['globalClock'] = globalClock
     __builtins__['vfs'] = vfs
     __builtins__['hidden'] = self.hidden
     self.restart()
Esempio n. 3
0
    def handleDatagram(self, di):
        if self.notify.getDebug():
            print("ClientRepository received datagram:")
            di.getDatagram().dumpHex(Notify.out())

        msgType = self.getMsgType()
        self.currentSenderId = None

        # These are the sort of messages we may expect from the public
        # Panda server.

        if msgType == SET_DOID_RANGE_CMU:
            self.handleSetDoIdrange(di)
        elif msgType == OBJECT_GENERATE_CMU:
            self.handleGenerate(di)
        elif msgType == OBJECT_UPDATE_FIELD_CMU:
            self.handleUpdateField(di)
        elif msgType == OBJECT_DISABLE_CMU:
            self.handleDisable(di)
        elif msgType == OBJECT_DELETE_CMU:
            self.handleDelete(di)
        elif msgType == REQUEST_GENERATES_CMU:
            self.handleRequestGenerates(di)
        else:
            self.handleMessageType(msgType, di)

        # If we're processing a lot of datagrams within one frame, we
        # may forget to send heartbeats.  Keep them coming!
        self.considerHeartbeat()
Esempio n. 4
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()
 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)
Esempio n. 6
0
this module's scope when instantiated."""

__all__ = []

from .ShowBase import ShowBase, WindowControls
from direct.directnotify.DirectNotifyGlobal import directNotify, giveNotify
from panda3d.core import VirtualFileSystem, Notify, ClockObject, PandaSystem
from panda3d.core import ConfigPageManager, ConfigVariableManager
from panda3d.core import NodePath, PGTop
from panda3d.direct import get_config_showbase

config = get_config_showbase()
__dev__ = config.GetBool('want-dev', __debug__)

vfs = VirtualFileSystem.getGlobalPtr()
ostream = Notify.out()
globalClock = ClockObject.getGlobalClock()
cpMgr = ConfigPageManager.getGlobalPtr()
cvMgr = ConfigVariableManager.getGlobalPtr()
pandaSystem = PandaSystem.getGlobalPtr()

# This is defined here so GUI elements can be instantiated before ShowBase.
aspect2d = NodePath(PGTop("aspect2d"))

# Set direct notify categories now that we have config
directNotify.setDconfigLevels()

def run():
    assert ShowBase.notify.warning("run() is deprecated, use base.run() instead")
    base.run()
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
Esempio n. 8
0
    def __init__(self):
        DirectObject.__init__(self)

        # We direct both our stdout and stderr objects onto Panda's
        # Notify stream.  This ensures that unadorned print statements
        # made within Python will get routed into the log properly.
        stream = StreamWriter(Notify.out(), False)
        sys.stdout = stream
        sys.stderr = stream

        # This is set true by dummyAppRunner(), below.
        self.dummy = False

        # These will be set from the application flags when
        # setP3DFilename() is called.
        self.allowPythonDev = False
        self.guiApp = False
        self.interactiveConsole = False
        self.initialAppImport = False
        self.trueFileIO = False
        self.respectPerPlatform = None

        self.verifyContents = self.P3DVCNone

        self.sessionId = 0
        self.packedAppEnvironmentInitialized = False
        self.gotWindow = False
        self.gotP3DFilename = False
        self.p3dFilename = None
        self.p3dUrl = None
        self.started = False
        self.windowOpened = False
        self.windowPrc = None

        self.http = None
        if hasattr(core, 'HTTPClient'):
            self.http = core.HTTPClient.getGlobalPtr()

        self.Undefined = Undefined
        self.ConcreteStruct = ConcreteStruct

        # This is per session.
        self.nextScriptId = 0

        # TODO: we need one of these per instance, not per session.
        self.instanceId = None

        # The root Panda3D install directory.  This is filled in when
        # the instance starts up.
        self.rootDir = None

        # The log directory.  Also filled in when the instance starts.
        self.logDirectory = None

        # self.superMirrorUrl, if nonempty, is the "super mirror" URL
        # that should be contacted first before trying the actual
        # host.  This is primarily used for "downloading" from a
        # locally-stored Panda3D installation.  This is also filled in
        # when the instance starts up.
        self.superMirrorUrl = None

        # A list of the Panda3D packages that have been loaded.
        self.installedPackages = []

        # A list of the Panda3D packages that in the queue to be
        # downloaded.
        self.downloadingPackages = []

        # A dictionary of HostInfo objects for the various download
        # hosts we have imported packages from.
        self.hosts = {}

        # The altHost string that is in effect from the HTML tokens,
        # if any, and the dictionary of URL remapping: orig host url
        # -> alt host url.
        self.altHost = None
        self.altHostMap = {}

        # The URL from which Panda itself should be downloaded.
        self.pandaHostUrl = PandaSystem.getPackageHostUrl()

        # Application code can assign a callable object here; if so,
        # it will be invoked when an uncaught exception propagates to
        # the top of the TaskMgr.run() loop.
        self.exceptionHandler = None

        # Managing packages for runtime download.
        self.downloadingPackages = []
        self.downloadTask = None

        # The mount point for the multifile.  For now, this is always
        # the current working directory, for convenience; but when we
        # move to multiple-instance sessions, it may have to be
        # different for each instance.
        self.multifileRoot = str(ExecutionEnvironment.getCwd())

        # The "main" object will be exposed to the DOM as a property
        # of the plugin object; that is, document.pluginobject.main in
        # JavaScript will be appRunner.main here.  This may be
        # replaced with a direct reference to the JavaScript object
        # later, in setInstanceInfo().
        self.main = ScriptAttributes()

        # By default, we publish a stop() method so the browser can
        # easy stop the plugin.  A particular application can remove
        # this if it chooses.
        self.main.stop = self.stop

        # This will be the browser's toplevel window DOM object;
        # e.g. self.dom.document will be the document.
        self.dom = None

        # This is the list of expressions we will evaluate when
        # self.dom gets assigned.
        self.deferredEvals = []

        # This is the default requestFunc that is installed if we
        # never call setRequestFunc().
        def defaultRequestFunc(*args):
            if args[1] == 'notify':
                # Quietly ignore notifies.
                return
            self.notify.info("Ignoring request: %s" % (args, ))

        self.requestFunc = defaultRequestFunc

        # This will be filled in with the default WindowProperties for
        # this instance, e.g. the WindowProperties necessary to
        # re-embed a window in the browser frame.
        self.windowProperties = None

        # Store our pointer so DirectStart-based apps can find us.
        if AppRunnerGlobal.appRunner is None:
            AppRunnerGlobal.appRunner = self

        # We use this messenger hook to dispatch this __startIfReady()
        # call back to the main thread.
        self.accept('AppRunner_startIfReady', self.__startIfReady)
Esempio n. 9
0
may not have been created yet; instead, ShowBase dynamically adds itself to
this module's scope when instantiated."""

__all__ = []

from .ShowBase import ShowBase, WindowControls
from direct.directnotify.DirectNotifyGlobal import directNotify, giveNotify
from panda3d.core import VirtualFileSystem, Notify, ClockObject, PandaSystem
from panda3d.core import ConfigPageManager, ConfigVariableManager
from panda3d.core import NodePath, PGTop
from . import DConfig as config

__dev__ = config.GetBool('want-dev', __debug__)

vfs = VirtualFileSystem.getGlobalPtr()
ostream = Notify.out()
globalClock = ClockObject.getGlobalClock()
cpMgr = ConfigPageManager.getGlobalPtr()
cvMgr = ConfigVariableManager.getGlobalPtr()
pandaSystem = PandaSystem.getGlobalPtr()

# This is defined here so GUI elements can be instantiated before ShowBase.
aspect2d = NodePath(PGTop("aspect2d"))

# Set direct notify categories now that we have config
directNotify.setDconfigLevels()


def run():
    assert ShowBase.notify.warning(
        "run() is deprecated, use base.run() instead")
Esempio n. 10
0
            value = cls._defaults[data_id]
            copier = cls._copiers.get(data_id)
            data[data_id] = copier(value) if copier else value


# Global data - accessible from both the Core and the GUI - can be set and
# retrieved through the following class.
class GlobalData(metaclass=GlobalMeta):

    showbase = ShowBase(
    )  # instancing ShowBase here ensures that setting up Panda3D's
    # notify system afterwards will work as expected


# make sure that Panda3D's notify system redirects its output to the designated log file
Notifier.streamWriter = StreamWriter(Notify.out(), False)


# Panda3D's notifiers are made accessible through the following class
class Notifiers:
    @classmethod
    def create(cls, name):

        notifier = directNotify.newCategory(name)
        notifier.setSeverity(2)  # "debug" level

        return notifier


# Create Panda3D notifiers for different categories
Notifiers.imprt = Notifiers.create("Import")
 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)
Esempio n. 12
0
 def getPandaCategories(self):
     from panda3d.core import Notify
     topCategory = Notify.ptr().getTopCategory()
     return self._getPandaCategories(topCategory)
Esempio n. 13
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
Esempio n. 14
0
    def __init__(self):
        #: The directory containing the main Python file of this application.
        self.mainDir = ExecutionEnvironment.getEnvironmentVariable("MAIN_DIR")
        self.main_dir = self.mainDir

        self.wantStats = self.config.GetBool('want-pstats', 0)

        # Do you want to enable a fixed simulation timestep?  Setting this true
        # only means that the builtin resetPrevTransform and collisionLoop
        # tasks are added onto the simTaskMgr instead of taskMgr, which runs at
        # a fixed time step.  You can still add your own fixed timestep tasks
        # when this is false, it only has to do with builtin simulation tasks.
        self.fixedSimulationStep = self.config.GetBool(
            'want-fixed-simulation-step', 0)

        #: The global event manager, as imported from `.EventManagerGlobal`.
        self.eventMgr = eventMgr
        #: The global messenger, as imported from `.MessengerGlobal`.
        self.messenger = messenger
        #: The global bulletin board, as imported from `.BulletinBoardGlobal`.
        self.bboard = bulletinBoard
        #: The global task manager, as imported from `.TaskManagerGlobal`.
        self.taskMgr = taskMgr
        self.task_mgr = taskMgr
        #: The global simulation task manager, as imported from `.TaskManagerGlobal`
        self.simTaskMgr = simTaskMgr
        self.sim_task_mgr = simTaskMgr
        #: The global job manager, as imported from `.JobManagerGlobal`.
        self.jobMgr = jobMgr

        #: `.Loader.Loader` object.
        self.loader = Loader(self)

        # Get a pointer to Panda's global ClockObject, used for
        # synchronizing events between Python and C.
        globalClock = ClockObject.getGlobalClock()
        # We will manually manage the clock
        globalClock.setMode(ClockObject.MSlave)
        self.globalClock = globalClock

        # Since we have already started up a TaskManager, and probably
        # a number of tasks; and since the TaskManager had to use the
        # TrueClock to tell time until this moment, make sure the
        # globalClock object is exactly in sync with the TrueClock.
        trueClock = TrueClock.getGlobalPtr()
        self.trueClock = trueClock
        globalClock.setRealTime(trueClock.getShortTime())
        globalClock.tick()

        # Now we can make the TaskManager start using the new globalClock.
        taskMgr.globalClock = globalClock
        simTaskMgr.globalClock = globalClock

        vfs = VirtualFileSystem.getGlobalPtr()
        self.vfs = vfs

        # Make sure we're not making more than one HostBase.
        if hasattr(builtins, 'base'):
            raise Exception("Attempt to spawn multiple HostBase instances!")

        # DO NOT ADD TO THIS LIST.  We're trying to phase out the use of
        # built-in variables by ShowBase.  Use a Global module if necessary.
        builtins.base = self
        builtins.taskMgr = self.taskMgr
        builtins.simTaskMgr = self.simTaskMgr
        builtins.jobMgr = self.jobMgr
        builtins.eventMgr = self.eventMgr
        builtins.messenger = self.messenger
        builtins.bboard = self.bboard
        builtins.loader = self.loader
        # Config needs to be defined before ShowBase is constructed
        #builtins.config = self.config
        builtins.ostream = Notify.out()
        builtins.directNotify = directNotify
        builtins.giveNotify = giveNotify
        builtins.globalClock = globalClock
        builtins.vfs = vfs
        builtins.cpMgr = ConfigPageManager.getGlobalPtr()
        builtins.cvMgr = ConfigVariableManager.getGlobalPtr()
        builtins.pandaSystem = PandaSystem.getGlobalPtr()

        # Now add this instance to the ShowBaseGlobal module scope.
        from . import ShowBaseGlobal
        builtins.run = ShowBaseGlobal.run
        ShowBaseGlobal.base = self

        # What is the current frame number?
        self.frameCount = 0
        # Time at beginning of current frame
        self.frameTime = self.globalClock.getRealTime()
        # How long did the last frame take.
        self.deltaTime = 0

        #
        # Variables pertaining to simulation ticks.
        #

        self.prevRemainder = 0
        self.remainder = 0
        # What is the current overall simulation tick?
        self.tickCount = 0
        # How many ticks are we going to run this frame?
        self.totalTicksThisFrame = 0
        # How many ticks have we run so far this frame?
        self.currentTicksThisFrame = 0
        # What tick are we currently on this frame?
        self.currentFrameTick = 0
        # How many simulations ticks are we running per-second?
        self.ticksPerSec = 60
        self.intervalPerTick = 1.0 / self.ticksPerSec

        self.taskMgr.finalInit()
from AIBase import AIBase
from direct.directnotify.DirectNotifyGlobal import directNotify
from panda3d.core import RescaleNormalAttrib, NodePath, Notify

__builtins__['base'] = AIBase()
__builtins__['ostream'] = Notify.out()
__builtins__['run'] = base.run
__builtins__['taskMgr'] = base.taskMgr
__builtins__['jobMgr'] = base.jobMgr
__builtins__['eventMgr'] = base.eventMgr
__builtins__['messenger'] = base.messenger
__builtins__['bboard'] = base.bboard
__builtins__['config'] = base.config
__builtins__['directNotify'] = directNotify
render = NodePath('render')
render.setAttrib(RescaleNormalAttrib.makeDefault())
render.setTwoSided(0)
__builtins__['render'] = render
from direct.showbase import Loader
base.loader = Loader.Loader(base)
__builtins__['loader'] = base.loader
directNotify.setDconfigLevels()

def inspect(anObject):
    from direct.tkpanels import Inspector
    Inspector.inspect(anObject)


__builtins__['inspect'] = inspect
taskMgr.finalInit()
Esempio n. 16
0
#
# 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")
Esempio n. 17
0
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')
Esempio n. 18
0
#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
Esempio n. 19
0
    def __init__(self):
        DirectObject.__init__(self)

        # We direct both our stdout and stderr objects onto Panda's
        # Notify stream.  This ensures that unadorned print statements
        # made within Python will get routed into the log properly.
        stream = StreamWriter(Notify.out(), False)
        sys.stdout = stream
        sys.stderr = stream

        # This is set true by dummyAppRunner(), below.
        self.dummy = False

        # These will be set from the application flags when
        # setP3DFilename() is called.
        self.allowPythonDev = False
        self.guiApp = False
        self.interactiveConsole = False
        self.initialAppImport = False
        self.trueFileIO = False
        self.respectPerPlatform = None

        self.verifyContents = self.P3DVCNone

        self.sessionId = 0
        self.packedAppEnvironmentInitialized = False
        self.gotWindow = False
        self.gotP3DFilename = False
        self.p3dFilename = None
        self.p3dUrl = None
        self.started = False
        self.windowOpened = False
        self.windowPrc = None

        self.http = None
        if hasattr(core, 'HTTPClient'):
            self.http = core.HTTPClient.getGlobalPtr()

        self.Undefined = Undefined
        self.ConcreteStruct = ConcreteStruct

        # This is per session.
        self.nextScriptId = 0

        # TODO: we need one of these per instance, not per session.
        self.instanceId = None

        # The root Panda3D install directory.  This is filled in when
        # the instance starts up.
        self.rootDir = None

        # The log directory.  Also filled in when the instance starts.
        self.logDirectory = None

        # self.superMirrorUrl, if nonempty, is the "super mirror" URL
        # that should be contacted first before trying the actual
        # host.  This is primarily used for "downloading" from a
        # locally-stored Panda3D installation.  This is also filled in
        # when the instance starts up.
        self.superMirrorUrl = None

        # A list of the Panda3D packages that have been loaded.
        self.installedPackages = []

        # A list of the Panda3D packages that in the queue to be
        # downloaded.
        self.downloadingPackages = []

        # A dictionary of HostInfo objects for the various download
        # hosts we have imported packages from.
        self.hosts = {}

        # The altHost string that is in effect from the HTML tokens,
        # if any, and the dictionary of URL remapping: orig host url
        # -> alt host url.
        self.altHost = None
        self.altHostMap = {}

        # The URL from which Panda itself should be downloaded.
        self.pandaHostUrl = PandaSystem.getPackageHostUrl()

        # Application code can assign a callable object here; if so,
        # it will be invoked when an uncaught exception propagates to
        # the top of the TaskMgr.run() loop.
        self.exceptionHandler = None

        # Managing packages for runtime download.
        self.downloadingPackages = []
        self.downloadTask = None

        # The mount point for the multifile.  For now, this is always
        # the current working directory, for convenience; but when we
        # move to multiple-instance sessions, it may have to be
        # different for each instance.
        self.multifileRoot = str(ExecutionEnvironment.getCwd())

        # The "main" object will be exposed to the DOM as a property
        # of the plugin object; that is, document.pluginobject.main in
        # JavaScript will be appRunner.main here.  This may be
        # replaced with a direct reference to the JavaScript object
        # later, in setInstanceInfo().
        self.main = ScriptAttributes()

        # By default, we publish a stop() method so the browser can
        # easy stop the plugin.  A particular application can remove
        # this if it chooses.
        self.main.stop = self.stop

        # This will be the browser's toplevel window DOM object;
        # e.g. self.dom.document will be the document.
        self.dom = None

        # This is the list of expressions we will evaluate when
        # self.dom gets assigned.
        self.deferredEvals = []

        # This is the default requestFunc that is installed if we
        # never call setRequestFunc().
        def defaultRequestFunc(*args):
            if args[1] == 'notify':
                # Quietly ignore notifies.
                return
            self.notify.info("Ignoring request: %s" % (args,))
        self.requestFunc = defaultRequestFunc

        # This will be filled in with the default WindowProperties for
        # this instance, e.g. the WindowProperties necessary to
        # re-embed a window in the browser frame.
        self.windowProperties = None

        # Store our pointer so DirectStart-based apps can find us.
        if AppRunnerGlobal.appRunner is None:
            AppRunnerGlobal.appRunner = self

        # We use this messenger hook to dispatch this __startIfReady()
        # call back to the main thread.
        self.accept('AppRunner_startIfReady', self.__startIfReady)
 def getPandaCategories(self):
     from panda3d.core import Notify
     topCategory = Notify.ptr().getTopCategory()
     return self._getPandaCategories(topCategory)
Esempio n. 21
0
class Notifier:
    serverDelta = 0

    # If this object is set to something, it is used to print output
    # messages instead of writing them to the console.  This is
    # particularly useful for integrating the Python notify system
    # with the C++ notify system.
    streamWriter = None
    if ConfigVariableBool('notify-integrate', True):
        streamWriter = StreamWriter(Notify.out(), False)

    showTime = ConfigVariableBool('notify-timestamp', False)

    def __init__(self, name, logger=None):
        """
        name is a string
        logger is a Logger

        Create a new instance of the Notifier class with a given name
        and an optional Logger class for piping output to. If no logger
        specified, use the global default
        """
        self.__name = name

        if (logger==None):
            self.__logger = defaultLogger
        else:
            self.__logger = logger

        # Global default levels are initialized here
        self.__info = 1
        self.__warning = 1
        self.__debug = 0
        self.__logging = 0

    def setServerDelta(self, delta, timezone):
        """
        Call this method on any Notify object to globally change the
        timestamp printed for each line of all Notify objects.

        This synchronizes the timestamp with the server's known time
        of day, and also switches into the server's timezone.
        """
        delta = int(round(delta))
        Notifier.serverDelta = delta + time.timezone - timezone

        # The following call is necessary to make the output from C++
        # notify messages show the same timestamp as those generated
        # from Python-level notify messages.
        NotifyCategory.setServerDelta(self.serverDelta)

        self.info("Notify clock adjusted by %s (and timezone adjusted by %s hours) to synchronize with server." % (PythonUtil.formatElapsedSeconds(delta), (time.timezone - timezone) / 3600))

    def getTime(self):
        """
        Return the time as a string suitable for printing at the
        head of any notify message
        """
        # for some strange reason, time.time() updates only once/minute if
        # the task is out of focus on win32.  time.clock doesn't have this problem.
        return time.strftime(":%m-%d-%Y %H:%M:%S ", time.localtime(time.time() + self.serverDelta))

    def getOnlyTime(self):
        """
        Return the time as a string.
        The Only in the name is referring to not showing the date.
        """
        return time.strftime("%H:%M:%S", time.localtime(time.time() + self.serverDelta))

    def __str__(self):
        """
        Print handling routine
        """
        return "%s: info = %d, warning = %d, debug = %d, logging = %d" % \
               (self.__name, self.__info, self.__warning, self.__debug, self.__logging)

    # Severity funcs
    def setSeverity(self, severity):
        from panda3d.core import NSDebug, NSInfo, NSWarning, NSError
        if severity >= NSError:
            self.setWarning(0)
            self.setInfo(0)
            self.setDebug(0)
        elif severity == NSWarning:
            self.setWarning(1)
            self.setInfo(0)
            self.setDebug(0)
        elif severity == NSInfo:
            self.setWarning(1)
            self.setInfo(1)
            self.setDebug(0)
        elif severity <= NSDebug:
            self.setWarning(1)
            self.setInfo(1)
            self.setDebug(1)

    def getSeverity(self):
        from panda3d.core import NSDebug, NSInfo, NSWarning, NSError
        if self.getDebug():
            return NSDebug
        elif self.getInfo():
            return NSInfo
        elif self.getWarning():
            return NSWarning
        else:
            return NSError

    # error funcs
    def error(self, errorString, exception=StandardError):
        """
        Raise an exception with given string and optional type:
        Exception: error
        """
        message = str(errorString)
        if Notifier.showTime.getValue():
            string = (self.getTime() + str(exception) + ": " + self.__name + "(error): " + message)
        else:
            string = (str(exception) + ": " + self.__name + "(error): " + message)
        self.__log(string)
        raise exception(errorString)

    # warning funcs
    def warning(self, warningString):
        """
        Issue the warning message if warn flag is on
        """
        if self.__warning:
            message = str(warningString)
            if Notifier.showTime.getValue():
                string = (self.getTime() + self.__name + '(warning): ' + message)
            else:
                string = (":" + self.__name + '(warning): ' + message)
            self.__log(string)
            self.__print(string)
        return 1 # to allow assert myNotify.warning("blah")

    def setWarning(self, bool):
        """
        Enable/Disable the printing of warning messages
        """
        self.__warning = bool

    def getWarning(self):
        """
        Return whether the printing of warning messages is on or off
        """
        return(self.__warning)

    # debug funcs
    def debug(self, debugString):
        """
        Issue the debug message if debug flag is on
        """
        if self.__debug:
            message = str(debugString)
            if Notifier.showTime.getValue():
                string = (self.getTime() + self.__name + '(debug): ' + message)
            else:
                string = (':' + self.__name + '(debug): ' + message)
            self.__log(string)
            self.__print(string)
        return 1 # to allow assert myNotify.debug("blah")

    def setDebug(self, bool):
        """
        Enable/Disable the printing of debug messages
        """
        self.__debug = bool

    def getDebug(self):
        """
        Return whether the printing of debug messages is on or off
        """
        return self.__debug

    # info funcs
    def info(self, infoString):
        """
        Print the given informational string, if info flag is on
        """
        if self.__info:
            message = str(infoString)
            if Notifier.showTime.getValue():
                string = (self.getTime() + self.__name + ': ' + message)
            else:
                string = (':' + self.__name + ': ' + message)
            self.__log(string)
            self.__print(string)
        return 1 # to allow assert myNotify.info("blah")

    def getInfo(self):
        """
        Return whether the printing of info messages is on or off
        """
        return self.__info

    def setInfo(self, bool):
        """
        Enable/Disable informational message  printing
        """
        self.__info = bool

    # log funcs
    def __log(self, logEntry):
        """
        Determine whether to send informational message to the logger
        """
        if self.__logging:
            self.__logger.log(logEntry)

    def getLogging(self):
        """
        Return 1 if logging enabled, 0 otherwise
        """
        return (self.__logging)

    def setLogging(self, bool):
        """
        Set the logging flag to int (1=on, 0=off)
        """
        self.__logging = bool

    def __print(self, string):
        """
        Prints the string to output followed by a newline.
        """
        if self.streamWriter:
            self.streamWriter.appendData(string + '\n')
        else:
            print >> sys.stderr, string

    def debugStateCall(self, obj=None, fsmMemberName='fsm',
            secondaryFsm='secondaryFSM'):
        """
        If this notify is in debug mode, print the time of the
        call followed by the [fsm state] notifier category and
        the function call (with parameters).
        """
        #f.f_locals['self'].__init__.im_class.__name__
        if self.__debug:
            state = ''
            doId = ''
            if obj is not None:

                fsm=obj.__dict__.get(fsmMemberName)
                if fsm is not None:
                    stateObj = fsm.getCurrentState()
                    if stateObj is not None:
                        #state = "%s=%s"%(fsmMemberName, stateObj.getName())
                        state = stateObj.getName()

                fsm=obj.__dict__.get(secondaryFsm)
                if fsm is not None:
                    stateObj = fsm.getCurrentState()
                    if stateObj is not None:
                        #state = "%s=%s"%(fsmMemberName, stateObj.getName())
                        state = "%s, %s"%(state, stateObj.getName())

                if hasattr(obj, 'doId'):
                    doId = " doId:%s"%(obj.doId,)
            #if type(obj) == types.ClassType:
            #    name = "%s."%(obj.__class__.__name__,)
            string = ":%s:%s [%-7s] id(%s)%s %s"%(
                self.getOnlyTime(),
                self.__name,
                state,
                id(obj),
                doId,
                PythonUtil.traceParentCall())
            self.__log(string)
            self.__print(string)
        return 1 # to allow assert self.notify.debugStateCall(self)

    def debugCall(self, debugString=''):
        """
        If this notify is in debug mode, print the time of the
        call followed by the notifier category and
        the function call (with parameters).
        """
        if self.__debug:
            message = str(debugString)
            string = ":%s:%s \"%s\" %s"%(
                self.getOnlyTime(),
                self.__name,
                message,
                PythonUtil.traceParentCall())
            self.__log(string)
            self.__print(string)
        return 1 # to allow assert self.notify.debugCall("blah")
class Notifier:
    serverDelta = 0
    streamWriter = None
    if ConfigVariableBool('notify-integrate', True):
        streamWriter = StreamWriter(Notify.out(), False)
    showTime = ConfigVariableBool('notify-timestamp', False)

    def __init__(self, name, logger=None):
        self.__name = name
        if logger == None:
            self.__logger = defaultLogger
        else:
            self.__logger = logger
        self.__info = 1
        self.__warning = 1
        self.__debug = 0
        self.__logging = 0
        return

    def setServerDelta(self, delta, timezone):
        delta = int(round(delta))
        Notifier.serverDelta = delta + time.timezone - timezone
        NotifyCategory.setServerDelta(self.serverDelta)
        self.info(
            'Notify clock adjusted by %s (and timezone adjusted by %s hours) to synchronize with server.'
            % (PythonUtil.formatElapsedSeconds(delta),
               (time.timezone - timezone) / 3600))

    def getTime(self):
        return time.strftime(':%m-%d-%Y %H:%M:%S ',
                             time.localtime(time.time() + self.serverDelta))

    def getOnlyTime(self):
        return time.strftime('%H:%M:%S',
                             time.localtime(time.time() + self.serverDelta))

    def __str__(self):
        return '%s: info = %d, warning = %d, debug = %d, logging = %d' % (
            self.__name, self.__info, self.__warning, self.__debug,
            self.__logging)

    def setSeverity(self, severity):
        from panda3d.core import NSDebug, NSInfo, NSWarning, NSError
        if severity >= NSError:
            self.setWarning(0)
            self.setInfo(0)
            self.setDebug(0)
        else:
            if severity == NSWarning:
                self.setWarning(1)
                self.setInfo(0)
                self.setDebug(0)
            else:
                if severity == NSInfo:
                    self.setWarning(1)
                    self.setInfo(1)
                    self.setDebug(0)
                else:
                    if severity <= NSDebug:
                        self.setWarning(1)
                        self.setInfo(1)
                        self.setDebug(1)

    def getSeverity(self):
        from panda3d.core import NSDebug, NSInfo, NSWarning, NSError
        if self.getDebug():
            return NSDebug
        if self.getInfo():
            return NSInfo
        if self.getWarning():
            return NSWarning
        return NSError

    def error(self, errorString, exception=StandardError):
        message = str(errorString)
        if Notifier.showTime.getValue():
            string = self.getTime() + str(
                exception) + ': ' + self.__name + '(error): ' + message
        else:
            string = str(
                exception) + ': ' + self.__name + '(error): ' + message
        self.__log(string)
        raise exception(errorString)

    def warning(self, warningString):
        if self.__warning:
            message = str(warningString)
            if Notifier.showTime.getValue():
                string = self.getTime() + self.__name + '(warning): ' + message
            else:
                string = ':' + self.__name + '(warning): ' + message
            self.__log(string)
            self.__print(string)
        return 1

    def setWarning(self, bool):
        self.__warning = bool

    def getWarning(self):
        return self.__warning

    def debug(self, debugString):
        if self.__debug:
            message = str(debugString)
            if Notifier.showTime.getValue():
                string = self.getTime() + self.__name + '(debug): ' + message
            else:
                string = ':' + self.__name + '(debug): ' + message
            self.__log(string)
            self.__print(string)
        return 1

    def setDebug(self, bool):
        self.__debug = bool

    def getDebug(self):
        return self.__debug

    def info(self, infoString):
        if self.__info:
            message = str(infoString)
            if Notifier.showTime.getValue():
                string = self.getTime() + self.__name + ': ' + message
            else:
                string = ':' + self.__name + ': ' + message
            self.__log(string)
            self.__print(string)
        return 1

    def getInfo(self):
        return self.__info

    def setInfo(self, bool):
        self.__info = bool

    def __log(self, logEntry):
        if self.__logging:
            self.__logger.log(logEntry)

    def getLogging(self):
        return self.__logging

    def setLogging(self, bool):
        self.__logging = bool

    def __print(self, string):
        if self.streamWriter:
            self.streamWriter.write(string + '\n')
        else:
            print >> sys.stderr, string

    def debugStateCall(self,
                       obj=None,
                       fsmMemberName='fsm',
                       secondaryFsm='secondaryFSM'):
        if self.__debug:
            state = ''
            doId = ''
            if obj is not None:
                fsm = obj.__dict__.get(fsmMemberName)
                if fsm is not None:
                    stateObj = fsm.getCurrentState()
                    if stateObj is not None:
                        state = stateObj.getName()
                fsm = obj.__dict__.get(secondaryFsm)
                if fsm is not None:
                    stateObj = fsm.getCurrentState()
                    if stateObj is not None:
                        state = '%s, %s' % (state, stateObj.getName())
                if hasattr(obj, 'doId'):
                    doId = ' doId:%s' % (obj.doId, )
            string = ':%s:%s [%-7s] id(%s)%s %s' % (
                self.getOnlyTime(), self.__name, state, id(obj), doId,
                PythonUtil.traceParentCall())
            self.__log(string)
            self.__print(string)
        return 1

    def debugCall(self, debugString=''):
        if self.__debug:
            message = str(debugString)
            string = ':%s:%s "%s" %s' % (self.getOnlyTime(), self.__name,
                                         message, PythonUtil.traceParentCall())
            self.__log(string)
            self.__print(string)
        return 1