Example #1
0
    def __init__(self, shared):
        loadPrcFileData("",
                        """load-display pandagl
                        sync-video #t
                        fullscreen #f
                        win-origin 0 0
                        undecorated #t
                        cursor-hidden #t
                        win-size 7680 1080
                        show-frame-rate-meter #t
                        auto-single-cpu-affinity #f
                        """)

        TrueClock.getGlobalPtr().setCpuAffinity(0xFFFFFFFF)

        self.shared = shared

        ShowBase.__init__(self)

        self.global_time = 0.0

        self.statustex1 = create_color_texture([0, 0, 0])
        self.statustex2 = create_color_texture([255, 255, 255])

        self.statusimage1 = OnscreenImage(self.statustex1, scale=(0.015, 0.015, 0.015), sort=20,
                                          pos=(self.getAspectRatio() - 0.01, 0, -1 + 0.01))

        self.taskMgr.add(self.loop, "Primary loop")

        # Calibration details:
        self.calibrated_length = 4 * 56.9
def __speedHackCheckTask(task):
    global lastSpeedHackCheck
    global lastTrueClockTime
    global speedHackBeginTime
    global speedHackMaxTime
    now = time.time()
    elapsed = now - lastSpeedHackCheck
    tcElapsed = TrueClock.getGlobalPtr().getLongTime() - lastTrueClockTime

    if tcElapsed > (elapsed + timeEpsilon):
        # Possible speed hacking.
        if speedHackBeginTime == -1:
            speedHackBeginTime = now
        elif now - speedHackBeginTime >= speedHackMaxTime:
            # The clock discrepancy has been going on for a bit,
            # they are more than likely speed hacking.
            print "Detected speed hacks, closing game."
            sys.exit()
            return task.done
    else:
        speedHackBeginTime = -1

    lastSpeedHackCheck = time.time()
    lastTrueClockTime = TrueClock.getGlobalPtr().getLongTime()
    return task.cont
Example #3
0
def __speedHackCheckTask(task):
    global lastSpeedHackCheck
    global lastTrueClockTime
    elapsed = time.time() - lastSpeedHackCheck
    tcElapsed = TrueClock.getGlobalPtr().getLongTime() - lastTrueClockTime
    if tcElapsed > elapsed + 0.05:
        print 'Detected speed hacks, closing game.'
        sys.exit()
        return task.done
    lastSpeedHackCheck = time.time()
    lastTrueClockTime = TrueClock.getGlobalPtr().getLongTime()
    return task.cont
