Example #1
0
    def downloadNextFile(self, task):
        while self.nextNewsFile < len(self.newsFiles) and 'aaver' in self.newsFiles[self.nextNewsFile]:
            self.nextNewsFile += 1

        if self.nextNewsFile >= len(self.newsFiles):
            self.notify.info('Done downloading news.')
            self.percentDownloaded = 1
            del self.newsFiles
            del self.nextNewsFile
            del self.newsUrl
            del self.newsDir
            del self.ch
            del self.url
            if hasattr(self, 'filename'):
                del self.filename
            self.redownloadingNews = False
            if self.active:
                self.parseNewsContent()
            return task.done
        self.percentDownloaded = float(self.nextNewsFile) / float(len(self.newsFiles))
        self.filename = self.newsFiles[self.nextNewsFile]
        self.nextNewsFile += 1
        self.url = self.newsUrl + self.filename
        localFilename = Filename(self.newsDir, self.filename)
        self.notify.info('testing for %s' % localFilename.getFullpath())
        doc = DocumentSpec(self.url)
        if self.filename in self.newsCache:
            size, date = self.newsCache[self.filename]
            if date and localFilename.exists() and (size == 0 or localFilename.getFileSize() == size):
                doc.setDate(date)
                doc.setRequestMode(doc.RMNewer)
        self.ch.beginGetDocument(doc)
        self.ch.downloadToFile(localFilename)
        taskMgr.remove(self.RedownloadTaskName)
        taskMgr.add(self.downloadCurrentFileTask, self.RedownloadTaskName)
Example #2
0
def makeBundle(startDir):
    fstartDir = Filename.fromOsSpecific(startDir)

    # Search for nppandad along $DYLD_LIBRARY_PATH.
    path = DSearchPath()
    if 'LD_LIBRARY_PATH' in os.environ:
        path.appendPath(os.environ['LD_LIBRARY_PATH'])
    if 'DYLD_LIBRARY_PATH' in os.environ:
        path.appendPath(os.environ['DYLD_LIBRARY_PATH'])
    nppanda3d = path.findFile('nppanda3d')
    if not nppanda3d:
        raise Exception("Couldn't find nppanda3d on path.")

    # Generate the bundle directory structure
    rootFilename = Filename(fstartDir, 'bundle')

    if os.path.exists(rootFilename.toOsSpecific()):
        shutil.rmtree(rootFilename.toOsSpecific())

    bundleFilename = Filename(rootFilename, 'nppanda3d.plugin')
    plistFilename = Filename(bundleFilename, 'Contents/Info.plist')
    plistFilename.makeDir()
    exeFilename = Filename(bundleFilename, 'Contents/MacOS/nppanda3d')
    exeFilename.makeDir()
    resourceFilename = Filename(bundleFilename,
                                'Contents/Resources/nppanda3d.rsrc')
    resourceFilename.makeDir()

    # Compile the .r file to an .rsrc file.
    os.system('/Developer/Tools/Rez -useDF -o %s %s' %
              (resourceFilename.toOsSpecific(),
               Filename(fstartDir, "nppanda3d.r").toOsSpecific()))

    if not resourceFilename.exists():
        raise IOError('Unable to run Rez')

    # Copy in Info.plist and the compiled executable.
    shutil.copyfile(
        Filename(fstartDir, "nppanda3d.plist").toOsSpecific(),
        plistFilename.toOsSpecific())
    shutil.copyfile(nppanda3d.toOsSpecific(), exeFilename.toOsSpecific())

    # All done!
    bundleFilename.touch()
    print(bundleFilename.toOsSpecific())
