def setSound(self, soundFilepath):
   # if there is already a model defined, remove it
   if self.soundEffect is not None:
     self.soundEffect.remove()
   
   if soundFilepath is not None:
     filepath = str(Filename.fromOsSpecific(soundFilepath))
     # add the model path to the panda-path
     pandaPath = None
     from pandac.PandaModules import getModelPath
     for searchPath in str(getModelPath()).split():
       if searchPath == filepath:
         pandaPath = searchPath
     if pandaPath is None:
       pandaPath = '/'.join(filepath.split('/')[:-1])
       from pandac.PandaModules import getModelPath
       getModelPath().appendPath(pandaPath)
     
     # the path to the model we handle
     self.soundFilepath = soundFilepath
     self.setFilepath(soundFilepath)
     # load the model
     self.soundEffect = soundManager.get3dManager().loadSfx(soundFilepath)
   
   # if the model loading fails or no path given, use a dummy object
   if self.soundEffect is None:
     print "W: NodePathWrapper.setModel: model could not be loaded, loading dummy"
     self.soundEffect = soundManager.get3dManager().loadSfx(SOUND_NOT_FOUND_SOUND)
   # make the model visible
   soundManager.get3dManager().attachSoundToObject( self.soundEffect, self.getNodepath() )
   
   self.soundEffect.setLoop(True)
   self.soundEffect.play()
   soundManager.get3dManager().setSoundVelocityAuto( self.soundEffect )
Ejemplo n.º 2
0
 def loaderPhaseChecker(self, path, loaderOptions):
     if 'audio/' in path:
         return 1
     file = Filename(path)
     if not file.getExtension():
         file.setExtension('bam')
     mp = getModelPath()
     path = mp.findFile(file).cStr()
     if not path:
         return
     match = re.match('.*phase_([^/]+)/', path)
     if not match:
         if 'dmodels' in path:
             return
         else:
             self.errorAccumulatorBuffer += 'file not in phase (%s, %s)\n' % (file, path)
             return
     basePhase = float(match.groups()[0])
     if not launcher.getPhaseComplete(basePhase):
         self.errorAccumulatorBuffer += 'phase is not loaded for this model %s\n' % path
     model = loader.loader.loadSync(Filename(path), loaderOptions)
     if model:
         model = NodePath(model)
         for tex in model.findAllTextures():
             texPath = tex.getFullpath().cStr()
             match = re.match('.*phase_([^/]+)/', texPath)
             if match:
                 texPhase = float(match.groups()[0])
                 if texPhase > basePhase:
                     self.errorAccumulatorBuffer += 'texture phase is higher than the models (%s, %s)\n' % (path, texPath)
Ejemplo n.º 3
0
 def loaderPhaseChecker(self, path, loaderOptions):
     if 'audio/' in path:
         return 1
     file = Filename(path)
     if not file.getExtension():
         file.setExtension('bam')
     mp = getModelPath()
     path = mp.findFile(file).cStr()
     if not path:
         return
     match = re.match('.*phase_([^/]+)/', path)
     if not match:
         if 'dmodels' in path:
             return
         else:
             self.errorAccumulatorBuffer += 'file not in phase (%s, %s)\n' % (
                 file, path)
             return
     basePhase = float(match.groups()[0])
     if not launcher.getPhaseComplete(basePhase):
         self.errorAccumulatorBuffer += 'phase is not loaded for this model %s\n' % path
     model = loader.loader.loadSync(Filename(path), loaderOptions)
     if model:
         model = NodePath(model)
         for tex in model.findAllTextures():
             texPath = tex.getFullpath().cStr()
             match = re.match('.*phase_([^/]+)/', texPath)
             if match:
                 texPhase = float(match.groups()[0])
                 if texPhase > basePhase:
                     self.errorAccumulatorBuffer += 'texture phase is higher than the models (%s, %s)\n' % (
                         path, texPath)