def __speedHackCheckTask(task):
    global lastSpeedHackCheck
    global lastTrueClockTime
    elapsed = time.time() - lastSpeedHackCheck
    tcElapsed = TrueClock.getGlobalPtr().getLongTime() - lastTrueClockTime
    if tcElapsed > elapsed + 0.05:
        print 'Detected speed hacks, closing game.'
        sys.exit()
        return task.done
    lastSpeedHackCheck = time.time()
    lastTrueClockTime = TrueClock.getGlobalPtr().getLongTime()
    return task.cont
 def __init__(self):
     self.config = getConfigShowbase()
     vfs = VirtualFileSystem.getGlobalPtr()
     self.eventMgr = eventMgr
     self.messenger = messenger
     self.bboard = bulletinBoard
     self.taskMgr = taskMgr
     self.AISleep = self.config.GetFloat('ai-sleep', 0.04)
     Task.TaskManager.taskTimerVerbose = self.config.GetBool(
         'task-timer-verbose', 0)
     Task.TaskManager.extendedExceptions = self.config.GetBool(
         'extended-exceptions', 0)
     self.sfxManagerList = None
     self.musicManager = None
     self.jobMgr = jobMgr
     self.hidden = NodePath('hidden')
     self.graphicsEngine = GraphicsEngine.getGlobalPtr()
     globalClock = ClockObject.getGlobalClock()
     self.trueClock = TrueClock.getGlobalPtr()
     globalClock.setRealTime(self.trueClock.getShortTime())
     globalClock.setAverageFrameRateInterval(30.0)
     globalClock.tick()
     taskMgr.globalClock = globalClock
     __builtins__['ostream'] = Notify.out()
     __builtins__['globalClock'] = globalClock
     __builtins__['vfs'] = vfs
     __builtins__['hidden'] = self.hidden
     self.restart()
    def startShow(self, cr, launcherServer=None):
        self.cr = cr
        if self.display.antialias:
            render.setAntialias(AntialiasAttrib.MAuto)
        base.graphicsEngine.renderFrame()
        self.downloadWatcher = ToontownDownloadWatcher.ToontownDownloadWatcher(
            TTLocalizer.LauncherPhaseNames)
        if launcher.isDownloadComplete():
            self.cleanupDownloadWatcher()
        else:
            self.acceptOnce(
                'launcherAllPhasesComplete',
                self.cleanupDownloadWatcher)
        gameServer = config.GetString('game-server', '')
        if gameServer:
            self.notify.info(
                'Using game-server from Configrc: %s ' %
                gameServer)
        elif launcherServer:
            gameServer = launcherServer
            self.notify.info(
                'Using gameServer from launcher: %s ' %
                gameServer)
        else:
            gameServer = 'localhost'
        serverPort = config.GetInt('server-port', 7198)
        serverList = []
        for name in gameServer.split(';'):
            url = URLSpec(name, 1)
            if config.GetBool('server-force-ssl', False):
                url.setScheme('s')
            if not url.hasPort():
                url.setPort(serverPort)
            serverList.append(url)

        if len(serverList) == 1:
            failover = config.GetString('server-failover', '')
            serverURL = serverList[0]
            for arg in failover.split():
                try:
                    port = int(arg)
                    url = URLSpec(serverURL)
                    url.setPort(port)
                except:
                    url = URLSpec(arg, 1)

                if url != serverURL:
                    serverList.append(url)

        cr.loginFSM.request('connect', [serverList])
        self.ttAccess = ToontownAccess.ToontownAccess()
        self.ttAccess.initModuleInfo()

        if config.GetBool('want-speedhack-fix', False):
            # Start checking for speedhacks.
            self.lastSpeedhackCheck = time.time()
            self.trueClock = TrueClock.getGlobalPtr()
            self.lastTrueClockTime = self.trueClock.getLongTime()
            taskMgr.add(self.__speedhackCheckTick, 'speedhack-tick')
Example #7
0
    def startShow(self, cr, launcherServer=None):
        self.cr = cr
        if self.display.antialias:
            render.setAntialias(AntialiasAttrib.MAuto)
        base.graphicsEngine.renderFrame()
        self.downloadWatcher = ToontownDownloadWatcher.ToontownDownloadWatcher(
            TTLocalizer.LauncherPhaseNames)
        if launcher.isDownloadComplete():
            self.cleanupDownloadWatcher()
        else:
            self.acceptOnce('launcherAllPhasesComplete',
                            self.cleanupDownloadWatcher)
        gameServer = config.GetString('game-server', '')
        if gameServer:
            self.notify.info('Using game-server from Configrc: %s ' %
                             gameServer)
        elif launcherServer:
            gameServer = launcherServer
            self.notify.info('Using gameServer from launcher: %s ' %
                             gameServer)
        else:
            gameServer = 'localhost'
        serverPort = config.GetInt('server-port', 7198)
        serverList = []
        for name in gameServer.split(';'):
            url = URLSpec(name, 1)
            if config.GetBool('server-force-ssl', False):
                url.setScheme('s')
            if not url.hasPort():
                url.setPort(serverPort)
            serverList.append(url)

        if len(serverList) == 1:
            failover = config.GetString('server-failover', '')
            serverURL = serverList[0]
            for arg in failover.split():
                try:
                    port = int(arg)
                    url = URLSpec(serverURL)
                    url.setPort(port)
                except:
                    url = URLSpec(arg, 1)

                if url != serverURL:
                    serverList.append(url)

        cr.loginFSM.request('connect', [serverList])
        self.ttAccess = ToontownAccess.ToontownAccess()
        self.ttAccess.initModuleInfo()

        if config.GetBool('want-speedhack-fix', False):
            # Start checking for speedhacks.
            self.lastSpeedhackCheck = time.time()
            self.trueClock = TrueClock.getGlobalPtr()
            self.lastTrueClockTime = self.trueClock.getLongTime()
            taskMgr.add(self.__speedhackCheckTick, 'speedhack-tick')