Example #3
0
def makeBundle(startDir):
    fstartDir = Filename.fromOsSpecific(startDir)

    # Search for nppandad along $DYLD_LIBRARY_PATH.
    path = DSearchPath()
    if 'LD_LIBRARY_PATH' in os.environ:
        path.appendPath(os.environ['LD_LIBRARY_PATH'])
    if 'DYLD_LIBRARY_PATH' in os.environ:
        path.appendPath(os.environ['DYLD_LIBRARY_PATH'])
    nppanda3d = path.findFile('nppanda3d')
    if not nppanda3d:
        raise Exception("Couldn't find nppanda3d on path.")

    # Generate the bundle directory structure
    rootFilename = Filename(fstartDir, 'bundle')

    if os.path.exists(rootFilename.toOsSpecific()):
        shutil.rmtree(rootFilename.toOsSpecific())

    bundleFilename = Filename(rootFilename, 'nppanda3d.plugin')
    plistFilename = Filename(bundleFilename, 'Contents/Info.plist')
    plistFilename.makeDir()
    exeFilename = Filename(bundleFilename, 'Contents/MacOS/nppanda3d')
    exeFilename.makeDir()
    resourceFilename = Filename(bundleFilename, 'Contents/Resources/nppanda3d.rsrc')
    resourceFilename.makeDir()

    # Compile the .r file to an .rsrc file.
    os.system('/Developer/Tools/Rez -useDF -o %s %s' % (
        resourceFilename.toOsSpecific(), Filename(fstartDir, "nppanda3d.r").toOsSpecific()))

    if not resourceFilename.exists():
        raise IOError('Unable to run Rez')

    # Copy in Info.plist and the compiled executable.
    shutil.copyfile(Filename(fstartDir, "nppanda3d.plist").toOsSpecific(), plistFilename.toOsSpecific())
    shutil.copyfile(nppanda3d.toOsSpecific(), exeFilename.toOsSpecific())

    # All done!
    bundleFilename.touch()
    print(bundleFilename.toOsSpecific())
Example #4
0
    def __init__(self, fileName, size, hpr, position, tag, color, texture, name, parent, duration, frame, joints, animation):
        Proxy.Proxy.__init__(self, name = str(name) + ":" + str(PandaGlobals.nextModelId), updater = modelUpdater,
                             types = {"position": p3Type, "hpr": hprType , "size": numType,
                                      "color": colorType, "texture": stringType})
        modelTypes = {"localOrientation": hprType, "localSize": numType, "localPosition": p3Type,
                      "cRadius": numType, "cType": stringType, "cFloor": numType, "cTop": numType}
        #(p3Type, SP3(0,0,0)), "hpr": (hprType, SHPR(0,0,0)), "size": (numType, 1)})
        PandaGlobals.nextModelId = PandaGlobals.nextModelId + 1
        self._parent = getModel(parent)
        self._mFile = FileSearch.fileSearch(fileName, "models", ["egg"])
        #print("Object Name: "+ str(fileName)+"-gID: "+str(PandaGlobals.nextModelId))
        if type(tag) == type("s"):
            collections = [tag]
        else:
            collections = tag
        self._collections = collections
        if fileName in parameterCache:
            self._mParams = parameterCache[fileName]
        elif self._mFile is None:
            print("Can't find model " + repr(fileName)) #should substitute pandafor unknown models
        #self._mFile = Filename("/c/Panda3D-1.8.1/models/"+fileName)
        #print("File Path: " + repr(mFile))
        else:
            mParamFile = Filename(self._mFile)
            #print(repr(mParamFile))
            mParamFile.setExtension("model")
            if mParamFile.exists():
                self._mParams = FileIO.loadDict(mParamFile, types = modelTypes, defaults = defaultModelParameters)
            else:
                print("No .model for " + str(fileName))
                self._mParams = defaultModelParameters
            parameterCache[fileName] = self._mParams
        self._hasJoints = len(joints) != 0
        self._joints = joints
        self._jointNodes = {}
        self._animation = animation
        
        if animation != None:
            self._pandaModel = Actor.Actor(fileName, animation)
            if frame != None:
                self._frame = frame
        else:   #  Not animated
            self._pandaModel = loader.loadModel(self._mFile)
            if self._pandaModel == None:
                print('Model not found: ' + fileName)
                exit()
        if self._hasJoints:
            for j,pj in joints:
                self._jointNodes[j] = self._pandaModel.controlJoint(None, "modelRoot", pj)
                if self._jointNodes[j] == None:
                    print('joint not found: ' + j)
                    exit()
        self._pandaModel.setTag('rpandaid', str(self._name))
        self._fileName = fileName
        self._onScreen = False
        self._animPlaying = False
        self._size=self._mParams['localSize']
        self._hpr=self._mParams['localOrientation']
        self._position=self._mParams['localPosition']
        self._cRadius = float(self._mParams['cRadius'])
        self._cType = self._mParams['cType']
        self._cFloor = float(self._mParams['cFloor'])
        self._cTop = float(self._mParams['cTop'])
        self._currentTexture = ""
        self._onscreen = False   # This defers the reparenting until the model has been updated the first time
        self._parent = getModel(parent)
        if position is not None:
            self.position = position
        else:
            self.position = P3(0,0,0)
        if hpr is not None:
            self.hpr = hpr
        else:
            self.hpr = SHPR(0,0,0)
        if size is not None:
            self.size = size
        else:
            self.size = 1
        if texture is not None:
            self.texture = texture
        else:
            self.texture = ""
        if color is not None:
            self.color = color
        else:
            self.color = noColor
        for tag in collections:
            if tag not in frpGlobals.collections:
                frpGlobals.collections[tag] = [self]
            frpGlobals.collections[tag].append(self)

        #Get saved reaction functions for this collection
        for t, v in frpGlobals.collectionReactions.items():
            for tag in collections:
                if tag in v:
                    for args in v[tag]:
                        getattr(Functions, t)(self, args[0], what = args[1])
        if duration > 0:
            react(self, delay(duration), exitScene)