Ejemplo n.º 4
0
    def setModelFilepath(self, modelFilepath):

        if modelFilepath is not None:
            filepath = str(Filename.fromOsSpecific(modelFilepath))
            # add the model path to the panda-path
            pandaPath = None
            from pandac.PandaModules import getModelPath
            for searchPath in str(getModelPath()).split():
                if searchPath == filepath:
                    pandaPath = searchPath
            if pandaPath is None:
                pandaPath = '/'.join(filepath.split('/')[:-1])
                from pandac.PandaModules import getModelPath
                getModelPath().appendPath(pandaPath)

            # the path to the model we handle
            self.modelFilepath = modelFilepath

            try:
                # load the model
                self.model = loader.loadModel(filepath)
            except:
                self.model = None

            if self.isEditmodeEnabled():
                self.enableSubNodes()

        if self.model is None:
            # if the model loading fails or no path given, use a dummy object
            print "W: NodePathWrapper.setModel: model could not be loaded, loading dummy"
            self.model = loader.loadModel(MODEL_NOT_FOUND_MODEL)
            # make the model visible
            self.model.reparentTo(self.getNodepath())
            # delete the filepath
            #self.clearFilepath()
        else:
            # store the full filepath of the model
            #self.setFilepath(filepath) # dont do that, in here, but in the egg-data

            if self.isEditmodeEnabled():
                # reread the model from the egg-data, this reloads the model when
                # editmode is enabled
                self.updateModelFromEggData()
            else:
                # parent the model to out nodepath
                self.model.reparentTo(self.getNodepath())
def makeBundle(startDir):
    fstartDir = Filename.fromOsSpecific(startDir)

    # Search for panda3d_mac along $PATH.
    path = DSearchPath()
    if 'PATH' in os.environ:
        path.appendPath(os.environ['PATH'])
    path.appendPath(os.defpath)
    panda3d_mac = path.findFile('panda3d_mac')
    if not panda3d_mac:
        raise StandardError, "Couldn't find panda3d_mac on path."

    # Construct a search path to look for the images.
    search = DSearchPath()

    # First on the path: an explicit $PLUGIN_IMAGES env var.
    if ExecutionEnvironment.hasEnvironmentVariable('PLUGIN_IMAGES'):
        search.appendDirectory(Filename.expandFrom('$PLUGIN_IMAGES'))

    # Next on the path: the models/plugin_images directory within the
    # current directory.
    search.appendDirectory('models/plugin_images')

    # Finally on the path: models/plugin_images within the model
    # search path.
    for dir in getModelPath().getDirectories():
        search.appendDirectory(Filename(dir, 'plugin_images'))

    # Now find the icon file on the above search path.
    icons = search.findFile('panda3d.icns')
    if not icons:
        raise StandardError, "Couldn't find panda3d.icns on model-path."

    # Generate the bundle directory structure
    rootFilename = Filename(fstartDir)
    bundleFilename = Filename(rootFilename, 'Panda3D.app')
    if os.path.exists(bundleFilename.toOsSpecific()):
        shutil.rmtree(bundleFilename.toOsSpecific())

    plistFilename = Filename(bundleFilename, 'Contents/Info.plist')
    plistFilename.makeDir()
    exeFilename = Filename(bundleFilename, 'Contents/MacOS/panda3d_mac')
    exeFilename.makeDir()
    iconFilename = Filename(bundleFilename, 'Contents/Resources/panda3d.icns')
    iconFilename.makeDir()

    # Copy in Info.plist, the icon file, and the compiled executable.
    shutil.copyfile(
        Filename(fstartDir, "panda3d_mac.plist").toOsSpecific(),
        plistFilename.toOsSpecific())
    shutil.copyfile(icons.toOsSpecific(), iconFilename.toOsSpecific())
    print panda3d_mac, exeFilename
    shutil.copyfile(panda3d_mac.toOsSpecific(), exeFilename.toOsSpecific())
    os.chmod(exeFilename.toOsSpecific(), 0755)

    # All done!
    bundleFilename.touch()
    print bundleFilename.toOsSpecific()
