PythonUtil.py 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969
  1. """Undocumented Module"""
  2. __all__ = ['indent',
  3. 'StackTrace', 'traceFunctionCall', 'traceParentCall', 'printThisCall',
  4. 'doc', 'adjust', 'difference', 'intersection', 'union',
  5. 'sameElements', 'makeList', 'makeTuple', 'list2dict', 'invertDict',
  6. 'invertDictLossless', 'uniqueElements', 'disjoint', 'contains',
  7. 'replace', 'reduceAngle', 'fitSrcAngle2Dest', 'fitDestAngle2Src',
  8. 'closestDestAngle2', 'closestDestAngle', 'binaryRepr', 'profileFunc',
  9. 'profiled', 'startProfile', 'printProfile', 'getSetterName',
  10. 'getSetter', 'Functor', 'Stack', 'Queue',
  11. 'bound', 'clamp', 'lerp', 'average', 'addListsByValue',
  12. 'boolEqual', 'lineupPos', 'formatElapsedSeconds', 'solveQuadratic',
  13. 'stackEntryInfo', 'lineInfo', 'callerInfo', 'lineTag',
  14. 'findPythonModule', 'mostDerivedLast',
  15. 'weightedChoice', 'randFloat', 'normalDistrib',
  16. 'weightedRand', 'randUint31', 'randInt32', 'randUint32',
  17. 'SerialNumGen', 'serialNum', 'uniqueName', 'Enum', 'Singleton',
  18. 'SingletonError', 'printListEnum', 'safeRepr',
  19. 'fastRepr', 'isDefaultValue',
  20. 'ScratchPad', 'Sync', 'itype', 'getNumberedTypedString',
  21. 'getNumberedTypedSortedString', 'getNumberedTypedSortedStringWithReferrers',
  22. 'getNumberedTypedSortedStringWithReferrersGen',
  23. 'printNumberedTyped', 'DelayedCall', 'DelayedFunctor',
  24. 'FrameDelayedCall', 'SubframeCall', 'getBase',
  25. 'HotkeyBreaker','logMethodCalls','GoldenRatio',
  26. 'GoldenRectangle', 'rad90', 'rad180', 'rad270', 'rad360',
  27. 'nullGen', 'loopGen', 'makeFlywheelGen', 'flywheel', 'choice',
  28. 'printStack', 'printReverseStack', 'listToIndex2item', 'listToItem2index',
  29. 'pandaBreak','pandaTrace','formatTimeCompact',
  30. 'deeptype','getProfileResultString','StdoutCapture','StdoutPassthrough',
  31. 'Averager', 'getRepository', 'formatTimeExact', 'startSuperLog', 'endSuperLog',
  32. 'typeName', 'safeTypeName', 'histogramDict', 'unescapeHtmlString']
  33. import types
  34. import string
  35. import re
  36. import math
  37. import operator
  38. import inspect
  39. import os
  40. import sys
  41. import random
  42. import time
  43. import gc
  44. #if __debug__:
  45. import traceback
  46. import __builtin__
  47. from StringIO import StringIO
  48. import marshal
  49. import unicodedata
  50. import bisect
  51. __report_indent = 3
  52. from direct.directutil import Verify
  53. from panda3d.core import ConfigVariableBool
  54. ScalarTypes = (types.FloatType, types.IntType, types.LongType)
  55. """
  56. # with one integer positional arg, this uses about 4/5 of the memory of the Functor class below
  57. def Functor(function, *args, **kArgs):
  58. argsCopy = args[:]
  59. def functor(*cArgs, **ckArgs):
  60. kArgs.update(ckArgs)
  61. return function(*(argsCopy + cArgs), **kArgs)
  62. return functor
  63. """
  64. class Functor:
  65. def __init__(self, function, *args, **kargs):
  66. assert callable(function), "function should be a callable obj"
  67. self._function = function
  68. self._args = args
  69. self._kargs = kargs
  70. if hasattr(self._function, '__name__'):
  71. self.__name__ = self._function.__name__
  72. else:
  73. self.__name__ = str(itype(self._function))
  74. if hasattr(self._function, '__doc__'):
  75. self.__doc__ = self._function.__doc__
  76. else:
  77. self.__doc__ = self.__name__
  78. def destroy(self):
  79. del self._function
  80. del self._args
  81. del self._kargs
  82. del self.__name__
  83. del self.__doc__
  84. def _do__call__(self, *args, **kargs):
  85. _kargs = self._kargs.copy()
  86. _kargs.update(kargs)
  87. return self._function(*(self._args + args), **_kargs)
  88. # this method is used in place of __call__ if we are recording creation stacks
  89. def _exceptionLoggedCreationStack__call__(self, *args, **kargs):
  90. try:
  91. return self._do__call__(*args, **kargs)
  92. except Exception, e:
  93. print '-->Functor creation stack (%s): %s' % (
  94. self.__name__, self.getCreationStackTraceCompactStr())
  95. raise
  96. __call__ = _do__call__
  97. def __repr__(self):
  98. s = 'Functor(%s' % self._function.__name__
  99. for arg in self._args:
  100. try:
  101. argStr = repr(arg)
  102. except:
  103. argStr = 'bad repr: %s' % arg.__class__
  104. s += ', %s' % argStr
  105. for karg, value in self._kargs.items():
  106. s += ', %s=%s' % (karg, repr(value))
  107. s += ')'
  108. return s
  109. class Stack:
  110. def __init__(self):
  111. self.__list = []
  112. def push(self, item):
  113. self.__list.append(item)
  114. def top(self):
  115. # return the item on the top of the stack without popping it off
  116. return self.__list[-1]
  117. def pop(self):
  118. return self.__list.pop()
  119. def clear(self):
  120. self.__list = []
  121. def isEmpty(self):
  122. return len(self.__list) == 0
  123. def __len__(self):
  124. return len(self.__list)
  125. class Queue:
  126. # FIFO queue
  127. # interface is intentionally identical to Stack (LIFO)
  128. def __init__(self):
  129. self.__list = []
  130. def push(self, item):
  131. self.__list.append(item)
  132. def top(self):
  133. # return the next item at the front of the queue without popping it off
  134. return self.__list[0]
  135. def front(self):
  136. return self.__list[0]
  137. def back(self):
  138. return self.__list[-1]
  139. def pop(self):
  140. return self.__list.pop(0)
  141. def clear(self):
  142. self.__list = []
  143. def isEmpty(self):
  144. return len(self.__list) == 0
  145. def __len__(self):
  146. return len(self.__list)
  147. if __debug__ and __name__ == '__main__':
  148. q = Queue()
  149. assert q.isEmpty()
  150. q.clear()
  151. assert q.isEmpty()
  152. q.push(10)
  153. assert not q.isEmpty()
  154. q.push(20)
  155. assert not q.isEmpty()
  156. assert len(q) == 2
  157. assert q.front() == 10
  158. assert q.back() == 20
  159. assert q.top() == 10
  160. assert q.top() == 10
  161. assert q.pop() == 10
  162. assert len(q) == 1
  163. assert not q.isEmpty()
  164. assert q.pop() == 20
  165. assert len(q) == 0
  166. assert q.isEmpty()
  167. def indent(stream, numIndents, str):
  168. """
  169. Write str to stream with numIndents in front of it
  170. """
  171. # To match emacs, instead of a tab character we will use 4 spaces
  172. stream.write(' ' * numIndents + str)
  173. #if __debug__: #RAU accdg to Darren its's ok that StackTrace is not protected by __debug__
  174. # DCR: if somebody ends up using StackTrace in production, either
  175. # A) it will be OK because it hardly ever gets called, or
  176. # B) it will be easy to track it down (grep for StackTrace)
  177. class StackTrace:
  178. def __init__(self, label="", start=0, limit=None):
  179. """
  180. label is a string (or anything that be be a string)
  181. that is printed as part of the trace back.
  182. This is just to make it easier to tell what the
  183. stack trace is referring to.
  184. start is an integer number of stack frames back
  185. from the most recent. (This is automatically
  186. bumped up by one to skip the __init__ call
  187. to the StackTrace).
  188. limit is an integer number of stack frames
  189. to record (or None for unlimited).
  190. """
  191. self.label = label
  192. if limit is not None:
  193. self.trace = traceback.extract_stack(sys._getframe(1+start),
  194. limit=limit)
  195. else:
  196. self.trace = traceback.extract_stack(sys._getframe(1+start))
  197. def compact(self):
  198. r = ''
  199. comma = ','
  200. for filename, lineNum, funcName, text in self.trace:
  201. r += '%s.%s:%s%s' % (filename[:filename.rfind('.py')][filename.rfind('\\')+1:], funcName, lineNum, comma)
  202. if len(r):
  203. r = r[:-len(comma)]
  204. return r
  205. def reverseCompact(self):
  206. r = ''
  207. comma = ','
  208. for filename, lineNum, funcName, text in self.trace:
  209. r = '%s.%s:%s%s%s' % (filename[:filename.rfind('.py')][filename.rfind('\\')+1:], funcName, lineNum, comma, r)
  210. if len(r):
  211. r = r[:-len(comma)]
  212. return r
  213. def __str__(self):
  214. r = "Debug stack trace of %s (back %s frames):\n"%(
  215. self.label, len(self.trace),)
  216. for i in traceback.format_list(self.trace):
  217. r+=i
  218. r+="***** NOTE: This is not a crash. This is a debug stack trace. *****"
  219. return r
  220. def printStack():
  221. print StackTrace(start=1).compact()
  222. return True
  223. def printReverseStack():
  224. print StackTrace(start=1).reverseCompact()
  225. return True
  226. def printVerboseStack():
  227. print StackTrace(start=1)
  228. return True
  229. #-----------------------------------------------------------------------------
  230. def traceFunctionCall(frame):
  231. """
  232. return a string that shows the call frame with calling arguments.
  233. e.g.
  234. foo(x=234, y=135)
  235. """
  236. f = frame
  237. co = f.f_code
  238. dict = f.f_locals
  239. n = co.co_argcount
  240. if co.co_flags & 4: n = n+1
  241. if co.co_flags & 8: n = n+1
  242. r=''
  243. if 'self' in dict:
  244. r = '%s.'%(dict['self'].__class__.__name__,)
  245. r+="%s("%(f.f_code.co_name,)
  246. comma=0 # formatting, whether we should type a comma.
  247. for i in range(n):
  248. name = co.co_varnames[i]
  249. if name=='self':
  250. continue
  251. if comma:
  252. r+=', '
  253. else:
  254. # ok, we skipped the first one, the rest get commas:
  255. comma=1
  256. r+=name
  257. r+='='
  258. if name in dict:
  259. v=safeRepr(dict[name])
  260. if len(v)>2000:
  261. # r+="<too big for debug>"
  262. r += (v[:2000] + "...")
  263. else:
  264. r+=v
  265. else: r+="*** undefined ***"
  266. return r+')'
  267. def traceParentCall():
  268. return traceFunctionCall(sys._getframe(2))
  269. def printThisCall():
  270. print traceFunctionCall(sys._getframe(1))
  271. return 1 # to allow "assert printThisCall()"
  272. # Magic numbers: These are the bit masks in func_code.co_flags that
  273. # reveal whether or not the function has a *arg or **kw argument.
  274. _POS_LIST = 4
  275. _KEY_DICT = 8
  276. def doc(obj):
  277. if (isinstance(obj, types.MethodType)) or \
  278. (isinstance(obj, types.FunctionType)):
  279. print obj.__doc__
  280. def adjust(command = None, dim = 1, parent = None, **kw):
  281. """
  282. adjust(command = None, parent = None, **kw)
  283. Popup and entry scale to adjust a parameter
  284. Accepts any Slider keyword argument. Typical arguments include:
  285. command: The one argument command to execute
  286. min: The min value of the slider
  287. max: The max value of the slider
  288. resolution: The resolution of the slider
  289. text: The label on the slider
  290. These values can be accessed and/or changed after the fact
  291. >>> vg = adjust()
  292. >>> vg['min']
  293. 0.0
  294. >>> vg['min'] = 10.0
  295. >>> vg['min']
  296. 10.0
  297. """
  298. # Make sure we enable Tk
  299. from direct.tkwidgets import Valuator
  300. # Set command if specified
  301. if command:
  302. kw['command'] = lambda x: apply(command, x)
  303. if parent is None:
  304. kw['title'] = command.__name__
  305. kw['dim'] = dim
  306. # Create toplevel if needed
  307. if not parent:
  308. vg = apply(Valuator.ValuatorGroupPanel, (parent,), kw)
  309. else:
  310. vg = apply(Valuator.ValuatorGroup, (parent,), kw)
  311. vg.pack(expand = 1, fill = 'x')
  312. return vg
  313. def difference(a, b):
  314. """
  315. difference(list, list):
  316. """
  317. if not a: return b
  318. if not b: return a
  319. d = []
  320. for i in a:
  321. if (i not in b) and (i not in d):
  322. d.append(i)
  323. for i in b:
  324. if (i not in a) and (i not in d):
  325. d.append(i)
  326. return d
  327. def intersection(a, b):
  328. """
  329. intersection(list, list):
  330. """
  331. if not a: return []
  332. if not b: return []
  333. d = []
  334. for i in a:
  335. if (i in b) and (i not in d):
  336. d.append(i)
  337. for i in b:
  338. if (i in a) and (i not in d):
  339. d.append(i)
  340. return d
  341. def union(a, b):
  342. """
  343. union(list, list):
  344. """
  345. # Copy a
  346. c = a[:]
  347. for i in b:
  348. if (i not in c):
  349. c.append(i)
  350. return c
  351. def sameElements(a, b):
  352. if len(a) != len(b):
  353. return 0
  354. for elem in a:
  355. if elem not in b:
  356. return 0
  357. for elem in b:
  358. if elem not in a:
  359. return 0
  360. return 1
  361. def makeList(x):
  362. """returns x, converted to a list"""
  363. if type(x) is types.ListType:
  364. return x
  365. elif type(x) is types.TupleType:
  366. return list(x)
  367. else:
  368. return [x,]
  369. def makeTuple(x):
  370. """returns x, converted to a tuple"""
  371. if type(x) is types.ListType:
  372. return tuple(x)
  373. elif type(x) is types.TupleType:
  374. return x
  375. else:
  376. return (x,)
  377. def list2dict(L, value=None):
  378. """creates dict using elements of list, all assigned to same value"""
  379. return dict([(k, value) for k in L])
  380. def listToIndex2item(L):
  381. """converts list to dict of list index->list item"""
  382. d = {}
  383. for i, item in enumerate(L):
  384. d[i] = item
  385. return d
  386. assert listToIndex2item(['a','b']) == {0: 'a', 1: 'b',}
  387. def listToItem2index(L):
  388. """converts list to dict of list item->list index
  389. This is lossy if there are duplicate list items"""
  390. d = {}
  391. for i, item in enumerate(L):
  392. d[item] = i
  393. return d
  394. assert listToItem2index(['a','b']) == {'a': 0, 'b': 1,}
  395. def invertDict(D, lossy=False):
  396. """creates a dictionary by 'inverting' D; keys are placed in the new
  397. dictionary under their corresponding value in the old dictionary.
  398. It is an error if D contains any duplicate values.
  399. >>> old = {'key1':1, 'key2':2}
  400. >>> invertDict(old)
  401. {1: 'key1', 2: 'key2'}
  402. """
  403. n = {}
  404. for key, value in D.items():
  405. if not lossy and value in n:
  406. raise 'duplicate key in invertDict: %s' % value
  407. n[value] = key
  408. return n
  409. def invertDictLossless(D):
  410. """similar to invertDict, but values of new dict are lists of keys from
  411. old dict. No information is lost.
  412. >>> old = {'key1':1, 'key2':2, 'keyA':2}
  413. >>> invertDictLossless(old)
  414. {1: ['key1'], 2: ['key2', 'keyA']}
  415. """
  416. n = {}
  417. for key, value in D.items():
  418. n.setdefault(value, [])
  419. n[value].append(key)
  420. return n
  421. def uniqueElements(L):
  422. """are all elements of list unique?"""
  423. return len(L) == len(list2dict(L))
  424. def disjoint(L1, L2):
  425. """returns non-zero if L1 and L2 have no common elements"""
  426. used = dict([(k, None) for k in L1])
  427. for k in L2:
  428. if k in used:
  429. return 0
  430. return 1
  431. def contains(whole, sub):
  432. """
  433. Return 1 if whole contains sub, 0 otherwise
  434. """
  435. if (whole == sub):
  436. return 1
  437. for elem in sub:
  438. # The first item you find not in whole, return 0
  439. if elem not in whole:
  440. return 0
  441. # If you got here, whole must contain sub
  442. return 1
  443. def replace(list, old, new, all=0):
  444. """
  445. replace 'old' with 'new' in 'list'
  446. if all == 0, replace first occurrence
  447. otherwise replace all occurrences
  448. returns the number of items replaced
  449. """
  450. if old not in list:
  451. return 0
  452. if not all:
  453. i = list.index(old)
  454. list[i] = new
  455. return 1
  456. else:
  457. numReplaced = 0
  458. for i in xrange(len(list)):
  459. if list[i] == old:
  460. numReplaced += 1
  461. list[i] = new
  462. return numReplaced
  463. rad90 = math.pi / 2.
  464. rad180 = math.pi
  465. rad270 = 1.5 * math.pi
  466. rad360 = 2. * math.pi
  467. def reduceAngle(deg):
  468. """
  469. Reduces an angle (in degrees) to a value in [-180..180)
  470. """
  471. return (((deg + 180.) % 360.) - 180.)
  472. def fitSrcAngle2Dest(src, dest):
  473. """
  474. given a src and destination angle, returns an equivalent src angle
  475. that is within [-180..180) of dest
  476. examples:
  477. fitSrcAngle2Dest(30, 60) == 30
  478. fitSrcAngle2Dest(60, 30) == 60
  479. fitSrcAngle2Dest(0, 180) == 0
  480. fitSrcAngle2Dest(-1, 180) == 359
  481. fitSrcAngle2Dest(-180, 180) == 180
  482. """
  483. return dest + reduceAngle(src - dest)
  484. def fitDestAngle2Src(src, dest):
  485. """
  486. given a src and destination angle, returns an equivalent dest angle
  487. that is within [-180..180) of src
  488. examples:
  489. fitDestAngle2Src(30, 60) == 60
  490. fitDestAngle2Src(60, 30) == 30
  491. fitDestAngle2Src(0, 180) == -180
  492. fitDestAngle2Src(1, 180) == 180
  493. """
  494. return src + (reduceAngle(dest - src))
  495. def closestDestAngle2(src, dest):
  496. # The function above didn't seem to do what I wanted. So I hacked
  497. # this one together. I can't really say I understand it. It's more
  498. # from impirical observation... GRW
  499. diff = src - dest
  500. if diff > 180:
  501. # if the difference is greater that 180 it's shorter to go the other way
  502. return dest - 360
  503. elif diff < -180:
  504. # or perhaps the OTHER other way...
  505. return dest + 360
  506. else:
  507. # otherwise just go to the original destination
  508. return dest
  509. def closestDestAngle(src, dest):
  510. # The function above didn't seem to do what I wanted. So I hacked
  511. # this one together. I can't really say I understand it. It's more
  512. # from impirical observation... GRW
  513. diff = src - dest
  514. if diff > 180:
  515. # if the difference is greater that 180 it's shorter to go the other way
  516. return src - (diff - 360)
  517. elif diff < -180:
  518. # or perhaps the OTHER other way...
  519. return src - (360 + diff)
  520. else:
  521. # otherwise just go to the original destination
  522. return dest
  523. def binaryRepr(number, max_length = 32):
  524. # This will only work reliably for relatively small numbers.
  525. # Increase the value of max_length if you think you're going
  526. # to use long integers
  527. assert number < 2L << max_length
  528. shifts = map (operator.rshift, max_length * [number], \
  529. range (max_length - 1, -1, -1))
  530. digits = map (operator.mod, shifts, max_length * [2])
  531. if not digits.count (1): return 0
  532. digits = digits [digits.index (1):]
  533. return ''.join([repr(digit) for digit in digits])
  534. class StdoutCapture:
  535. # redirects stdout to a string
  536. def __init__(self):
  537. self._oldStdout = sys.stdout
  538. sys.stdout = self
  539. self._string = ''
  540. def destroy(self):
  541. sys.stdout = self._oldStdout
  542. del self._oldStdout
  543. def getString(self):
  544. return self._string
  545. # internal
  546. def write(self, string):
  547. self._string = ''.join([self._string, string])
  548. class StdoutPassthrough(StdoutCapture):
  549. # like StdoutCapture but also allows output to go through to the OS as normal
  550. # internal
  551. def write(self, string):
  552. self._string = ''.join([self._string, string])
  553. self._oldStdout.write(string)
  554. # constant profile defaults
  555. PyUtilProfileDefaultFilename = 'profiledata'
  556. PyUtilProfileDefaultLines = 80
  557. PyUtilProfileDefaultSorts = ['cumulative', 'time', 'calls']
  558. _ProfileResultStr = ''
  559. def getProfileResultString():
  560. # if you called profile with 'log' not set to True,
  561. # you can call this function to get the results as
  562. # a string
  563. global _ProfileResultStr
  564. return _ProfileResultStr
  565. def profileFunc(callback, name, terse, log=True):
  566. global _ProfileResultStr
  567. if 'globalProfileFunc' in __builtin__.__dict__:
  568. # rats. Python profiler is not re-entrant...
  569. base.notify.warning(
  570. 'PythonUtil.profileStart(%s): aborted, already profiling %s'
  571. #'\nStack Trace:\n%s'
  572. % (name, __builtin__.globalProfileFunc,
  573. #StackTrace()
  574. ))
  575. return
  576. __builtin__.globalProfileFunc = callback
  577. __builtin__.globalProfileResult = [None]
  578. prefix = '***** START PROFILE: %s *****' % name
  579. if log:
  580. print prefix
  581. startProfile(cmd='globalProfileResult[0]=globalProfileFunc()', callInfo=(not terse), silent=not log)
  582. suffix = '***** END PROFILE: %s *****' % name
  583. if log:
  584. print suffix
  585. else:
  586. _ProfileResultStr = '%s\n%s\n%s' % (prefix, _ProfileResultStr, suffix)
  587. result = globalProfileResult[0]
  588. del __builtin__.__dict__['globalProfileFunc']
  589. del __builtin__.__dict__['globalProfileResult']
  590. return result
  591. def profiled(category=None, terse=False):
  592. """ decorator for profiling functions
  593. turn categories on and off via "want-profile-categoryName 1"
  594. e.g.
  595. @profiled('particles')
  596. def loadParticles():
  597. ...
  598. want-profile-particles 1
  599. """
  600. assert type(category) in (types.StringType, types.NoneType), "must provide a category name for @profiled"
  601. # allow profiling in published versions
  602. """
  603. try:
  604. null = not __dev__
  605. except:
  606. null = not __debug__
  607. if null:
  608. # if we're not in __dev__, just return the function itself. This
  609. # results in zero runtime overhead, since decorators are evaluated
  610. # at module-load.
  611. def nullDecorator(f):
  612. return f
  613. return nullDecorator
  614. """
  615. def profileDecorator(f):
  616. def _profiled(*args, **kArgs):
  617. name = '(%s) %s from %s' % (category, f.func_name, f.__module__)
  618. # showbase might not be loaded yet, so don't use
  619. # base.config. Instead, query the ConfigVariableBool.
  620. if (category is None) or ConfigVariableBool('want-profile-%s' % category, 0).getValue():
  621. return profileFunc(Functor(f, *args, **kArgs), name, terse)
  622. else:
  623. return f(*args, **kArgs)
  624. _profiled.__doc__ = f.__doc__
  625. return _profiled
  626. return profileDecorator
  627. # intercept profile-related file operations to avoid disk access
  628. movedOpenFuncs = []
  629. movedDumpFuncs = []
  630. movedLoadFuncs = []
  631. profileFilenames = set()
  632. profileFilenameList = Stack()
  633. profileFilename2file = {}
  634. profileFilename2marshalData = {}
  635. def _profileOpen(filename, *args, **kArgs):
  636. # this is a replacement for the file open() builtin function
  637. # for use during profiling, to intercept the file open
  638. # operation used by the Python profiler and profile stats
  639. # systems
  640. if filename in profileFilenames:
  641. # if this is a file related to profiling, create an
  642. # in-RAM file object
  643. if filename not in profileFilename2file:
  644. file = StringIO()
  645. file._profFilename = filename
  646. profileFilename2file[filename] = file
  647. else:
  648. file = profileFilename2file[filename]
  649. else:
  650. file = movedOpenFuncs[-1](filename, *args, **kArgs)
  651. return file
  652. def _profileMarshalDump(data, file):
  653. # marshal.dump doesn't work with StringIO objects
  654. # simulate it
  655. if isinstance(file, StringIO) and hasattr(file, '_profFilename'):
  656. if file._profFilename in profileFilenames:
  657. profileFilename2marshalData[file._profFilename] = data
  658. return None
  659. return movedDumpFuncs[-1](data, file)
  660. def _profileMarshalLoad(file):
  661. # marshal.load doesn't work with StringIO objects
  662. # simulate it
  663. if isinstance(file, StringIO) and hasattr(file, '_profFilename'):
  664. if file._profFilename in profileFilenames:
  665. return profileFilename2marshalData[file._profFilename]
  666. return movedLoadFuncs[-1](file)
  667. def _installProfileCustomFuncs(filename):
  668. assert filename not in profileFilenames
  669. profileFilenames.add(filename)
  670. profileFilenameList.push(filename)
  671. movedOpenFuncs.append(__builtin__.open)
  672. __builtin__.open = _profileOpen
  673. movedDumpFuncs.append(marshal.dump)
  674. marshal.dump = _profileMarshalDump
  675. movedLoadFuncs.append(marshal.load)
  676. marshal.load = _profileMarshalLoad
  677. def _getProfileResultFileInfo(filename):
  678. return (profileFilename2file.get(filename, None),
  679. profileFilename2marshalData.get(filename, None))
  680. def _setProfileResultsFileInfo(filename, info):
  681. f, m = info
  682. if f:
  683. profileFilename2file[filename] = f
  684. if m:
  685. profileFilename2marshalData[filename] = m
  686. def _clearProfileResultFileInfo(filename):
  687. profileFilename2file.pop(filename, None)
  688. profileFilename2marshalData.pop(filename, None)
  689. def _removeProfileCustomFuncs(filename):
  690. assert profileFilenameList.top() == filename
  691. marshal.load = movedLoadFuncs.pop()
  692. marshal.dump = movedDumpFuncs.pop()
  693. __builtin__.open = movedOpenFuncs.pop()
  694. profileFilenames.remove(filename)
  695. profileFilenameList.pop()
  696. profileFilename2file.pop(filename, None)
  697. # don't let marshalled data pile up
  698. profileFilename2marshalData.pop(filename, None)
  699. # call this from the prompt, and break back out to the prompt
  700. # to stop profiling
  701. #
  702. # OR to do inline profiling, you must make a globally-visible
  703. # function to be profiled, i.e. to profile 'self.load()', do
  704. # something like this:
  705. #
  706. # def func(self=self):
  707. # self.load()
  708. # import __builtin__
  709. # __builtin__.func = func
  710. # PythonUtil.startProfile(cmd='func()', filename='profileData')
  711. # del __builtin__.func
  712. #
  713. def _profileWithoutGarbageLeak(cmd, filename):
  714. # The profile module isn't necessarily installed on every Python
  715. # installation, so we import it here, instead of in the module
  716. # scope.
  717. import profile
  718. # this is necessary because the profile module creates a memory leak
  719. Profile = profile.Profile
  720. statement = cmd
  721. sort = -1
  722. retVal = None
  723. #### COPIED FROM profile.run ####
  724. prof = Profile()
  725. try:
  726. prof = prof.run(statement)
  727. except SystemExit:
  728. pass
  729. if filename is not None:
  730. prof.dump_stats(filename)
  731. else:
  732. #return prof.print_stats(sort) #DCR
  733. retVal = prof.print_stats(sort) #DCR
  734. #################################
  735. # eliminate the garbage leak
  736. del prof.dispatcher
  737. return retVal
  738. def startProfile(filename=PyUtilProfileDefaultFilename,
  739. lines=PyUtilProfileDefaultLines,
  740. sorts=PyUtilProfileDefaultSorts,
  741. silent=0,
  742. callInfo=1,
  743. useDisk=False,
  744. cmd='run()'):
  745. # uniquify the filename to allow multiple processes to profile simultaneously
  746. filename = '%s.%s%s' % (filename, randUint31(), randUint31())
  747. if not useDisk:
  748. # use a RAM file
  749. _installProfileCustomFuncs(filename)
  750. _profileWithoutGarbageLeak(cmd, filename)
  751. if silent:
  752. extractProfile(filename, lines, sorts, callInfo)
  753. else:
  754. printProfile(filename, lines, sorts, callInfo)
  755. if not useDisk:
  756. # discard the RAM file
  757. _removeProfileCustomFuncs(filename)
  758. else:
  759. os.remove(filename)
  760. # call these to see the results again, as a string or in the log
  761. def printProfile(filename=PyUtilProfileDefaultFilename,
  762. lines=PyUtilProfileDefaultLines,
  763. sorts=PyUtilProfileDefaultSorts,
  764. callInfo=1):
  765. import pstats
  766. s = pstats.Stats(filename)
  767. s.strip_dirs()
  768. for sort in sorts:
  769. s.sort_stats(sort)
  770. s.print_stats(lines)
  771. if callInfo:
  772. s.print_callees(lines)
  773. s.print_callers(lines)
  774. # same args as printProfile
  775. def extractProfile(*args, **kArgs):
  776. global _ProfileResultStr
  777. # capture print output
  778. sc = StdoutCapture()
  779. # print the profile output, redirected to the result string
  780. printProfile(*args, **kArgs)
  781. # make a copy of the print output
  782. _ProfileResultStr = sc.getString()
  783. # restore stdout to what it was before
  784. sc.destroy()
  785. def getSetterName(valueName, prefix='set'):
  786. # getSetterName('color') -> 'setColor'
  787. # getSetterName('color', 'get') -> 'getColor'
  788. return '%s%s%s' % (prefix, valueName[0].upper(), valueName[1:])
  789. def getSetter(targetObj, valueName, prefix='set'):
  790. # getSetter(smiley, 'pos') -> smiley.setPos
  791. return getattr(targetObj, getSetterName(valueName, prefix))
  792. def mostDerivedLast(classList):
  793. """pass in list of classes. sorts list in-place, with derived classes
  794. appearing after their bases"""
  795. class ClassSortKey(object):
  796. __slots__ = 'classobj',
  797. def __init__(self, classobj):
  798. self.classobj = classobj
  799. def __lt__(self, other):
  800. return issubclass(other.classobj, self.classobj)
  801. classList.sort(key=ClassSortKey)
  802. def bound(value, bound1, bound2):
  803. """
  804. returns value if value is between bound1 and bound2
  805. otherwise returns bound that is closer to value
  806. """
  807. if bound1 > bound2:
  808. return min(max(value, bound2), bound1)
  809. else:
  810. return min(max(value, bound1), bound2)
  811. clamp = bound
  812. def lerp(v0, v1, t):
  813. """
  814. returns a value lerped between v0 and v1, according to t
  815. t == 0 maps to v0, t == 1 maps to v1
  816. """
  817. return v0 + ((v1 - v0) * t)
  818. def getShortestRotation(start, end):
  819. """
  820. Given two heading values, return a tuple describing
  821. the shortest interval from 'start' to 'end'. This tuple
  822. can be used to lerp a camera between two rotations
  823. while avoiding the 'spin' problem.
  824. """
  825. start, end = start % 360, end % 360
  826. if abs(end - start) > 180:
  827. if end < start:
  828. end += 360
  829. else:
  830. start += 360
  831. return (start, end)
  832. def average(*args):
  833. """ returns simple average of list of values """
  834. val = 0.
  835. for arg in args:
  836. val += arg
  837. return val / len(args)
  838. class Averager:
  839. def __init__(self, name):
  840. self._name = name
  841. self.reset()
  842. def reset(self):
  843. self._total = 0.
  844. self._count = 0
  845. def addValue(self, value):
  846. self._total += value
  847. self._count += 1
  848. def getAverage(self):
  849. return self._total / self._count
  850. def getCount(self):
  851. return self._count
  852. def addListsByValue(a, b):
  853. """
  854. returns a new array containing the sums of the two array arguments
  855. (c[0] = a[0 + b[0], etc.)
  856. """
  857. c = []
  858. for x, y in zip(a, b):
  859. c.append(x + y)
  860. return c
  861. def boolEqual(a, b):
  862. """
  863. returns true if a and b are both true or both false.
  864. returns false otherwise
  865. (a.k.a. xnor -- eXclusive Not OR).
  866. """
  867. return (a and b) or not (a or b)
  868. def lineupPos(i, num, spacing):
  869. """
  870. use to line up a series of 'num' objects, in one dimension,
  871. centered around zero
  872. 'i' is the index of the object in the lineup
  873. 'spacing' is the amount of space between objects in the lineup
  874. """
  875. assert num >= 1
  876. assert i >= 0 and i < num
  877. pos = float(i) * spacing
  878. return pos - ((float(spacing) * (num-1))/2.)
  879. def formatElapsedSeconds(seconds):
  880. """
  881. Returns a string of the form "mm:ss" or "hh:mm:ss" or "n days",
  882. representing the indicated elapsed time in seconds.
  883. """
  884. sign = ''
  885. if seconds < 0:
  886. seconds = -seconds
  887. sign = '-'
  888. # We use math.floor() instead of casting to an int, so we avoid
  889. # problems with numbers that are too large to represent as
  890. # type int.
  891. seconds = math.floor(seconds)
  892. hours = math.floor(seconds / (60 * 60))
  893. if hours > 36:
  894. days = math.floor((hours + 12) / 24)
  895. return "%s%d days" % (sign, days)
  896. seconds -= hours * (60 * 60)
  897. minutes = (int)(seconds / 60)
  898. seconds -= minutes * 60
  899. if hours != 0:
  900. return "%s%d:%02d:%02d" % (sign, hours, minutes, seconds)
  901. else:
  902. return "%s%d:%02d" % (sign, minutes, seconds)
  903. def solveQuadratic(a, b, c):
  904. # quadratic equation: ax^2 + bx + c = 0
  905. # quadratic formula: x = [-b +/- sqrt(b^2 - 4ac)] / 2a
  906. # returns None, root, or [root1, root2]
  907. # a cannot be zero.
  908. if a == 0.:
  909. return None
  910. # calculate the determinant (b^2 - 4ac)
  911. D = (b * b) - (4. * a * c)
  912. if D < 0:
  913. # there are no solutions (sqrt(negative number) is undefined)
  914. return None
  915. elif D == 0:
  916. # only one root
  917. return (-b) / (2. * a)
  918. else:
  919. # OK, there are two roots
  920. sqrtD = math.sqrt(D)
  921. twoA = 2. * a
  922. root1 = ((-b) - sqrtD) / twoA
  923. root2 = ((-b) + sqrtD) / twoA
  924. return [root1, root2]
  925. def stackEntryInfo(depth=0, baseFileName=1):
  926. """
  927. returns the sourcefilename, line number, and function name of
  928. an entry in the stack.
  929. 'depth' is how far back to go in the stack; 0 is the caller of this
  930. function, 1 is the function that called the caller of this function, etc.
  931. by default, strips off the path of the filename; override with baseFileName
  932. returns (fileName, lineNum, funcName) --> (string, int, string)
  933. returns (None, None, None) on error
  934. """
  935. try:
  936. stack = None
  937. frame = None
  938. try:
  939. stack = inspect.stack()
  940. # add one to skip the frame associated with this function
  941. frame = stack[depth+1]
  942. filename = frame[1]
  943. if baseFileName:
  944. filename = os.path.basename(filename)
  945. lineNum = frame[2]
  946. funcName = frame[3]
  947. result = (filename, lineNum, funcName)
  948. finally:
  949. del stack
  950. del frame
  951. except:
  952. result = (None, None, None)
  953. return result
  954. def lineInfo(baseFileName=1):
  955. """
  956. returns the sourcefilename, line number, and function name of the
  957. code that called this function
  958. (answers the question: 'hey lineInfo, where am I in the codebase?')
  959. see stackEntryInfo, above, for info on 'baseFileName' and return types
  960. """
  961. return stackEntryInfo(1, baseFileName)
  962. def callerInfo(baseFileName=1, howFarBack=0):
  963. """
  964. returns the sourcefilename, line number, and function name of the
  965. caller of the function that called this function
  966. (answers the question: 'hey callerInfo, who called me?')
  967. see stackEntryInfo, above, for info on 'baseFileName' and return types
  968. """
  969. return stackEntryInfo(2+howFarBack, baseFileName)
  970. def lineTag(baseFileName=1, verbose=0, separator=':'):
  971. """
  972. returns a string containing the sourcefilename and line number
  973. of the code that called this function
  974. (equivalent to lineInfo, above, with different return type)
  975. see stackEntryInfo, above, for info on 'baseFileName'
  976. if 'verbose' is false, returns a compact string of the form
  977. 'fileName:lineNum:funcName'
  978. if 'verbose' is true, returns a longer string that matches the
  979. format of Python stack trace dumps
  980. returns empty string on error
  981. """
  982. fileName, lineNum, funcName = callerInfo(baseFileName)
  983. if fileName is None:
  984. return ''
  985. if verbose:
  986. return 'File "%s", line %s, in %s' % (fileName, lineNum, funcName)
  987. else:
  988. return '%s%s%s%s%s' % (fileName, separator, lineNum, separator,
  989. funcName)
  990. def findPythonModule(module):
  991. # Look along the python load path for the indicated filename.
  992. # Returns the located pathname, or None if the filename is not
  993. # found.
  994. filename = module + '.py'
  995. for dir in sys.path:
  996. pathname = os.path.join(dir, filename)
  997. if os.path.exists(pathname):
  998. return pathname
  999. return None
  1000. def weightedChoice(choiceList, rng=random.random, sum=None):
  1001. """given a list of (weight, item) pairs, chooses an item based on the
  1002. weights. rng must return 0..1. if you happen to have the sum of the
  1003. weights, pass it in 'sum'."""
  1004. # TODO: add support for dicts
  1005. if sum is None:
  1006. sum = 0.
  1007. for weight, item in choiceList:
  1008. sum += weight
  1009. rand = rng()
  1010. accum = rand * sum
  1011. for weight, item in choiceList:
  1012. accum -= weight
  1013. if accum <= 0.:
  1014. return item
  1015. # rand is ~1., and floating-point error prevented accum from hitting 0.
  1016. # Or you passed in a 'sum' that was was too large.
  1017. # Return the last item.
  1018. return item
  1019. def randFloat(a, b=0., rng=random.random):
  1020. """returns a random float in [a, b]
  1021. call with single argument to generate random float between arg and zero
  1022. """
  1023. return lerp(a, b, rng())
  1024. def normalDistrib(a, b, gauss=random.gauss):
  1025. """
  1026. NOTE: assumes a < b
  1027. Returns random number between a and b, using gaussian distribution, with
  1028. mean=avg(a, b), and a standard deviation that fits ~99.7% of the curve
  1029. between a and b.
  1030. For ease of use, outlying results are re-computed until result is in [a, b]
  1031. This should fit the remaining .3% of the curve that lies outside [a, b]
  1032. uniformly onto the curve inside [a, b]
  1033. ------------------------------------------------------------------------
  1034. http://www-stat.stanford.edu/~naras/jsm/NormalDensity/NormalDensity.html
  1035. The 68-95-99.7% Rule
  1036. ====================
  1037. All normal density curves satisfy the following property which is often
  1038. referred to as the Empirical Rule:
  1039. 68% of the observations fall within 1 standard deviation of the mean.
  1040. 95% of the observations fall within 2 standard deviations of the mean.
  1041. 99.7% of the observations fall within 3 standard deviations of the mean.
  1042. Thus, for a normal distribution, almost all values lie within 3 standard
  1043. deviations of the mean.
  1044. ------------------------------------------------------------------------
  1045. In calculating our standard deviation, we divide (b-a) by 6, since the
  1046. 99.7% figure includes 3 standard deviations _on_either_side_ of the mean.
  1047. """
  1048. while True:
  1049. r = gauss((a+b)*.5, (b-a)/6.)
  1050. if (r >= a) and (r <= b):
  1051. return r
  1052. def weightedRand(valDict, rng=random.random):
  1053. """
  1054. pass in a dictionary with a selection -> weight mapping. Eg.
  1055. {"Choice 1": 10,
  1056. "Choice 2": 30,
  1057. "bear": 100}
  1058. -Weights need not add up to any particular value.
  1059. -The actual selection will be returned.
  1060. """
  1061. selections = valDict.keys()
  1062. weights = valDict.values()
  1063. totalWeight = 0
  1064. for weight in weights:
  1065. totalWeight += weight
  1066. # get a random value between 0 and the total of the weights
  1067. randomWeight = rng() * totalWeight
  1068. # find the index that corresponds with this weight
  1069. for i in range(len(weights)):
  1070. totalWeight -= weights[i]
  1071. if totalWeight <= randomWeight:
  1072. return selections[i]
  1073. assert True, "Should never get here"
  1074. return selections[-1]
  1075. def randUint31(rng=random.random):
  1076. """returns a random integer in [0..2^31).
  1077. rng must return float in [0..1]"""
  1078. return int(rng() * 0x7FFFFFFF)
  1079. def randInt32(rng=random.random):
  1080. """returns a random integer in [-2147483648..2147483647].
  1081. rng must return float in [0..1]
  1082. """
  1083. i = int(rng() * 0x7FFFFFFF)
  1084. if rng() < .5:
  1085. i *= -1
  1086. return i
  1087. def randUint32(rng=random.random):
  1088. """returns a random integer in [0..2^32).
  1089. rng must return float in [0..1]"""
  1090. return long(rng() * 0xFFFFFFFFL)
  1091. class SerialNumGen:
  1092. """generates serial numbers"""
  1093. def __init__(self, start=None):
  1094. if start is None:
  1095. start = 0
  1096. self.__counter = start-1
  1097. def next(self):
  1098. self.__counter += 1
  1099. return self.__counter
  1100. class SerialMaskedGen(SerialNumGen):
  1101. def __init__(self, mask, start=None):
  1102. self._mask = mask
  1103. SerialNumGen.__init__(self, start)
  1104. def next(self):
  1105. v = SerialNumGen.next(self)
  1106. return v & self._mask
  1107. _serialGen = SerialNumGen()
  1108. def serialNum():
  1109. global _serialGen
  1110. return _serialGen.next()
  1111. def uniqueName(name):
  1112. global _serialGen
  1113. return '%s-%s' % (name, _serialGen.next())
  1114. class EnumIter:
  1115. def __init__(self, enum):
  1116. self._values = enum._stringTable.keys()
  1117. self._index = 0
  1118. def __iter__(self):
  1119. return self
  1120. def next(self):
  1121. if self._index >= len(self._values):
  1122. raise StopIteration
  1123. self._index += 1
  1124. return self._values[self._index-1]
  1125. class Enum:
  1126. """Pass in list of strings or string of comma-separated strings.
  1127. Items are accessible as instance.item, and are assigned unique,
  1128. increasing integer values. Pass in integer for 'start' to override
  1129. starting value.
  1130. Example:
  1131. >>> colors = Enum('red, green, blue')
  1132. >>> colors.red
  1133. 0
  1134. >>> colors.green
  1135. 1
  1136. >>> colors.blue
  1137. 2
  1138. >>> colors.getString(colors.red)
  1139. 'red'
  1140. """
  1141. if __debug__:
  1142. # chars that cannot appear within an item string.
  1143. InvalidChars = string.whitespace
  1144. def _checkValidIdentifier(item):
  1145. invalidChars = string.whitespace+string.punctuation
  1146. invalidChars = invalidChars.replace('_','')
  1147. invalidFirstChars = invalidChars+string.digits
  1148. if item[0] in invalidFirstChars:
  1149. raise SyntaxError, ("Enum '%s' contains invalid first char" %
  1150. item)
  1151. if not disjoint(item, invalidChars):
  1152. for char in item:
  1153. if char in invalidChars:
  1154. raise SyntaxError, (
  1155. "Enum\n'%s'\ncontains illegal char '%s'" %
  1156. (item, char))
  1157. return 1
  1158. _checkValidIdentifier = staticmethod(_checkValidIdentifier)
  1159. def __init__(self, items, start=0):
  1160. if type(items) == types.StringType:
  1161. items = items.split(',')
  1162. self._stringTable = {}
  1163. # make sure we don't overwrite an existing element of the class
  1164. assert self._checkExistingMembers(items)
  1165. assert uniqueElements(items)
  1166. i = start
  1167. for item in items:
  1168. # remove leading/trailing whitespace
  1169. item = string.strip(item)
  1170. # is there anything left?
  1171. if len(item) == 0:
  1172. continue
  1173. # make sure there are no invalid characters
  1174. assert Enum._checkValidIdentifier(item)
  1175. self.__dict__[item] = i
  1176. self._stringTable[i] = item
  1177. i += 1
  1178. def __iter__(self):
  1179. return EnumIter(self)
  1180. def hasString(self, string):
  1181. return string in set(self._stringTable.values())
  1182. def fromString(self, string):
  1183. if self.hasString(string):
  1184. return self.__dict__[string]
  1185. # throw an error
  1186. {}[string]
  1187. def getString(self, value):
  1188. return self._stringTable[value]
  1189. def __contains__(self, value):
  1190. return value in self._stringTable
  1191. def __len__(self):
  1192. return len(self._stringTable)
  1193. def copyTo(self, obj):
  1194. # copies all members onto obj
  1195. for name, value in self._stringTable:
  1196. setattr(obj, name, value)
  1197. if __debug__:
  1198. def _checkExistingMembers(self, items):
  1199. for item in items:
  1200. if hasattr(self, item):
  1201. return 0
  1202. return 1
  1203. ############################################################
  1204. # class: Singleton
  1205. # Purpose: This provides a base metaclass for all classes
  1206. # that require one and only one instance.
  1207. #
  1208. # Example: class mySingleton:
  1209. # __metaclass__ = PythonUtil.Singleton
  1210. # def __init__(self, ...):
  1211. # ...
  1212. #
  1213. # Note: This class is based on Python's New-Style Class
  1214. # design. An error will occur if a defined class
  1215. # attemps to inherit from a Classic-Style Class only,
  1216. # ie: class myClassX:
  1217. # def __init__(self, ...):
  1218. # ...
  1219. #
  1220. # class myNewClassX(myClassX):
  1221. # __metaclass__ = PythonUtil.Singleton
  1222. # def __init__(self, ...):
  1223. # myClassX.__init__(self, ...)
  1224. # ...
  1225. #
  1226. # This causes problems because myNewClassX is a
  1227. # New-Style class that inherits from only a
  1228. # Classic-Style base class. There are two ways
  1229. # simple ways to resolve this issue.
  1230. #
  1231. # First, if possible, make myClassX a
  1232. # New-Style class by inheriting from object
  1233. # object. IE: class myClassX(object):
  1234. #
  1235. # If for some reason that is not an option, make
  1236. # myNewClassX inherit from object and myClassX.
  1237. # IE: class myNewClassX(object, myClassX):
  1238. ############################################################
  1239. class Singleton(type):
  1240. def __init__(cls, name, bases, dic):
  1241. super(Singleton, cls).__init__(name, bases, dic)
  1242. cls.instance=None
  1243. def __call__(cls, *args, **kw):
  1244. if cls.instance is None:
  1245. cls.instance=super(Singleton, cls).__call__(*args, **kw)
  1246. return cls.instance
  1247. class SingletonError(ValueError):
  1248. """ Used to indicate an inappropriate value for a Singleton."""
  1249. def printListEnumGen(l):
  1250. # log each individual item with a number in front of it
  1251. digits = 0
  1252. n = len(l)
  1253. while n > 0:
  1254. digits += 1
  1255. n //= 10
  1256. format = '%0' + '%s' % digits + 'i:%s'
  1257. for i in range(len(l)):
  1258. print format % (i, l[i])
  1259. yield None
  1260. def printListEnum(l):
  1261. for result in printListEnumGen(l):
  1262. pass
  1263. # base class for all Panda C++ objects
  1264. # libdtoolconfig doesn't seem to have this, grab it off of PandaNode
  1265. dtoolSuperBase = None
  1266. def _getDtoolSuperBase():
  1267. global dtoolSuperBase
  1268. from panda3d.core import TypedObject
  1269. dtoolSuperBase = TypedObject.__bases__[0]
  1270. assert repr(dtoolSuperBase) == "<type 'libdtoolconfig.DTOOL_SUPER_BASE111'>" \
  1271. or repr(dtoolSuperBase) == "<type 'libdtoolconfig.DTOOL_SUPPER_BASE111'>" \
  1272. or repr(dtoolSuperBase) == "<type 'dtoolconfig.DTOOL_SUPER_BASE111'>" \
  1273. or repr(dtoolSuperBase) == "<type 'dtoolconfig.DTOOL_SUPER_BASE'>"
  1274. safeReprNotify = None
  1275. def _getSafeReprNotify():
  1276. global safeReprNotify
  1277. from direct.directnotify.DirectNotifyGlobal import directNotify
  1278. safeReprNotify = directNotify.newCategory("safeRepr")
  1279. return safeReprNotify
  1280. def safeRepr(obj):
  1281. global dtoolSuperBase
  1282. if dtoolSuperBase is None:
  1283. _getDtoolSuperBase()
  1284. global safeReprNotify
  1285. if safeReprNotify is None:
  1286. _getSafeReprNotify()
  1287. if isinstance(obj, dtoolSuperBase):
  1288. # repr of C++ object could crash, particularly if the object has been deleted
  1289. # log that we're calling repr
  1290. safeReprNotify.info('calling repr on instance of %s.%s' % (obj.__class__.__module__, obj.__class__.__name__))
  1291. sys.stdout.flush()
  1292. try:
  1293. return repr(obj)
  1294. except:
  1295. return '<** FAILED REPR OF %s instance at %s **>' % (obj.__class__.__name__, hex(id(obj)))
  1296. def safeReprTypeOnFail(obj):
  1297. global dtoolSuperBase
  1298. if dtoolSuperBase is None:
  1299. _getDtoolSuperBase()
  1300. global safeReprNotify
  1301. if safeReprNotify is None:
  1302. _getSafeReprNotify()
  1303. if isinstance(obj, dtoolSuperBase):
  1304. return type(obj)
  1305. try:
  1306. return repr(obj)
  1307. except:
  1308. return '<** FAILED REPR OF %s instance at %s **>' % (obj.__class__.__name__, hex(id(obj)))
  1309. def fastRepr(obj, maxLen=200, strFactor=10, _visitedIds=None):
  1310. """ caps the length of iterable types, so very large objects will print faster.
  1311. also prevents infinite recursion """
  1312. try:
  1313. if _visitedIds is None:
  1314. _visitedIds = set()
  1315. if id(obj) in _visitedIds:
  1316. return '<ALREADY-VISITED %s>' % itype(obj)
  1317. if type(obj) in (types.TupleType, types.ListType):
  1318. s = ''
  1319. s += {types.TupleType: '(',
  1320. types.ListType: '[',}[type(obj)]
  1321. if maxLen is not None and len(obj) > maxLen:
  1322. o = obj[:maxLen]
  1323. ellips = '...'
  1324. else:
  1325. o = obj
  1326. ellips = ''
  1327. _visitedIds.add(id(obj))
  1328. for item in o:
  1329. s += fastRepr(item, maxLen, _visitedIds=_visitedIds)
  1330. s += ', '
  1331. _visitedIds.remove(id(obj))
  1332. s += ellips
  1333. s += {types.TupleType: ')',
  1334. types.ListType: ']',}[type(obj)]
  1335. return s
  1336. elif type(obj) is types.DictType:
  1337. s = '{'
  1338. if maxLen is not None and len(obj) > maxLen:
  1339. o = obj.keys()[:maxLen]
  1340. ellips = '...'
  1341. else:
  1342. o = obj.keys()
  1343. ellips = ''
  1344. _visitedIds.add(id(obj))
  1345. for key in o:
  1346. value = obj[key]
  1347. s += '%s: %s, ' % (fastRepr(key, maxLen, _visitedIds=_visitedIds),
  1348. fastRepr(value, maxLen, _visitedIds=_visitedIds))
  1349. _visitedIds.remove(id(obj))
  1350. s += ellips
  1351. s += '}'
  1352. return s
  1353. elif type(obj) is types.StringType:
  1354. if maxLen is not None:
  1355. maxLen *= strFactor
  1356. if maxLen is not None and len(obj) > maxLen:
  1357. return safeRepr(obj[:maxLen])
  1358. else:
  1359. return safeRepr(obj)
  1360. else:
  1361. r = safeRepr(obj)
  1362. maxLen *= strFactor
  1363. if len(r) > maxLen:
  1364. r = r[:maxLen]
  1365. return r
  1366. except:
  1367. return '<** FAILED REPR OF %s **>' % obj.__class__.__name__
  1368. def convertTree(objTree, idList):
  1369. newTree = {}
  1370. for key in objTree.keys():
  1371. obj = (idList[key],)
  1372. newTree[obj] = {}
  1373. r_convertTree(objTree[key], newTree[obj], idList)
  1374. return newTree
  1375. def r_convertTree(oldTree, newTree, idList):
  1376. for key in oldTree.keys():
  1377. obj = idList.get(key)
  1378. if(not obj):
  1379. continue
  1380. obj = str(obj)[:100]
  1381. newTree[obj] = {}
  1382. r_convertTree(oldTree[key], newTree[obj], idList)
  1383. def pretty_print(tree):
  1384. for name in tree.keys():
  1385. print name
  1386. r_pretty_print(tree[name], 0)
  1387. def r_pretty_print(tree, num):
  1388. num+=1
  1389. for name in tree.keys():
  1390. print " "*num,name
  1391. r_pretty_print(tree[name],num)
  1392. def isDefaultValue(x):
  1393. return x == type(x)()
  1394. def appendStr(obj, st):
  1395. """adds a string onto the __str__ output of an instance"""
  1396. def appendedStr(oldStr, st, self):
  1397. return oldStr() + st
  1398. oldStr = getattr(obj, '__str__', None)
  1399. if oldStr is None:
  1400. def stringer(s):
  1401. return s
  1402. oldStr = Functor(stringer, str(obj))
  1403. stringer = None
  1404. obj.__str__ = types.MethodType(Functor(appendedStr, oldStr, st), obj, obj.__class__)
  1405. appendedStr = None
  1406. return obj
  1407. class ScratchPad:
  1408. """empty class to stick values onto"""
  1409. def __init__(self, **kArgs):
  1410. for key, value in kArgs.iteritems():
  1411. setattr(self, key, value)
  1412. self._keys = set(kArgs.keys())
  1413. def add(self, **kArgs):
  1414. for key, value in kArgs.iteritems():
  1415. setattr(self, key, value)
  1416. self._keys.update(kArgs.keys())
  1417. def destroy(self):
  1418. for key in self._keys:
  1419. delattr(self, key)
  1420. # allow dict [] syntax
  1421. def __getitem__(self, itemName):
  1422. return getattr(self, itemName)
  1423. def get(self, itemName, default=None):
  1424. return getattr(self, itemName, default)
  1425. # allow 'in'
  1426. def __contains__(self, itemName):
  1427. return itemName in self._keys
  1428. class Sync:
  1429. _SeriesGen = SerialNumGen()
  1430. def __init__(self, name, other=None):
  1431. self._name = name
  1432. if other is None:
  1433. self._series = self._SeriesGen.next()
  1434. self._value = 0
  1435. else:
  1436. self._series = other._series
  1437. self._value = other._value
  1438. def invalidate(self):
  1439. self._value = None
  1440. def change(self):
  1441. self._value += 1
  1442. def sync(self, other):
  1443. if (self._series != other._series) or (self._value != other._value):
  1444. self._series = other._series
  1445. self._value = other._value
  1446. return True
  1447. else:
  1448. return False
  1449. def isSynced(self, other):
  1450. return ((self._series == other._series) and
  1451. (self._value == other._value))
  1452. def __repr__(self):
  1453. return '%s(%s)<family=%s,value=%s>' % (self.__class__.__name__,
  1454. self._name, self._series, self._value)
  1455. def itype(obj):
  1456. # version of type that gives more complete information about instance types
  1457. global dtoolSuperBase
  1458. t = type(obj)
  1459. if t is types.InstanceType:
  1460. return '%s of <class %s>>' % (repr(types.InstanceType)[:-1],
  1461. str(obj.__class__))
  1462. else:
  1463. # C++ object instances appear to be types via type()
  1464. # check if this is a C++ object
  1465. if dtoolSuperBase is None:
  1466. _getDtoolSuperBase()
  1467. if isinstance(obj, dtoolSuperBase):
  1468. return '%s of %s>' % (repr(types.InstanceType)[:-1],
  1469. str(obj.__class__))
  1470. return t
  1471. def deeptype(obj, maxLen=100, _visitedIds=None):
  1472. if _visitedIds is None:
  1473. _visitedIds = set()
  1474. if id(obj) in _visitedIds:
  1475. return '<ALREADY-VISITED %s>' % itype(obj)
  1476. t = type(obj)
  1477. if t in (types.TupleType, types.ListType):
  1478. s = ''
  1479. s += {types.TupleType: '(',
  1480. types.ListType: '[',}[type(obj)]
  1481. if maxLen is not None and len(obj) > maxLen:
  1482. o = obj[:maxLen]
  1483. ellips = '...'
  1484. else:
  1485. o = obj
  1486. ellips = ''
  1487. _visitedIds.add(id(obj))
  1488. for item in o:
  1489. s += deeptype(item, maxLen, _visitedIds=_visitedIds)
  1490. s += ', '
  1491. _visitedIds.remove(id(obj))
  1492. s += ellips
  1493. s += {types.TupleType: ')',
  1494. types.ListType: ']',}[type(obj)]
  1495. return s
  1496. elif type(obj) is types.DictType:
  1497. s = '{'
  1498. if maxLen is not None and len(obj) > maxLen:
  1499. o = obj.keys()[:maxLen]
  1500. ellips = '...'
  1501. else:
  1502. o = obj.keys()
  1503. ellips = ''
  1504. _visitedIds.add(id(obj))
  1505. for key in o:
  1506. value = obj[key]
  1507. s += '%s: %s, ' % (deeptype(key, maxLen, _visitedIds=_visitedIds),
  1508. deeptype(value, maxLen, _visitedIds=_visitedIds))
  1509. _visitedIds.remove(id(obj))
  1510. s += ellips
  1511. s += '}'
  1512. return s
  1513. else:
  1514. return str(itype(obj))
  1515. def getNumberedTypedString(items, maxLen=5000, numPrefix=''):
  1516. """get a string that has each item of the list on its own line,
  1517. and each item is numbered on the left from zero"""
  1518. digits = 0
  1519. n = len(items)
  1520. while n > 0:
  1521. digits += 1
  1522. n //= 10
  1523. digits = digits
  1524. format = numPrefix + '%0' + '%s' % digits + 'i:%s \t%s'
  1525. first = True
  1526. s = ''
  1527. snip = '<SNIP>'
  1528. for i in xrange(len(items)):
  1529. if not first:
  1530. s += '\n'
  1531. first = False
  1532. objStr = fastRepr(items[i])
  1533. if len(objStr) > maxLen:
  1534. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  1535. s += format % (i, itype(items[i]), objStr)
  1536. return s
  1537. def getNumberedTypedSortedString(items, maxLen=5000, numPrefix=''):
  1538. """get a string that has each item of the list on its own line,
  1539. the items are stringwise-sorted, and each item is numbered on
  1540. the left from zero"""
  1541. digits = 0
  1542. n = len(items)
  1543. while n > 0:
  1544. digits += 1
  1545. n //= 10
  1546. digits = digits
  1547. format = numPrefix + '%0' + '%s' % digits + 'i:%s \t%s'
  1548. snip = '<SNIP>'
  1549. strs = []
  1550. for item in items:
  1551. objStr = fastRepr(item)
  1552. if len(objStr) > maxLen:
  1553. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  1554. strs.append(objStr)
  1555. first = True
  1556. s = ''
  1557. strs.sort()
  1558. for i in xrange(len(strs)):
  1559. if not first:
  1560. s += '\n'
  1561. first = False
  1562. objStr = strs[i]
  1563. s += format % (i, itype(items[i]), strs[i])
  1564. return s
  1565. def getNumberedTypedSortedStringWithReferrersGen(items, maxLen=10000, numPrefix=''):
  1566. """get a string that has each item of the list on its own line,
  1567. the items are stringwise-sorted, the object's referrers are shown,
  1568. and each item is numbered on the left from zero"""
  1569. digits = 0
  1570. n = len(items)
  1571. while n > 0:
  1572. digits += 1
  1573. n //= 10
  1574. digits = digits
  1575. format = numPrefix + '%0' + '%s' % digits + 'i:%s @ %s \t%s'
  1576. snip = '<SNIP>'
  1577. strs = []
  1578. for item in items:
  1579. strs.append(fastRepr(item))
  1580. strs.sort()
  1581. for i in xrange(len(strs)):
  1582. item = items[i]
  1583. objStr = strs[i]
  1584. objStr += ', \tREFERRERS=['
  1585. referrers = gc.get_referrers(item)
  1586. for ref in referrers:
  1587. objStr += '%s@%s, ' % (itype(ref), id(ref))
  1588. objStr += ']'
  1589. if len(objStr) > maxLen:
  1590. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  1591. yield format % (i, itype(items[i]), id(items[i]), objStr)
  1592. def getNumberedTypedSortedStringWithReferrers(items, maxLen=10000, numPrefix=''):
  1593. """get a string that has each item of the list on its own line,
  1594. the items are stringwise-sorted, the object's referrers are shown,
  1595. and each item is numbered on the left from zero"""
  1596. s = ''
  1597. for line in getNumberedTypedSortedStringWithReferrersGen(items, maxLen, numPrefix):
  1598. s += '%s\n' % line
  1599. return s
  1600. def printNumberedTyped(items, maxLen=5000):
  1601. """print out each item of the list on its own line,
  1602. with each item numbered on the left from zero"""
  1603. digits = 0
  1604. n = len(items)
  1605. while n > 0:
  1606. digits += 1
  1607. n //= 10
  1608. digits = digits
  1609. format = '%0' + '%s' % digits + 'i:%s \t%s'
  1610. for i in xrange(len(items)):
  1611. objStr = fastRepr(items[i])
  1612. if len(objStr) > maxLen:
  1613. snip = '<SNIP>'
  1614. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  1615. print format % (i, itype(items[i]), objStr)
  1616. def printNumberedTypesGen(items, maxLen=5000):
  1617. digits = 0
  1618. n = len(items)
  1619. while n > 0:
  1620. digits += 1
  1621. n //= 10
  1622. digits = digits
  1623. format = '%0' + '%s' % digits + 'i:%s'
  1624. for i in xrange(len(items)):
  1625. print format % (i, itype(items[i]))
  1626. yield None
  1627. def printNumberedTypes(items, maxLen=5000):
  1628. """print out the type of each item of the list on its own line,
  1629. with each item numbered on the left from zero"""
  1630. for result in printNumberedTypesGen(items, maxLen):
  1631. yield result
  1632. class DelayedCall:
  1633. """ calls a func after a specified delay """
  1634. def __init__(self, func, name=None, delay=None):
  1635. if name is None:
  1636. name = 'anonymous'
  1637. if delay is None:
  1638. delay = .01
  1639. self._func = func
  1640. self._taskName = 'DelayedCallback-%s' % name
  1641. self._delay = delay
  1642. self._finished = False
  1643. self._addDoLater()
  1644. def destroy(self):
  1645. self._finished = True
  1646. self._removeDoLater()
  1647. def finish(self):
  1648. if not self._finished:
  1649. self._doCallback()
  1650. self.destroy()
  1651. def _addDoLater(self):
  1652. taskMgr.doMethodLater(self._delay, self._doCallback, self._taskName)
  1653. def _removeDoLater(self):
  1654. taskMgr.remove(self._taskName)
  1655. def _doCallback(self, task):
  1656. self._finished = True
  1657. func = self._func
  1658. del self._func
  1659. func()
  1660. class FrameDelayedCall:
  1661. """ calls a func after N frames """
  1662. def __init__(self, name, callback, frames=None, cancelFunc=None):
  1663. # checkFunc is optional; called every frame, if returns True, FrameDelay is cancelled
  1664. # and callback is not called
  1665. if frames is None:
  1666. frames = 1
  1667. self._name = name
  1668. self._frames = frames
  1669. self._callback = callback
  1670. self._cancelFunc = cancelFunc
  1671. self._taskName = uniqueName('%s-%s' % (self.__class__.__name__, self._name))
  1672. self._finished = False
  1673. self._startTask()
  1674. def destroy(self):
  1675. self._finished = True
  1676. self._stopTask()
  1677. def finish(self):
  1678. if not self._finished:
  1679. self._finished = True
  1680. self._callback()
  1681. self.destroy()
  1682. def _startTask(self):
  1683. taskMgr.add(self._frameTask, self._taskName)
  1684. self._counter = 0
  1685. def _stopTask(self):
  1686. taskMgr.remove(self._taskName)
  1687. def _frameTask(self, task):
  1688. if self._cancelFunc and self._cancelFunc():
  1689. self.destroy()
  1690. return task.done
  1691. self._counter += 1
  1692. if self._counter >= self._frames:
  1693. self.finish()
  1694. return task.done
  1695. return task.cont
  1696. class DelayedFunctor:
  1697. """ Waits for this object to be called, then calls supplied functor after a delay.
  1698. Effectively inserts a time delay between the caller and the functor. """
  1699. def __init__(self, functor, name=None, delay=None):
  1700. self._functor = functor
  1701. self._name = name
  1702. # FunctionInterval requires __name__
  1703. self.__name__ = self._name
  1704. self._delay = delay
  1705. def _callFunctor(self):
  1706. cb = Functor(self._functor, *self._args, **self._kwArgs)
  1707. del self._functor
  1708. del self._name
  1709. del self._delay
  1710. del self._args
  1711. del self._kwArgs
  1712. del self._delayedCall
  1713. del self.__name__
  1714. cb()
  1715. def __call__(self, *args, **kwArgs):
  1716. self._args = args
  1717. self._kwArgs = kwArgs
  1718. self._delayedCall = DelayedCall(self._callFunctor, self._name, self._delay)
  1719. class SubframeCall:
  1720. """Calls a callback at a specific time during the frame using the
  1721. task system"""
  1722. def __init__(self, functor, taskPriority, name=None):
  1723. self._functor = functor
  1724. self._name = name
  1725. self._taskName = uniqueName('SubframeCall-%s' % self._name)
  1726. taskMgr.add(self._doCallback,
  1727. self._taskName,
  1728. priority=taskPriority)
  1729. def _doCallback(self, task):
  1730. functor = self._functor
  1731. del self._functor
  1732. functor()
  1733. del self._name
  1734. self._taskName = None
  1735. return task.done
  1736. def cleanup(self):
  1737. if (self._taskName):
  1738. taskMgr.remove(self._taskName)
  1739. self._taskName = None
  1740. class PStatScope:
  1741. collectors = {}
  1742. def __init__(self, level = None):
  1743. self.levels = []
  1744. if level:
  1745. self.levels.append(level)
  1746. def copy(self, push = None):
  1747. c = PStatScope()
  1748. c.levels = self.levels[:]
  1749. if push:
  1750. c.push(push)
  1751. return c
  1752. def __repr__(self):
  1753. return 'PStatScope - \'%s\'' % (self,)
  1754. def __str__(self):
  1755. return ':'.join(self.levels)
  1756. def push(self, level):
  1757. self.levels.append(level.replace('_',''))
  1758. def pop(self):
  1759. return self.levels.pop()
  1760. def start(self, push = None):
  1761. if push:
  1762. self.push(push)
  1763. pass
  1764. self.getCollector().start()
  1765. def stop(self, pop = False):
  1766. self.getCollector().stop()
  1767. if pop:
  1768. self.pop()
  1769. def getCollector(self):
  1770. label = str(self)
  1771. if label not in self.collectors:
  1772. from panda3d.core import PStatCollector
  1773. self.collectors[label] = PStatCollector(label)
  1774. pass
  1775. # print ' ',self.collectors[label]
  1776. return self.collectors[label]
  1777. def pstatcollect(scope, level = None):
  1778. def decorator(f):
  1779. return f
  1780. try:
  1781. if not (__dev__ or config.GetBool('force-pstatcollect', 0)) or \
  1782. not scope:
  1783. return decorator
  1784. def decorator(f):
  1785. def wrap(*args, **kw):
  1786. scope.start(push = (level or f.__name__))
  1787. val = f(*args, **kw)
  1788. scope.stop(pop = True)
  1789. return val
  1790. return wrap
  1791. pass
  1792. except:
  1793. pass
  1794. return decorator
  1795. __report_indent = 0
  1796. def report(types = [], prefix = '', xform = None, notifyFunc = None, dConfigParam = []):
  1797. """
  1798. This is a decorator generating function. Use is similar to
  1799. a @decorator, except you must be sure to call it as a function.
  1800. It actually returns the decorator which is then used to transform
  1801. your decorated function. Confusing at first, I know.
  1802. Decoration occurs at function definition time.
  1803. If __dev__ is not defined, or resolves to False, this function
  1804. has no effect and no wrapping/transform occurs. So in production,
  1805. it's as if the report has been asserted out.
  1806. Parameters::
  1807. types : A subset list of ['timeStamp', 'frameCount', 'avLocation']
  1808. This allows you to specify certain useful bits of info.
  1809. module: Prints the module that this report statement
  1810. can be found in.
  1811. args: Prints the arguments as they were passed to
  1812. this function.
  1813. timeStamp: Adds the current frame time to the output.
  1814. deltaStamp: Adds the current AI synched frame time to
  1815. the output
  1816. frameCount: Adds the current frame count to the output.
  1817. Usually cleaner than the timeStamp output.
  1818. avLocation: Adds the localAvatar's network location
  1819. to the output. Useful for interest debugging.
  1820. interests: Prints the current interest state after the
  1821. report.
  1822. stackTrace: Prints a stack trace after the report.
  1823. prefix: Optional string to prepend to output, just before the function.
  1824. Allows for easy grepping and is useful when merging AI/Client
  1825. reports into a single file.
  1826. xform: Optional callback that accepts a single parameter: argument 0 to
  1827. the decorated function. (assumed to be 'self')
  1828. It should return a value to be inserted into the report output string.
  1829. notifyFunc: A notify function such as info, debug, warning, etc.
  1830. By default the report will be printed to stdout. This
  1831. will allow you send the report to a designated 'notify'
  1832. output.
  1833. dConfigParam: A list of Config.prc string variables.
  1834. By default the report will always print. If you
  1835. specify this param, it will only print if one of the
  1836. specified config strings resolve to True.
  1837. """
  1838. def indent(str):
  1839. global __report_indent
  1840. return ' '*__report_indent+str
  1841. def decorator(f):
  1842. return f
  1843. try:
  1844. if not (__dev__ or config.GetBool('force-reports', 0)):
  1845. return decorator
  1846. # determine whether we should use the decorator
  1847. # based on the value of dConfigParam.
  1848. dConfigParamList = []
  1849. doPrint = False
  1850. if not dConfigParam:
  1851. doPrint = True
  1852. else:
  1853. if not isinstance(dConfigParam, (list,tuple)):
  1854. dConfigParams = (dConfigParam,)
  1855. else:
  1856. dConfigParams = dConfigParam
  1857. dConfigParamList = [param for param in dConfigParams \
  1858. if config.GetBool('want-%s-report' % (param,), 0)]
  1859. doPrint = bool(dConfigParamList)
  1860. pass
  1861. if not doPrint:
  1862. return decorator
  1863. # Determine any prefixes defined in our Config.prc.
  1864. if prefix:
  1865. prefixes = set([prefix])
  1866. else:
  1867. prefixes = set()
  1868. pass
  1869. for param in dConfigParamList:
  1870. prefix = config.GetString('prefix-%s-report' % (param,), '')
  1871. if prefix:
  1872. prefixes.add(prefix)
  1873. pass
  1874. pass
  1875. except NameError,e:
  1876. return decorator
  1877. from direct.distributed.ClockDelta import globalClockDelta
  1878. def decorator(f):
  1879. def wrap(*args,**kwargs):
  1880. if args:
  1881. rArgs = [args[0].__class__.__name__ + ', ']
  1882. else:
  1883. rArgs = []
  1884. if 'args' in types:
  1885. rArgs += [repr(x)+', ' for x in args[1:]] + \
  1886. [ x + ' = ' + '%s, ' % repr(y) for x,y in kwargs.items()]
  1887. if not rArgs:
  1888. rArgs = '()'
  1889. else:
  1890. rArgs = '(' + reduce(str.__add__,rArgs)[:-2] + ')'
  1891. outStr = '%s%s' % (f.func_name, rArgs)
  1892. # Insert prefix place holder, if needed
  1893. if prefixes:
  1894. outStr = '%%s %s' % (outStr,)
  1895. if 'module' in types:
  1896. outStr = '%s {M:%s}' % (outStr, f.__module__.split('.')[-1])
  1897. if 'frameCount' in types:
  1898. outStr = '%-8d : %s' % (globalClock.getFrameCount(), outStr)
  1899. if 'timeStamp' in types:
  1900. outStr = '%-8.3f : %s' % (globalClock.getFrameTime(), outStr)
  1901. if 'deltaStamp' in types:
  1902. outStr = '%-8.2f : %s' % (globalClock.getRealTime() - \
  1903. globalClockDelta.delta, outStr)
  1904. if 'avLocation' in types:
  1905. outStr = '%s : %s' % (outStr, str(localAvatar.getLocation()))
  1906. if xform:
  1907. outStr = '%s : %s' % (outStr, xform(args[0]))
  1908. if prefixes:
  1909. # This will print the same report once for each prefix
  1910. for prefix in prefixes:
  1911. if notifyFunc:
  1912. notifyFunc(outStr % (prefix,))
  1913. else:
  1914. print indent(outStr % (prefix,))
  1915. else:
  1916. if notifyFunc:
  1917. notifyFunc(outStr)
  1918. else:
  1919. print indent(outStr)
  1920. if 'interests' in types:
  1921. base.cr.printInterestSets()
  1922. if 'stackTrace' in types:
  1923. print StackTrace()
  1924. global __report_indent
  1925. rVal = None
  1926. try:
  1927. __report_indent += 1
  1928. rVal = f(*args,**kwargs)
  1929. finally:
  1930. __report_indent -= 1
  1931. if rVal is not None:
  1932. print indent(' -> '+repr(rVal))
  1933. pass
  1934. pass
  1935. return rVal
  1936. wrap.func_name = f.func_name
  1937. wrap.func_dict = f.func_dict
  1938. wrap.func_doc = f.func_doc
  1939. wrap.__module__ = f.__module__
  1940. return wrap
  1941. return decorator
  1942. def getBase():
  1943. try:
  1944. return base
  1945. except:
  1946. return simbase
  1947. def getRepository():
  1948. try:
  1949. return base.cr
  1950. except:
  1951. return simbase.air
  1952. exceptionLoggedNotify = None
  1953. def exceptionLogged(append=True):
  1954. """decorator that outputs the function name and all arguments
  1955. if an exception passes back through the stack frame
  1956. if append is true, string is appended to the __str__ output of
  1957. the exception. if append is false, string is printed to the log
  1958. directly. If the output will take up many lines, it's recommended
  1959. to set append to False so that the exception stack is not hidden
  1960. by the output of this decorator.
  1961. """
  1962. try:
  1963. null = not __dev__
  1964. except:
  1965. null = not __debug__
  1966. if null:
  1967. # if we're not in __dev__, just return the function itself. This
  1968. # results in zero runtime overhead, since decorators are evaluated
  1969. # at module-load.
  1970. def nullDecorator(f):
  1971. return f
  1972. return nullDecorator
  1973. def _decoratorFunc(f, append=append):
  1974. global exceptionLoggedNotify
  1975. if exceptionLoggedNotify is None:
  1976. from direct.directnotify.DirectNotifyGlobal import directNotify
  1977. exceptionLoggedNotify = directNotify.newCategory("ExceptionLogged")
  1978. def _exceptionLogged(*args, **kArgs):
  1979. try:
  1980. return f(*args, **kArgs)
  1981. except Exception, e:
  1982. try:
  1983. s = '%s(' % f.func_name
  1984. for arg in args:
  1985. s += '%s, ' % arg
  1986. for key, value in kArgs.items():
  1987. s += '%s=%s, ' % (key, value)
  1988. if len(args) or len(kArgs):
  1989. s = s[:-2]
  1990. s += ')'
  1991. if append:
  1992. appendStr(e, '\n%s' % s)
  1993. else:
  1994. exceptionLoggedNotify.info(s)
  1995. except:
  1996. exceptionLoggedNotify.info(
  1997. '%s: ERROR IN PRINTING' % f.func_name)
  1998. raise
  1999. _exceptionLogged.__doc__ = f.__doc__
  2000. return _exceptionLogged
  2001. return _decoratorFunc
  2002. # class 'decorator' that records the stack at the time of creation
  2003. # be careful with this, it creates a StackTrace, and that can take a
  2004. # lot of CPU
  2005. def recordCreationStack(cls):
  2006. if not hasattr(cls, '__init__'):
  2007. raise 'recordCreationStack: class \'%s\' must define __init__' % cls.__name__
  2008. cls.__moved_init__ = cls.__init__
  2009. def __recordCreationStack_init__(self, *args, **kArgs):
  2010. self._creationStackTrace = StackTrace(start=1)
  2011. return self.__moved_init__(*args, **kArgs)
  2012. def getCreationStackTrace(self):
  2013. return self._creationStackTrace
  2014. def getCreationStackTraceCompactStr(self):
  2015. return self._creationStackTrace.compact()
  2016. def printCreationStackTrace(self):
  2017. print self._creationStackTrace
  2018. cls.__init__ = __recordCreationStack_init__
  2019. cls.getCreationStackTrace = getCreationStackTrace
  2020. cls.getCreationStackTraceCompactStr = getCreationStackTraceCompactStr
  2021. cls.printCreationStackTrace = printCreationStackTrace
  2022. return cls
  2023. # like recordCreationStack but stores the stack as a compact stack list-of-strings
  2024. # scales well for memory usage
  2025. def recordCreationStackStr(cls):
  2026. if not hasattr(cls, '__init__'):
  2027. raise 'recordCreationStackStr: class \'%s\' must define __init__' % cls.__name__
  2028. cls.__moved_init__ = cls.__init__
  2029. def __recordCreationStackStr_init__(self, *args, **kArgs):
  2030. # store as list of strings to conserve memory
  2031. self._creationStackTraceStrLst = StackTrace(start=1).compact().split(',')
  2032. return self.__moved_init__(*args, **kArgs)
  2033. def getCreationStackTraceCompactStr(self):
  2034. return ','.join(self._creationStackTraceStrLst)
  2035. def printCreationStackTrace(self):
  2036. print ','.join(self._creationStackTraceStrLst)
  2037. cls.__init__ = __recordCreationStackStr_init__
  2038. cls.getCreationStackTraceCompactStr = getCreationStackTraceCompactStr
  2039. cls.printCreationStackTrace = printCreationStackTrace
  2040. return cls
  2041. # class 'decorator' that logs all method calls for a particular class
  2042. def logMethodCalls(cls):
  2043. if not hasattr(cls, 'notify'):
  2044. raise 'logMethodCalls: class \'%s\' must have a notify' % cls.__name__
  2045. for name in dir(cls):
  2046. method = getattr(cls, name)
  2047. if hasattr(method, '__call__'):
  2048. def getLoggedMethodCall(method):
  2049. def __logMethodCall__(obj, *args, **kArgs):
  2050. s = '%s(' % method.__name__
  2051. for arg in args:
  2052. try:
  2053. argStr = repr(arg)
  2054. except:
  2055. argStr = 'bad repr: %s' % arg.__class__
  2056. s += '%s, ' % argStr
  2057. for karg, value in kArgs.items():
  2058. s += '%s=%s, ' % (karg, repr(value))
  2059. if len(args) or len(kArgs):
  2060. s = s[:-2]
  2061. s += ')'
  2062. obj.notify.info(s)
  2063. return method(obj, *args, **kArgs)
  2064. return __logMethodCall__
  2065. setattr(cls, name, getLoggedMethodCall(method))
  2066. __logMethodCall__ = None
  2067. return cls
  2068. # http://en.wikipedia.org/wiki/Golden_ratio
  2069. GoldenRatio = (1. + math.sqrt(5.)) / 2.
  2070. class GoldenRectangle:
  2071. @staticmethod
  2072. def getLongerEdge(shorter):
  2073. return shorter * GoldenRatio
  2074. @staticmethod
  2075. def getShorterEdge(longer):
  2076. return longer / GoldenRatio
  2077. class HotkeyBreaker:
  2078. def __init__(self,breakKeys = []):
  2079. from direct.showbase.DirectObject import DirectObject
  2080. self.do = DirectObject()
  2081. self.breakKeys = {}
  2082. if not isinstance(breakKeys, (list,tuple)):
  2083. breakKeys = (breakKeys,)
  2084. for key in breakKeys:
  2085. self.addBreakKey(key)
  2086. def addBreakKey(self,breakKey):
  2087. if __dev__:
  2088. self.do.accept(breakKey,self.breakFunc,extraArgs = [breakKey])
  2089. def removeBreakKey(self,breakKey):
  2090. if __dev__:
  2091. self.do.ignore(breakKey)
  2092. def breakFunc(self,breakKey):
  2093. if __dev__:
  2094. self.breakKeys[breakKey] = True
  2095. def setBreakPt(self, breakKey = None, persistent = False):
  2096. if __dev__:
  2097. if not breakKey:
  2098. import pdb;pdb.set_trace()
  2099. return True
  2100. else:
  2101. if self.breakKeys.get(breakKey,False):
  2102. if not persistent:
  2103. self.breakKeys.pop(breakKey)
  2104. import pdb;pdb.set_trace()
  2105. return True
  2106. return True
  2107. def clearBreakPt(self, breakKey):
  2108. if __dev__:
  2109. return bool(self.breakKeys.pop(breakKey,None))
  2110. def nullGen():
  2111. # generator that ends immediately
  2112. if False:
  2113. # yield that never runs but still exists, making this func a generator
  2114. yield None
  2115. def loopGen(l):
  2116. # generator that yields the items of an iterable object forever
  2117. def _gen(l):
  2118. while True:
  2119. for item in l:
  2120. yield item
  2121. gen = _gen(l)
  2122. # don't leak
  2123. _gen = None
  2124. return gen
  2125. def makeFlywheelGen(objects, countList=None, countFunc=None, scale=None):
  2126. # iterates and finally yields a flywheel generator object
  2127. # the number of appearances for each object is controlled by passing in
  2128. # a list of counts, or a functor that returns a count when called with
  2129. # an object from the 'objects' list.
  2130. # if scale is provided, all counts are scaled by the scale value and then int()'ed.
  2131. def flywheel(index2objectAndCount):
  2132. # generator to produce a sequence whose elements appear a specific number of times
  2133. while len(index2objectAndCount):
  2134. keyList = index2objectAndCount.keys()
  2135. for key in keyList:
  2136. if index2objectAndCount[key][1] > 0:
  2137. yield index2objectAndCount[key][0]
  2138. index2objectAndCount[key][1] -= 1
  2139. if index2objectAndCount[key][1] <= 0:
  2140. del index2objectAndCount[key]
  2141. # if we were not given a list of counts, create it by calling countFunc
  2142. if countList is None:
  2143. countList = []
  2144. for object in objects:
  2145. yield None
  2146. countList.append(countFunc(object))
  2147. if scale is not None:
  2148. # scale the counts if we've got a scale factor
  2149. for i in xrange(len(countList)):
  2150. yield None
  2151. if countList[i] > 0:
  2152. countList[i] = max(1, int(countList[i] * scale))
  2153. # create a dict for the flywheel to use during its iteration to efficiently select
  2154. # the objects for the sequence
  2155. index2objectAndCount = {}
  2156. for i in xrange(len(countList)):
  2157. yield None
  2158. index2objectAndCount[i] = [objects[i], countList[i]]
  2159. # create the flywheel generator
  2160. yield flywheel(index2objectAndCount)
  2161. def flywheel(*args, **kArgs):
  2162. # create a flywheel generator
  2163. # see arguments and comments in flywheelGen above
  2164. # example usage:
  2165. """
  2166. >>> for i in flywheel([1,2,3], countList=[10, 5, 1]):
  2167. ... print i,
  2168. ...
  2169. 1 2 3 1 2 1 2 1 2 1 2 1 1 1 1 1
  2170. """
  2171. for flywheel in makeFlywheelGen(*args, **kArgs):
  2172. pass
  2173. return flywheel
  2174. if __debug__ and __name__ == '__main__':
  2175. f = flywheel(['a','b','c','d'], countList=[11,20,3,4])
  2176. obj2count = {}
  2177. for obj in f:
  2178. obj2count.setdefault(obj, 0)
  2179. obj2count[obj] += 1
  2180. assert obj2count['a'] == 11
  2181. assert obj2count['b'] == 20
  2182. assert obj2count['c'] == 3
  2183. assert obj2count['d'] == 4
  2184. f = flywheel([1,2,3,4], countFunc=lambda x: x*2)
  2185. obj2count = {}
  2186. for obj in f:
  2187. obj2count.setdefault(obj, 0)
  2188. obj2count[obj] += 1
  2189. assert obj2count[1] == 2
  2190. assert obj2count[2] == 4
  2191. assert obj2count[3] == 6
  2192. assert obj2count[4] == 8
  2193. f = flywheel([1,2,3,4], countFunc=lambda x: x, scale = 3)
  2194. obj2count = {}
  2195. for obj in f:
  2196. obj2count.setdefault(obj, 0)
  2197. obj2count[obj] += 1
  2198. assert obj2count[1] == 1 * 3
  2199. assert obj2count[2] == 2 * 3
  2200. assert obj2count[3] == 3 * 3
  2201. assert obj2count[4] == 4 * 3
  2202. def quickProfile(name="unnamed"):
  2203. import pstats
  2204. def profileDecorator(f):
  2205. if(not config.GetBool("use-profiler",0)):
  2206. return f
  2207. def _profiled(*args, **kArgs):
  2208. # must do this in here because we don't have base/simbase
  2209. # at the time that PythonUtil is loaded
  2210. if(not config.GetBool("profile-debug",0)):
  2211. #dumb timings
  2212. st=globalClock.getRealTime()
  2213. f(*args,**kArgs)
  2214. s=globalClock.getRealTime()-st
  2215. print "Function %s.%s took %s seconds"%(f.__module__, f.__name__,s)
  2216. else:
  2217. import profile as prof, pstats
  2218. #detailed profile, stored in base.stats under (
  2219. if(not hasattr(base,"stats")):
  2220. base.stats={}
  2221. if(not base.stats.get(name)):
  2222. base.stats[name]=[]
  2223. prof.runctx('f(*args, **kArgs)', {'f':f,'args':args,'kArgs':kArgs},None,"t.prof")
  2224. s=pstats.Stats("t.prof")
  2225. #p=hotshot.Profile("t.prof")
  2226. #p.runctx('f(*args, **kArgs)', {'f':f,'args':args,'kArgs':kArgs},None)
  2227. #s = hotshot.stats.load("t.prof")
  2228. s.strip_dirs()
  2229. s.sort_stats("cumulative")
  2230. base.stats[name].append(s)
  2231. _profiled.__doc__ = f.__doc__
  2232. return _profiled
  2233. return profileDecorator
  2234. def getTotalAnnounceTime():
  2235. td=0
  2236. for objs in base.stats.values():
  2237. for stat in objs:
  2238. td+=getAnnounceGenerateTime(stat)
  2239. return td
  2240. def getAnnounceGenerateTime(stat):
  2241. val=0
  2242. stats=stat.stats
  2243. for i in stats.keys():
  2244. if(i[2]=="announceGenerate"):
  2245. newVal=stats[i][3]
  2246. if(newVal>val):
  2247. val=newVal
  2248. return val
  2249. def choice(condition, ifTrue, ifFalse):
  2250. # equivalent of C++ (condition ? ifTrue : ifFalse)
  2251. if condition:
  2252. return ifTrue
  2253. else:
  2254. return ifFalse
  2255. class MiniLog:
  2256. def __init__(self, name):
  2257. self.indent = 1
  2258. self.name = name
  2259. self.lines = []
  2260. def __str__(self):
  2261. return '%s\nMiniLog: %s\n%s\n%s\n%s' % \
  2262. ('*'*50, self.name, '-'*50, '\n'.join(self.lines), '*'*50)
  2263. def enterFunction(self, funcName, *args, **kw):
  2264. rArgs = [repr(x)+', ' for x in args] + \
  2265. [ x + ' = ' + '%s, ' % repr(y) for x,y in kw.items()]
  2266. if not rArgs:
  2267. rArgs = '()'
  2268. else:
  2269. rArgs = '(' + reduce(str.__add__,rArgs)[:-2] + ')'
  2270. line = '%s%s' % (funcName, rArgs)
  2271. self.appendFunctionCall(line)
  2272. self.indent += 1
  2273. return line
  2274. def exitFunction(self):
  2275. self.indent -= 1
  2276. return self.indent
  2277. def appendFunctionCall(self, line):
  2278. self.lines.append(' '*(self.indent*2) + line)
  2279. return line
  2280. def appendLine(self, line):
  2281. self.lines.append(' '*(self.indent*2) + '<< ' + line + ' >>')
  2282. return line
  2283. def flush(self):
  2284. outStr = str(self)
  2285. self.indent = 0
  2286. self.lines = []
  2287. return outStr
  2288. class MiniLogSentry:
  2289. def __init__(self, log, funcName, *args, **kw):
  2290. self.log = log
  2291. if self.log:
  2292. self.log.enterFunction(funcName, *args, **kw)
  2293. def __del__(self):
  2294. if self.log:
  2295. self.log.exitFunction()
  2296. del self.log
  2297. def logBlock(id, msg):
  2298. print '<< LOGBLOCK(%03d)' % id
  2299. print str(msg)
  2300. print '/LOGBLOCK(%03d) >>' % id
  2301. class HierarchyException(Exception):
  2302. JOSWILSO = 0
  2303. def __init__(self, owner, description):
  2304. self.owner = owner
  2305. self.desc = description
  2306. def __str__(self):
  2307. return '(%s): %s' % (self.owner, self.desc)
  2308. def __repr__(self):
  2309. return 'HierarchyException(%s)' % (self.owner, )
  2310. # __dev__ is not defined at import time, call this after it's defined
  2311. def recordFunctorCreationStacks():
  2312. global Functor
  2313. from panda3d.direct import get_config_showbase
  2314. config = get_config_showbase()
  2315. # off by default, very slow
  2316. if __dev__ and config.GetBool('record-functor-creation-stacks', 0):
  2317. if not hasattr(Functor, '_functorCreationStacksRecorded'):
  2318. Functor = recordCreationStackStr(Functor)
  2319. Functor._functorCreationStacksRecorded = True
  2320. Functor.__call__ = Functor._exceptionLoggedCreationStack__call__
  2321. def formatTimeCompact(seconds):
  2322. # returns string in format '1d3h22m43s'
  2323. result = ''
  2324. a = int(seconds)
  2325. seconds = a % 60
  2326. a //= 60
  2327. if a > 0:
  2328. minutes = a % 60
  2329. a //= 60
  2330. if a > 0:
  2331. hours = a % 24
  2332. a //= 24
  2333. if a > 0:
  2334. days = a
  2335. result += '%sd' % days
  2336. result += '%sh' % hours
  2337. result += '%sm' % minutes
  2338. result += '%ss' % seconds
  2339. return result
  2340. if __debug__ and __name__ == '__main__':
  2341. ftc = formatTimeCompact
  2342. assert ftc(0) == '0s'
  2343. assert ftc(1) == '1s'
  2344. assert ftc(60) == '1m0s'
  2345. assert ftc(64) == '1m4s'
  2346. assert ftc(60*60) == '1h0m0s'
  2347. assert ftc(24*60*60) == '1d0h0m0s'
  2348. assert ftc(24*60*60 + 2*60*60 + 34*60 + 12) == '1d2h34m12s'
  2349. del ftc
  2350. def formatTimeExact(seconds):
  2351. # like formatTimeCompact but leaves off '0 seconds', '0 minutes' etc. for
  2352. # times that are e.g. 1 hour, 3 days etc.
  2353. # returns string in format '1d3h22m43s'
  2354. result = ''
  2355. a = int(seconds)
  2356. seconds = a % 60
  2357. a //= 60
  2358. if a > 0:
  2359. minutes = a % 60
  2360. a //= 60
  2361. if a > 0:
  2362. hours = a % 24
  2363. a //= 24
  2364. if a > 0:
  2365. days = a
  2366. result += '%sd' % days
  2367. if hours or minutes or seconds:
  2368. result += '%sh' % hours
  2369. if minutes or seconds:
  2370. result += '%sm' % minutes
  2371. if seconds or result == '':
  2372. result += '%ss' % seconds
  2373. return result
  2374. if __debug__ and __name__ == '__main__':
  2375. fte = formatTimeExact
  2376. assert fte(0) == '0s'
  2377. assert fte(1) == '1s'
  2378. assert fte(2) == '2s'
  2379. assert fte(61) == '1m1s'
  2380. assert fte(60) == '1m'
  2381. assert fte(60*60) == '1h'
  2382. assert fte(24*60*60) == '1d'
  2383. assert fte((24*60*60) + (2 * 60)) == '1d0h2m'
  2384. del fte
  2385. class AlphabetCounter:
  2386. # object that produces 'A', 'B', 'C', ... 'AA', 'AB', etc.
  2387. def __init__(self):
  2388. self._curCounter = ['A']
  2389. def next(self):
  2390. result = ''.join([c for c in self._curCounter])
  2391. index = -1
  2392. while True:
  2393. curChar = self._curCounter[index]
  2394. if curChar is 'Z':
  2395. nextChar = 'A'
  2396. carry = True
  2397. else:
  2398. nextChar = chr(ord(self._curCounter[index])+1)
  2399. carry = False
  2400. self._curCounter[index] = nextChar
  2401. if carry:
  2402. if (-index) == len(self._curCounter):
  2403. self._curCounter = ['A',] + self._curCounter
  2404. break
  2405. else:
  2406. index -= 1
  2407. carry = False
  2408. else:
  2409. break
  2410. return result
  2411. if __debug__ and __name__ == '__main__':
  2412. def testAlphabetCounter():
  2413. tempList = []
  2414. ac = AlphabetCounter()
  2415. for i in xrange(26*3):
  2416. tempList.append(ac.next())
  2417. assert tempList == [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  2418. 'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ',
  2419. 'BA','BB','BC','BD','BE','BF','BG','BH','BI','BJ','BK','BL','BM','BN','BO','BP','BQ','BR','BS','BT','BU','BV','BW','BX','BY','BZ',]
  2420. ac = AlphabetCounter()
  2421. num = 26 # A-Z
  2422. num += (26*26) # AA-ZZ
  2423. num += 26 # AAZ
  2424. num += 1 # ABA
  2425. num += 2 # ABC
  2426. for i in xrange(num):
  2427. x = ac.next()
  2428. assert x == 'ABC'
  2429. testAlphabetCounter()
  2430. del testAlphabetCounter
  2431. globalPdb = None
  2432. traceCalled = False
  2433. def setupPdb():
  2434. import pdb;
  2435. class pandaPdb(pdb.Pdb):
  2436. def stop_here(self, frame):
  2437. global traceCalled
  2438. if(traceCalled):
  2439. result = pdb.Pdb.stop_here(self, frame)
  2440. if(result == True):
  2441. traceCalled = False
  2442. return result
  2443. if frame is self.stopframe:
  2444. return True
  2445. return False
  2446. global globalPdb
  2447. globalPdb = pandaPdb()
  2448. globalPdb.reset()
  2449. sys.settrace(globalPdb.trace_dispatch)
  2450. def pandaTrace():
  2451. if __dev__:
  2452. if not globalPdb:
  2453. setupPdb()
  2454. global traceCalled
  2455. globalPdb.set_trace(sys._getframe().f_back)
  2456. traceCalled = True
  2457. packageMap = {
  2458. "toontown":"$TOONTOWN",
  2459. "direct":"$DIRECT",
  2460. "otp":"$OTP",
  2461. "pirates":"$PIRATES",
  2462. }
  2463. #assuming . dereferncing for nice linking to imports
  2464. def pandaBreak(dotpath, linenum, temporary = 0, cond = None):
  2465. if __dev__:
  2466. from panda3d.core import Filename
  2467. if not globalPdb:
  2468. setupPdb()
  2469. dirs = dotpath.split(".")
  2470. root = Filename.expandFrom(packageMap[dirs[0]]).toOsSpecific()
  2471. filename = root + "\\src"
  2472. for d in dirs[1:]:
  2473. filename="%s\\%s"%(filename,d)
  2474. print filename
  2475. globalPdb.set_break(filename+".py", linenum, temporary, cond)
  2476. class Default:
  2477. # represents 'use the default value'
  2478. # useful for keyword arguments to virtual methods
  2479. pass
  2480. superLogFile = None
  2481. def startSuperLog(customFunction = None):
  2482. global superLogFile
  2483. if(not superLogFile):
  2484. superLogFile = open("c:\\temp\\superLog.txt", "w")
  2485. def trace_dispatch(a,b,c):
  2486. if(b=='call' and a.f_code.co_name != '?' and a.f_code.co_name.find("safeRepr")<0):
  2487. vars = dict(a.f_locals)
  2488. if 'self' in vars:
  2489. del vars['self']
  2490. if '__builtins__' in vars:
  2491. del vars['__builtins__']
  2492. for i in vars:
  2493. vars[i] = safeReprTypeOnFail(vars[i])
  2494. if customFunction:
  2495. superLogFile.write( "before = %s\n"%customFunction())
  2496. superLogFile.write( "%s(%s):%s:%s\n"%(a.f_code.co_filename.split("\\")[-1],a.f_code.co_firstlineno, a.f_code.co_name, vars))
  2497. if customFunction:
  2498. superLogFile.write( "after = %s\n"%customFunction())
  2499. return trace_dispatch
  2500. sys.settrace(trace_dispatch)
  2501. def endSuperLog():
  2502. global superLogFile
  2503. if(superLogFile):
  2504. sys.settrace(None)
  2505. superLogFile.close()
  2506. superLogFile = None
  2507. def isInteger(n):
  2508. return type(n) in (types.IntType, types.LongType)
  2509. def configIsToday(configName):
  2510. # TODO: replace usage of strptime with something else
  2511. # returns true if config string is a valid representation of today's date
  2512. today = time.localtime()
  2513. confStr = config.GetString(configName, '')
  2514. for format in ('%m/%d/%Y', '%m-%d-%Y', '%m.%d.%Y'):
  2515. try:
  2516. confDate = time.strptime(confStr, format)
  2517. except ValueError:
  2518. pass
  2519. else:
  2520. if (confDate.tm_year == today.tm_year and
  2521. confDate.tm_mon == today.tm_mon and
  2522. confDate.tm_mday == today.tm_mday):
  2523. return True
  2524. return False
  2525. def typeName(o):
  2526. if hasattr(o, '__class__'):
  2527. return o.__class__.__name__
  2528. else:
  2529. return o.__name__
  2530. def safeTypeName(o):
  2531. try:
  2532. return typeName(o)
  2533. except:
  2534. pass
  2535. try:
  2536. return type(o)
  2537. except:
  2538. pass
  2539. return '<failed safeTypeName()>'
  2540. def histogramDict(l):
  2541. d = {}
  2542. for e in l:
  2543. d.setdefault(e, 0)
  2544. d[e] += 1
  2545. return d
  2546. def unescapeHtmlString(s):
  2547. # converts %## to corresponding character
  2548. # replaces '+' with ' '
  2549. result = ''
  2550. i = 0
  2551. while i < len(s):
  2552. char = s[i]
  2553. if char == '+':
  2554. char = ' '
  2555. elif char == '%':
  2556. if i < (len(s)-2):
  2557. num = int(s[i+1:i+3], 16)
  2558. char = chr(num)
  2559. i += 2
  2560. i += 1
  2561. result += char
  2562. return result
  2563. if __debug__ and __name__ == '__main__':
  2564. assert unescapeHtmlString('asdf') == 'asdf'
  2565. assert unescapeHtmlString('as+df') == 'as df'
  2566. assert unescapeHtmlString('as%32df') == 'as2df'
  2567. assert unescapeHtmlString('asdf%32') == 'asdf2'
  2568. def unicodeUtf8(s):
  2569. # * -> Unicode UTF-8
  2570. if type(s) is types.UnicodeType:
  2571. return s
  2572. else:
  2573. return unicode(str(s), 'utf-8')
  2574. def encodedUtf8(s):
  2575. # * -> 8-bit-encoded UTF-8
  2576. return unicodeUtf8(s).encode('utf-8')
  2577. import __builtin__
  2578. __builtin__.Functor = Functor
  2579. __builtin__.Stack = Stack
  2580. __builtin__.Queue = Queue
  2581. __builtin__.Enum = Enum
  2582. __builtin__.SerialNumGen = SerialNumGen
  2583. __builtin__.SerialMaskedGen = SerialMaskedGen
  2584. __builtin__.ScratchPad = ScratchPad
  2585. __builtin__.uniqueName = uniqueName
  2586. __builtin__.serialNum = serialNum
  2587. __builtin__.profiled = profiled
  2588. __builtin__.itype = itype
  2589. __builtin__.exceptionLogged = exceptionLogged
  2590. __builtin__.appendStr = appendStr
  2591. __builtin__.bound = bound
  2592. __builtin__.clamp = clamp
  2593. __builtin__.lerp = lerp
  2594. __builtin__.makeList = makeList
  2595. __builtin__.makeTuple = makeTuple
  2596. __builtin__.printStack = printStack
  2597. __builtin__.printReverseStack = printReverseStack
  2598. __builtin__.printVerboseStack = printVerboseStack
  2599. __builtin__.DelayedCall = DelayedCall
  2600. __builtin__.DelayedFunctor = DelayedFunctor
  2601. __builtin__.FrameDelayedCall = FrameDelayedCall
  2602. __builtin__.SubframeCall = SubframeCall
  2603. __builtin__.invertDict = invertDict
  2604. __builtin__.invertDictLossless = invertDictLossless
  2605. __builtin__.getBase = getBase
  2606. __builtin__.getRepository = getRepository
  2607. __builtin__.safeRepr = safeRepr
  2608. __builtin__.fastRepr = fastRepr
  2609. __builtin__.nullGen = nullGen
  2610. __builtin__.flywheel = flywheel
  2611. __builtin__.loopGen = loopGen
  2612. __builtin__.StackTrace = StackTrace
  2613. __builtin__.choice = choice
  2614. __builtin__.report = report
  2615. __builtin__.pstatcollect = pstatcollect
  2616. __builtin__.MiniLog = MiniLog
  2617. __builtin__.MiniLogSentry = MiniLogSentry
  2618. __builtin__.logBlock = logBlock
  2619. __builtin__.HierarchyException = HierarchyException
  2620. __builtin__.deeptype = deeptype
  2621. __builtin__.Default = Default
  2622. __builtin__.isInteger = isInteger
  2623. __builtin__.configIsToday = configIsToday
  2624. __builtin__.typeName = typeName
  2625. __builtin__.safeTypeName = safeTypeName
  2626. __builtin__.histogramDict = histogramDict
  2627. __builtin__.unicodeUtf8 = unicodeUtf8
  2628. __builtin__.encodedUtf8 = encodedUtf8