Example #5
0
if shortname == '':
    shortname = appFilename.getBasenameWoExtension()

if shortname.lower() != shortname or ' ' in shortname:
    print(
        '\nProvided short name should be lowercase, and may not contain spaces!\n'
    )

if version == '' and deploy_mode == 'installer':
    print('\nA version number is required in "installer" mode.\n')
    sys.exit(1)

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:
Example #6
0
    def __downloadFile(self,
                       step,
                       fileSpec,
                       urlbase=None,
                       filename=None,
                       allowPartial=False):
        """ Downloads the indicated file from the host into
        packageDir.  Yields one of stepComplete, stepFailed,
        restartDownload, or stepContinue. """

        if self.host.appRunner and self.host.appRunner.verifyContents == self.host.appRunner.P3DVCNever:
            # We're not allowed to download anything.
            yield self.stepFailed
            return

        self.updated = True

        if not urlbase:
            urlbase = self.descFileDirname + '/' + fileSpec.filename

        # Build up a list of URL's to try downloading from.  Unlike
        # the C++ implementation in P3DPackage.cxx, here we build the
        # URL's in forward order.
        tryUrls = []

        if self.host.appRunner and self.host.appRunner.superMirrorUrl:
            # We start with the "super mirror", if it's defined.
            url = self.host.appRunner.superMirrorUrl + urlbase
            tryUrls.append((url, False))

        if self.host.mirrors:
            # Choose two mirrors at random.
            mirrors = self.host.mirrors[:]
            for i in range(2):
                mirror = random.choice(mirrors)
                mirrors.remove(mirror)
                url = mirror + urlbase
                tryUrls.append((url, False))
                if not mirrors:
                    break

        # After trying two mirrors and failing (or if there are no
        # mirrors), go get it from the original host.
        url = self.host.downloadUrlPrefix + urlbase
        tryUrls.append((url, False))

        # And finally, if the original host also fails, try again with
        # a cache-buster.
        tryUrls.append((url, True))

        for url, cacheBust in tryUrls:
            request = DocumentSpec(url)

            if cacheBust:
                # On the last attempt to download a particular file,
                # we bust through the cache: append a query string to
                # do this.
                url += '?' + str(int(time.time()))
                request = DocumentSpec(url)
                request.setCacheControl(DocumentSpec.CCNoCache)

            self.notify.info("%s downloading %s" % (self.packageName, url))

            if not filename:
                filename = fileSpec.filename
            targetPathname = Filename(self.getPackageDir(), filename)
            targetPathname.setBinary()

            channel = self.http.makeChannel(False)

            # If there's a previous partial download, attempt to resume it.
            bytesStarted = 0
            if allowPartial and not cacheBust and targetPathname.exists():
                bytesStarted = targetPathname.getFileSize()

            if bytesStarted < 1024 * 1024:
                # Not enough bytes downloaded to be worth the risk of
                # a partial download.
                bytesStarted = 0
            elif bytesStarted >= fileSpec.size:
                # Couldn't possibly be our file.
                bytesStarted = 0

            if bytesStarted:
                self.notify.info(
                    "Resuming %s after %s bytes already downloaded" %
                    (url, bytesStarted))
                # Make sure the file is writable.
                os.chmod(targetPathname.toOsSpecific(), 0o644)
                channel.beginGetSubdocument(request, bytesStarted, 0)
            else:
                # No partial download possible; get the whole file.
                targetPathname.makeDir()
                targetPathname.unlink()
                channel.beginGetDocument(request)

            channel.downloadToFile(targetPathname)
            while channel.run():
                if step:
                    step.bytesDone = channel.getBytesDownloaded(
                    ) + channel.getFirstByteDelivered()
                    if step.bytesDone > step.bytesNeeded:
                        # Oops, too much data.  Might as well abort;
                        # it's the wrong file.
                        self.notify.warning(
                            "Got more data than expected for download %s" %
                            (url))
                        break

                    self.__updateStepProgress(step)

                if taskMgr.destroyed:
                    # If the task manager has been destroyed, we must
                    # be shutting down.  Get out of here.
                    self.notify.warning("Task Manager destroyed, aborting %s" %
                                        (url))
                    yield self.stepFailed
                    return

                yield self.stepContinue

            if step:
                step.bytesDone = channel.getBytesDownloaded(
                ) + channel.getFirstByteDelivered()
                self.__updateStepProgress(step)

            if not channel.isValid():
                self.notify.warning("Failed to download %s" % (url))

            elif not fileSpec.fullVerify(self.getPackageDir(),
                                         pathname=targetPathname,
                                         notify=self.notify):
                self.notify.warning(
                    "After downloading, %s incorrect" %
                    (Filename(fileSpec.filename).getBasename()))

                # This attempt failed.  Maybe the original contents.xml
                # file is stale.  Try re-downloading it now, just to be
                # sure.
                if self.host.redownloadContentsFile(self.http):
                    # Yes!  Go back and start over from the beginning.
                    yield self.restartDownload
                    return

            else:
                # Success!
                yield self.stepComplete
                return

            # Maybe the mirror is bad.  Go back and try the next
            # mirror.

        # All attempts failed.  Maybe the original contents.xml file
        # is stale.  Try re-downloading it now, just to be sure.
        if self.host.redownloadContentsFile(self.http):
            # Yes!  Go back and start over from the beginning.
            yield self.restartDownload
            return

        # All mirrors failed; the server (or the internet connection)
        # must be just fubar.
        yield self.stepFailed
        return