Ejemplo n.º 6
0
    def initPackedAppEnvironment(self):
        """ This function sets up the Python environment suitably for
        running a packed app.  It should only run once in any given
        session (and it includes logic to ensure this). """

        if self.packedAppEnvironmentInitialized:
            return

        self.packedAppEnvironmentInitialized = True

        vfs = VirtualFileSystem.getGlobalPtr()

        # Now set up Python to import this stuff.
        VFSImporter.register()
        sys.path.append(self.multifileRoot)

        # Make sure that $MAIN_DIR is set to the p3d root before we
        # start executing the code in this file.
        ExecutionEnvironment.setEnvironmentVariable(
            "MAIN_DIR",
            Filename(self.multifileRoot).toOsSpecific())

        # Put our root directory on the model-path, too.
        getModelPath().appendDirectory(self.multifileRoot)

        if not self.trueFileIO:
            # Replace the builtin open and file symbols so user code will get
            # our versions by default, which can open and read files out of
            # the multifile.
            __builtin__.file = file.file
            __builtin__.open = file.open
            __builtin__.execfile = file.execfile
            os.listdir = file.listdir
            os.walk = file.walk
            os.path.join = file.join
            os.path.isfile = file.isfile
            os.path.isdir = file.isdir
            os.path.exists = file.exists
            os.path.lexists = file.lexists
            os.path.getmtime = file.getmtime
            os.path.getsize = file.getsize
            sys.modules['glob'] = glob

        self.checkDiskUsage()
 def setParticleConfig(self, filepath):
   if filepath is not None:
     # check if model file is in pandaModelPath
     filepath = str(Filename.fromOsSpecific(filepath))
     
     # add the model path to the panda-path
     pandaPath = None
     from pandac.PandaModules import getModelPath
     for searchPath in str(getModelPath()).split():
       if searchPath == filepath:
         pandaPath = searchPath
     if pandaPath is None:
       pandaPath = '/'.join(filepath.split('/')[:-1])
       from pandac.PandaModules import getModelPath
       getModelPath().appendPath( pandaPath )
   
   self.particleFilename = filepath
   try:
     #Start of the code from steam.ptf
     self.particleSystem.loadConfig(Filename(filepath))
     self.setFilepath(filepath)
   except:
     print "W: particleSystemWrapper.setParticleConfig: Error loading file"
     print "  -", filepath
     traceback.print_exc()
     
     print "  - Creating dummy particle Effect"
     # create new one if loading failed (particlepanel requires at least one particle)
     particles = Particles()
     particles.setBirthRate(0.02)
     particles.setLitterSize(10)
     particles.setLitterSpread(0)
     particles.setFactory("PointParticleFactory")
     particles.setRenderer("PointParticleRenderer")
     particles.setEmitter("SphereVolumeEmitter")
     particles.enable()
     self.particleSystem.addParticles(particles)
     self.clearFilepath()
   #Sets particles to birth relative to the teapot, but to render at toplevel
   self.particleSystem.start(self.getNodepath())
   
   # a bugfix, somewhere must be some color assigned to most nodes, i dont know why
   # this looks very bad on particle systems
   self.getNodepath().setColorOff(0)
Ejemplo n.º 8
0
    def setParticleConfig(self, filepath):
        if filepath is not None:
            # check if model file is in pandaModelPath
            filepath = str(Filename.fromOsSpecific(filepath))

            # add the model path to the panda-path
            pandaPath = None
            from pandac.PandaModules import getModelPath
            for searchPath in str(getModelPath()).split():
                if searchPath == filepath:
                    pandaPath = searchPath
            if pandaPath is None:
                pandaPath = '/'.join(filepath.split('/')[:-1])
                from pandac.PandaModules import getModelPath
                getModelPath().appendPath(pandaPath)

        self.particleFilename = filepath
        try:
            #Start of the code from steam.ptf
            self.particleSystem.loadConfig(Filename(filepath))
            self.setFilepath(filepath)
        except:
            print "W: particleSystemWrapper.setParticleConfig: Error loading file"
            print "  -", filepath
            traceback.print_exc()

            print "  - Creating dummy particle Effect"
            # create new one if loading failed (particlepanel requires at least one particle)
            particles = Particles()
            particles.setBirthRate(0.02)
            particles.setLitterSize(10)
            particles.setLitterSpread(0)
            particles.setFactory("PointParticleFactory")
            particles.setRenderer("PointParticleRenderer")
            particles.setEmitter("SphereVolumeEmitter")
            particles.enable()
            self.particleSystem.addParticles(particles)
            self.clearFilepath()
        #Sets particles to birth relative to the teapot, but to render at toplevel
        self.particleSystem.start(self.getNodepath())

        # a bugfix, somewhere must be some color assigned to most nodes, i dont know why
        # this looks very bad on particle systems
        self.getNodepath().setColorOff(0)