Example #8
0
 def __init__(self):
     self.config = DConfig
     self.graphicsEngine = GraphicsEngine()
     globalClock = ClockObject.getGlobalClock()
     self.trueClock = TrueClock.getGlobalPtr()
     globalClock.setRealTime(self.trueClock.getShortTime())
     globalClock.setAverageFrameRateInterval(30.0)
     globalClock.tick()
     __builtins__['globalClock'] = globalClock
     taskMgr.globalClock = globalClock
     self.vfs = VirtualFileSystem.getGlobalPtr()
     __builtins__['vfs'] = self.vfs
Example #9
0
########################################
# Filename: SpeedHackChecker.py
# Created by: blach (19Apr15)
########################################

import sys
import time
from panda3d.core import TrueClock

lastSpeedHackCheck = time.time()
lastTrueClockTime = TrueClock.getGlobalPtr().getLongTime()


def __speedHackCheckTask(task):
    global lastSpeedHackCheck
    global lastTrueClockTime
    elapsed = time.time() - lastSpeedHackCheck
    tcElapsed = TrueClock.getGlobalPtr().getLongTime() - lastTrueClockTime

    if tcElapsed > (elapsed + 0.05):
        print "Detected speed hacks, closing game."
        sys.exit()
        return task.done

    lastSpeedHackCheck = time.time()
    lastTrueClockTime = TrueClock.getGlobalPtr().getLongTime()
    return task.cont


def startChecking():
    taskMgr.add(__speedHackCheckTask, "speedHackCheckTask")