Example #7
0
    def __buildInstallPlans(self):
        """ Sets up self.installPlans, a list of one or more "plans"
        to download and install the package. """

        pc = PStatCollector(':App:PackageInstaller:buildInstallPlans')
        pc.start()

        self.hasPackage = False

        if self.host.appRunner and self.host.appRunner.verifyContents == self.host.appRunner.P3DVCNever:
            # We're not allowed to download anything.
            self.installPlans = []
            pc.stop()
            return

        if self.asMirror:
            # If we're just downloading a mirror archive, we only need
            # to get the compressed archive file.

            # Build a one-item install plan to download the compressed
            # archive.
            downloadSize = self.compressedArchive.size
            func = lambda step, fileSpec=self.compressedArchive: self.__downloadFile(
                step, fileSpec, allowPartial=True)

            step = self.InstallStep(func, downloadSize, self.downloadFactor,
                                    'download')
            installPlan = [step]
            self.installPlans = [installPlan]
            pc.stop()
            return

        # The normal download process.  Determine what we will need to
        # download, and build a plan (or two) to download it all.
        self.installPlans = None

        # We know we will at least need to unpack the archive contents
        # at the end.
        unpackSize = 0
        for file in self.extracts:
            unpackSize += file.size
        step = self.InstallStep(self.__unpackArchive, unpackSize,
                                self.unpackFactor, 'unpack')
        planA = [step]

        # If the uncompressed archive file is good, that's all we'll
        # need to do.
        self.uncompressedArchive.actualFile = None
        if self.uncompressedArchive.quickVerify(self.getPackageDir(),
                                                notify=self.notify):
            self.installPlans = [planA]
            pc.stop()
            return

        # Maybe the compressed archive file is good.
        if self.compressedArchive.quickVerify(self.getPackageDir(),
                                              notify=self.notify):
            uncompressSize = self.uncompressedArchive.size
            step = self.InstallStep(self.__uncompressArchive, uncompressSize,
                                    self.uncompressFactor, 'uncompress')
            planA = [step] + planA
            self.installPlans = [planA]
            pc.stop()
            return

        # Maybe we can download one or more patches.  We'll come back
        # to that in a minute as plan A.  For now, construct plan B,
        # which will be to download the whole archive.
        planB = planA[:]

        uncompressSize = self.uncompressedArchive.size
        step = self.InstallStep(self.__uncompressArchive, uncompressSize,
                                self.uncompressFactor, 'uncompress')
        planB = [step] + planB

        downloadSize = self.compressedArchive.size
        func = lambda step, fileSpec=self.compressedArchive: self.__downloadFile(
            step, fileSpec, allowPartial=True)

        step = self.InstallStep(func, downloadSize, self.downloadFactor,
                                'download')
        planB = [step] + planB

        # Now look for patches.  Start with the md5 hash from the
        # uncompressedArchive file we have on disk, and see if we can
        # find a patch chain from this file to our target.
        pathname = Filename(self.getPackageDir(),
                            self.uncompressedArchive.filename)
        fileSpec = self.uncompressedArchive.actualFile
        if fileSpec is None and pathname.exists():
            fileSpec = FileSpec()
            fileSpec.fromFile(self.getPackageDir(),
                              self.uncompressedArchive.filename)
        plan = None
        if fileSpec:
            plan = self.__findPatchChain(fileSpec)
        if plan:
            # We can download patches.  Great!  That means this is
            # plan A, and the full download is plan B (in case
            # something goes wrong with the patching).
            planA = plan + planA
            self.installPlans = [planA, planB]
        else:
            # There are no patches to download, oh well.  Stick with
            # plan B as the only plan.
            self.installPlans = [planB]

        # In case of unexpected failures on the internet, we will retry
        # the full download instead of just giving up.
        retries = core.ConfigVariableInt('package-full-dl-retries',
                                         1).getValue()
        for retry in range(retries):
            self.installPlans.append(planB[:])

        pc.stop()