def makeBundle(startDir):
    fstartDir = Filename.fromOsSpecific(startDir)

    # Search for panda3d_mac along $PATH.
    path = DSearchPath()
    if 'PATH' in os.environ:
        path.appendPath(os.environ['PATH'])
    path.appendPath(os.defpath)
    panda3d_mac = path.findFile('panda3d_mac')
    if not panda3d_mac:
        raise StandardError, "Couldn't find panda3d_mac on path."

    # Construct a search path to look for the images.
    search = DSearchPath()

    # First on the path: an explicit $PLUGIN_IMAGES env var.
    if ExecutionEnvironment.hasEnvironmentVariable('PLUGIN_IMAGES'):
        search.appendDirectory(Filename.expandFrom('$PLUGIN_IMAGES'))

    # Next on the path: the models/plugin_images directory within the
    # current directory.
    search.appendDirectory('models/plugin_images')

    # Finally on the path: models/plugin_images within the model
    # search path.
    for dir in getModelPath().getDirectories():
        search.appendDirectory(Filename(dir, 'plugin_images'))

    # Now find the icon file on the above search path.
    icons = search.findFile('panda3d.icns')
    if not icons:
        raise StandardError, "Couldn't find panda3d.icns on model-path."

    # Generate the bundle directory structure
    rootFilename = Filename(fstartDir)
    bundleFilename = Filename(rootFilename, 'Panda3D.app')
    if os.path.exists(bundleFilename.toOsSpecific()):
        shutil.rmtree(bundleFilename.toOsSpecific())

    plistFilename = Filename(bundleFilename, 'Contents/Info.plist')
    plistFilename.makeDir()
    exeFilename = Filename(bundleFilename, 'Contents/MacOS/panda3d_mac')
    exeFilename.makeDir()
    iconFilename = Filename(bundleFilename, 'Contents/Resources/panda3d.icns')
    iconFilename.makeDir()

    # Copy in Info.plist, the icon file, and the compiled executable.
    shutil.copyfile(Filename(fstartDir, "panda3d_mac.plist").toOsSpecific(), plistFilename.toOsSpecific())
    shutil.copyfile(icons.toOsSpecific(), iconFilename.toOsSpecific())
    print panda3d_mac, exeFilename
    shutil.copyfile(panda3d_mac.toOsSpecific(), exeFilename.toOsSpecific())
    os.chmod(exeFilename.toOsSpecific(), 0755)

    # All done!
    bundleFilename.touch()
    print bundleFilename.toOsSpecific()
Ejemplo n.º 10
0
    def initPackedAppEnvironment(self):
        """ This function sets up the Python environment suitably for
        running a packed app.  It should only run once in any given
        session (and it includes logic to ensure this). """

        if self.packedAppEnvironmentInitialized:
            return

        self.packedAppEnvironmentInitialized = True

        vfs = VirtualFileSystem.getGlobalPtr()

        # Now set up Python to import this stuff.
        VFSImporter.register()
        sys.path.append(self.multifileRoot)

        # Make sure that $MAIN_DIR is set to the p3d root before we
        # start executing the code in this file.
        ExecutionEnvironment.setEnvironmentVariable("MAIN_DIR", Filename(self.multifileRoot).toOsSpecific())

        # Put our root directory on the model-path, too.
        getModelPath().appendDirectory(self.multifileRoot)

        if not self.trueFileIO:
            # Replace the builtin open and file symbols so user code will get
            # our versions by default, which can open and read files out of
            # the multifile.
            __builtin__.file = file.file
            __builtin__.open = file.open
            __builtin__.execfile = file.execfile
            os.listdir = file.listdir
            os.walk = file.walk
            os.path.join = file.join
            os.path.isfile = file.isfile
            os.path.isdir = file.isdir
            os.path.exists = file.exists
            os.path.lexists = file.lexists
            os.path.getmtime = file.getmtime
            os.path.getsize = file.getsize
            sys.modules['glob'] = glob

        self.checkDiskUsage()
Ejemplo n.º 11
0
    def setSound(self, soundFilepath):
        # if there is already a model defined, remove it
        if self.soundEffect is not None:
            self.soundEffect.remove()

        if soundFilepath is not None:
            filepath = str(Filename.fromOsSpecific(soundFilepath))
            # add the model path to the panda-path
            pandaPath = None
            from pandac.PandaModules import getModelPath
            for searchPath in str(getModelPath()).split():
                if searchPath == filepath:
                    pandaPath = searchPath
            if pandaPath is None:
                pandaPath = '/'.join(filepath.split('/')[:-1])
                from pandac.PandaModules import getModelPath
                getModelPath().appendPath(pandaPath)

            # the path to the model we handle
            self.soundFilepath = soundFilepath
            self.setFilepath(soundFilepath)
            # load the model
            self.soundEffect = soundManager.get3dManager().loadSfx(
                soundFilepath)

        # if the model loading fails or no path given, use a dummy object
        if self.soundEffect is None:
            print "W: NodePathWrapper.setModel: model could not be loaded, loading dummy"
            self.soundEffect = soundManager.get3dManager().loadSfx(
                SOUND_NOT_FOUND_SOUND)
        # make the model visible
        soundManager.get3dManager().attachSoundToObject(
            self.soundEffect, self.getNodepath())

        self.soundEffect.setLoop(True)
        self.soundEffect.play()
        soundManager.get3dManager().setSoundVelocityAuto(self.soundEffect)
