PythonUtil.py 99 KB

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