Example #10
0
class ProfileSession:
    # class that encapsulates a profile of a single callable using Python's standard
    # 'profile' module
    #
    # defers formatting of profile results until they are requested
    #
    # implementation sidesteps memory leak in Python profile module,
    # and redirects file output to RAM file for efficiency
    TrueClock = TrueClock.getGlobalPtr()

    notify = directNotify.newCategory("ProfileSession")

    def __init__(self, name, func=None, logAfterProfile=False):
        self._func = func
        self._name = name
        self._logAfterProfile = logAfterProfile
        self._filenameBase = 'profileData-%s-%s' % (self._name, id(self))
        self._refCount = 0
        # if true, accumulate profile results every time we run
        # if false, throw out old results every time we run
        self._aggregate = False
        self._lines = 500
        self._sorts = ['cumulative', 'time', 'calls']
        self._callInfo = True
        self._totalTime = None
        self._reset()
        self.acquire()

    def getReference(self):
        # call this when you want to store a new reference to this session that will
        # manage its acquire/release reference count independently of an existing reference
        self.acquire()
        return self

    def acquire(self):
        self._refCount += 1

    def release(self):
        self._refCount -= 1
        if not self._refCount:
            self._destroy()

    def _destroy(self):
        del self._func
        del self._name
        del self._filenameBase
        del self._filenameCounter
        del self._filenames
        del self._duration
        del self._filename2ramFile
        del self._resultCache
        del self._successfulProfiles

    def _reset(self):
        self._filenameCounter = 0
        self._filenames = []
        # index of next file to be added to stats object
        self._statFileCounter = 0
        self._successfulProfiles = 0
        self._duration = None
        self._filename2ramFile = {}
        self._stats = None
        self._resultCache = {}

    def _getNextFilename(self):
        filename = '%s-%s' % (self._filenameBase, self._filenameCounter)
        self._filenameCounter += 1
        return filename

    def run(self):
        # make sure this instance doesn't get destroyed inside self._func
        self.acquire()

        if not self._aggregate:
            self._reset()

        # if we're already profiling, just run the func and don't profile
        if 'globalProfileSessionFunc' in __builtin__.__dict__:
            self.notify.warning('could not profile %s' % self._func)
            result = self._func()
            if self._duration is None:
                self._duration = 0.
        else:
            # put the function in the global namespace so that profile can find it
            assert hasattr(self._func, '__call__')
            __builtin__.globalProfileSessionFunc = self._func
            __builtin__.globalProfileSessionResult = [None]

            # set up the RAM file
            self._filenames.append(self._getNextFilename())
            filename = self._filenames[-1]
            _installProfileCustomFuncs(filename)

            # do the profiling
            Profile = profile.Profile
            statement = 'globalProfileSessionResult[0]=globalProfileSessionFunc()'
            sort = -1
            retVal = None

            # this is based on profile.run, the code is replicated here to allow us to
            # eliminate a memory leak
            prof = Profile()
            try:
                prof = prof.run(statement)
            except SystemExit:
                pass
            # this has to be run immediately after profiling for the timings to be accurate
            # tell the Profile object to generate output to the RAM file
            prof.dump_stats(filename)

            # eliminate the memory leak
            del prof.dispatcher

            # store the RAM file for later
            profData = _getProfileResultFileInfo(filename)
            self._filename2ramFile[filename] = profData
            # calculate the duration (this is dependent on the internal Python profile data format.
            # see profile.py and pstats.py, this was copied from pstats.Stats.strip_dirs)
            maxTime = 0.
            for cc, nc, tt, ct, callers in profData[1].itervalues():
                if ct > maxTime:
                    maxTime = ct
            self._duration = maxTime
            # clean up the RAM file support
            _removeProfileCustomFuncs(filename)

            # clean up the globals
            result = globalProfileSessionResult[0]
            del __builtin__.__dict__['globalProfileSessionFunc']
            del __builtin__.__dict__['globalProfileSessionResult']

            self._successfulProfiles += 1

            if self._logAfterProfile:
                self.notify.info(self.getResults())

        self.release()
        return result

    def getDuration(self):
        return self._duration

    def profileSucceeded(self):
        return self._successfulProfiles > 0

    def _restoreRamFile(self, filename):
        # set up the RAM file
        _installProfileCustomFuncs(filename)
        # install the stored RAM file from self.run()
        _setProfileResultsFileInfo(filename, self._filename2ramFile[filename])

    def _discardRamFile(self, filename):
        # take down the RAM file
        _removeProfileCustomFuncs(filename)
        # and discard it
        del self._filename2ramFile[filename]

    def setName(self, name):
        self._name = name

    def getName(self):
        return self._name

    def setFunc(self, func):
        self._func = func

    def getFunc(self):
        return self._func

    def setAggregate(self, aggregate):
        self._aggregate = aggregate

    def getAggregate(self):
        return self._aggregate

    def setLogAfterProfile(self, logAfterProfile):
        self._logAfterProfile = logAfterProfile

    def getLogAfterProfile(self):
        return self._logAfterProfile

    def setLines(self, lines):
        self._lines = lines

    def getLines(self):
        return self._lines

    def setSorts(self, sorts):
        self._sorts = sorts

    def getSorts(self):
        return self._sorts

    def setShowCallInfo(self, showCallInfo):
        self._showCallInfo = showCallInfo

    def getShowCallInfo(self):
        return self._showCallInfo

    def setTotalTime(self, totalTime=None):
        self._totalTime = totalTime

    def resetTotalTime(self):
        self._totalTime = None

    def getTotalTime(self):
        return self._totalTime

    def aggregate(self, other):
        # pull in stats from another ProfileSession
        other._compileStats()
        self._compileStats()
        self._stats.add(other._stats)

    def _compileStats(self):
        # make sure our stats object exists and is up-to-date
        statsChanged = (self._statFileCounter < len(self._filenames))

        if self._stats is None:
            for filename in self._filenames:
                self._restoreRamFile(filename)
            self._stats = PercentStats(*self._filenames)
            self._statFileCounter = len(self._filenames)
            for filename in self._filenames:
                self._discardRamFile(filename)
        else:
            while self._statFileCounter < len(self._filenames):
                filename = self._filenames[self._statFileCounter]
                self._restoreRamFile(filename)
                self._stats.add(filename)
                self._discardRamFile(filename)

        if statsChanged:
            self._stats.strip_dirs()
            # throw out any cached result strings
            self._resultCache = {}

        return statsChanged

    def getResults(self,
                   lines=Default,
                   sorts=Default,
                   callInfo=Default,
                   totalTime=Default):
        if not self.profileSucceeded():
            output = '%s: profiler already running, could not profile' % self._name
        else:
            if lines is Default:
                lines = self._lines
            if sorts is Default:
                sorts = self._sorts
            if callInfo is Default:
                callInfo = self._callInfo
            if totalTime is Default:
                totalTime = self._totalTime

            self._compileStats()

            if totalTime is None:
                totalTime = self._stats.total_tt

            # make sure the arguments will hash efficiently if callers provide different types
            lines = int(lines)
            sorts = list(sorts)
            callInfo = bool(callInfo)
            totalTime = float(totalTime)
            k = str((lines, sorts, callInfo, totalTime))
            if k in self._resultCache:
                # we've already created this output string, get it from the cache
                output = self._resultCache[k]
            else:
                # now get human-readable output from the profile stats

                # capture print output to a string
                sc = StdoutCapture()

                # print the info to stdout
                s = self._stats
                # make sure our percentages are relative to the correct total time
                s.setTotalTime(totalTime)
                for sort in sorts:
                    s.sort_stats(sort)
                    s.print_stats(lines)
                    if callInfo:
                        s.print_callees(lines)
                        s.print_callers(lines)

                # make a copy of the print output
                output = sc.getString()

                # restore stdout to what it was before
                sc.destroy()

                # cache this result
                self._resultCache[k] = output

        return output