Ejemplo n.º 12
0
 def __init__(self):
   # Disable Panda's base camera mover
   base.disableMouse()
   base.setBackgroundColor(0,0,0,0)
   self.state = Game.STATE_INITIALIZING
   # contains a list of the ships in game
   self.ships = None
   self.players = None
   self.bullets = None
   self.stars = None
   self.planet = None
   self.time = 0.0
   self.isListening = False
   getModelPath().prependDirectory( Filename('./media/') )
   
   self.physWorld = OdeWorld()
   self.physWorld.setGravity(0, 0, 0)
   self.physWorld.initSurfaceTable(1)
   self.physWorld.setSurfaceEntry(
     0,
     0,
     1.0, # u
     .35, # elasticity
     .01, # minimum threshold for physical movement
     .01, #
     .00000001, # softening
     .01, #
     .01) # dampening
   
   self.physSpace = OdeHashSpace()
   self.winnerText = None
   self.gameFrames = 0
   self.lastWarp = 0
   self.cameraMode = Game.CAMERA_MODE_GAME
   self.lastCameraPos = None
   self.pause = False
Ejemplo n.º 13
0
    def __init__(self):
        # Disable Panda's base camera mover
        base.disableMouse()
        base.setBackgroundColor(0, 0, 0, 0)
        self.state = Game.STATE_INITIALIZING
        # contains a list of the ships in game
        self.ships = None
        self.players = None
        self.bullets = None
        self.stars = None
        self.planet = None
        self.time = 0.0
        self.isListening = False
        getModelPath().prependDirectory(Filename('./media/'))

        self.physWorld = OdeWorld()
        self.physWorld.setGravity(0, 0, 0)
        self.physWorld.initSurfaceTable(1)
        self.physWorld.setSurfaceEntry(
            0,
            0,
            1.0,  # u
            .35,  # elasticity
            .01,  # minimum threshold for physical movement
            .01,  #
            .00000001,  # softening
            .01,  #
            .01)  # dampening

        self.physSpace = OdeHashSpace()
        self.winnerText = None
        self.gameFrames = 0
        self.lastWarp = 0
        self.cameraMode = Game.CAMERA_MODE_GAME
        self.lastCameraPos = None
        self.pause = False
Ejemplo n.º 14
0
    def loaderPhaseChecker(self, path, loaderOptions):
        # See if this path is in the phase system
        # It should look something like "phase_5/models/char/joe"

        # HACK: let's try .bam if it has no extension
        # Other way to do this: after we load the model, call model.node().getFullpath()
        if ("audio/" in path):
            return 1
        file = Filename(path)
        if not file.getExtension():
            file.setExtension('bam')
        mp = getModelPath()
        path = mp.findFile(file).cStr()
        if not path:
            return

        match = re.match(".*phase_([^/]+)/", path)
        if (not match):
            if ('dmodels' in path):
                return
            else:
                self.errorAccumulatorBuffer += "file not in phase (%s, %s)\n" % (
                    file, path)
                return

        basePhase = float(match.groups()[0])
        if (not launcher.getPhaseComplete(basePhase)):
            self.errorAccumulatorBuffer += "phase is not loaded for this model %s\n" % (
                path)
        #grab the model
        model = loader.loader.loadSync(Filename(path), loaderOptions)

        if (model):
            model = NodePath(model)
            for tex in model.findAllTextures():
                texPath = tex.getFullpath().cStr()
                match = re.match(".*phase_([^/]+)/", texPath)
                if (match):
                    texPhase = float(match.groups()[0])
                    if (texPhase > basePhase):
                        self.errorAccumulatorBuffer += "texture phase is higher than the models (%s, %s)\n" % (
                            path, texPath)
Ejemplo n.º 15
0
import os
import sys

# Initialize ihooks importer On the production servers, we run genPyCode -n
# meaning no squeeze, so nobody else does this. When we squeeze, the
# unpacker does this for us and it does not hurt to do in either case.
import ihooks
ihooks.install()

if os.getenv('TTMODELS'):
    from pandac.PandaModules import getModelPath, Filename
    # In the publish environment, TTMODELS won't be on the model
    # path by default, so we always add it there.  In the dev
    # environment, it'll be on the model path already, but it
    # doesn't hurt to add it again.
    getModelPath().appendDirectory(Filename.expandFrom("$TTMODELS/built"))

from direct.showbase.PythonUtil import *
from otp.uberdog.UberDogGlobal import *
from toontown.coderedemption import TTCodeRedemptionConsts
from toontown.uberdog.ToontownUberDog import ToontownUberDog
from toontown.uberdog import PartiesUdConfig

print "Initializing the Toontown UberDog (Uber Distributed Object Globals server)..."

uber.mdip = uber.config.GetString("msg-director-ip", "localhost")
uber.mdport = uber.config.GetInt("msg-director-port", 6666)

