def interrogate():
    """ Runs interrogate over the source directory """

    # Collect source files and convert them to a relative path
    all_sources = find_sources(".")

    # Create the interrogate command
    cmd = [join(get_panda_bin_path(), 'interrogate')]

    if VERBOSE_LVL == 1:
        cmd += ["-v"]
    elif VERBOSE_LVL == 2:
        cmd += ["-vv"]

    cmd += ["-fnames", "-string", "-refcount", "-assert", "-python-native"]
    cmd += ["-S" + get_panda_include_path() + "/parser-inc"]
    cmd += ["-S" + get_panda_include_path() + "/"]

    # Add all subdirectories
    for pth in listdir("."):
        if isdir(pth):
            cmd += ["-I" + pth]

    cmd += ["-srcdir", "."]
    cmd += ["-oc", "interrogate_wrapper.cpp"]
    cmd += ["-od", "interrogate.in"]
    cmd += ["-module", MODULE_NAME]
    cmd += ["-library", MODULE_NAME]

    if PandaSystem.get_major_version() > 1 or PandaSystem.get_minor_version() > 9:
        # Add nomangle option, but only for recent builds
        cmd += ["-nomangle"]

    if PandaSystem.get_major_version() == 1 and PandaSystem.get_minor_version() < 10:
        # Old interrogate options cant handle volatile
        cmd += ["-Dvolatile="]

    # Defines required to parse the panda source
    defines = ["INTERROGATE", "CPPPARSER", "__STDC__=1", "__cplusplus=201103L"]

    if get_compiler_name() == "MSC":
        defines += ["__inline", "_X86_", "WIN32_VC", "WIN32", "_WIN32"]
        if is_64_bit():
            defines += ["WIN64_VC", "WIN64", "_WIN64"]
        # NOTE: this 1600 value is the version number for VC2010.
        defines += ["_MSC_VER=1600", '"__declspec(param)="', "__cdecl", "_near",
                    "_far", "__near", "__far", "__stdcall"]

    if get_compiler_name() == "GCC":
        defines += ['__attribute__\(x\)=']
        if is_64_bit():
            defines += ['_LP64']
        else:
            defines += ['__i386__']

    for define in defines:
        cmd += ["-D" + define]

    cmd += all_sources
    try_execute(*cmd, verbose=VERBOSE_LVL != 0)
    def __init__(self, outdated_parameter=None):
        """ Creates a new pipeline with a given showbase instance. This should
        be done before intializing the ShowBase, the pipeline will take care of
        that. """
        RPObject.__init__(self)
        if outdated_parameter is not None:
            self.fatal(
                "The render pipeline no longer takes the ShowBase argument "
                "as constructor parameter. Please have a look at the "
                "00-Loading the pipeline sample to see how to initialize "
                "the pipeline properly.")
        self.debug("Using Python {}.{} with architecture {}".format(
            sys.version_info.major, sys.version_info.minor,
            PandaSystem.get_platform()))
        self.debug("Using Panda3D {} built on {}".format(
            PandaSystem.get_version_string(), PandaSystem.get_build_date()))
        if PandaSystem.get_git_commit():
            self.debug("Using git commit {}".format(
                PandaSystem.get_git_commit()))
        else:
            self.debug("Using custom Panda3D build")
        self.mount_mgr = MountManager(self)
        self.settings = {}
        self._pre_showbase_initialized = False
        self._first_frame = None
        self.set_default_loading_screen()

        # Check for the right Panda3D version
        if not self._check_version():
            self.fatal(
                "Your Panda3D version is outdated! Please update to the newest \n"
                "git version! Checkout https://github.com/panda3d/panda3d to "
                "compile panda from source, or get a recent buildbot build.")