Example #8
0
    def __downloadFile(self, step, fileSpec, urlbase = None, filename = None,
                       allowPartial = False):
        """ Downloads the indicated file from the host into
        packageDir.  Yields one of stepComplete, stepFailed,
        restartDownload, or stepContinue. """

        if self.host.appRunner and self.host.appRunner.verifyContents == self.host.appRunner.P3DVCNever:
            # We're not allowed to download anything.
            yield self.stepFailed; return

        self.updated = True

        if not urlbase:
            urlbase = self.descFileDirname + '/' + fileSpec.filename

        # Build up a list of URL's to try downloading from.  Unlike
        # the C++ implementation in P3DPackage.cxx, here we build the
        # URL's in forward order.
        tryUrls = []

        if self.host.appRunner and self.host.appRunner.superMirrorUrl:
            # We start with the "super mirror", if it's defined.
            url = self.host.appRunner.superMirrorUrl + urlbase
            tryUrls.append((url, False))

        if self.host.mirrors:
            # Choose two mirrors at random.
            mirrors = self.host.mirrors[:]
            for i in range(2):
                mirror = random.choice(mirrors)
                mirrors.remove(mirror)
                url = mirror + urlbase
                tryUrls.append((url, False))
                if not mirrors:
                    break

        # After trying two mirrors and failing (or if there are no
        # mirrors), go get it from the original host.
        url = self.host.downloadUrlPrefix + urlbase
        tryUrls.append((url, False))

        # And finally, if the original host also fails, try again with
        # a cache-buster.
        tryUrls.append((url, True))

        for url, cacheBust in tryUrls:
            request = DocumentSpec(url)

            if cacheBust:
                # On the last attempt to download a particular file,
                # we bust through the cache: append a query string to
                # do this.
                url += '?' + str(int(time.time()))
                request = DocumentSpec(url)
                request.setCacheControl(DocumentSpec.CCNoCache)

            self.notify.info("%s downloading %s" % (self.packageName, url))

            if not filename:
                filename = fileSpec.filename
            targetPathname = Filename(self.getPackageDir(), filename)
            targetPathname.setBinary()

            channel = self.http.makeChannel(False)

            # If there's a previous partial download, attempt to resume it.
            bytesStarted = 0
            if allowPartial and not cacheBust and targetPathname.exists():
                bytesStarted = targetPathname.getFileSize()

            if bytesStarted < 1024*1024:
                # Not enough bytes downloaded to be worth the risk of
                # a partial download.
                bytesStarted = 0
            elif bytesStarted >= fileSpec.size:
                # Couldn't possibly be our file.
                bytesStarted = 0

            if bytesStarted:
                self.notify.info("Resuming %s after %s bytes already downloaded" % (url, bytesStarted))
                # Make sure the file is writable.
                os.chmod(targetPathname.toOsSpecific(), 0o644)
                channel.beginGetSubdocument(request, bytesStarted, 0)
            else:
                # No partial download possible; get the whole file.
                targetPathname.makeDir()
                targetPathname.unlink()
                channel.beginGetDocument(request)

            channel.downloadToFile(targetPathname)
            while channel.run():
                if step:
                    step.bytesDone = channel.getBytesDownloaded() + channel.getFirstByteDelivered()
                    if step.bytesDone > step.bytesNeeded:
                        # Oops, too much data.  Might as well abort;
                        # it's the wrong file.
                        self.notify.warning("Got more data than expected for download %s" % (url))
                        break

                    self.__updateStepProgress(step)

                if taskMgr.destroyed:
                    # If the task manager has been destroyed, we must
                    # be shutting down.  Get out of here.
                    self.notify.warning("Task Manager destroyed, aborting %s" % (url))
                    yield self.stepFailed; return

                yield self.stepContinue

            if step:
                step.bytesDone = channel.getBytesDownloaded() + channel.getFirstByteDelivered()
                self.__updateStepProgress(step)

            if not channel.isValid():
                self.notify.warning("Failed to download %s" % (url))

            elif not fileSpec.fullVerify(self.getPackageDir(), pathname = targetPathname, notify = self.notify):
                self.notify.warning("After downloading, %s incorrect" % (Filename(fileSpec.filename).getBasename()))

                # This attempt failed.  Maybe the original contents.xml
                # file is stale.  Try re-downloading it now, just to be
                # sure.
                if self.host.redownloadContentsFile(self.http):
                    # Yes!  Go back and start over from the beginning.
                    yield self.restartDownload; return

            else:
                # Success!
                yield self.stepComplete; return

            # Maybe the mirror is bad.  Go back and try the next
            # mirror.

        # All attempts failed.  Maybe the original contents.xml file
        # is stale.  Try re-downloading it now, just to be sure.
        if self.host.redownloadContentsFile(self.http):
            # Yes!  Go back and start over from the beginning.
            yield self.restartDownload; return

        # All mirrors failed; the server (or the internet connection)
        # must be just fubar.
        yield self.stepFailed; return