uber.esip = uber.config.GetString("event-server-ip", "localhost")
uber.esport = uber.config.GetInt("event-server-port", 4343)
Ejemplo n.º 16
0
    def installPackage(self, appRunner):
        """ Mounts the package and sets up system paths so it becomes
        available for use.  Returns true on success, false on failure. """

        assert self.hasPackage
        if self.installed:
            # Already installed.
            return True
        assert self not in appRunner.installedPackages

        mfPathname = Filename(self.getPackageDir(),
                              self.uncompressedArchive.filename)
        mf = Multifile()
        if not mf.openRead(mfPathname):
            self.notify.warning("Couldn't open %s" % (mfPathname))
            return False

        # We mount it under its actual location on disk.
        root = self.getPackageDir().cStr()

        vfs = VirtualFileSystem.getGlobalPtr()
        vfs.mount(mf, root, vfs.MFReadOnly)

        # Add this to the Python search path, if it's not already
        # there.  We have to take a bit of care to check if it's
        # already there, since there can be some ambiguity in
        # os-specific path strings.
        osRoot = self.getPackageDir().toOsSpecific()
        foundOnPath = False
        for p in sys.path:
            if osRoot == p:
                # Already here, exactly.
                foundOnPath = True
                break
            elif osRoot == Filename.fromOsSpecific(p).toOsSpecific():
                # Already here, with some futzing.
                foundOnPath = True
                break

        if not foundOnPath:
            # Not already here; add it.
            sys.path.append(osRoot)

        # Put it on the model-path, too.  We do this indiscriminantly,
        # because the Panda3D runtime won't be adding things to the
        # model-path, so it shouldn't be already there.
        getModelPath().appendDirectory(self.getPackageDir())

        # Set the environment variable to reference the package root.
        envvar = '%s_ROOT' % (self.packageName.upper())
        ExecutionEnvironment.setEnvironmentVariable(envvar, osRoot)

        # Add the package root to the system paths.
        if sys.platform.startswith('win'):
            path = os.environ.get('PATH', '')
            os.environ['PATH'] = "%s;%s" % (osRoot, path)
        else:
            path = os.environ.get('PATH', '')
            os.environ['PATH'] = "%s:%s" % (osRoot, path)
            path = os.environ.get('LD_LIBRARY_PATH', '')
            os.environ['LD_LIBRARY_PATH'] = "%s:%s" % (osRoot, path)

        if sys.platform == "darwin":
            path = os.environ.get('DYLD_LIBRARY_PATH', '')
            os.environ['DYLD_LIBRARY_PATH'] = "%s:%s" % (osRoot, path)

        # Now that the environment variable is set, read all of the
        # prc files in the package.
        appRunner.loadMultifilePrcFiles(mf, self.getPackageDir())

        # Also, find any toplevel Python packages, and add these as
        # shared packages.  This will allow different packages
        # installed in different directories to share Python files as
        # if they were all in the same directory.
        for filename in mf.getSubfileNames():
            if filename.endswith('/__init__.pyc') or \
               filename.endswith('/__init__.pyo') or \
               filename.endswith('/__init__.py'):
                components = filename.split('/')[:-1]
                moduleName = '.'.join(components)
                VFSImporter.sharedPackages[moduleName] = True

        # Fix up any shared directories so we can load packages from
        # disparate locations.
        VFSImporter.reloadSharedPackages()

        self.installed = True
        appRunner.installedPackages.append(self)

        self.markUsed()

        return True