Exemple #3
0
    def _analyze_system(self):
        """ Prints information about the system used, including information
        about the used Panda3D build. Also checks if the Panda3D build is out
        of date. """
        self.debug("Using Python {}.{} with architecture {}".format(
            sys.version_info.major, sys.version_info.minor,
            PandaSystem.get_platform()))

        build_date = getattr(PandaSystem, 'build_date', None)
        if build_date:
            self.debug("Using Panda3D {} built on {}".format(
                PandaSystem.get_version_string(), build_date))
        else:
            self.debug("Using Panda3D {}".format(
                PandaSystem.get_version_string()))

        if PandaSystem.get_git_commit():
            self.debug("Using git commit {}".format(
                PandaSystem.get_git_commit()))
        else:
            self.debug("Using custom Panda3D build")
        if not self._check_version():
            self.fatal(
                "Your Panda3D version is outdated! Please update to the newest \n"
                "git version! Checkout https://github.com/panda3d/panda3d to "
                "compile panda from source, or get a recent buildbot build.")
    def __init__(self, outdated_parameter=None):
        """ Creates a new pipeline with a given showbase instance. This should
        be done before intializing the ShowBase, the pipeline will take care of
        that. """
        RPObject.__init__(self)
        if outdated_parameter is not None:
            self.fatal("The render pipeline no longer takes the ShowBase argument "
                       "as constructor parameter. Please have a look at the "
                       "00-Loading the pipeline sample to see how to initialize "
                       "the pipeline properly.")
        self.debug("Using Python {}.{} with architecture {}".format(
            sys.version_info.major, sys.version_info.minor, PandaSystem.get_platform()))
        self.debug("Using Panda3D {} built on {}".format(
            PandaSystem.get_version_string(), PandaSystem.get_build_date()))
        if PandaSystem.get_git_commit():
            self.debug("Using git commit {}".format(PandaSystem.get_git_commit()))
        else:
            self.debug("Using custom Panda3D build")
        self.mount_mgr = MountManager(self)
        self.settings = {}
        self._pre_showbase_initialized = False
        self._first_frame = None
        self.set_default_loading_screen()

        # Check for the right Panda3D version
        if not self._check_version():
            self.fatal("Your Panda3D version is outdated! Please update to the newest \n"
                       "git version! Checkout https://github.com/panda3d/panda3d to "
                       "compile panda from source, or get a recent buildbot build.")
    def checkPandaVersionOutOfDate(self, minDay, minMonth, minYear):
        """ Checks if the panda build is out of date, so users don't complain
        about stuff not working, because they simply didn't update """

        built = PandaSystem.getBuildDate()
        formated = datetime.datetime.strptime(built, "%b %d %Y %H:%M:%S")
        required = datetime.datetime(minYear, minMonth, minDay, 12, 00)

        if formated < required:
            print "ERROR: Your Panda3D Build is out of date. Update to the latest"
            print "git build in order to use the pipeline: "
            print "https://github.com/panda3d/panda3d"
            sys.exit(0)

        # Check version
        versionMinMinor = 9
        versionMinMajor = 1

        versionMismatch = False
        if PandaSystem.getMajorVersion() < versionMinMajor:
            versionMismatch = True
        elif PandaSystem.getMinorVersion() < versionMinMinor:
            versionMismatch = True

        if versionMismatch:
            print "ERROR: Your current panda build (", PandaSystem.getVersionString(), ") is"
            print "not supported! The minimum required build is", str(versionMinMajor) + "." + str(versionMinMinor) + ".0"
            sys.exit(0)
    def checkPandaVersionOutOfDate(self, minDay, minMonth, minYear):
        """ Checks if the panda build is out of date, so users don't complain
        about stuff not working, because they simply didn't update """

        built = PandaSystem.getBuildDate()
        formated = datetime.datetime.strptime(built, "%b %d %Y %H:%M:%S")
        required = datetime.datetime(minYear, minMonth, minDay, 00, 00)

        if formated < required:
            print "ERROR: Your Panda3D Build is out of date. Update to the latest"
            print "git build in order to use the pipeline: "
            print "https://github.com/panda3d/panda3d"
            sys.exit(0)

        # Check version
        versionMinMinor = 9
        versionMinMajor = 1

        versionMismatch = False
        if PandaSystem.getMajorVersion() < versionMinMajor:
            versionMismatch = True
        elif PandaSystem.getMinorVersion() < versionMinMinor:
            versionMismatch = True

        if versionMismatch:
            print "ERROR: Your current panda build (", PandaSystem.getVersionString(
            ), ") is"
            print "not supported! The minimum required build is", str(
                versionMinMajor) + "." + str(versionMinMinor) + ".0"
            sys.exit(0)
 def __init__(self):
     """ Creates a new pipeline with a given showbase instance. This should
     be done before intializing the ShowBase, the pipeline will take care of
     that. If the showbase has been initialized before, have a look at
     the alternative initialization of the render pipeline (the first sample)."""
     RPObject.__init__(self)
     self.debug("Using Python {}.{} with architecture {}".format(
         sys.version_info.major, sys.version_info.minor,
         PandaSystem.get_platform()))
     self.debug("Using Panda3D {} built on {}".format(
         PandaSystem.get_version_string(), PandaSystem.get_build_date()))
     if PandaSystem.get_git_commit():
         self.debug("Using git commit {}".format(
             PandaSystem.get_git_commit()))
     else:
         self.debug("Using custom Panda3D build")
     if not self._check_version():
         self.fatal(
             "Your Panda3D version is outdated! Please update to the newest \n"
             "git version! Checkout https://github.com/panda3d/panda3d to "
             "compile panda from source, or get a recent buildbot build.")
     self.mount_mgr = MountManager(self)
     self.settings = {}
     self._pre_showbase_initialized = False
     self._first_frame = None
     self.set_loading_screen_image("/$$rp/data/gui/loading_screen_bg.txo")
Exemple #8
0
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
Exemple #9
0
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
Exemple #10
0
 def print_info(self):
     print("Python version:", platform.python_version())
     print("Panda version: %s (%s) by %s (%s)" % (PandaSystem.getVersionString(),
                                                  PandaSystem.getGitCommit(),
                                                  PandaSystem.getDistributor(),
                                                  PandaSystem.getBuildDate()))
     print("Panda Systems:")
     for system in PandaSystem.get_global_ptr().get_systems():
         print("\t", system)
     print("Data type:", "double" if settings.use_double else 'float')