Example #9
0
    def __buildInstallPlans(self):
        """ Sets up self.installPlans, a list of one or more "plans"
        to download and install the package. """

        pc = PStatCollector(':App:PackageInstaller:buildInstallPlans')
        pc.start()

        self.hasPackage = False

        if self.host.appRunner and self.host.appRunner.verifyContents == self.host.appRunner.P3DVCNever:
            # We're not allowed to download anything.
            self.installPlans = []
            pc.stop()
            return

        if self.asMirror:
            # If we're just downloading a mirror archive, we only need
            # to get the compressed archive file.

            # Build a one-item install plan to download the compressed
            # archive.
            downloadSize = self.compressedArchive.size
            func = lambda step, fileSpec = self.compressedArchive: self.__downloadFile(step, fileSpec, allowPartial = True)

            step = self.InstallStep(func, downloadSize, self.downloadFactor, 'download')
            installPlan = [step]
            self.installPlans = [installPlan]
            pc.stop()
            return

        # The normal download process.  Determine what we will need to
        # download, and build a plan (or two) to download it all.
        self.installPlans = None

        # We know we will at least need to unpack the archive contents
        # at the end.
        unpackSize = 0
        for file in self.extracts:
            unpackSize += file.size
        step = self.InstallStep(self.__unpackArchive, unpackSize, self.unpackFactor, 'unpack')
        planA = [step]

        # If the uncompressed archive file is good, that's all we'll
        # need to do.
        self.uncompressedArchive.actualFile = None
        if self.uncompressedArchive.quickVerify(self.getPackageDir(), notify = self.notify):
            self.installPlans = [planA]
            pc.stop()
            return

        # Maybe the compressed archive file is good.
        if self.compressedArchive.quickVerify(self.getPackageDir(), notify = self.notify):
            uncompressSize = self.uncompressedArchive.size
            step = self.InstallStep(self.__uncompressArchive, uncompressSize, self.uncompressFactor, 'uncompress')
            planA = [step] + planA
            self.installPlans = [planA]
            pc.stop()
            return

        # Maybe we can download one or more patches.  We'll come back
        # to that in a minute as plan A.  For now, construct plan B,
        # which will be to download the whole archive.
        planB = planA[:]

        uncompressSize = self.uncompressedArchive.size
        step = self.InstallStep(self.__uncompressArchive, uncompressSize, self.uncompressFactor, 'uncompress')
        planB = [step] + planB

        downloadSize = self.compressedArchive.size
        func = lambda step, fileSpec = self.compressedArchive: self.__downloadFile(step, fileSpec, allowPartial = True)

        step = self.InstallStep(func, downloadSize, self.downloadFactor, 'download')
        planB = [step] + planB

        # Now look for patches.  Start with the md5 hash from the
        # uncompressedArchive file we have on disk, and see if we can
        # find a patch chain from this file to our target.
        pathname = Filename(self.getPackageDir(), self.uncompressedArchive.filename)
        fileSpec = self.uncompressedArchive.actualFile
        if fileSpec is None and pathname.exists():
            fileSpec = FileSpec()
            fileSpec.fromFile(self.getPackageDir(), self.uncompressedArchive.filename)
        plan = None
        if fileSpec:
            plan = self.__findPatchChain(fileSpec)
        if plan:
            # We can download patches.  Great!  That means this is
            # plan A, and the full download is plan B (in case
            # something goes wrong with the patching).
            planA = plan + planA
            self.installPlans = [planA, planB]
        else:
            # There are no patches to download, oh well.  Stick with
            # plan B as the only plan.
            self.installPlans = [planB]

        # In case of unexpected failures on the internet, we will retry
        # the full download instead of just giving up.
        retries = core.ConfigVariableInt('package-full-dl-retries', 1).getValue()
        for retry in range(retries):
            self.installPlans.append(planB[:])

        pc.stop()
    def __init__(self, fileName, size, hpr, position, tag, color, texture, name, parent, duration, frame, joints, animation):
        Proxy.Proxy.__init__(self, name = str(name) + ":" + str(PandaGlobals.nextModelId), updater = modelUpdater,
                             types = {"position": p3Type, "hpr": hprType , "size": numType,
                                      "color": colorType, "texture": stringType})
        modelTypes = {"localOrientation": hprType, "localSize": numType, "localPosition": p3Type,
                      "cRadius": numType, "cType": stringType, "cFloor": numType, "cTop": numType}
        #(p3Type, SP3(0,0,0)), "hpr": (hprType, SHPR(0,0,0)), "size": (numType, 1)})
        PandaGlobals.nextModelId = PandaGlobals.nextModelId + 1
        self._parent = getModel(parent)
        self._mFile = FileSearch.fileSearch(fileName, "models",["egg"])
        #print "Object Name: "+ str(fileName)+"-gID: "+str(PandaGlobals.nextModelId);
        if type(tag) == type("s"):
            collections = [tag]
        else:
            collections = tag
        self._collections = collections
        if fileName in parameterCache:
            self._mParams = parameterCache[fileName]
        elif self._mFile is None:
            print("Can't find model " + repr(fileName)) #should substitute pandafor unknown models
        #self._mFile = Filename("/c/Panda3D-1.8.1/models/"+fileName)
        #print "File Path: " + repr(mFile)
        else:
            mParamFile = Filename(self._mFile)
            #print repr(mParamFile)
            mParamFile.setExtension("model")
            if mParamFile.exists():
                self._mParams = FileIO.loadDict(mParamFile,types = modelTypes,  defaults = defaultModelParameters)
            else:
                print("No .model for " + str(fileName))
                self._mParams = defaultModelParameters
            parameterCache[fileName] = self._mParams
        self._hasJoints = len(joints) != 0
        self._joints = joints
        self._jointNodes = {}
        self._animation = animation
        
        if animation != None:
            self._pandaModel = Actor.Actor(fileName, animation)
            if frame != None:
                self._frame = frame
        else:   #  Not animated
            self._pandaModel = loader.loadModel(self._mFile)
            if self._pandaModel == None:
                print 'Model not found: ' + fileName
                exit()
        if self._hasJoints:
            for j,pj in joints:
                self._jointNodes[j] = self._pandaModel.controlJoint(None, "modelRoot", pj)
                if self._jointNodes[j] == None:
                    print 'joint not found: ' + j
                    exit()
        self._pandaModel.setTag('rpandaid', str(self._name))
        self._fileName = fileName
        self._onScreen = False
        self._animPlaying = False
        self._size=self._mParams['localSize']
        self._hpr=self._mParams['localOrientation']
        self._position=self._mParams['localPosition']
        self._cRadius = float(self._mParams['cRadius'])
        self._cType = self._mParams['cType']
        self._cFloor = float(self._mParams['cFloor'])
        self._cTop = float(self._mParams['cTop'])
        self._currentTexture = ""
        self._onscreen = False   # This defers the reparenting until the model has been updated the first time
        self._parent = getModel(parent)
        if position is not None:
            self.position = position
        else:
            self.position = P3(0,0,0)
        if hpr is not None:
            self.hpr = hpr
        else:
            self.hpr = SHPR(0,0,0)
        if size is not None:
            self.size = size
        else:
            self.size = 1
        if texture is not None:
            self.texture = texture
        else:
            self.texture = ""
        if color is not None:
            self.color = color
        else:
            self.color = noColor
        for tag in collections:
            if tag not in frpGlobals.collections:
                frpGlobals.collections[tag] = [self]
            frpGlobals.collections[tag].append(self)

        #Get saved reaction functions for this collection
        for t, v in frpGlobals.collectionReactions.items():
            for tag in collections:
                if tag in v:
                    for args in v[tag]:
                        getattr(Functions, t)(self, args[0], what = args[1])
        if duration > 0:
            react(self, delay(duration), exitScene)