class ProfileSession:
    TrueClock = TrueClock.getGlobalPtr()
    notify = directNotify.newCategory('ProfileSession')

    def __init__(self, name, func=None, logAfterProfile=False):
        self._func = func
        self._name = name
        self._logAfterProfile = logAfterProfile
        self._filenameBase = 'profileData-%s-%s' % (self._name, id(self))
        self._refCount = 0
        self._aggregate = False
        self._lines = 500
        self._sorts = ['cumulative', 'time', 'calls']
        self._callInfo = True
        self._totalTime = None
        self._reset()
        self.acquire()
        return

    def getReference(self):
        self.acquire()
        return self

    def acquire(self):
        self._refCount += 1

    def release(self):
        self._refCount -= 1
        if not self._refCount:
            self._destroy()

    def _destroy(self):
        del self._func
        del self._name
        del self._filenameBase
        del self._filenameCounter
        del self._filenames
        del self._duration
        del self._filename2ramFile
        del self._resultCache
        del self._successfulProfiles

    def _reset(self):
        self._filenameCounter = 0
        self._filenames = []
        self._statFileCounter = 0
        self._successfulProfiles = 0
        self._duration = None
        self._filename2ramFile = {}
        self._stats = None
        self._resultCache = {}
        return

    def _getNextFilename(self):
        filename = '%s-%s' % (self._filenameBase, self._filenameCounter)
        self._filenameCounter += 1
        return filename

    def run(self):
        self.acquire()
        if not self._aggregate:
            self._reset()
        if 'globalProfileSessionFunc' in __builtin__.__dict__:
            self.notify.warning('could not profile %s' % self._func)
            result = self._func()
            if self._duration is None:
                self._duration = 0.0
        else:
            __builtin__.globalProfileSessionFunc = self._func
            __builtin__.globalProfileSessionResult = [None]
            self._filenames.append(self._getNextFilename())
            filename = self._filenames[-1]
            _installProfileCustomFuncs(filename)
            Profile = profile.Profile
            statement = 'globalProfileSessionResult[0]=globalProfileSessionFunc()'
            sort = -1
            retVal = None
            prof = Profile()
            try:
                prof = prof.run(statement)
            except SystemExit:
                pass

        prof.dump_stats(filename)
        del prof.dispatcher
        profData = _getProfileResultFileInfo(filename)
        self._filename2ramFile[filename] = profData
        maxTime = 0.0
        for cc, nc, tt, ct, callers in profData[1].itervalues():
            if ct > maxTime:
                maxTime = ct

        self._duration = maxTime
        _removeProfileCustomFuncs(filename)
        result = globalProfileSessionResult[0]
        del __builtin__.__dict__['globalProfileSessionFunc']
        del __builtin__.__dict__['globalProfileSessionResult']
        self._successfulProfiles += 1
        if self._logAfterProfile:
            self.notify.info(self.getResults())
        self.release()
        return result

    def getDuration(self):
        return self._duration

    def profileSucceeded(self):
        return self._successfulProfiles > 0

    def _restoreRamFile(self, filename):
        _installProfileCustomFuncs(filename)
        _setProfileResultsFileInfo(filename, self._filename2ramFile[filename])

    def _discardRamFile(self, filename):
        _removeProfileCustomFuncs(filename)
        del self._filename2ramFile[filename]

    def setName(self, name):
        self._name = name

    def getName(self):
        return self._name

    def setFunc(self, func):
        self._func = func

    def getFunc(self):
        return self._func

    def setAggregate(self, aggregate):
        self._aggregate = aggregate

    def getAggregate(self):
        return self._aggregate

    def setLogAfterProfile(self, logAfterProfile):
        self._logAfterProfile = logAfterProfile

    def getLogAfterProfile(self):
        return self._logAfterProfile

    def setLines(self, lines):
        self._lines = lines

    def getLines(self):
        return self._lines

    def setSorts(self, sorts):
        self._sorts = sorts

    def getSorts(self):
        return self._sorts

    def setShowCallInfo(self, showCallInfo):
        self._showCallInfo = showCallInfo

    def getShowCallInfo(self):
        return self._showCallInfo

    def setTotalTime(self, totalTime=None):
        self._totalTime = totalTime

    def resetTotalTime(self):
        self._totalTime = None
        return

    def getTotalTime(self):
        return self._totalTime

    def aggregate(self, other):
        other._compileStats()
        self._compileStats()
        self._stats.add(other._stats)

    def _compileStats(self):
        statsChanged = self._statFileCounter < len(self._filenames)
        if self._stats is None:
            for filename in self._filenames:
                self._restoreRamFile(filename)

            self._stats = PercentStats(*self._filenames)
            self._statFileCounter = len(self._filenames)
            for filename in self._filenames:
                self._discardRamFile(filename)

        else:
            while self._statFileCounter < len(self._filenames):
                filename = self._filenames[self._statFileCounter]
                self._restoreRamFile(filename)
                self._stats.add(filename)
                self._discardRamFile(filename)

        if statsChanged:
            self._stats.strip_dirs()
            self._resultCache = {}
        return statsChanged

    def getResults(self,
                   lines=Default,
                   sorts=Default,
                   callInfo=Default,
                   totalTime=Default):
        if not self.profileSucceeded():
            output = '%s: profiler already running, could not profile' % self._name
        else:
            if lines is Default:
                lines = self._lines
            if sorts is Default:
                sorts = self._sorts
            if callInfo is Default:
                callInfo = self._callInfo
            if totalTime is Default:
                totalTime = self._totalTime
            self._compileStats()
            if totalTime is None:
                totalTime = self._stats.total_tt
            lines = int(lines)
            sorts = list(sorts)
            callInfo = bool(callInfo)
            totalTime = float(totalTime)
            k = str((lines, sorts, callInfo, totalTime))
            if k in self._resultCache:
                output = self._resultCache[k]
            else:
                sc = StdoutCapture()
                s = self._stats
                s.setTotalTime(totalTime)
                for sort in sorts:
                    s.sort_stats(sort)
                    s.print_stats(lines)
                    if callInfo:
                        s.print_callees(lines)
                        s.print_callers(lines)

                output = sc.getString()
                sc.destroy()
                self._resultCache[k] = output
        return output