def get_output_name():
    """ Returns the name of the output dir, depending on the system architecture """
    compiler_suffix = ""
    if is_windows():
        compiler_suffix = "_" + get_panda_mscv_version().suffix

    version_suffix = "panda" + PandaSystem.get_version_string()

    return PandaSystem.getPlatform().lower() + "_{}_py{}{}{}".format(
        version_suffix, sys.version_info.major, sys.version_info.minor,
        compiler_suffix)
    def __init__(self, page):
        OptionsCategory.__init__(self, page)
        DirectObject.__init__(self)

        self.logoNode, self.logoImg = CIGlobals.getLogoImage(
            self.page.book, 0.75, (0, 0, 0.48))

        self.creditsScreen = None

        self.exitConfirmDlg = None

        font = CIGlobals.getToonLogoFont()

        self.gVersionText = OnscreenText(metadata.getBuildInformation(),
                                         parent=self.page.book,
                                         pos=(0, 0.15, 0.15),
                                         font=font,
                                         fg=(1, 1, 1, 1))
        self.gBuildDate = OnscreenText(text=metadata.BUILD_DATE,
                                       parent=self.page.book,
                                       pos=(0, 0.085, 0.085),
                                       scale=0.06,
                                       font=font,
                                       fg=(1, 1, 1, 1))

        self.eVersionText = OnscreenText(text="Engine Version {0}".format(
            PandaSystem.getVersionString()),
                                         parent=self.page.book,
                                         pos=(0, -0.05),
                                         font=font,
                                         fg=(1, 1, 1, 1))
        self.eBuildDate = OnscreenText(text=PandaSystem.getBuildDate(),
                                       parent=self.page.book,
                                       pos=(0, -0.115),
                                       scale=0.06,
                                       font=font,
                                       fg=(1, 1, 1, 1))

        self.exitToontown = CIGlobals.makeDefaultBtn(
            "Exit Toontown",
            pos=(-0.62, -0.62, -0.62),
            parent=self.page.book,
            scale=1.2,
            command=self.showConfirmDlg,
            geom_scale=(0.8, 0.8, 0.8))

        self.credits = CIGlobals.makeDefaultBtn("Credits",
                                                pos=(0.0, 0.5, -0.62),
                                                parent=self.page.book,
                                                scale=1.2,
                                                command=self.rollCredits,
                                                geom_scale=(0.8, 0.8, 0.8))
 def _analyze_system(self):
     """ Prints information about the system used, including information
     about the used Panda3D build. Also checks if the Panda3D build is out
     of date. """
     self.debug("Using Python {}.{} with architecture {}".format(
         sys.version_info.major, sys.version_info.minor, PandaSystem.get_platform()))
     self.debug("Using Panda3D {} built on {}".format(
         PandaSystem.get_version_string(), PandaSystem.get_build_date()))
     if PandaSystem.get_git_commit():
         self.debug("Using git commit {}".format(PandaSystem.get_git_commit()))
     else:
         self.debug("Using custom Panda3D build")
     if not self._check_version():
         self.fatal("Your Panda3D version is outdated! Please update to the newest \n"
                    "git version! Checkout https://github.com/panda3d/panda3d to "
                    "compile panda from source, or get a recent buildbot build.")
Exemple #14
0
def handle_cmake_error(output):
    """ Improves the cmake output messages """
    print_error("\n\n\n")
    print_error("-" * 60)
    print_error("\nCMake Error:")

    if "Re-run cmake with a different source directory." in output:
        print_error(
            "You moved the project folder, please add ' --clean' to the command line."
        )

    elif "No CMAKE_CXX_COMPILER could be found." in output or "No CMAKE_C_COMPILER could be found." in output:
        print_error("Could not find the required compiler!")
        if is_windows():
            print_error(
                "\nPlease make sure you installed the following compiler:")
            bitness = "64 bit" if is_64_bit() else ""
            print_error(get_panda_mscv_version().cmake_str, bitness)
        else:
            print_error("The required compiler is:",
                        PandaSystem.get_compiler())

    print_error("\n")
    print_error("-" * 60)
    print_error("\n\n\n")
    exit(-1)
Exemple #15
0
    def getAllPackages(self, includeAllPlatforms = False):
        """ Returns a list of all available packages provided by this
        host. """

        result = []

        items = sorted(self.packages.items())
        for key, platforms in items:
            if self.perPlatform or includeAllPlatforms:
                # If we maintain a different answer per platform,
                # return all of them.
                pitems = sorted(platforms.items())
                for pkey, package in pitems:
                    result.append(package)
            else:
                # If we maintain a host for the current platform
                # only (e.g. a client copy), then return only the
                # current platform, or no particular platform.
                package = platforms.get(PandaSystem.getPlatform(), None)
                if not package:
                    package = platforms.get(None, None)

                if package:
                    result.append(package)

        return result
Exemple #16
0
    def getAllPackages(self, includeAllPlatforms=False):
        """ Returns a list of all available packages provided by this
        host. """

        result = []

        items = sorted(self.packages.items())
        for key, platforms in items:
            if self.perPlatform or includeAllPlatforms:
                # If we maintain a different answer per platform,
                # return all of them.
                pitems = sorted(platforms.items())
                for pkey, package in pitems:
                    result.append(package)
            else:
                # If we maintain a host for the current platform
                # only (e.g. a client copy), then return only the
                # current platform, or no particular platform.
                package = platforms.get(PandaSystem.getPlatform(), None)
                if not package:
                    package = platforms.get("", None)

                if package:
                    result.append(package)

        return result
Exemple #17
0
 def log_conf(self):
     self.log('version: ' + eng.logic.version)
     self.log('operative system: ' + system() + ' ' + release() + ' ' +
              version())
     self.log('architecture: ' + str(architecture()))
     self.log('machine: ' + machine())
     self.log('platform: ' + platform())
     self.log('processor: ' + processor())
     try:
         self.log('cores: ' + str(cpu_count()))
     except NotImplementedError:  # on Windows
         self.log('cores: not implemented')
     self.log('panda version: ' + PandaSystem.get_version_string() + ' ' +
              PandaSystem.get_git_commit())
     self.log('bullet version: ' + str(get_bullet_version()))
     self.log('appdata: ' + str(Filename.get_user_appdata_directory()))