Example #11
0
    sys.exit(1)

if shortname == '':
    shortname = appFilename.getBasenameWoExtension()

if shortname.lower() != shortname or ' ' in shortname:
    print '\nProvided short name should be lowercase, and may not contain spaces!\n'

if version == '' and deploy_mode == 'installer':
    print '\nA version number is required in "installer" mode.\n'
    sys.exit(1)

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:
Example #12
0

for directory in directories:
    files = glob(directory + "/*")
    if not os.path.exists(directory + "/png-output"):
        os.mkdir(directory + "/png-output")

    for file in files:
        baseName = os.path.splitext(file)[0]
        fileExtension = os.path.splitext(file)[1]

        if fileExtension == ".jpg":
            rgbFileName = baseName + "_a.rgb"
            rgbFile = Filename(rgbFileName)
            
            if rgbFile.exists():
                tex = loader.loadTexture(file, rgbFile)
                tex.write(baseName + ".png")
               
            else:
                tex = loader.loadTexture(file)
                tex.write(baseName + ".png")
        
        if fileExtension ==".rgb":
            jpgFileName = file.split('_a.')
            jpgFile = Filename(jpgFileName[0] + ".jpg")
            if not jpgFile.exists():
                tex = loader.loadTexture(file)
                tex.write(baseName + ".png")

        clean()