PythonUtil.py 100 KB

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