def interrogate_module():
    """ Runs the interrogate module command """

    # Create module command
    cmd = [join_abs(get_panda_bin_path(), "interrogate_module")]
    cmd += ["-python-native"]

    if PandaSystem.get_major_version() > 1 or PandaSystem.get_minor_version(
    ) > 9:
        # Older panda3d versions don't have this
        cmd += ["-import", "panda3d.core"]

    cmd += ["-module", MODULE_NAME]
    cmd += ["-library", MODULE_NAME]
    cmd += ["-oc", "interrogate_module.cpp"]
    cmd += ["interrogate.in"]
    try_execute(*cmd)
def interrogate_module():
    """ Runs the interrogate module command """

    # Create module command
    cmd = [join_abs(get_panda_bin_path(), "interrogate_module")]
    cmd += ["-python-native"]

    if PandaSystem.get_major_version() > 1 or PandaSystem.get_minor_version() > 9:
        # Older panda3d versions don't have this
        cmd += ["-import", "panda3d.core"]

    cmd += ["-module", MODULE_NAME]
    cmd += ["-library", MODULE_NAME]
    cmd += ["-oc", "interrogate_module.cpp"]
    cmd += ["interrogate.in"]

    try_execute(*cmd, verbose=VERBOSE_LVL != 0)
def have_bullet():
    """ Returns whether this panda3d build has bullet support """
    try:
        import panda3d.bullet
    except Exception as msg:
        return False

    return PandaSystem.get_global_ptr().has_system("Bullet")
Exemple #21
0
    def run(self):
        """Starts the main loop of the application."""

        if PandaSystem.getPlatform() == 'emscripten':
            return

        # Set the clock to have last frame's time in case we were
        # Paused at the prompt for a long time
        t = self.globalClock.getFrameTime()
        timeDelta = t - self.globalClock.getRealTime()
        self.globalClock.setRealTime(t)
        self.messenger.send("resetClock", [timeDelta])

        if self.taskMgr.resumeFunc != None:
            self.taskMgr.resumeFunc()

        if self.taskMgr.stepping:
            self.doRunFrame()
        else:
            self.taskMgr.running = True
            while self.taskMgr.running:
                try:
                    self.doRunFrame()
                except KeyboardInterrupt:
                    self.taskMgr.stop()
                except SystemError:
                    self.taskMgr.stop()
                    raise
                except IOError as ioError:
                    code, _ = self.taskMgr.unpackIOError(ioError)
                    # Since upgrading to Python 2.4.1, pausing the execution
                    # often gives this IOError during the sleep function:
                    #     IOError: [Errno 4] Interrupted function call
                    # So, let's just handle that specific exception and stop.
                    # All other IOErrors should still get raised.
                    # Only problem: legit IOError 4s will be obfuscated.
                    if code == 4:
                        self.taskMgr.stop()
                    else:
                        raise
                except Exception as e:
                    if self.taskMgr.extendedExceptions:
                        self.taskMgr.stop()
                        Task.print_exc_plus()
                    else:
                        if (ExceptionVarDump.wantStackDumpLog
                                and ExceptionVarDump.dumpOnExceptionInit):
                            ExceptionVarDump._varDump__print(e)
                        raise
                except:
                    if self.taskMgr.extendedExceptions:
                        self.taskMgr.stop()
                        Task.print_exc_plus()
                    else:
                        raise

        self.taskMgr.mgr.stopThreads()
 def __init__(self, showbase):
     """ Creates a new pipeline with a given showbase instance. This should
     be done before intializing the ShowBase, the pipeline will take care of
     that. """
     DebugObject.__init__(self, "RenderPipeline")
     self.debug("Using Python {} with architecture {}".format(
         sys.version_info.major, PandaSystem.get_platform()))
     self._showbase = showbase
     self._mount_mgr = MountManager(self)
     self._settings = SettingsLoader(self, "Pipeline Settings")
     self.set_default_loading_screen()
 def __init__(self):
     """ Creates a new pipeline with a given showbase instance. This should
     be done before intializing the ShowBase, the pipeline will take care of
     that. If the showbase has been initialized before, have a look at
     the alternative initialization of the render pipeline (the first sample)."""
     RPObject.__init__(self)
     self.debug("Using Python {}.{} with architecture {}".format(
         sys.version_info.major, sys.version_info.minor, PandaSystem.get_platform()))
     self.debug("Using Panda3D {} built on {}".format(
         PandaSystem.get_version_string(), PandaSystem.get_build_date()))
     if PandaSystem.get_git_commit():
         self.debug("Using git commit {}".format(PandaSystem.get_git_commit()))
     else:
         self.debug("Using custom Panda3D build")
     if not self._check_version():
         self.fatal("Your Panda3D version is outdated! Please update to the newest \n"
                    "git version! Checkout https://github.com/panda3d/panda3d to "
                    "compile panda from source, or get a recent buildbot build.")
     self.mount_mgr = MountManager(self)
     self.settings = {}
     self._pre_showbase_initialized = False
     self._first_frame = None
     self.set_loading_screen_image("/$$rp/data/gui/loading_screen_bg.txo")