Example #12
0
    def __init__(self):
        DirectObject.__init__(self)

        if ConfigVariableBool("want-pstats", False):
            PStatClient.connect()

        self.docTitle = ""
        self.viewportName = ""

        self.renderRequested = False

        ###################################################################
        # Minimal emulation of ShowBase glue code. Note we're not using
        # ShowBase because there's too much going on in there that assumes
        # too much (one camera, one lens, one aspect2d, lots of bloat).

        self.graphicsEngine = GraphicsEngine.getGlobalPtr()
        self.pipe = GraphicsPipeSelection.getGlobalPtr().makeDefaultPipe()
        if not self.pipe:
            self.notify.error("No graphics pipe is available!")
            return

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

        self.loader = CogInvasionLoader(self)
        self.graphicsEngine.setDefaultLoader(self.loader.loader)
        builtins.loader = self.loader

        self.taskMgr = taskMgr
        builtins.taskMgr = self.taskMgr

        self.dgTrav = DataGraphTraverser()

        self.dataRoot = NodePath("data")
        self.hidden = NodePath("hidden")

        self.aspect2d = NodePath("aspect2d")
        builtins.aspect2d = self.aspect2d

        # Messages that are sent regardless of the active document.
        self.messenger = messenger
        builtins.messenger = self.messenger

        builtins.base = self
        builtins.hidden = self.hidden

        ###################################################################

        self.clickTrav = CollisionTraverser()

        # All open documents.
        self.documents = []
        # The focused document.
        self.document = None

        TextNode.setDefaultFont(
            loader.loadFont("resources/models/fonts/consolas.ttf"))

        self.initialize()