Ejemplo n.º 17
0
def runPackedApp(args):
    if not args:
        raise ArgumentError, "No Panda app specified.  Use:\npython RunAppMF.py app.mf"

    vfs = VirtualFileSystem.getGlobalPtr()

    fname = Filename.fromOsSpecific(args[0])
    if not vfs.exists(fname):
        raise ArgumentError, "No such file: %s" % (args[0])

    mf = Multifile()
    if not mf.openRead(fname):
        raise ArgumentError, "Not a Panda Multifile: %s" % (args[0])

    # Clear *all* the mount points, including "/", so that we no
    # longer access the disk directly.
    vfs.unmountAll()

    # Mount the Multifile under /mf, by convention, and make that our
    # "current directory".
    vfs.mount(mf, MultifileRoot, vfs.MFReadOnly)
    vfs.chdir(MultifileRoot)

    # Make sure the directories on our standard Python path are mounted
    # read-only, so we can still load Python.
    for dirname in sys.path:
        vfs.mount(dirname, dirname, vfs.MFReadOnly)

    # Also mount some standard directories read-write (temporary and
    # app-data directories).
    tdir = Filename.temporary('', '')
    for dirname in set([
            tdir.getDirname(),
            Filename.getTempDirectory().cStr(),
            Filename.getUserAppdataDirectory().cStr(),
            Filename.getCommonAppdataDirectory().cStr()
    ]):
        vfs.mount(dirname, dirname, 0)

    # Now set up Python to import this stuff.
    VFSImporter.register()
    sys.path = [MultifileRoot] + sys.path

    # Put our root directory on the model-path and prc-path, too.
    getModelPath().prependDirectory(MultifileRoot)

    # Load the implicit App.prc file.
    loadPrcFileData(AppPrcFilename, AppPrc)

    # Load any prc files in the root.  We have to load them
    # explicitly, since the ConfigPageManager can't directly look
    # inside the vfs.
    for f in vfs.scanDirectory(MultifileRoot):
        if f.getFilename().getExtension() == 'prc':
            data = f.readFile(True)
            loadPrcFileData(f.getFilename().cStr(), data)

    # Replace the builtin open and file symbols so user code will get
    # our versions by default, which can open and read files out of
    # the multifile.
    __builtin__.file = file.file
    __builtin__.open = file.open
    os.listdir = file.listdir
    os.walk = file.walk

    import main
    if hasattr(main, 'main') and callable(main.main):
        main.main()
 def setScene(self, relativePath):
   # load the scene
   
   def loadRecursiveChildrens(eggParentData, parent, transform, filepath, loadedObjects):
     if type(eggParentData) == EggData:
       # search the childrens
       for childData in eggParentData.getChildren():
         # search the children
         parent, loadedObjects = loadRecursiveChildrens(childData, parent, transform, filepath, loadedObjects)
     
     elif type(eggParentData) == EggGroup:
       
       # a eggGroup modifies the matrix of the model
       if type(eggParentData) == EggGroup:
         # convert the matrix from double to single
         mat4d = eggParentData.getTransform3d()
         mat4 = Mat4()
         for x in xrange(4):
             for y in xrange(4):
                 mat4.setCell(x, y, mat4d.getCell(x,y))
         # multiply the matrix for later applial onto model
         transform = mat4 * transform
       
       if eggParentData.hasTag(MODEL_WRAPPER_TYPE_TAG):
         # if the eggData contains a tag that specifies the type of the object
         wrapperType = eggParentData.getTag(MODEL_WRAPPER_TYPE_TAG)
         wrapperTypeDecap = wrapperType[0].lower() + wrapperType[1:]
         try:
           # import the module responsible for handling the data
           module = __import__('core.modules.p%s' % wrapperType, globals(), locals(), [wrapperType], -1)
           # load the eggParentData using the module
           #print "I: EditorClass.loadEggModelsFile: parent", wrapperType, parent 
           object = getattr(module, wrapperType).loadFromEggGroup(eggParentData, parent, filepath)
           # append loaded object to list
           loadedObjects.append([object, eggParentData])
         except:
           print "W: EditorClass.loadEggModelsFile: unknown or invalid entry"
           traceback.print_exc()
           print "W: --- start of invalid data ---"
           print eggParentData
           print "W: --- end of invalid data ---"
           #object = parent.attachNewNode('%s-failed' % wrapperType)
           object = None
         
         if object is not None:
           if object.hasNodepath():
             # apply the transformation on the object
             object.getNodepath().setMat(transform)
             transform = Mat4.identMat()
           # if it contains additional childrens recurse into them
           for childData in eggParentData.getChildren()[1:]:
             # search the children
             loadRecursiveChildrens(childData, object, transform, filepath, loadedObjects)
         else:
           print "E: core.EditorClass.loadEggModelsFile: no object returned (most likely error in module)"
           print "  -", wrapperType
       else:
         # search for childrens
         for childData in eggParentData.getChildren():
           # search the children
           parent, loadedObjects = loadRecursiveChildrens(childData, parent, transform, filepath, loadedObjects)
     else:
       if DEBUG:
         print "W: EditorApp.loadEggModelsFile.loadRecursiveChildrens:"
         print "   - skipping unkown eggData", type(eggParentData)
     
     return parent, loadedObjects
   
   if relativePath != None and relativePath != '' and relativePath != ' ':
     p3filename = Filename.fromOsSpecific(relativePath)
     p3filename.makeAbsolute()
     # destroy old models
     #self.destroyAllModels()
     
     eggData = EggData()
     eggData.read(p3filename)
     
     # the absolute path of the file we load, referenced files are relative
     # to this path
     filepath = p3filename.getDirname()
     
     # store the full filepath of the model
     self.setFilepath(str(p3filename))
     # add the path to the model-path
     from pandac.PandaModules import getModelPath
     getModelPath().appendPath(filepath)
     # read the eggData
     parent, loadedObjects = loadRecursiveChildrens(eggData, self, Mat4.identMat(), filepath, list())
     
     for objectInstance, eggData in loadedObjects:
       objectInstance.loadFromData(eggData, filepath)
     
     #parent.getNodepath().flattenStrong()
     
     # refresh the scenegraphbrowser
     messenger.send(EVENT_SCENEGRAPH_REFRESH)
   
   # relative path to editor / or parent scene
   self.relativePath = relativePath # examples/sample.egs
   # absolute path of the file (different on every computer)
   self.fullPath = posixpath.abspath(relativePath) # /home/user/editor/example/samples.egs
   # folder where the file is at
   self.dirname = posixpath.dirname(self.fullPath) # /home/user/editor/example/
   print "I: SceneNodeWrapper.setScene: loaded"
   print "  - relativePath", self.relativePath
   print "  - fullPath", self.fullPath
   print "  - relativePath", self.relativePath