Exemple #24
0
    def __init__(self):
        print("We are running version " + PandaSystem.getVersionString() +
              " of Panda3d")
        ShowBase.__init__(self)
        props = panda3d.core.WindowProperties()
        props.set_title("Demo")
        self.win.request_properties(props)
        self.win.set_clear_color((0, 0, 0, 1))

        Globals.game_states.request("MainMenu")

        Globals.g_task_manager = taskMgr
        #Globals.win = self.win
        Globals.controls = Controls()
Exemple #25
0
def get_panda_msvc_version():
    """ Returns the MSVC version panda was built with """
    compiler = PandaSystem.get_compiler()
    for msvc_version in MSVC_VERSIONS:
        if msvc_version.compiler_search_string in compiler:
            return msvc_version

    print("FATAL ERROR: Unable to detect visual studio version of your Panda3D Build!", file=sys.stderr)
    print("Unknown compiler string was: '" + compiler + "'", file=sys.stderr)
    print("", file=sys.stderr)
    print("Known visual studio versions are:", file=sys.stderr)
    for msvc_version in MSVC_VERSIONS:
        print("-", msvc_version.cmake_str, "(" + msvc_version.compiler_search_string + ")", file=sys.stderr)
    print("", file=sys.stderr)
    fatal_error("Unable to determine compiler")
def run():
    global outputCodeDir
    global outputHTMLDir
    global directDir
    global extensionsDir
    global interrogateLib
    global codeLibs
    global doSqueeze
    global deleteSourceAfterSqueeze
    global etcPath
    global pythonSourcePath

    doGetopts()
    doErrorCheck()

    # Ok, now we can start generating code
    if native:
        generateNativeWrappers()

    else:
        from direct.ffi import FFIInterrogateDatabase
        db = FFIInterrogateDatabase.FFIInterrogateDatabase(etcPath=etcPath)
        db.generateCode(outputCodeDir, extensionsDir)

        if doSqueeze:
            db.squeezeGeneratedCode(outputCodeDir, deleteSourceAfterSqueeze)

    if doHTML:
        from direct.directscripts import gendocs
        from panda3d.core import PandaSystem
        versionString = '%s %s' % (PandaSystem.getDistributor(),
                                   PandaSystem.getVersionString())

        gendocs.generate(versionString, etcPath, pythonSourcePath,
                         outputHTMLDir, HTMLHeader % time.asctime(),
                         HTMLFooter, '', '.html')
def run():
    global outputCodeDir
    global outputHTMLDir
    global directDir
    global extensionsDir
    global interrogateLib
    global codeLibs
    global doSqueeze
    global deleteSourceAfterSqueeze
    global etcPath
    global pythonSourcePath

    doGetopts()
    doErrorCheck()

    # Ok, now we can start generating code
    if native:
        generateNativeWrappers()

    else:
        from direct.ffi import FFIInterrogateDatabase
        db = FFIInterrogateDatabase.FFIInterrogateDatabase(etcPath = etcPath)
        db.generateCode(outputCodeDir, extensionsDir)

        if doSqueeze:
            db.squeezeGeneratedCode(outputCodeDir, deleteSourceAfterSqueeze)

    if doHTML:
        from direct.directscripts import gendocs
        from panda3d.core import PandaSystem
        versionString = '%s %s' % (
            PandaSystem.getDistributor(), PandaSystem.getVersionString())

        gendocs.generate(versionString, etcPath, pythonSourcePath,
                         outputHTMLDir, HTMLHeader % time.asctime(),
                         HTMLFooter, '', '.html')
    def __init__(self, showbase):
        """ Creates a new pipeline with a given showbase instance. This should
        be done before intializing the ShowBase, the pipeline will take care of
        that. """
        DebugObject.__init__(self, "RenderPipeline")
        self.debug("Using Python {} with architecture {}".format(
            sys.version_info.major, PandaSystem.get_platform()))
        self._showbase = showbase
        self._mount_mgr = MountManager(self)
        self._settings = SettingsLoader(self, "Pipeline Settings")
        self.set_default_loading_screen()

        # Check for the right Panda3D version
        if not self._check_version():
            self.fatal("Your Panda3D version is too old! Please update to a newer "
                       " version! (You need a development version of panda).")
