PythonUtil.py 101 KB

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