コード例 #1
0
ファイル: common.py プロジェクト: pmp-p/panda3d-interrogator
def get_panda_lib_path():
    """ Returns the path to the panda3d libraries """
    if is_windows():
        return find_in_sdk("lib", "libpanda.lib")
    elif is_linux() or is_macos() or is_freebsd():
        return dirname(ExecutionEnvironment.get_dtool_name())
    raise NotImplementedError("Unsupported OS")
コード例 #2
0
ファイル: common.py プロジェクト: tobspr/P3DModuleBuilder
def get_panda_lib_path():
    """ Returns the path to the panda3d libraries """
    if is_windows():
        return first_existing_path([join(get_panda_sdk_path(), "lib")], "libpanda.lib")
    elif is_linux():
        return dirname(ExecutionEnvironment.get_dtool_name())
    raise NotImplementedError("Unsupported OS")
コード例 #3
0
def get_panda_lib_path():
    """ Returns the path to the panda3d libraries """
    if is_windows():
        return first_existing_path([join(get_panda_sdk_path(), "lib")],
                                   "libpanda.lib")
    elif is_linux():
        return dirname(ExecutionEnvironment.get_dtool_name())
    raise NotImplementedError("Unsupported OS")
コード例 #4
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 Exception("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 Exception("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('%s %s' % (panda3d_mac, exeFilename))
    shutil.copyfile(panda3d_mac.toOsSpecific(), exeFilename.toOsSpecific())
    os.chmod(exeFilename.toOsSpecific(), 0o755)

    # All done!
    bundleFilename.touch()
    print(bundleFilename.toOsSpecific())
コード例 #5
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.
            builtins.open = file.open
            if sys.version_info < (3, 0):
                builtins.file = file.open
                builtins.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()
コード例 #6
0
    def __init__(self):
        rootdir = ExecutionEnvironment.getEnvironmentVariable("MAIN_DIR")
        self.classConfigurationCSV = os.path.join(rootdir, "config",
                                                  "playerClasses.csv")
        self.classDefinitions = []

        with open(self.classConfigurationCSV, newline='') as csvfile:
            for row in csv.DictReader(csvfile):
                self.classDefinitions.append(row)
コード例 #7
0
ファイル: AppRunner.py プロジェクト: chongzhang5097/panda3d
def dummyAppRunner(tokens=[], argv=None):
    """ This function creates a dummy global AppRunner object, which
    is useful for testing running in a packaged environment without
    actually bothering to package up the application.  Call this at
    the start of your application to enable it.

    It places the current working directory under /mf, as if it were
    mounted from a packed multifile.  It doesn't convert egg files to
    bam files, of course; and there are other minor differences from
    running in an actual packaged environment.  But it can be a useful
    first-look sanity check. """

    if AppRunnerGlobal.appRunner:
        print("Already have AppRunner, not creating a new one.")
        return AppRunnerGlobal.appRunner

    appRunner = AppRunner()
    appRunner.dummy = True
    AppRunnerGlobal.appRunner = appRunner

    platform = PandaSystem.getPlatform()
    version = PandaSystem.getPackageVersionString()
    hostUrl = PandaSystem.getPackageHostUrl()

    if platform.startswith('win'):
        rootDir = Filename(Filename.getUserAppdataDirectory(), 'Panda3D')
    elif platform.startswith('osx'):
        rootDir = Filename(Filename.getHomeDirectory(),
                           'Library/Caches/Panda3D')
    else:
        rootDir = Filename(Filename.getHomeDirectory(), '.panda3d')

    appRunner.rootDir = rootDir
    appRunner.logDirectory = Filename(rootDir, 'log')

    # Of course we will have the panda3d application loaded.
    appRunner.addPackageInfo('panda3d', platform, version, hostUrl)

    appRunner.tokens = tokens
    appRunner.tokenDict = dict(tokens)
    if argv is None:
        argv = sys.argv
    appRunner.argv = argv
    appRunner.altHost = appRunner.tokenDict.get('alt_host', None)

    appRunner.p3dInfo = None
    appRunner.p3dPackage = None

    # Mount the current directory under the multifileRoot, as if it
    # were coming from a multifile.
    cwd = ExecutionEnvironment.getCwd()
    vfs = VirtualFileSystem.getGlobalPtr()
    vfs.mount(cwd, appRunner.multifileRoot, vfs.MFReadOnly)

    appRunner.initPackedAppEnvironment()

    return appRunner
コード例 #8
0
ファイル: AppRunner.py プロジェクト: Just-D/panda3d
def dummyAppRunner(tokens = [], argv = None):
    """ This function creates a dummy global AppRunner object, which
    is useful for testing running in a packaged environment without
    actually bothering to package up the application.  Call this at
    the start of your application to enable it.

    It places the current working directory under /mf, as if it were
    mounted from a packed multifile.  It doesn't convert egg files to
    bam files, of course; and there are other minor differences from
    running in an actual packaged environment.  But it can be a useful
    first-look sanity check. """

    if AppRunnerGlobal.appRunner:
        print("Already have AppRunner, not creating a new one.")
        return AppRunnerGlobal.appRunner

    appRunner = AppRunner()
    appRunner.dummy = True
    AppRunnerGlobal.appRunner = appRunner

    platform = PandaSystem.getPlatform()
    version = PandaSystem.getPackageVersionString()
    hostUrl = PandaSystem.getPackageHostUrl()

    if platform.startswith('win'):
        rootDir = Filename(Filename.getUserAppdataDirectory(), 'Panda3D')
    elif platform.startswith('osx'):
        rootDir = Filename(Filename.getHomeDirectory(), 'Library/Caches/Panda3D')
    else:
        rootDir = Filename(Filename.getHomeDirectory(), '.panda3d')

    appRunner.rootDir = rootDir
    appRunner.logDirectory = Filename(rootDir, 'log')

    # Of course we will have the panda3d application loaded.
    appRunner.addPackageInfo('panda3d', platform, version, hostUrl)

    appRunner.tokens = tokens
    appRunner.tokenDict = dict(tokens)
    if argv is None:
        argv = sys.argv
    appRunner.argv = argv
    appRunner.altHost = appRunner.tokenDict.get('alt_host', None)

    appRunner.p3dInfo = None
    appRunner.p3dPackage = None

    # Mount the current directory under the multifileRoot, as if it
    # were coming from a multifile.
    cwd = ExecutionEnvironment.getCwd()
    vfs = VirtualFileSystem.getGlobalPtr()
    vfs.mount(cwd, appRunner.multifileRoot, vfs.MFReadOnly)

    appRunner.initPackedAppEnvironment()

    return appRunner
コード例 #9
0
ファイル: make_osx_bundle.py プロジェクト: Astron/panda3d
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 Exception("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 Exception("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('%s %s' % (panda3d_mac, exeFilename))
    shutil.copyfile(panda3d_mac.toOsSpecific(), exeFilename.toOsSpecific())
    os.chmod(exeFilename.toOsSpecific(), 0o755)

    # All done!
    bundleFilename.touch()
    print(bundleFilename.toOsSpecific())
コード例 #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.
            builtins.open = file.open
            if sys.version_info < (3, 0):
                builtins.file = file.open
                builtins.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()
コード例 #11
0
    def __init__(self, enemyFieldName, difficultyNameID):
        rootdir = ExecutionEnvironment.getEnvironmentVariable("MAIN_DIR")
        self.enemyConfigurationCSV = os.path.join(rootdir, "config",
                                                  "enemies.csv")
        self.enemyDefinitions = []

        # create the enemies dice
        self.dice = SixSidedDice()

        self.enemyFieldName = enemyFieldName
        self.difficultyName = RoomGlobals.DIFFICULTIES_AS_NAMES[
            difficultyNameID]

        # load the csv file data
        with open(self.enemyConfigurationCSV, newline='') as csvfile:
            for row in csv.DictReader(csvfile):
                self.enemyDefinitions.append(row)

        self.numEnemies = self.getNumEnemies()
コード例 #12
0
ファイル: main.py プロジェクト: DiamondsBattle/panda3d-openvr
 def init_action(self):
     main_dir = ExecutionEnvironment.getEnvironmentVariable("MAIN_DIR")
     filename = os.path.join(main_dir, "ralph_actions.json")
     self.load_action_manifest(filename, "/actions/ralph")
     self.action_haptic_left = self.vr_input.getActionHandle(
         '/actions/ralph/out/Haptic_Left')
     self.source_left = self.vr_input.getInputSourceHandle(
         '/user/hand/left')
     self.action_pose_left = self.vr_input.getActionHandle(
         '/actions/ralph/in/Hand_Left')
     self.action_haptic_right = self.vr_input.getActionHandle(
         '/actions/ralph/out/Haptic_Right')
     self.source_right = self.vr_input.getInputSourceHandle(
         '/user/hand/right')
     self.action_pose_right = self.vr_input.getActionHandle(
         '/actions/ralph/in/Hand_Right')
     self.action_trackpad_click = self.vr_input.getActionHandle(
         '/actions/ralph/in/trackpadclick')
     self.action_trackpad_pos = self.vr_input.getActionHandle(
         '/actions/ralph/in/trackpadpos')
コード例 #13
0
ファイル: main.py プロジェクト: zurgeg/panda3d-openvr
 def init_action(self):
     main_dir = ExecutionEnvironment.getEnvironmentVariable("MAIN_DIR")
     filename = os.path.join(main_dir, "demo_actions.json")
     self.load_action_manifest(filename, "/actions/demo")
     self.action_haptic_left = self.vr_input.getActionHandle(
         '/actions/demo/out/Haptic_Left')
     self.source_left = self.vr_input.getInputSourceHandle(
         '/user/hand/left')
     self.action_pose_left = self.vr_input.getActionHandle(
         '/actions/demo/in/Hand_Left')
     self.action_haptic_right = self.vr_input.getActionHandle(
         '/actions/demo/out/Haptic_Right')
     self.source_right = self.vr_input.getInputSourceHandle(
         '/user/hand/right')
     self.action_pose_right = self.vr_input.getActionHandle(
         '/actions/demo/in/Hand_Right')
     self.action_left_trigger = self.vr_input.getActionHandle(
         '/actions/demo/in/left_trigger')
     self.action_right_trigger = self.vr_input.getActionHandle(
         '/actions/demo/in/right_trigger')
コード例 #14
0
ファイル: main.py プロジェクト: el-dee/panda3d-openvr
    def __init__(self, ovr):
        self.ovr = ovr

        # Setup the application manifest, it will identify and configure the app
        # We force it in case it has changed.
        main_dir = ExecutionEnvironment.getEnvironmentVariable("MAIN_DIR")
        ovr.identify_application(os.path.join(main_dir, "skeleton.vrmanifest"),
                                 "p3dopenvr.demo.skeleton",
                                 force=True)

        # Load the actions manifest, it must be the same as the manifest referenced in the application manifest
        ovr.load_action_manifest(
            os.path.join(main_dir, "../manifest/actions.json"))

        # Use the '/actions/default' action set. This action set will be updated each frame
        ovr.add_action_set("/actions/default")

        # Get the handle of the action '/actions/default/in/Pose'. This hande will be used to update the position of the hands.
        hands_pose = ovr.vr_input.getActionHandle('/actions/default/in/Pose')

        # Get the handle of the skeleton actions. These handle will be used to update the
        # animation of the hands
        left_hand_skeleton_input = ovr.vr_input.getActionHandle(
            '/actions/default/in/SkeletonLeftHand')
        right_hand_skeleton_input = ovr.vr_input.getActionHandle(
            '/actions/default/in/SkeletonRightHand')

        # Create the representation of the left hand and attach a skinned hand model to it
        self.left_hand = LeftHand(ovr, "models/vr_glove_left_model.glb",
                                  hands_pose)
        self.left_hand.set_skeleton(
            DefaultLeftHandSkeleton(ovr, left_hand_skeleton_input))

        # Create the representation of the left hand and attach a skinned hand model to it
        self.right_hand = RightHand(ovr, "models/vr_glove_right_model.glb",
                                    hands_pose)
        self.right_hand.set_skeleton(
            DefaultRightHandSkeleton(ovr, right_hand_skeleton_input))

        # Register the update task with the correct sort number
        taskMgr.add(self.update, sort=ovr.get_update_task_sort())
コード例 #15
0
ファイル: main.py プロジェクト: el-dee/panda3d-openvr
    def __init__(self, ovr):
        self.ovr = ovr

        # Setup the application manifest, it will identify and configure the app
        # We force it in case it has changed.
        main_dir = ExecutionEnvironment.getEnvironmentVariable("MAIN_DIR")
        ovr.identify_application(os.path.join(main_dir, "actions.vrmanifest"),
                                 "p3dopenvr.demo.actions",
                                 force=True)

        # Load the actions manifest, it must be the same as the manifest referenced in the application manifest
        ovr.load_action_manifest(
            os.path.join(main_dir, "../manifest/actions.json"))

        # Use the '/actions/default' action set. This action set will be updated each frame
        ovr.add_action_set("/actions/default")

        # Get the handle of the action '/actions/default/out/Haptic'. This hande will be used to trigger the haptic vibration.
        self.action_haptic = ovr.vr_input.getActionHandle(
            '/actions/default/out/Haptic')

        # Get the handle of the action '/actions/default/in/Pose'. This hande will be used to update the position of the hands.
        hands_pose = ovr.vr_input.getActionHandle('/actions/default/in/Pose')

        # Get the handle of the action '/actions/default/in/GrabGrip'. This hande will be used to retrieve the data of the action.
        self.action_grip = ovr.vr_input.getActionHandle(
            '/actions/default/in/GrabGrip')

        # Create the representation of the left hand and attach a simple box on it
        self.left_hand = LeftHand(ovr, "box", hands_pose)
        self.left_hand.model.set_scale(0.1)

        # Create the representation of the right hand and attach a simple box on it
        self.right_hand = RightHand(ovr, "box", hands_pose)
        self.right_hand.model.set_scale(0.1)

        # Register the update task with the correct sort number
        taskMgr.add(self.update, sort=ovr.get_update_task_sort())
コード例 #16
0
    def loadFGDFiles(self):
        """Reads the .fgd files specified in the config file"""

        self.fgd = Fgd()
        numVals = LEConfig.fgd_files.getNumUniqueValues()

        if numVals == 0:
            QtWidgets.QMessageBox.critical(
                None, LEGlobals.AppName,
                "No FGD files specified in local config!",
                QtWidgets.QMessageBox.Ok)
            sys.exit(1)

        vfs = VirtualFileSystem.getGlobalPtr()
        searchPath = getModelPath().getValue()

        for i in range(numVals):
            fgdFilename = LEConfig.fgd_files.getUniqueValue(i)
            fgdFilename = ExecutionEnvironment.expandString(fgdFilename)
            fgdFilename = Filename(fgdFilename)
            vfs.resolveFilename(fgdFilename, searchPath)
            fgd = FgdParse(fgdFilename.toOsSpecific())
            self.fgd.add_include(fgd)
コード例 #17
0
                if len(files) > 0:
                    return files[0]
        return None

    def find_texture(self, pattern):
        return self.find_file('textures', pattern)

    def find_model(self, pattern):
        return self.find_file('models', pattern)

    def find_data(self, pattern):
        return self.find_file('data', pattern)

    def find_script(self, pattern):
        return self.find_file('scripts', pattern)

    def find_font(self, pattern):
        return self.find_file('fonts', pattern)

    def find_shader(self, pattern):
        return self.find_file('shaders', pattern)

    def find_doc(self, pattern):
        return self.find_file('doc', pattern)


defaultDirContext = DirContext()
main_dir = ExecutionEnvironment.getEnvironmentVariable("MAIN_DIR")
defaultDirContext.add_all_path_auto(main_dir)
defaultDirContext.add_all_path(main_dir)
コード例 #18
0
ファイル: PackageInfo.py プロジェクト: colout/ansi_3d
    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()

        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
コード例 #19
0
ファイル: PackageInfo.py プロジェクト: Astron/panda3d
    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()

        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
コード例 #20
0
class ControlState(DirectObject):
    """Specific control state classes should inherit from this."""
    conf_parser = SafeConfigParser()
    f = Filename(EE.expandString("$MAIN_DIR/etc/keybindings.ini"))
    conf_parser.read(f.toOsSpecific())

    @classmethod
    def reloadKeybindings(cls, filenames="etc/keybindings.ini"):
        """Read the keybindings file again. Existing instances won't update
        until you call loadKeybindings() on them."""
        cls.conf_parser.read(filenames)

    def __init__(self):
        self.name = self.__class__.__name__
        self.paused = False
        self.active = False
        self.keymap = {}
        self.functionmap = {}
        self.requested_actions = set()

    def __repr__(self):
        t = "ControlState: " + self.name
        if self.paused: t += " (paused)"
        if not self.active: t += " (inactive)"
        t += "\nlistens to the following events:\n" + self.getAllAccepting()
        t += "\nkeymap:\n" + self.keymap
        t += "\nfunctionmap:\n" + self.functionmap
        t += "\nrequested actions:\n" + self.requested_actions
        t += "\n"
        return t

    def __str__(self):
        return self.name

    def loadKeybindings(self):
        """Overrides the hardcoded keymap with those found in the keybindings
        file (or owerwrites previously loaded ones). Only defined actions are
        overwritten - no extra actions are added from the keybindings file.
        """
        try:
            keys_from_file = ControlState.conf_parser.items(self.name)
            for a in self.keymap:
                for action, key in keys_from_file:
                    if a == action:
                        for k in map(str.strip, key.split(',')):
                            self.keymap[a] = k
        except NoSectionError:
            #notify.warning("".join("Keybindings for section {0} not found. ",
            #                      "Using built-in bindings").format(self.name))
            pass

    def activate(self):
        if self.active is True:
            return False
        #notify.info("Activating %s" % self.name)

        def assignKey(key, action):
            self.accept(key, self.requested_actions.add, [action])
            self.accept(key + "-up", self.requested_actions.discard, [action])
            if action in self.functionmap:
                self.accept(key, self.functionmap[action])

        for action, key in self.keymap.items():
            if isinstance(key, basestring):
                assignKey(key, action)
            elif isinstance(key, list):
                for k in key:
                    assignKey(k, action)

        self.loadKeybindings()

        for task in self.tasks:
            if callable(task):
                self.addTask(task, task.__name__, taskChain="world")
            else:
                self.addTask(*task, taskChain="world")

        self.active = True
        #ControlState.active_states.append(self)

    def deactivate(self):
        if self.active is False:
            return False
        #notify.info("Deactivating %s" % self.name)
        self.ignoreAll()
        self.requested_actions.clear()
        #for task in self.tasks:
        #    self.removeTask(task)
        #self.removeAllTasks()
        self.active = False
コード例 #21
0
options and starts the core finite state machine, followed by Panda's task
manager."""

import sys
import os

from panda3d.core import ExecutionEnvironment as EE
from panda3d.core import Filename

from options import options

# If we only need to print version, do this first and leave everything else
# untouched.
if options.print_version:
    try:
        print open(EE.expandString("$MAIN_DIR/VERSION")).read()
    except IOError:
        print "Version unknown. Can't find the VERSION file."
    sys.exit()

try:
    from pandac.PandaModules import loadPrcFile
    from pandac.PandaModules import Filename
except ImportError:
    print "It seems you haven't got Panda3D installed properly."
    sys.exit(1)
# Config file should be loaded as soon as possible.
# TODO(Nemesis#13): this must get smarter
loadPrcFile(EE.expandString("$MAIN_DIR/etc/azure.prc"))
from direct.showbase.ShowBase import ShowBase
コード例 #22
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()
コード例 #23
0
ファイル: main.py プロジェクト: el-dee/panda3d-openvr
    def __init__(self):
        # Set up the window, camera, etc.
        ShowBase.__init__(self)

        # Create and configure the VR environment

        self.ovr = P3DOpenVR()
        self.ovr.init(msaa=4)
        main_dir = ExecutionEnvironment.getEnvironmentVariable("MAIN_DIR")
        # Setup the application manifest, it will identify and configure the app
        # We force it in case it has changed.
        self.ovr.identify_application(os.path.join(main_dir,
                                                   "ralph.vrmanifest"),
                                      "p3dopenvr.demo.ralph",
                                      force=True)
        # Load the actions manifest, it must be the same as the manifest referenced in the application manifest
        self.ovr.load_action_manifest(
            os.path.join(main_dir, "manifest/actions.json"))
        # Use the '/actions/platformer' action set. This action set will be updated each frame
        self.ovr.add_action_set("/actions/platformer")
        # Get the handle of the action '/actions/platformer/in/Move'. This hande will be used to retrieve the data of the action.
        self.action_move = self.ovr.vr_input.getActionHandle(
            '/actions/platformer/in/Move')

        # Set the background color to black
        self.win.setClearColor((0, 0, 0, 1))

        # Post the instructions
        self.title = addTitle(
            "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.06, "[ESC]: Quit")
        self.inst2 = addInstructions(0.12, "[Left trackpad]: Rotate Left")
        self.inst3 = addInstructions(0.18, "[Right trackpad]: Rotate Right")
        self.inst4 = addInstructions(0.24, "[Up trackpad]: Walk Forward")
        self.inst4 = addInstructions(0.30, "[Down trackpad]: Walk Backward")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        self.environ = loader.loadModel("models/world")
        self.environ.reparentTo(render)

        # Create the main character, Ralph

        self.ralph = render.attachNewNode('ralph')
        self.ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ovr.tracking_space.setPos(self.ralphStartPos)
        self.ralph.setPos(self.ovr.hmd_anchor.getPos(render))

        self.accept("escape", sys.exit)

        taskMgr.add(self.move, "moveTask")
        taskMgr.add(self.collision, "collisionTask")

        # Set up the camera
        self.disableMouse()

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 9)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection((-5, -5, -5))
        directionalLight.setColor((1, 1, 1, 1))
        directionalLight.setSpecularColor((1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
コード例 #24
0
try:
    import panda3d
except ImportError:
    print "It seems you haven't got Panda3D installed properly."
    sys.exit(1)

from panda3d.core import ExecutionEnvironment as EE
from panda3d.core import Filename
from options import options

# If we only need to print version, do this first and leave everything else
# untouched.
if options.print_version:
    try:
        f = Filename(EE.expandString("$MAIN_DIR/VERSION")).toOsSpecific()
        print open(f).read()
    except IOError:
        print "Version unknown. Can't find the VERSION file."
    sys.exit()

from pandac.PandaModules import loadPrcFile
from pandac.PandaModules import Filename
# Config file should be loaded as soon as possible.
loadPrcFile(Filename.expandFrom("$MAIN_DIR/etc/azure.prc"))
from direct.showbase.ShowBase import ShowBase

from core import Core


class Azure(ShowBase):
コード例 #25
0
ファイル: AppRunner.py プロジェクト: Just-D/panda3d
    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)
コード例 #26
0
from panda3d.core import CardMaker , NodePath , ExecutionEnvironment
from direct.interval.IntervalGlobal import Sequence
from panda3d.core import Point3
from random import random , uniform ,seed

MAIN_DIR = ExecutionEnvironment.expandString("$MAIN_DIR")

class MenuBackground():
    
    def getNP(self):
        return self.menuNP

    def _addCard(self,texture):
        tex = loader.loadTexture(MAIN_DIR+"/../assets/models/bamboo/"+texture)
        cm = CardMaker('card')
        ratio = float(tex.getXSize())/tex.getYSize()
        cm.setFrame(-0.5*ratio,0.5*ratio,-0.5,0.5)
        card = self.menuNP.attachNewNode(cm.generate())
        card.setTexture(tex)
        return card

   
    def __init__(self):
        seed(1236)
        self.menuNP = NodePath("menunp")
        background = self._addCard('bamboo-menu-layer-4.jpg')
        background.setY( 10)
        background.setScale(6)

        for i in range(20):
            bamboo3 = self._addCard('bamboo-menu-layer-3.png')
コード例 #27
0
ファイル: AppRunner.py プロジェクト: chongzhang5097/panda3d
    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)
コード例 #28
0
import os
import yaml
import random
import imageio
import argparse
import numpy as np
import time
import cv2
from direct.showbase.ShowBase import ShowBase
from panda3d.core import loadPrcFileData, Vec3, \
    ConfigVariableFilename, ExecutionEnvironment
from pynput import keyboard
from direct.gui.OnscreenImage import OnscreenImage

print('XDG_CACHE_HOME={xch}'.format(
    xch=ExecutionEnvironment.getEnvironmentVariable('XDG_CACHE_HOME')))
print('WARNING: models will be cached to {mcd}'.format(
    mcd=ConfigVariableFilename('model-cache-dir')))

loadPrcFileData('', 'window-type offscreen')
loadPrcFileData('', 'sync-video 0')
loadPrcFileData('', 'load-file-type p3assimp')
loadPrcFileData('', 'win-size {w} {h}'.format(w=600, h=450))

KEY_W = keyboard.KeyCode.from_char('w')
KEY_A = keyboard.KeyCode.from_char('a')
KEY_S = keyboard.KeyCode.from_char('s')
KEY_D = keyboard.KeyCode.from_char('d')
KEY_F = keyboard.KeyCode.from_char('f')
KEY_U = keyboard.KeyCode.from_char('u')