Exemple #29
0
    def handleCommand(self, command):
        if command is None:
            # hack for Ctrl-Break
            self.spewInProgress = False
            self.console.addLine("*** break ***")
            self.console.allowEditing(True)
            return

        command = command.strip()
        if not command:
            return

        tokens = [x.strip() for x in command.split(' ')]
        command = tokens[0].lower()

        if command == 'help':
            self.console.addLines([
                "Sorry, this is utter fakery.",
                "You won't get much more",
                "out of this simulation unless",
                "you program it yourself. :)"
            ])
        elif command == 'dir':
            self.console.addLines([
                "Directory of C:\\:",
                "HELP     COM    72 05-06-2015 14:07",
                "DIR      COM   121 05-06-2015 14:11",
                "SPEW     COM   666 05-06-2015 15:02",
                "   2 Files(s)  859 Bytes.",
                "   0 Dirs(s)  7333 Bytes free.",
                ""])
        elif command == 'cls':
            self.console.cls()
        elif command == 'echo':
            self.console.addLine(' '.join(tokens[1:]))
        elif command == 'ver':
            self.console.addLine('Panda DOS v0.01 in Panda3D ' + PandaSystem.getVersionString())
        elif command == 'spew':
            self.startSpew()
        elif command == 'exit':
            self.console.setPrompt("System is shutting down NOW!")
            self.terminateMonitor()
        else:
            self.console.addLine("command not found")
    def analyze(self):
        """ Analyzes the user system. This should help debugging when the user
        shares his log. """
        print "System analyzer:"

        def stat(name, *args):
            print " ", str(name).ljust(20, " "), "=", ''.join([str(i) for i in args])

        stat("System", sys.platform, " / ", os.name)
        stat("Bitness", 8 * struct.calcsize("P"))
        stat("Panda3D-Build Date", PandaSystem.getBuildDate())
        stat("Panda3D-Compiler", PandaSystem.getCompiler())
        stat("Panda3D-Distributor", PandaSystem.getDistributor())
        stat("Panda3D-Version", PandaSystem.getVersionString())
        stat("Panda3D-GITCommit", PandaSystem.getGitCommit())
        stat("Panda3D-Platform", PandaSystem.getPlatform())
        stat("Panda3D-Official?", PandaSystem.isOfficialVersion())
    def analyze(self):
        """ Analyzes the user system. This should help debugging when the user
        shares his log. """
        print "System analyzer:"

        def stat(name, *args):
            print " ", str(name).ljust(20, " "), "=", ''.join(
                [str(i) for i in args])

        stat("System", sys.platform, " / ", os.name)
        stat("Bitness", 8 * struct.calcsize("P"))
        stat("Panda3D-Build Date", PandaSystem.getBuildDate())
        stat("Panda3D-Compiler", PandaSystem.getCompiler())
        stat("Panda3D-Distributor", PandaSystem.getDistributor())
        stat("Panda3D-Version", PandaSystem.getVersionString())
        stat("Panda3D-GITCommit", PandaSystem.getGitCommit())
        stat("Panda3D-Platform", PandaSystem.getPlatform())
        stat("Panda3D-Official?", PandaSystem.isOfficialVersion())
Exemple #32
0
    def mouseTask(self, task):
        if self.reset:  # It seems that reseting the mouse pointer sometimes take a frame, threfore after a reset ignore the mouse for the next frame. Bad, yes, but better than a flick.
            self.reset = False
            return task.cont

        md = base.win.getPointer(0)
        ox = md.getX() - self.originX
        oy = md.getY() - self.originY
        #print ox,oy,md.getX(),md.getY(),self.originX,self.originY
        self.originX = md.getX()
        self.originY = md.getY()

        # The if statement is not necessary - it exists so if you start the program with the mouse cursor outside the window and then move it into the window the camera will not jerk. It of course could prevent really fast rotation in game.
        if abs(ox) < base.win.getXSize() // 3 and abs(
                oy) < base.win.getYSize() // 3:
            if self.xNode: self.xNode.setH(self.xNode.getH() - ox * self.speed)
            if self.yNode:
                self.yNode.setP(
                    min(max(self.yNode.getP() - oy * self.speed, self.minY),
                        self.maxY))

        xoob = self.originX < base.win.getXSize() // 4 or self.originX > (
            base.win.getXSize() * 3) // 4
        yoob = self.originY < base.win.getYSize() // 4 or self.originY > (
            base.win.getYSize() * 3) // 4

        # OSX had relative mouse support all along, Windows never had, and 1.7.0 added it for Linux.
        if (xoob or yoob) and platform != "darwin" and (
                platform.startswith("win")
                or PandaSystem.getMinorVersion() < 7):
            cx = base.win.getXSize() // 2
            cy = base.win.getYSize() // 2
            if base.win.movePointer(0, cx, cy):
                self.originX = cx
                self.originY = cy
                self.reset = True
                #print 'reset'

        return task.cont
Exemple #33
0
    def getPackage(self, name, version, platform = None):
        """ Returns a PackageInfo that matches the indicated name and
        version and the indicated platform or the current runtime
        platform, if one is provided by this host, or None if not. """

        assert self.hasContentsFile
        platforms = self.packages.get((name, version or None), {})

        if platform is not None:
            # In this case, we are looking for a specific platform
            # only.
            return platforms.get(platform or None, None)

        # We are looking for one matching the current runtime
        # platform.  First, look for a package matching the current
        # platform exactly.
        package = platforms.get(PandaSystem.getPlatform(), None)

        # If not found, look for one matching no particular platform.
        if not package:
            package = platforms.get(None, None)

        return package
Exemple #34
0
    def getPackage(self, name, version, platform=None):
        """ Returns a PackageInfo that matches the indicated name and
        version and the indicated platform or the current runtime
        platform, if one is provided by this host, or None if not. """

        assert self.hasContentsFile
        platforms = self.packages.get((name, version or ""), {})

        if platform:
            # In this case, we are looking for a specific platform
            # only.
            return platforms.get(platform, None)

        # We are looking for one matching the current runtime
        # platform.  First, look for a package matching the current
        # platform exactly.
        package = platforms.get(PandaSystem.getPlatform(), None)

        # If not found, look for one matching no particular platform.
        if not package:
            package = platforms.get("", None)

        return package
 def __init__(self):
     self.platform = self.__get_platform()
     self.os_version = self.__get_os_version()
     self.manufacturer = self.__getManufacturer()
     self.sdk_version = 'rest api v2'
     self.build_version = config.GetString('server-version', 'pirates-dev')
     self.engine_version = 'Panda3D %s' % PandaSystem.getVersionString()
     self.game_key = config.GetString('analytics-game-key', '')
     self.secret_key = config.GetString('analytics-secret-key', '')
     self.use_gzip = config.GetBool('analytics-gzip', True)
     self.client_ts_offset = 0
     self.session_id = None
     self.url_init = 'http://api.gameanalytics.com/v2/' + self.game_key + '/init'
     self.url_events = 'http://api.gameanalytics.com/v2/' + self.game_key + '/events'
     if config.GetBool('want-analytics-sandbox', False):
         self.notify.warning('Running in Sandbox')
         self.url_init = 'http://sandbox-api.gameanalytics.com/v2/' + self.game_key + '/init'
         self.url_events = 'http://sandbox-api.gameanalytics.com/v2/' + self.game_key + '/events'
     self.event_queue = []
     self.session_start_time = None
     self.ready = False
     if config.GetBool('want-analytics', False):
         self.__initialize()