Ejemplo n.º 19
0
    def installPackage(self, appRunner):
        """ Mounts the package and sets up system paths so it becomes
        available for use.  Returns true on success, false on failure. """

        assert self.hasPackage
        if self.installed:
            # Already installed.
            return True
        assert self not in appRunner.installedPackages

        mfPathname = Filename(self.getPackageDir(), self.uncompressedArchive.filename)
        mf = Multifile()
        if not mf.openRead(mfPathname):
            self.notify.warning("Couldn't open %s" % (mfPathname))
            return False

        # We mount it under its actual location on disk.
        root = self.getPackageDir().cStr()

        vfs = VirtualFileSystem.getGlobalPtr()
        vfs.mount(mf, root, vfs.MFReadOnly)

        # Add this to the Python search path, if it's not already
        # there.  We have to take a bit of care to check if it's
        # already there, since there can be some ambiguity in
        # os-specific path strings.
        osRoot = self.getPackageDir().toOsSpecific()
        foundOnPath = False
        for p in sys.path:
            if osRoot == p:
                # Already here, exactly.
                foundOnPath = True
                break
            elif osRoot == Filename.fromOsSpecific(p).toOsSpecific():
                # Already here, with some futzing.
                foundOnPath = True
                break

        if not foundOnPath:
            # Not already here; add it.
            sys.path.append(osRoot)

        # Put it on the model-path, too.  We do this indiscriminantly,
        # because the Panda3D runtime won't be adding things to the
        # model-path, so it shouldn't be already there.
        getModelPath().appendDirectory(self.getPackageDir())

        # Set the environment variable to reference the package root.
        envvar = '%s_ROOT' % (self.packageName.upper())
        ExecutionEnvironment.setEnvironmentVariable(envvar, osRoot)

        # Now that the environment variable is set, read all of the
        # prc files in the package.
        appRunner.loadMultifilePrcFiles(mf, self.getPackageDir())

        # Also, find any toplevel Python packages, and add these as
        # shared packages.  This will allow different packages
        # installed in different directories to share Python files as
        # if they were all in the same directory.
        for filename in mf.getSubfileNames():
            if filename.endswith('/__init__.pyc') or \
               filename.endswith('/__init__.pyo') or \
               filename.endswith('/__init__.py'):
                components = filename.split('/')[:-1]
                moduleName = '.'.join(components)
                VFSImporter.sharedPackages[moduleName] = True

        # Fix up any shared directories so we can load packages from
        # disparate locations.
        VFSImporter.reloadSharedPackages()

        self.installed = True
        appRunner.installedPackages.append(self)

        self.markUsed()

        return True
Ejemplo n.º 20
0
    
    return sc

if __name__ == '__main__':
    import direct.directbase.DirectStart
    
    print 'MAXIMUM # OF TEXTURE STAGES (SHADOWS + TEXTURES) :',base.win.getGsg().getMaxTextureStages()
    print '''if the texture count on the objects you use,
is the same like the texture stages, you cant add shadows to them'''

    # change the model paths
    from pandac.PandaModules import getModelPath
    from pandac.PandaModules import getTexturePath
    from pandac.PandaModules import getSoundPath 
    modelPath = '/usr/local/panda:.'
    getModelPath( ).appendPath( modelPath )
    getTexturePath( ).appendPath( modelPath )
    getSoundPath( ).appendPath( modelPath ) 
    
    camera.setPos(55,-30,25)
    camera.lookAt(render)
    camera.setP(camera,3)
    cameraMat=Mat4(camera.getMat())
    cameraMat.invertInPlace()
    base.mouseInterfaceNode.setMat(cameraMat)
    
    # load the models
    # shadow casting object
    modelNp = loader.loadModelCopy( 'models/panda.egg' )
    modelNp.reparentTo( render )
    # shadow receiving object