Example #13
0
# Embedded file name: lib.coginvasion.base.SpeedHackChecker
"""

  Filename: SpeedHackChecker.py
  Created by: blach (19Apr15)

"""
import sys
import time
from panda3d.core import TrueClock
lastSpeedHackCheck = time.time()
lastTrueClockTime = TrueClock.getGlobalPtr().getLongTime()

def __speedHackCheckTask(task):
    global lastSpeedHackCheck
    global lastTrueClockTime
    elapsed = time.time() - lastSpeedHackCheck
    tcElapsed = TrueClock.getGlobalPtr().getLongTime() - lastTrueClockTime
    if tcElapsed > elapsed + 0.05:
        print 'Detected speed hacks, closing game.'
        sys.exit()
        return task.done
    lastSpeedHackCheck = time.time()
    lastTrueClockTime = TrueClock.getGlobalPtr().getLongTime()
    return task.cont


def startChecking():
    taskMgr.add(__speedHackCheckTask, 'speedHackCheckTask')

Example #14
0
    def __init__(self):
        #: The directory containing the main Python file of this application.
        self.mainDir = ExecutionEnvironment.getEnvironmentVariable("MAIN_DIR")
        self.main_dir = self.mainDir

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

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

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

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

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

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

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

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

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

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

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

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

        #
        # Variables pertaining to simulation ticks.
        #

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

        self.taskMgr.finalInit()
###########
fish_index = 0
user_prefix = 'LS100_' ##!!

###########

# -*- coding: utf-8 -*-
if __name__ == "__main__":
    import sys
    import numpy as np

    from multiprocessing import Value, Array, Queue
    from panda3d.core import TrueClock

    TrueClock.getGlobalPtr().setCpuAffinity(0xFFFFFFFF)

    from camera_alignment_gui import GUI_Process

    gui = GUI_Process(fish_index)
    gui.start()

    from direct.showbase.ShowBase import ShowBase
    from panda3d.core import *
    import numpy as np
    import sys
    import time
    import os
    import pickle
    import socket