Exemple #36
0
def run_cmake(config, args):
    """ Runs cmake in the output dir """

    configuration = "Release"
    if config["generate_pdb"].lower() in ["1", "true", "yes", "y"]:
        configuration = "RelWithDebInfo"

    cmake_args = ["-DCMAKE_BUILD_TYPE=" + configuration]
    cmake_args += ["-DPYTHON_EXECUTABLE:STRING=" + sys.executable]
    cmake_args += ["-DPROJECT_NAME:STRING=" + config["module_name"]]

    lib_prefix = "lib" if is_windows() else ""

    # Check for the right interrogate lib
    if PandaSystem.get_major_version() > 1 or PandaSystem.get_minor_version() > 9:
        cmake_args += ["-DINTERROGATE_LIB:STRING=" + lib_prefix + "p3interrogatedb"]
    else:

        # Buildbot versions do not have the core lib, instead try using libpanda
        if not isfile(join_abs(get_panda_lib_path(), "core.lib")):
            cmake_args += ["-DINTERROGATE_LIB:STRING=" + lib_prefix + "panda"]
        else:
            cmake_args += ["-DINTERROGATE_LIB:STRING=core"]

    if is_windows():
        # Specify 64-bit compiler when using a 64 bit panda sdk build
        bit_suffix = " Win64" if is_64_bit() else ""
        cmake_args += ["-G" + config["vc_version"] + bit_suffix]

    # Specify python version, once as integer, once seperated by a dot
    pyver = "{}{}".format(sys.version_info.major, sys.version_info.minor)
    pyver_dot = "{}.{}".format(sys.version_info.major, sys.version_info.minor)

    if is_windows():
        cmake_args += ["-DPYTHONVER:STRING=" + pyver]

    if is_linux():
        cmake_args += ["-DPYTHONVERDOT:STRING=" + pyver_dot]

    # Libraries
    for lib in ["freetype", "bullet", "eigen"]:
        if "use_lib_" + lib in config and config["use_lib_" + lib] in ["1", "yes", "y"]:
            cmake_args += ["-DUSE_LIB_" + lib.upper() + "=TRUE"]

    # Optimization level
    optimize = 3
    if args.optimize is None:
        # No optimization level set. Try to find it in the config
        if "optimize" in config:
            optimize = config["optimize"]
    else:
        optimize = args.optimize

    # Verbose level
    if "verbose_igate" in config:
        cmake_args += ["-DIGATE_VERBOSE=" + str(config["verbose_igate"])]
    else:
        cmake_args += ["-DIGATE_VERBOSE=0"]

    cmake_args += ["-DOPTIMIZE=" + str(optimize)]

    try_execute("cmake", join_abs(get_script_dir(), ".."), *cmake_args)
def is_64_bit():
    """ Returns whether the build system is 64 bit (=True) or 32 bit (=False) """
    return PandaSystem.get_platform() in ["win_amd64"]
Exemple #38
0
from .ShowBase import ShowBase, WindowControls
from direct.directnotify.DirectNotifyGlobal import directNotify, giveNotify
from panda3d.core import VirtualFileSystem, Notify, ClockObject, PandaSystem
from panda3d.core import ConfigPageManager, ConfigVariableManager
from panda3d.core import NodePath, PGTop
from panda3d.direct import get_config_showbase

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

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

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

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

def run():
    assert ShowBase.notify.warning("run() is deprecated, use base.run() instead")
    base.run()

def inspect(anObject):
    # Don't use a regular import, to prevent ModuleFinder from picking
    # it up as a dependency when building a .p3d package.
    import importlib
if not outputDir:
    print '\nYou must name the output directory with the -o parameter.\n'
    sys.exit(1)
if not outputDir.exists():
    print '\nThe specified output directory does not exist!\n'
    sys.exit(1)
elif not outputDir.isDirectory():
    print '\nThe specified output directory is a file!\n'
    sys.exit(1)

if deploy_mode == 'standalone':
    s = Standalone(appFilename, tokens)
    s.basename = shortname

    if currentPlatform:
        platform = PandaSystem.getPlatform()
        if platform.startswith("win"):
            s.build(Filename(outputDir, shortname + ".exe"), platform)
        else:
            s.build(Filename(outputDir, shortname), platform)
    elif len(platforms) == 0:
        s.buildAll(outputDir)
    else:
        for platform in platforms:
            if platform.startswith("win"):
                s.build(Filename(outputDir, platform + "/" + shortname + ".exe"), platform)
            else:
                s.build(Filename(outputDir, platform + "/" + shortname), platform)

elif deploy_mode == 'installer':
    if includeRequires:
def have_freetype():
    """ Returns whether this panda3d build has freetype support """
    return PandaSystem.get_global_ptr().has_system("Freetype")
def have_eigen():
    """ Returns whether this panda3d build has eigen support """
    return PandaSystem.get_global_ptr().has_system("eigen")
def get_compiler_name():
    """ Returns the name of the used compiler, either 'MSC', 'GCC' or 'CLANG' """
    full_name = PandaSystem.get_compiler()
    compiler_name = full_name.split()[0]
    return compiler_name.upper()
Exemple #43
0
if not outputDir:
    print('\nYou must name the output directory with the -o parameter.\n')
    sys.exit(1)
if not outputDir.exists():
    print('\nThe specified output directory does not exist!\n')
    sys.exit(1)
elif not outputDir.isDirectory():
    print('\nThe specified output directory is a file!\n')
    sys.exit(1)

if deploy_mode == 'standalone':
    s = Standalone(appFilename, tokens)
    s.basename = shortname

    if currentPlatform:
        platform = PandaSystem.getPlatform()
        if platform.startswith("win"):
            s.build(Filename(outputDir, shortname + ".exe"), platform)
        else:
            s.build(Filename(outputDir, shortname), platform)
    elif len(platforms) == 0:
        s.buildAll(outputDir)
    else:
        for platform in platforms:
            if platform.startswith("win"):
                s.build(
                    Filename(outputDir, platform + "/" + shortname + ".exe"),
                    platform)
            else:
                s.build(Filename(outputDir, platform + "/" + shortname),
                        platform)
Exemple #44
0
from .ShowBase import ShowBase, WindowControls
from direct.directnotify.DirectNotifyGlobal import directNotify, giveNotify
from panda3d.core import VirtualFileSystem, Notify, ClockObject, PandaSystem
from panda3d.core import ConfigPageManager, ConfigVariableManager
from panda3d.core import NodePath, PGTop
from . import DConfig as config

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

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

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

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


def run():
    assert ShowBase.notify.warning(
        "run() is deprecated, use base.run() instead")
    base.run()


def inspect(anObject):
Exemple #45
0
def is_64_bit():
    """ Returns whether the build system is 64 bit (=True) or 32 bit (=False) """
    return PandaSystem.get_platform() in ["win_amd64"]
Exemple #46
0
    def __init__(self):
        DirectObject.__init__(self)

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

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

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

        self.verifyContents = self.P3DVCNone

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

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

        self.Undefined = Undefined
        self.ConcreteStruct = ConcreteStruct

        # This is per session.
        self.nextScriptId = 0

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        # We use this messenger hook to dispatch this __startIfReady()
        # call back to the main thread.
        self.accept('AppRunner_startIfReady', self.__startIfReady)
Exemple #47
0
def get_compiler_name():
    """ Returns the name of the used compiler, either 'MSC', 'GCC' or 'CLANG' """
    full_name = PandaSystem.get_compiler()
    compiler_name = full_name.split()[0]
    return compiler_name.upper()
Exemple #48
0
from panda3d.core import Filename, getModelPath, loadPrcFile, PandaSystem
from path import path
import scenesim

if PandaSystem.getVersionString() != "1.9.0":
    import warnings
    warnings.warn(
        "You are using a version of Panda3D that may not work "
        "with these demos. If you encounter problems, please try "
        "version 1.9.0 instead.")

# load panda configuration
ROOT_PATH = path(__path__[0]).joinpath("..").abspath()

config_pth = ROOT_PATH.joinpath("Config.prc")
if config_pth.isfile():
    cp = Filename.fromOsSpecific(config_pth)
    cp.makeTrueCase()
    print "Loading config '%s'" % cp
    loadPrcFile(cp)

getModelPath().appendDirectory(ROOT_PATH.joinpath("models"))
getModelPath().appendDirectory(ROOT_PATH.joinpath("textures"))
Exemple #49
0
def get_output_name():
    """ Returns the name of the output dir, depending on the system architecture """
    return PandaSystem.getPlatform().lower() + "_py{}{}".format(
        sys.version_info.major, sys.version_info.minor)
Exemple #50
0
    def __init__(self):
        DirectObject.__init__(self)

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

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

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

        self.verifyContents = self.P3DVCNone

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

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

        self.Undefined = Undefined
        self.ConcreteStruct = ConcreteStruct

        # This is per session.
        self.nextScriptId = 0

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.requestFunc = defaultRequestFunc

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

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

        # We use this messenger hook to dispatch this __startIfReady()
        # call back to the main thread.
        self.accept('AppRunner_startIfReady', self.__startIfReady)
from panda3d.core import Filename, getModelPath, loadPrcFile, PandaSystem
from path import path
import scenesim

if PandaSystem.getVersionString() != "1.9.0":
    import warnings
    warnings.warn("You are using a version of Panda3D that may not work "
                  "with these demos. If you encounter problems, please try "
                  "version 1.9.0 instead.")

# load panda configuration
ROOT_PATH = path(__path__[0]).joinpath("..").abspath()

config_pth = ROOT_PATH.joinpath("Config.prc")
if config_pth.isfile():
    cp = Filename.fromOsSpecific(config_pth)
    cp.makeTrueCase()
    print "Loading config '%s'" % cp
    loadPrcFile(cp)

getModelPath().appendDirectory(ROOT_PATH.joinpath("models"))
getModelPath().appendDirectory(ROOT_PATH.joinpath("textures"))