makepandacore.py 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243
  1. ########################################################################
  2. ##
  3. ## Caution: there are two separate, independent build systems:
  4. ## 'makepanda', and 'ppremake'. Use one or the other, do not attempt
  5. ## to use both. This file is part of the 'makepanda' system.
  6. ##
  7. ## This file, makepandacore, contains all the global state and
  8. ## global functions for the makepanda system.
  9. ##
  10. ########################################################################
  11. import sys,os,time,stat,string,re,getopt,cPickle,fnmatch,threading,Queue,signal,shutil,platform,glob,getpass,signal
  12. from distutils import sysconfig
  13. SUFFIX_INC=[".cxx",".c",".h",".I",".yxx",".lxx",".mm",".rc",".r",".plist",".idl"]
  14. SUFFIX_DLL=[".dll",".dlo",".dle",".dli",".dlm",".mll",".exe",".pyd",".ocx"]
  15. SUFFIX_LIB=[".lib",".ilb"]
  16. STARTTIME=time.time()
  17. MAINTHREAD=threading.currentThread()
  18. OUTPUTDIR="built"
  19. CUSTOM_OUTPUTDIR=False
  20. THIRDPARTYBASE=None
  21. THIRDPARTYDIR=None
  22. OPTIMIZE="3"
  23. VERBOSE=False
  24. LINK_ALL_STATIC=False
  25. # Is the current Python a 32-bit or 64-bit build? There doesn't
  26. # appear to be a universal test for this.
  27. if sys.platform == 'darwin':
  28. # On OSX, platform.architecture reports '64bit' even if it is
  29. # currently running in 32-bit mode. But sys.maxint is a reliable
  30. # indicator.
  31. is_64 = (sys.maxint > 0x100000000L)
  32. else:
  33. # On Windows (and Linux?) sys.maxint reports 0x7fffffff even on a
  34. # 64-bit build. So we stick with platform.architecture in that
  35. # case.
  36. is_64 = (platform.architecture()[0] == '64bit')
  37. ########################################################################
  38. ##
  39. ## Maya and Max Version List (with registry keys)
  40. ##
  41. ########################################################################
  42. MAYAVERSIONINFO=[("MAYA6", "6.0"),
  43. ("MAYA65", "6.5"),
  44. ("MAYA7", "7.0"),
  45. ("MAYA8", "8.0"),
  46. ("MAYA85", "8.5"),
  47. ("MAYA2008","2008"),
  48. ("MAYA2009","2009"),
  49. ("MAYA2010","2010"),
  50. ("MAYA2011","2011"),
  51. ("MAYA2012","2012"),
  52. ]
  53. MAXVERSIONINFO = [("MAX6", "SOFTWARE\\Autodesk\\3DSMAX\\6.0", "installdir", "maxsdk\\cssdk\\include"),
  54. ("MAX7", "SOFTWARE\\Autodesk\\3DSMAX\\7.0", "Installdir", "maxsdk\\include\\CS"),
  55. ("MAX8", "SOFTWARE\\Autodesk\\3DSMAX\\8.0", "Installdir", "maxsdk\\include\\CS"),
  56. ("MAX9", "SOFTWARE\\Autodesk\\3DSMAX\\9.0", "Installdir", "maxsdk\\include\\CS"),
  57. ("MAX2009", "SOFTWARE\\Autodesk\\3DSMAX\\11.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  58. ("MAX2010", "SOFTWARE\\Autodesk\\3DSMAX\\12.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  59. ("MAX2011", "SOFTWARE\\Autodesk\\3DSMAX\\13.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  60. ("MAX2012", "SOFTWARE\\Autodesk\\3DSMAX\\14.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  61. ]
  62. MAYAVERSIONS=[]
  63. MAXVERSIONS=[]
  64. DXVERSIONS=["DX8","DX9"]
  65. for (ver,key) in MAYAVERSIONINFO:
  66. MAYAVERSIONS.append(ver)
  67. for (ver,key1,key2,subdir) in MAXVERSIONINFO:
  68. MAXVERSIONS.append(ver)
  69. ########################################################################
  70. ##
  71. ## Potentially Conflicting Files
  72. ##
  73. ## The next few functions can automatically move away files that
  74. ## are commonly generated by ppremake that may conflict with the
  75. ## build. When makepanda exits, those files will automatically be
  76. ## put back to their original location.
  77. ##
  78. ########################################################################
  79. CONFLICTING_FILES=["dtool/src/dtoolutil/pandaVersion.h",
  80. "dtool/src/dtoolutil/checkPandaVersion.h",
  81. "dtool/src/dtoolutil/checkPandaVersion.cxx",
  82. "dtool/src/prc/prc_parameters.h",
  83. "panda/src/speedtree/speedtree_parameters.h",
  84. "direct/src/plugin/p3d_plugin_config.h",
  85. "direct/src/plugin_activex/P3DActiveX.rc",
  86. "direct/src/plugin_npapi/nppanda3d.rc",
  87. "direct/src/plugin_standalone/panda3d.rc"]
  88. def MoveAwayConflictingFiles():
  89. for cfile in CONFLICTING_FILES:
  90. if os.path.exists(cfile):
  91. os.rename(cfile, cfile + ".moved")
  92. def MoveBackConflictingFiles():
  93. for cfile in CONFLICTING_FILES:
  94. if os.path.exists(cfile + ".moved"):
  95. os.rename(cfile + ".moved", cfile)
  96. ########################################################################
  97. ##
  98. ## The exit routine will normally
  99. ##
  100. ## - print a message
  101. ## - save the dependency cache
  102. ## - exit
  103. ##
  104. ## However, if it is invoked inside a thread, it instead:
  105. ##
  106. ## - prints a message
  107. ## - raises the "initiate-exit" exception
  108. ##
  109. ## If you create a thread, you must be prepared to catch this
  110. ## exception, save the dependency cache, and exit.
  111. ##
  112. ########################################################################
  113. WARNINGS=[]
  114. THREADS={}
  115. HAVE_COLORS=False
  116. SETF=""
  117. try:
  118. import curses
  119. curses.setupterm()
  120. SETF=curses.tigetstr("setf")
  121. if (SETF == None):
  122. SETF=curses.tigetstr("setaf")
  123. assert SETF != None
  124. HAVE_COLORS=sys.stdout.isatty()
  125. except: pass
  126. def DisableColors():
  127. global HAVE_COLORS
  128. HAVE_COLORS = False
  129. def GetColor(color = None):
  130. if not HAVE_COLORS: return ""
  131. if color != None: color = color.lower()
  132. if (color == "blue"):
  133. return curses.tparm(SETF, 1)
  134. elif (color == "green"):
  135. return curses.tparm(SETF, 2)
  136. elif (color == "cyan"):
  137. return curses.tparm(SETF, 3)
  138. elif (color == "red"):
  139. return curses.tparm(SETF, 4)
  140. elif (color == "magenta"):
  141. return curses.tparm(SETF, 5)
  142. elif (color == "yellow"):
  143. return curses.tparm(SETF, 6)
  144. else:
  145. return curses.tparm(curses.tigetstr("sgr0"))
  146. def PrettyTime(t):
  147. t = int(t)
  148. hours = t/3600
  149. t -= hours*3600
  150. minutes = t/60
  151. t -= minutes*60
  152. seconds = t
  153. if (hours): return str(hours)+" hours "+str(minutes)+" min"
  154. if (minutes): return str(minutes)+" min "+str(seconds)+" sec"
  155. return str(seconds)+" sec"
  156. def ProgressOutput(progress, msg, target = None):
  157. if (threading.currentThread() == MAINTHREAD):
  158. if (progress == None):
  159. print msg
  160. elif (progress >= 100.0):
  161. print "%s[%s%d%%%s] %s" % (GetColor("yellow"), GetColor("cyan"), progress, GetColor("yellow"), msg),
  162. elif (progress < 10.0):
  163. print "%s[%s %d%%%s] %s" % (GetColor("yellow"), GetColor("cyan"), progress, GetColor("yellow"), msg),
  164. else:
  165. print "%s[%s %d%%%s] %s" % (GetColor("yellow"), GetColor("cyan"), progress, GetColor("yellow"), msg),
  166. else:
  167. global THREADS
  168. ident = threading.currentThread().ident
  169. if (ident not in THREADS):
  170. THREADS[ident] = len(THREADS) + 1
  171. print "%s[%sT%d%s] %s" % (GetColor("yellow"), GetColor("cyan"), THREADS[ident], GetColor("yellow"), msg),
  172. if (target == None):
  173. print GetColor()
  174. else:
  175. print "%s%s%s" % (GetColor("green"), target, GetColor())
  176. def exit(msg = ""):
  177. sys.stdout.flush()
  178. sys.stderr.flush()
  179. if (threading.currentThread() == MAINTHREAD):
  180. SaveDependencyCache()
  181. MoveBackConflictingFiles()
  182. print "Elapsed Time: "+PrettyTime(time.time() - STARTTIME)
  183. print msg
  184. print GetColor("red") + "Build terminated." + GetColor()
  185. sys.stdout.flush()
  186. sys.stderr.flush()
  187. ##Don't quit the interperter if I'm running this file directly (debugging)
  188. if __name__ != '__main__':
  189. os._exit(1)
  190. else:
  191. print msg
  192. raise "initiate-exit"
  193. ########################################################################
  194. ##
  195. ## LocateBinary
  196. ##
  197. ## This function searches the system PATH for the binary. Returns its
  198. ## full path when it is found, or None when it was not found.
  199. ##
  200. ########################################################################
  201. def LocateBinary(binary):
  202. if os.path.isfile(binary):
  203. return binary
  204. if "PATH" not in os.environ or os.environ["PATH"] == "":
  205. p = os.defpath
  206. else:
  207. p = os.environ["PATH"]
  208. for path in p.split(os.pathsep):
  209. binpath = os.path.join(os.path.expanduser(path), binary)
  210. if os.access(binpath, os.X_OK):
  211. return os.path.abspath(os.path.realpath(binpath))
  212. return None
  213. ########################################################################
  214. ##
  215. ## Run a command.
  216. ##
  217. ########################################################################
  218. def oscmd(cmd, ignoreError = False):
  219. if VERBOSE:
  220. print GetColor("blue") + cmd.split(" ", 1)[0] + " " + GetColor("magenta") + cmd.split(" ", 1)[1] + GetColor()
  221. sys.stdout.flush()
  222. if sys.platform == "win32":
  223. exe = cmd.split()[0]
  224. if not (len(exe) > 4 and exe[-4:] == ".exe"):
  225. exe += ".exe"
  226. if os.path.isfile(exe)==0:
  227. for i in os.environ["PATH"].split(";"):
  228. if os.path.isfile(os.path.join(i, exe)):
  229. exe = os.path.join(i, exe)
  230. break
  231. if os.path.isfile(exe)==0:
  232. exit("Cannot find "+exe+" on search path")
  233. res = os.spawnl(os.P_WAIT, exe, cmd)
  234. else:
  235. res = os.system(cmd)
  236. sig = res & 0x7F
  237. if (GetVerbose() and res != 0):
  238. print GetColor("red") + "Process exited with exit status %d and signal code %d" % ((res & 0xFF00) >> 8, sig) + GetColor()
  239. if (sig == signal.SIGINT):
  240. exit("keyboard interrupt")
  241. # Don't ask me where the 35584 or 34304 come from...
  242. if (sig == signal.SIGSEGV or res == 35584 or res == 34304):
  243. if (LocateBinary("gdb") and GetVerbose()):
  244. print GetColor("red") + "Received SIGSEGV, retrieving traceback..." + GetColor()
  245. os.system("gdb -batch -ex 'handle SIG33 pass nostop noprint' -ex 'set pagination 0' -ex 'run' -ex 'bt full' -ex 'info registers' -ex 'thread apply all backtrace' -ex 'quit' --args %s < /dev/null" % cmd)
  246. else:
  247. print GetColor("red") + "Received SIGSEGV" + GetColor()
  248. exit("")
  249. if res != 0 and not ignoreError:
  250. if "interrogate" in cmd.split(" ", 1)[0] and GetVerbose():
  251. print GetColor("red") + "Interrogate failed, retrieving debug output..." + GetColor()
  252. if sys.platform == "win32":
  253. os.spawnl(os.P_WAIT, exe, cmd.split(" ", 1)[0] + " -v " + cmd.split(" ", 1)[1])
  254. else:
  255. os.system(cmd.split(" ", 1)[0] + " -v " + cmd.split(" ", 1)[1])
  256. exit("The following command returned a non-zero value: " + str(cmd))
  257. return res
  258. ########################################################################
  259. ##
  260. ## GetDirectoryContents
  261. ##
  262. ## At times, makepanda will use a function like "os.listdir" to process
  263. ## all the files in a directory. Unfortunately, that means that any
  264. ## accidental addition of a file to a directory could cause makepanda
  265. ## to misbehave without warning.
  266. ##
  267. ## To alleviate this weakness, we created GetDirectoryContents. This
  268. ## uses "os.listdir" to fetch the directory contents, but then it
  269. ## compares the results to the appropriate CVS/Entries to see if
  270. ## they match. If not, it prints a big warning message.
  271. ##
  272. ########################################################################
  273. def GetDirectoryContents(dir, filters="*", skip=[]):
  274. if (type(filters)==str):
  275. filters = [filters]
  276. actual = {}
  277. files = os.listdir(dir)
  278. for filter in filters:
  279. for file in fnmatch.filter(files, filter):
  280. if (skip.count(file)==0) and (os.path.isfile(dir + "/" + file)):
  281. actual[file] = 1
  282. if (os.path.isfile(dir + "/CVS/Entries")):
  283. cvs = {}
  284. srchandle = open(dir+"/CVS/Entries", "r")
  285. files = []
  286. for line in srchandle:
  287. if (line[0]=="/"):
  288. s = line.split("/",2)
  289. if (len(s)==3):
  290. files.append(s[1])
  291. srchandle.close()
  292. for filter in filters:
  293. for file in fnmatch.filter(files, filter):
  294. if (skip.count(file)==0):
  295. cvs[file] = 1
  296. for file in actual.keys():
  297. if (file not in cvs and VERBOSE):
  298. msg = "%sWARNING: %s is in %s, but not in CVS%s" % (GetColor("red"), GetColor("green") + file + GetColor(), GetColor("green") + dir + GetColor(), GetColor())
  299. print msg
  300. WARNINGS.append(msg)
  301. for file in cvs.keys():
  302. if (file not in actual and VERBOSE):
  303. msg = "%sWARNING: %s is not in %s, but is in CVS%s" % (GetColor("red"), GetColor("green") + file + GetColor(), GetColor("green") + dir + GetColor(), GetColor())
  304. print msg
  305. WARNINGS.append(msg)
  306. results = actual.keys()
  307. results.sort()
  308. return results
  309. def GetDirectorySize(dir):
  310. size = 0
  311. for (path, dirs, files) in os.walk(dir):
  312. for file in files:
  313. try:
  314. size += os.path.getsize(os.path.join(path, file))
  315. except: pass
  316. return size
  317. ########################################################################
  318. ##
  319. ## The Timestamp Cache
  320. ##
  321. ## The make utility is constantly fetching the timestamps of files.
  322. ## This can represent the bulk of the file accesses during the make
  323. ## process. The timestamp cache eliminates redundant checks.
  324. ##
  325. ########################################################################
  326. TIMESTAMPCACHE = {}
  327. def GetTimestamp(path):
  328. if path in TIMESTAMPCACHE:
  329. return TIMESTAMPCACHE[path]
  330. try: date = os.path.getmtime(path)
  331. except: date = 0
  332. TIMESTAMPCACHE[path] = date
  333. return date
  334. def ClearTimestamp(path):
  335. del TIMESTAMPCACHE[path]
  336. ########################################################################
  337. ##
  338. ## The Dependency cache.
  339. ##
  340. ## Makepanda's strategy for file dependencies is different from most
  341. ## make-utilities. Whenever a file is built, makepanda records
  342. ## that the file was built, and it records what the input files were,
  343. ## and what their dates were. Whenever a file is about to be built,
  344. ## panda compares the current list of input files and their dates,
  345. ## to the previous list of input files and their dates. If they match,
  346. ## there is no need to build the file.
  347. ##
  348. ########################################################################
  349. BUILTFROMCACHE = {}
  350. def JustBuilt(files,others):
  351. dates = []
  352. for file in files:
  353. del TIMESTAMPCACHE[file]
  354. dates.append(GetTimestamp(file))
  355. for file in others:
  356. dates.append(GetTimestamp(file))
  357. key = tuple(files)
  358. BUILTFROMCACHE[key] = [others,dates]
  359. def NeedsBuild(files,others):
  360. dates = []
  361. for file in files:
  362. dates.append(GetTimestamp(file))
  363. if (not os.path.exists(file)): return 1
  364. for file in others:
  365. dates.append(GetTimestamp(file))
  366. key = tuple(files)
  367. if (key in BUILTFROMCACHE):
  368. if (BUILTFROMCACHE[key] == [others,dates]):
  369. return 0
  370. else:
  371. oldothers = BUILTFROMCACHE[key][0]
  372. if (oldothers != others and VERBOSE):
  373. print "%sWARNING:%s file dependencies changed: %s%s%s" % (GetColor("red"), GetColor(), GetColor("green"), str(files), GetColor())
  374. return 1
  375. ########################################################################
  376. ##
  377. ## The CXX include cache:
  378. ##
  379. ## The following routine scans a CXX file and returns a list of
  380. ## the include-directives inside that file. It's not recursive:
  381. ## it just returns the includes that are textually inside the
  382. ## file. If you need recursive dependencies, you need the higher-level
  383. ## routine CxxCalcDependencies, defined elsewhere.
  384. ##
  385. ## Since scanning a CXX file is slow, we cache the result. It records
  386. ## the date of the source file and the list of includes that it
  387. ## contains. It assumes that if the file date hasn't changed, that
  388. ## the list of include-statements inside the file has not changed
  389. ## either. Once again, this particular routine does not return
  390. ## recursive dependencies --- it only returns an explicit list of
  391. ## include statements that are textually inside the file. That
  392. ## is what the cache stores, as well.
  393. ##
  394. ########################################################################
  395. CXXINCLUDECACHE = {}
  396. global CxxIncludeRegex
  397. CxxIncludeRegex = re.compile('^[ \t]*[#][ \t]*include[ \t]+"([^"]+)"[ \t\r\n]*$')
  398. def CxxGetIncludes(path):
  399. date = GetTimestamp(path)
  400. if (path in CXXINCLUDECACHE):
  401. cached = CXXINCLUDECACHE[path]
  402. if (cached[0]==date): return cached[1]
  403. try: sfile = open(path, 'rb')
  404. except:
  405. exit("Cannot open source file \""+path+"\" for reading.")
  406. include = []
  407. for line in sfile:
  408. match = CxxIncludeRegex.match(line,0)
  409. if (match):
  410. incname = match.group(1)
  411. include.append(incname)
  412. sfile.close()
  413. CXXINCLUDECACHE[path] = [date, include]
  414. return include
  415. ########################################################################
  416. ##
  417. ## SaveDependencyCache / LoadDependencyCache
  418. ##
  419. ## This actually saves both the dependency and cxx-include caches.
  420. ##
  421. ########################################################################
  422. DCACHE_BACKED_UP = False
  423. def SaveDependencyCache():
  424. global DCACHE_BACKED_UP
  425. if not DCACHE_BACKED_UP:
  426. try:
  427. if (os.path.exists(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"))):
  428. os.rename(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"),
  429. os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache-backup"))
  430. except: pass
  431. DCACHE_BACKED_UP = True
  432. try: icache = open(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"),'wb')
  433. except: icache = 0
  434. if (icache!=0):
  435. print "Storing dependency cache."
  436. cPickle.dump(CXXINCLUDECACHE, icache, 1)
  437. cPickle.dump(BUILTFROMCACHE, icache, 1)
  438. icache.close()
  439. def LoadDependencyCache():
  440. global CXXINCLUDECACHE
  441. global BUILTFROMCACHE
  442. try: icache = open(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"),'rb')
  443. except: icache = 0
  444. if (icache!=0):
  445. CXXINCLUDECACHE = cPickle.load(icache)
  446. BUILTFROMCACHE = cPickle.load(icache)
  447. icache.close()
  448. ########################################################################
  449. ##
  450. ## CxxFindSource: given a source file name and a directory list,
  451. ## searches the directory list for the given source file. Returns
  452. ## the full pathname of the located file.
  453. ##
  454. ## CxxFindHeader: given a source file, an include directive, and a
  455. ## directory list, searches the directory list for the given header
  456. ## file. Returns the full pathname of the located file.
  457. ##
  458. ## Of course, CxxFindSource and CxxFindHeader cannot find a source
  459. ## file that has not been created yet. This can cause dependency
  460. ## problems. So the function CreateStubHeader can be used to create
  461. ## a file that CxxFindSource or CxxFindHeader can subsequently find.
  462. ##
  463. ########################################################################
  464. def CxxFindSource(name, ipath):
  465. for dir in ipath:
  466. if (dir == "."): full = name
  467. else: full = dir + "/" + name
  468. if GetTimestamp(full) > 0: return full
  469. exit("Could not find source file: "+name)
  470. def CxxFindHeader(srcfile, incfile, ipath):
  471. if (incfile.startswith(".")):
  472. last = srcfile.rfind("/")
  473. if (last < 0): exit("CxxFindHeader cannot handle this case #1")
  474. srcdir = srcfile[:last+1]
  475. while (incfile[:1]=="."):
  476. if (incfile[:2]=="./"):
  477. incfile = incfile[2:]
  478. elif (incfile[:3]=="../"):
  479. incfile = incfile[3:]
  480. last = srcdir[:-1].rfind("/")
  481. if (last < 0): exit("CxxFindHeader cannot handle this case #2")
  482. srcdir = srcdir[:last+1]
  483. else: exit("CxxFindHeader cannot handle this case #3")
  484. full = srcdir + incfile
  485. if GetTimestamp(full) > 0: return full
  486. return 0
  487. else:
  488. for dir in ipath:
  489. full = dir + "/" + incfile
  490. if GetTimestamp(full) > 0: return full
  491. return 0
  492. ########################################################################
  493. ##
  494. ## CxxCalcDependencies(srcfile, ipath, ignore)
  495. ##
  496. ## Calculate the dependencies of a source file given a
  497. ## particular include-path. Any file in the list of files to
  498. ## ignore is not considered.
  499. ##
  500. ########################################################################
  501. global CxxIgnoreHeader
  502. global CxxDependencyCache
  503. CxxIgnoreHeader = {}
  504. CxxDependencyCache = {}
  505. def CxxCalcDependencies(srcfile, ipath, ignore):
  506. if (srcfile in CxxDependencyCache):
  507. return CxxDependencyCache[srcfile]
  508. if (ignore.count(srcfile)): return []
  509. dep = {}
  510. dep[srcfile] = 1
  511. includes = CxxGetIncludes(srcfile)
  512. for include in includes:
  513. header = CxxFindHeader(srcfile, include, ipath)
  514. if (header!=0):
  515. if (ignore.count(header)==0):
  516. hdeps = CxxCalcDependencies(header, ipath, [srcfile]+ignore)
  517. for x in hdeps: dep[x] = 1
  518. result = dep.keys()
  519. CxxDependencyCache[srcfile] = result
  520. return result
  521. ########################################################################
  522. ##
  523. ## Registry Key Handling
  524. ##
  525. ## Of course, these routines will fail if you call them on a
  526. ## non win32 platform. If you use them on a win64 platform, they
  527. ## will look in the win32 private hive first, then look in the
  528. ## win64 hive.
  529. ##
  530. ########################################################################
  531. if sys.platform == "win32":
  532. import _winreg
  533. def TryRegistryKey(path):
  534. try:
  535. key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path, 0, _winreg.KEY_READ)
  536. return key
  537. except: pass
  538. try:
  539. key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path, 0, _winreg.KEY_READ | 256)
  540. return key
  541. except: pass
  542. return 0
  543. def ListRegistryKeys(path):
  544. result=[]
  545. index=0
  546. key = TryRegistryKey(path)
  547. if (key != 0):
  548. try:
  549. while (1):
  550. result.append(_winreg.EnumKey(key, index))
  551. index = index + 1
  552. except: pass
  553. _winreg.CloseKey(key)
  554. return result
  555. def ListRegistryValues(path):
  556. result = []
  557. index = 0
  558. key = TryRegistryKey(path)
  559. if (key != 0):
  560. try:
  561. while (1):
  562. result.append(_winreg.EnumValue(key, index)[0])
  563. index = index + 1
  564. except: pass
  565. _winreg.CloseKey(key)
  566. return result
  567. def GetRegistryKey(path, subkey, override64=True):
  568. if (is_64 and override64==True):
  569. path = path.replace("SOFTWARE\\", "SOFTWARE\\Wow6432Node\\")
  570. k1=0
  571. key = TryRegistryKey(path)
  572. if (key != 0):
  573. try:
  574. k1, k2 = _winreg.QueryValueEx(key, subkey)
  575. except: pass
  576. _winreg.CloseKey(key)
  577. return k1
  578. def GetProgramFiles():
  579. if ("PROGRAMFILES" in os.environ):
  580. return os.environ["PROGRAMFILES"]
  581. elif (os.path.isdir("C:\\Program Files")):
  582. return "C:\\Program Files"
  583. elif (os.path.isdir("D:\\Program Files")):
  584. return "D:\\Program Files"
  585. elif (os.path.isdir("E:\\Program Files")):
  586. return "E:\\Program Files"
  587. return 0
  588. ########################################################################
  589. ##
  590. ## Parsing Compiler Option Lists
  591. ##
  592. ########################################################################
  593. def GetListOption(opts, prefix):
  594. res=[]
  595. for x in opts:
  596. if (x.startswith(prefix)):
  597. res.append(x[len(prefix):])
  598. return res
  599. def GetValueOption(opts, prefix):
  600. for x in opts:
  601. if (x.startswith(prefix)):
  602. return x[len(prefix):]
  603. return 0
  604. def GetOptimizeOption(opts):
  605. val = GetValueOption(opts, "OPT:")
  606. if (val == 0):
  607. return OPTIMIZE
  608. return val
  609. ########################################################################
  610. ##
  611. ## General File Manipulation
  612. ##
  613. ########################################################################
  614. def MakeDirectory(path):
  615. if os.path.isdir(path): return 0
  616. os.mkdir(path)
  617. def ReadFile(wfile):
  618. try:
  619. srchandle = open(wfile, "rb")
  620. data = srchandle.read()
  621. srchandle.close()
  622. return data
  623. except: exit("Cannot read "+wfile)
  624. def WriteFile(wfile,data):
  625. try:
  626. dsthandle = open(wfile, "wb")
  627. dsthandle.write(data)
  628. dsthandle.close()
  629. except: exit("Cannot write "+wfile)
  630. def ConditionalWriteFile(dest,desiredcontents):
  631. try:
  632. rfile = open(dest, 'rb')
  633. contents = rfile.read(-1)
  634. rfile.close()
  635. except:
  636. contents=0
  637. if contents != desiredcontents:
  638. sys.stdout.flush()
  639. WriteFile(dest,desiredcontents)
  640. def DeleteCVS(dir):
  641. if dir == "": dir = "."
  642. for entry in os.listdir(dir):
  643. subdir = os.path.join(dir, entry)
  644. if (os.path.isdir(subdir)):
  645. if (entry == "CVS" or entry == "CVSROOT"):
  646. shutil.rmtree(subdir)
  647. else:
  648. DeleteCVS(subdir)
  649. elif (os.path.isfile(subdir) and (entry == ".cvsignore" or entry.startswith(".#"))):
  650. os.remove(subdir)
  651. def DeleteBuildFiles(dir):
  652. if dir == "": dir = "."
  653. for entry in os.listdir(dir):
  654. subdir = os.path.join(dir, entry)
  655. if (os.path.isfile(subdir) and os.path.splitext(subdir)[-1] in [".pp", ".moved"]):
  656. os.remove(subdir)
  657. elif (os.path.isdir(subdir)):
  658. if (os.path.basename(subdir)[:3] == "Opt" and os.path.basename(subdir)[4] == "-"):
  659. shutil.rmtree(subdir)
  660. else:
  661. DeleteBuildFiles(subdir)
  662. def DeleteEmptyDirs(dir):
  663. if dir == "": dir = "."
  664. entries = os.listdir(dir)
  665. if not entries:
  666. os.rmdir(dir)
  667. return
  668. for entry in entries:
  669. subdir = os.path.join(dir, entry)
  670. if (os.path.isdir(subdir)):
  671. if (not os.listdir(subdir)):
  672. os.rmdir(subdir)
  673. else:
  674. DeleteEmptyDirs(subdir)
  675. def CreateFile(file):
  676. if (os.path.exists(file)==0):
  677. WriteFile(file,"")
  678. ########################################################################
  679. #
  680. # Create the panda build tree.
  681. #
  682. ########################################################################
  683. def MakeBuildTree():
  684. MakeDirectory(OUTPUTDIR)
  685. MakeDirectory(OUTPUTDIR+"/bin")
  686. MakeDirectory(OUTPUTDIR+"/lib")
  687. MakeDirectory(OUTPUTDIR+"/tmp")
  688. MakeDirectory(OUTPUTDIR+"/etc")
  689. MakeDirectory(OUTPUTDIR+"/plugins")
  690. MakeDirectory(OUTPUTDIR+"/include")
  691. MakeDirectory(OUTPUTDIR+"/models")
  692. MakeDirectory(OUTPUTDIR+"/models/audio")
  693. MakeDirectory(OUTPUTDIR+"/models/audio/sfx")
  694. MakeDirectory(OUTPUTDIR+"/models/icons")
  695. MakeDirectory(OUTPUTDIR+"/models/maps")
  696. MakeDirectory(OUTPUTDIR+"/models/misc")
  697. MakeDirectory(OUTPUTDIR+"/models/gui")
  698. MakeDirectory(OUTPUTDIR+"/pandac")
  699. MakeDirectory(OUTPUTDIR+"/pandac/input")
  700. ########################################################################
  701. #
  702. # Make sure that you are in the root of the panda tree.
  703. #
  704. ########################################################################
  705. def CheckPandaSourceTree():
  706. dir = os.getcwd()
  707. if ((os.path.exists(os.path.join(dir, "makepanda/makepanda.py"))==0) or
  708. (os.path.exists(os.path.join(dir, "dtool","src","dtoolbase","dtoolbase.h"))==0) or
  709. (os.path.exists(os.path.join(dir, "panda","src","pandabase","pandabase.h"))==0)):
  710. exit("Current directory is not the root of the panda tree.")
  711. ########################################################################
  712. ##
  713. ## Thirdparty libraries paths
  714. ##
  715. ########################################################################
  716. def GetThirdpartyBase():
  717. global THIRDPARTYBASE
  718. if (THIRDPARTYBASE != None):
  719. return THIRDPARTYBASE
  720. THIRDPARTYBASE = "thirdparty"
  721. if "MAKEPANDA_THIRDPARTY" in os.environ:
  722. THIRDPARTYBASE = os.environ["MAKEPANDA_THIRDPARTY"]
  723. return THIRDPARTYBASE
  724. def GetThirdpartyDir():
  725. global THIRDPARTYDIR
  726. if (THIRDPARTYDIR != None):
  727. return THIRDPARTYDIR
  728. if (sys.platform.startswith("win")):
  729. if (is_64):
  730. THIRDPARTYDIR=GetThirdpartyBase()+"/win-libs-vc9-x64/"
  731. else:
  732. THIRDPARTYDIR=GetThirdpartyBase()+"/win-libs-vc9/"
  733. if not os.path.isdir(THIRDPARTYDIR):
  734. THIRDPARTYDIR=GetThirdpartyBase()+"/win-libs-vc9/"
  735. elif (sys.platform == "darwin"):
  736. THIRDPARTYDIR=GetThirdpartyBase()+"/darwin-libs-a/"
  737. elif (sys.platform.startswith("linux")):
  738. if (platform.machine().startswith("arm")):
  739. THIRDPARTYDIR=GetThirdpartyBase()+"/linux-libs-arm/"
  740. elif (is_64):
  741. THIRDPARTYDIR=GetThirdpartyBase()+"/linux-libs-x64/"
  742. else:
  743. THIRDPARTYDIR=GetThirdpartyBase()+"/linux-libs-a/"
  744. elif (sys.platform.startswith("freebsd")):
  745. if (platform.machine().startswith("arm")):
  746. THIRDPARTYDIR=GetThirdpartyBase()+"/freebsd-libs-arm/"
  747. elif (is_64):
  748. THIRDPARTYDIR=GetThirdpartyBase()+"/freebsd-libs-x64/"
  749. else:
  750. THIRDPARTYDIR=GetThirdpartyBase()+"/freebsd-libs-a/"
  751. else:
  752. print GetColor("red") + "WARNING:" + GetColor("Unsupported platform: " + sys.platform)
  753. return THIRDPARTYDIR
  754. ########################################################################
  755. ##
  756. ## Visual Studio Manifest Manipulation.
  757. ## These functions exist to make sure we are referencing the same
  758. ## version of the VC runtime in the manifests that we are shipping
  759. ## with Panda3D, to avoid side-by-side configuration errors. Also,
  760. ## it also removes any dependency the VC80 CRT (as we only want to
  761. ## depend on the VC90 CRT).
  762. ##
  763. ########################################################################
  764. VC90CRTVERSIONRE=re.compile("name=['\"]Microsoft.VC90.CRT['\"]\\s+version=['\"]([0-9.]+)['\"]")
  765. VC80CRTASSEMBLYRE=re.compile("<dependency>[\t \r\n]*<dependentAssembly>[\t \r\n]*<assemblyIdentity[\t \r\na-zA-Z0-9.'\"=]*name=['\"]Microsoft[.]VC80[.]CRT['\"][\t \r\na-zA-Z0-9.'\"=/]*>[\t \r\n]*(</assemblyIdentity>)?[\t \r\n]*</dependentAssembly>[\t \r\n]*</dependency>[\t \r\n]*")
  766. VC90CRTVERSION=None
  767. def GetVC90CRTVersion(fn = None):
  768. global VC90CRTVERSION
  769. if (VC90CRTVERSION != None):
  770. return VC90CRTVERSION
  771. if (not sys.platform.startswith("win")):
  772. VC90CRTVERSION = 0
  773. return 0
  774. if (fn == None):
  775. fn = GetThirdpartyDir()+"extras/bin/Microsoft.VC90.CRT.manifest"
  776. manifest = ReadFile(fn)
  777. version = VC90CRTVERSIONRE.search(manifest)
  778. if (version == None):
  779. exit("Cannot locate version number in "+fn)
  780. VC90CRTVERSION = version.group(1)
  781. return version.group(1)
  782. def SetVC90CRTVersion(fn, ver = None):
  783. if (ver == None): ver = GetVC90CRTVersion()
  784. manifest = ReadFile(fn)
  785. subst = " name='Microsoft.VC90.CRT' version='"+ver+"' "
  786. manifest = VC90CRTVERSIONRE.sub(subst, manifest)
  787. manifest = VC80CRTASSEMBLYRE.sub("", manifest)
  788. WriteFile(fn, manifest)
  789. ########################################################################
  790. ##
  791. ## Gets or sets the output directory, by default "built".
  792. ## Gets or sets the optimize level.
  793. ## Gets or sets the verbose flag.
  794. ##
  795. ########################################################################
  796. def GetOutputDir():
  797. return OUTPUTDIR
  798. def IsCustomOutputDir():
  799. return CUSTOM_OUTPUTDIR
  800. def SetOutputDir(outputdir):
  801. global OUTPUTDIR, CUSTOM_OUTPUTDIR
  802. OUTPUTDIR=outputdir
  803. CUSTOM_OUTPUTDIR=True
  804. def GetOptimize():
  805. return int(OPTIMIZE)
  806. def SetOptimize(optimize):
  807. global OPTIMIZE
  808. OPTIMIZE=optimize
  809. def GetVerbose():
  810. return VERBOSE
  811. def SetVerbose(verbose):
  812. global VERBOSE
  813. VERBOSE=verbose
  814. def GetLinkAllStatic():
  815. return LINK_ALL_STATIC
  816. def SetLinkAllStatic(val = True):
  817. global LINK_ALL_STATIC
  818. LINK_ALL_STATIC = val
  819. def UnsetLinkAllStatic():
  820. global LINK_ALL_STATIC
  821. LINK_ALL_STATIC = False
  822. ########################################################################
  823. ##
  824. ## Package Selection
  825. ##
  826. ## This facility enables makepanda to keep a list of packages selected
  827. ## by the user for inclusion or omission.
  828. ##
  829. ########################################################################
  830. PKG_LIST_ALL=[]
  831. PKG_LIST_OMIT={}
  832. def PkgListSet(pkgs):
  833. global PKG_LIST_ALL
  834. global PKG_LIST_OMIT
  835. PKG_LIST_ALL=pkgs
  836. PKG_LIST_OMIT={}
  837. PkgEnableAll()
  838. def PkgListGet():
  839. return PKG_LIST_ALL
  840. def PkgEnableAll():
  841. for x in PKG_LIST_ALL:
  842. PKG_LIST_OMIT[x] = 0
  843. def PkgDisableAll():
  844. for x in PKG_LIST_ALL:
  845. PKG_LIST_OMIT[x] = 1
  846. def PkgEnable(pkg):
  847. PKG_LIST_OMIT[pkg] = 0
  848. def PkgDisable(pkg):
  849. PKG_LIST_OMIT[pkg] = 1
  850. def PkgSkip(pkg):
  851. return PKG_LIST_OMIT[pkg]
  852. def PkgSelected(pkglist, pkg):
  853. if (pkglist.count(pkg)==0): return 0
  854. if (PKG_LIST_OMIT[pkg]): return 0
  855. return 1
  856. ########################################################################
  857. ##
  858. ## DTOOL/PRC Option value override
  859. ##
  860. ## This facility enables makepanda to keep a list of parameters
  861. ## overriden by the command line.
  862. ##
  863. ########################################################################
  864. OVERRIDES_LIST={}
  865. def AddOverride(spec):
  866. if (spec.find("=")==-1):return
  867. pair = spec.split("=",1)
  868. OVERRIDES_LIST[pair[0]] = pair[1]
  869. def OverrideValue(parameter, value):
  870. if parameter in OVERRIDES_LIST:
  871. print "Overriding value of key \"" + parameter + "\" with value \"" + OVERRIDES_LIST[parameter] + "\""
  872. return OVERRIDES_LIST[parameter]
  873. else:
  874. return value
  875. ########################################################################
  876. ##
  877. ## These functions are for libraries which use pkg-config.
  878. ##
  879. ########################################################################
  880. def PkgConfigHavePkg(pkgname, tool = "pkg-config"):
  881. """Returns a bool whether the pkg-config package is installed."""
  882. if (sys.platform == "win32" or not LocateBinary(tool)):
  883. return False
  884. if (tool == "pkg-config"):
  885. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --modversion " + pkgname)
  886. else:
  887. return bool(LocateBinary(tool) != None)
  888. result = handle.read().strip()
  889. returnval = handle.close()
  890. if returnval != None and returnval != 0:
  891. return False
  892. return bool(len(result) > 0)
  893. def PkgConfigGetLibs(pkgname, tool = "pkg-config"):
  894. """Returns a list of libs for the package, prefixed by -l."""
  895. if (sys.platform == "win32" or not LocateBinary(tool)):
  896. return []
  897. if (tool == "pkg-config"):
  898. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --libs-only-l " + pkgname)
  899. elif (tool == "fltk-config"):
  900. handle = os.popen(LocateBinary("fltk-config") + " --ldstaticflags")
  901. else:
  902. handle = os.popen(LocateBinary(tool) + " --libs")
  903. result = handle.read().strip()
  904. handle.close()
  905. libs = []
  906. # Walk through the result arguments carefully. Look for -lname as
  907. # well as -framework name.
  908. r = result.split(' ')
  909. ri = 0
  910. while ri < len(r):
  911. l = r[ri]
  912. if l.startswith("-l") or l.startswith("/"):
  913. libs.append(l)
  914. elif l == '-framework':
  915. libs.append(l)
  916. ri += 1
  917. libs.append(r[ri])
  918. ri += 1
  919. return libs
  920. def PkgConfigGetIncDirs(pkgname, tool = "pkg-config"):
  921. """Returns a list of includes for the package, NOT prefixed by -I."""
  922. if (sys.platform == "win32" or not LocateBinary(tool)):
  923. return []
  924. if (tool == "pkg-config"):
  925. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --cflags-only-I " + pkgname)
  926. else:
  927. handle = os.popen(LocateBinary(tool) + " --cflags")
  928. result = handle.read().strip()
  929. if len(result) == 0: return []
  930. handle.close()
  931. libs = []
  932. for l in result.split(" "):
  933. if (l.startswith("-I")):
  934. libs.append(l.replace("-I", "").replace("\"", "").strip())
  935. return libs
  936. def PkgConfigGetLibDirs(pkgname, tool = "pkg-config"):
  937. """Returns a list of library paths for the package, NOT prefixed by -L."""
  938. if (sys.platform == "win32" or not LocateBinary(tool)):
  939. return []
  940. if (tool == "pkg-config"):
  941. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --libs-only-L " + pkgname)
  942. elif (tool == "wx-config"):
  943. return []
  944. else:
  945. handle = os.popen(LocateBinary(tool) + " --ldflags")
  946. result = handle.read().strip()
  947. handle.close()
  948. if len(result) == 0: return []
  949. libs = []
  950. for l in result.split(" "):
  951. if (l.startswith("-L")):
  952. libs.append(l.replace("-L", "").replace("\"", "").strip())
  953. return libs
  954. def PkgConfigGetDefSymbols(pkgname, tool = "pkg-config"):
  955. """Returns a dictionary of preprocessor definitions."""
  956. if (sys.platform == "win32" or not LocateBinary(tool)):
  957. return []
  958. if (tool == "pkg-config"):
  959. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --cflags " + pkgname)
  960. else:
  961. handle = os.popen(LocateBinary(tool) + " --cflags")
  962. result = handle.read().strip()
  963. handle.close()
  964. if len(result) == 0: return {}
  965. defs = {}
  966. for l in result.split(" "):
  967. if (l.startswith("-D")):
  968. d = l.replace("-D", "").replace("\"", "").strip().split("=")
  969. if (len(d) == 1):
  970. defs[d[0]] = ""
  971. else:
  972. defs[d[0]] = d[1]
  973. return defs
  974. def PkgConfigEnable(opt, pkgname, tool = "pkg-config"):
  975. """Adds the libraries and includes to IncDirectory, LibName and LibDirectory."""
  976. for i in PkgConfigGetIncDirs(pkgname, tool):
  977. IncDirectory(opt, i)
  978. for i in PkgConfigGetLibDirs(pkgname, tool):
  979. LibDirectory(opt, i)
  980. for i in PkgConfigGetLibs(pkgname, tool):
  981. LibName(opt, i)
  982. for i, j in PkgConfigGetDefSymbols(pkgname, tool).items():
  983. DefSymbol(opt, i, j)
  984. LD_CACHE = None
  985. STATIC_CACHE = None
  986. def GetLibCache():
  987. # Returns a list of cached libraries, not prefixed by lib and not suffixed by .so* or .a!
  988. global LD_CACHE
  989. if (LD_CACHE == None):
  990. LD_CACHE = []
  991. print "Generating library cache..."
  992. if (LocateBinary("ldconfig") != None and not sys.platform.startswith("freebsd")):
  993. handle = os.popen(LocateBinary("ldconfig") + " -NXp")
  994. result = handle.read().strip().split("\n")
  995. for line in result:
  996. lib = line.strip().split(" ", 1)[0]
  997. if (lib.endswith(".so") or ".so " in lib):
  998. lib = lib.split(".so", 1)[0][3:]
  999. LD_CACHE.append(lib)
  1000. libdirs = ["/lib", "/usr/lib", "/usr/local/lib", "/usr/PCBSD/local/lib", "/usr/X11/lib", "/usr/X11R6/lib"]
  1001. if is_64:
  1002. libdirs += ["/lib64", "/usr/lib64"]
  1003. if "LD_LIBRARY_PATH" in os.environ:
  1004. libdirs += os.environ["LD_LIBRARY_PATH"].split(":")
  1005. libdirs = list(set(libdirs))
  1006. libs = []
  1007. for path in libdirs:
  1008. if os.path.isdir(path):
  1009. libs += glob.glob(path + "/lib*.so")
  1010. libs += glob.glob(path + "/lib*.a")
  1011. if (sys.platform == "darwin"):
  1012. libs += glob.glob(path + "/lib*.dylib")
  1013. for l in libs:
  1014. lib = os.path.basename(l).split(".so", 1)[0].split(".a", 1)[0].split(".dylib", 1)[0][3:]
  1015. if lib not in LD_CACHE:
  1016. LD_CACHE.append(lib)
  1017. return LD_CACHE
  1018. def ChooseLib(*libs):
  1019. # Chooses a library from the parameters, in order of preference. Returns the first if none of them were found.
  1020. for l in libs:
  1021. libname = l
  1022. if (l.startswith("lib")):
  1023. libname = l[3:]
  1024. if (libname in GetLibCache()):
  1025. return libname
  1026. if (len(libs) > 0):
  1027. if (VERBOSE):
  1028. print GetColor("cyan") + "Couldn't find any of the libraries " + ", ".join(libs) + GetColor()
  1029. return libs[0]
  1030. def SmartPkgEnable(pkg, pkgconfig = None, libs = None, incs = None, defs = None, framework = None, target_pkg = None, tool = "pkg-config"):
  1031. global PKG_LIST_ALL
  1032. if (pkg in PkgListGet() and PkgSkip(pkg)):
  1033. return
  1034. if (target_pkg == "" or target_pkg == None):
  1035. target_pkg = pkg
  1036. if (pkgconfig == ""):
  1037. pkgconfig = None
  1038. if (framework == ""):
  1039. framework = None
  1040. if (libs == None or libs == ""):
  1041. libs = ()
  1042. elif (isinstance(libs, str)):
  1043. libs = (libs, )
  1044. if (incs == None or incs == ""):
  1045. incs = ()
  1046. elif (isinstance(incs, str)):
  1047. incs = (incs, )
  1048. if (defs == None or defs == "" or len(defs) == 0):
  1049. defs = {}
  1050. elif (isinstance(incs, str)):
  1051. defs = {defs : ""}
  1052. elif (isinstance(incs, list) or isinstance(incs, tuple) or isinstance(incs, set)):
  1053. olddefs = defs
  1054. defs = {}
  1055. for d in olddefs:
  1056. defs[d] = ""
  1057. if (pkg.lower() == "swscale" and os.path.isfile(GetThirdpartyDir() + "ffmpeg/include/libswscale/swscale.h")):
  1058. # Let it be handled by the ffmpeg package
  1059. LibName(target_pkg, "-lswscale")
  1060. return
  1061. if (os.path.isdir(GetThirdpartyDir() + pkg.lower())):
  1062. IncDirectory(target_pkg, GetThirdpartyDir() + pkg.lower() + "/include")
  1063. LibDirectory(target_pkg, GetThirdpartyDir() + pkg.lower() + "/lib")
  1064. # TODO: check for a .pc file in the lib/pkg-config/ dir
  1065. if (tool != None and os.path.isfile(GetThirdpartyDir() + pkg.lower() + "/bin/" + tool)):
  1066. tool = GetThirdpartyDir() + pkg.lower() + "/bin/" + tool
  1067. for i in PkgConfigGetLibs(None, tool):
  1068. LibName(target_pkg, i)
  1069. for i, j in PkgConfigGetDefSymbols(None, tool).items():
  1070. DefSymbol(target_pkg, i, j)
  1071. return
  1072. for l in libs:
  1073. libname = l
  1074. if (l.startswith("lib")):
  1075. libname = l[3:]
  1076. # This is for backward compatibility - in the thirdparty dir, we kept some libs with "panda" prefix, like libpandatiff.
  1077. if (len(glob.glob(GetThirdpartyDir() + pkg.lower() + "/lib/libpanda%s.*" % libname)) > 0 and
  1078. len(glob.glob(GetThirdpartyDir() + pkg.lower() + "/lib/lib%s.*" % libname)) == 0):
  1079. libname = "panda" + libname
  1080. LibName(target_pkg, "-l" + libname)
  1081. for d, v in defs.values():
  1082. DefSymbol(target_pkg, d, v)
  1083. return
  1084. elif (sys.platform == "darwin" and framework != None):
  1085. if (os.path.isdir("/Library/Frameworks/%s.framework" % framework) or
  1086. os.path.isdir("/System/Library/Frameworks/%s.framework" % framework) or
  1087. os.path.isdir("/Developer/Library/Frameworks/%s.framework" % framework) or
  1088. os.path.isdir("/Users/%s/System/Library/Frameworks/%s.framework" % (getpass.getuser(), framework))):
  1089. LibName(target_pkg, "-framework " + framework)
  1090. for d, v in defs.values():
  1091. DefSymbol(target_pkg, d, v)
  1092. elif (pkg in PkgListGet()):
  1093. print "%sWARNING:%s Could not locate framework %s, excluding from build" % (GetColor("red"), GetColor(), framework)
  1094. PkgDisable(pkg)
  1095. else:
  1096. print "%sERROR:%s Could not locate framework %s, aborting build" % (GetColor("red"), GetColor(), framework)
  1097. exit()
  1098. return
  1099. elif (LocateBinary(tool) != None and (tool != "pkg-config" or pkgconfig != None)):
  1100. if (isinstance(pkgconfig, str) or tool != "pkg-config"):
  1101. if (PkgConfigHavePkg(pkgconfig, tool)):
  1102. return PkgConfigEnable(target_pkg, pkgconfig, tool)
  1103. else:
  1104. have_all_pkgs = True
  1105. for pc in pkgconfig:
  1106. if (PkgConfigHavePkg(pc, tool)):
  1107. PkgConfigEnable(target_pkg, pc, tool)
  1108. else:
  1109. have_all_pkgs = False
  1110. if (have_all_pkgs):
  1111. return
  1112. if (pkgconfig != None and (libs == None or len(libs) == 0)):
  1113. if (pkg in PkgListGet()):
  1114. print "%sWARNING:%s Could not locate pkg-config package %s, excluding from build" % (GetColor("red"), GetColor(), pkgconfig)
  1115. PkgDisable(pkg)
  1116. else:
  1117. print "%sERROR:%s Could not locate pkg-config package %s, aborting build" % (GetColor("red"), GetColor(), pkgconfig)
  1118. exit()
  1119. else:
  1120. # Okay, our pkg-config attempts failed. Let's try locating the libs by ourselves.
  1121. have_pkg = True
  1122. for l in libs:
  1123. libname = l
  1124. if (l.startswith("lib")):
  1125. libname = l[3:]
  1126. if (libname in GetLibCache()):
  1127. LibName(target_pkg, "-l" + libname)
  1128. else:
  1129. if (VERBOSE):
  1130. print GetColor("cyan") + "Couldn't find library lib" + libname + GetColor()
  1131. have_pkg = False
  1132. for i in incs:
  1133. incdir = None
  1134. if (len(glob.glob("/usr/include/" + i)) > 0):
  1135. incdir = sorted(glob.glob("/usr/include/" + i))[-1]
  1136. elif (len(glob.glob("/usr/local/include/" + i)) > 0):
  1137. incdir = sorted(glob.glob("/usr/local/include/" + i))[-1]
  1138. elif (os.path.isdir("/usr/PCBSD") and len(glob.glob("/usr/PCBSD/local/include/" + i)) > 0):
  1139. incdir = sorted(glob.glob("/usr/PCBSD/local/include/" + i))[-1]
  1140. else:
  1141. have_pkg = False
  1142. # Try searching in the package's IncDirectories.
  1143. for ppkg, pdir in INCDIRECTORIES:
  1144. if (pkg == ppkg and len(glob.glob(os.path.join(pdir, i))) > 0):
  1145. incdir = sorted(glob.glob(os.path.join(pdir, i)))[-1]
  1146. have_pkg = True
  1147. if (incdir == None and VERBOSE and i.endswith(".h")):
  1148. print GetColor("cyan") + "Couldn't find header file " + i + GetColor()
  1149. # Note: It's possible to specify a file instead of a dir, for the sake of checking if it exists.
  1150. if (incdir != None and os.path.isdir(incdir)):
  1151. IncDirectory(target_pkg, incdir)
  1152. if (not have_pkg):
  1153. if (pkg in PkgListGet()):
  1154. print "%sWARNING:%s Could not locate thirdparty package %s, excluding from build" % (GetColor("red"), GetColor(), pkg.lower())
  1155. PkgDisable(pkg)
  1156. else:
  1157. print "%sERROR:%s Could not locate thirdparty package %s, aborting build" % (GetColor("red"), GetColor(), pkg.lower())
  1158. exit()
  1159. ########################################################################
  1160. ##
  1161. ## SDK Location
  1162. ##
  1163. ## This section is concerned with locating the install directories
  1164. ## for various third-party packages. The results are stored in the
  1165. ## SDK table.
  1166. ##
  1167. ## Microsoft keeps changing the &*#$*& registry key for the DirectX SDK.
  1168. ## The only way to reliably find it is to search through the installer's
  1169. ## uninstall-directories, look in each one, and see if it contains the
  1170. ## relevant files.
  1171. ##
  1172. ########################################################################
  1173. SDK = {}
  1174. def GetSdkDir(sdkname, sdkkey = None):
  1175. # Returns the default SDK directory. If it exists,
  1176. # and sdkkey is not None, it is put in SDK[sdkkey].
  1177. # Note: return value may not be an existing path.
  1178. sdkbase = "sdks"
  1179. if "MAKEPANDA_SDKS" in os.environ:
  1180. sdkbase = os.environ["MAKEPANDA_SDKS"]
  1181. sdir = sdkbase[:]
  1182. if (sys.platform.startswith("win")):
  1183. sdir += "/win"
  1184. sdir += platform.architecture()[0][:2]
  1185. elif (sys.platform.startswith("linux")):
  1186. sdir += "/linux"
  1187. sdir += platform.architecture()[0][:2]
  1188. elif (sys.platform == "darwin"):
  1189. sdir += "/macosx"
  1190. sdir += "/" + sdkname
  1191. # If it does not exist, try the old location.
  1192. if (not os.path.isdir(sdir)):
  1193. sdir = sdkbase + "/" + sdir
  1194. if (sys.platform.startswith("linux")):
  1195. sdir += "-linux"
  1196. sdir += platform.architecture()[0][:2]
  1197. elif (sys.platform == "darwin"):
  1198. sdir += "-osx"
  1199. if (sdkkey and os.path.isdir(sdir)):
  1200. SDK[sdkkey] = sdir
  1201. return sdir
  1202. def SdkLocateDirectX( strMode = 'default' ):
  1203. if (sys.platform != "win32"): return
  1204. if strMode == 'default':
  1205. GetSdkDir("directx8", "DX8")
  1206. GetSdkDir("directx9", "DX9")
  1207. if ("DX9" not in SDK):
  1208. strMode = 'latest'
  1209. if strMode == 'latest':
  1210. ## We first try to locate the August SDK in 64 bits, then 32.
  1211. if ("DX9" not in SDK):
  1212. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1213. if (dir != 0):
  1214. print "Using DirectX SDK June 2010"
  1215. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1216. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1217. if ("DX9" not in SDK):
  1218. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1219. if (dir != 0):
  1220. print "Using DirectX SDK June 2010"
  1221. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1222. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1223. if ("DX9" not in SDK):
  1224. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1225. if (dir != 0):
  1226. print "Using DirectX SDK Aug 2009"
  1227. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1228. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1229. if ("DX9" not in SDK):
  1230. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1231. if (dir != 0):
  1232. print "Using DirectX SDK Aug 2009"
  1233. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1234. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1235. if ("DX9" not in SDK):
  1236. ## Try to locate the key within the "new" March 2009 location in the registry (yecch):
  1237. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (March 2009)", "InstallPath")
  1238. if (dir != 0):
  1239. print "Using DirectX SDK March 2009"
  1240. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1241. archStr = "x86"
  1242. if (is_64): archStr = "x64"
  1243. if ("DX9" not in SDK) or ("DX8" not in SDK):
  1244. uninstaller = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
  1245. for subdir in ListRegistryKeys(uninstaller):
  1246. if (subdir[0]=="{"):
  1247. dir = GetRegistryKey(uninstaller+"\\"+subdir, "InstallLocation")
  1248. if (dir != 0):
  1249. if (("DX8" not in SDK) and
  1250. (os.path.isfile(dir+"\\Include\\d3d8.h")) and
  1251. (os.path.isfile(dir+"\\Include\\d3dx8.h")) and
  1252. (os.path.isfile(dir+"\\Lib\\d3d8.lib")) and
  1253. (os.path.isfile(dir+"\\Lib\\d3dx8.lib"))):
  1254. SDK["DX8"] = dir.replace("\\", "/").rstrip("/")
  1255. if (("DX9" not in SDK) and
  1256. (os.path.isfile(dir+"\\Include\\d3d9.h")) and
  1257. (os.path.isfile(dir+"\\Include\\d3dx9.h")) and
  1258. (os.path.isfile(dir+"\\Include\\dxsdkver.h")) and
  1259. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3d9.lib")) and
  1260. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3dx9.lib"))):
  1261. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1262. if ("DX9" not in SDK):
  1263. return
  1264. elif strMode == 'jun2010':
  1265. if ("DX9" not in SDK):
  1266. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1267. if (dir != 0):
  1268. print "Found DirectX SDK June 2010"
  1269. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1270. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1271. if ("DX9" not in SDK):
  1272. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1273. if (dir != 0):
  1274. print "Found DirectX SDK June 2010"
  1275. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1276. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1277. if ("DX9" not in SDK):
  1278. exit("Couldn't find DirectX June2010 SDK")
  1279. elif strMode == 'aug2009':
  1280. if ("DX9" not in SDK):
  1281. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1282. if (dir != 0):
  1283. print "Found DirectX SDK Aug 2009"
  1284. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1285. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1286. if ("DX9" not in SDK):
  1287. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1288. if (dir != 0):
  1289. print "Found DirectX SDK Aug 2009"
  1290. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1291. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1292. if ("DX9" not in SDK):
  1293. exit("Couldn't find DirectX Aug 2009 SDK")
  1294. elif strMode == 'mar2009':
  1295. if ("DX9" not in SDK):
  1296. ## Try to locate the key within the "new" March 2009 location in the registry (yecch):
  1297. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (March 2009)", "InstallPath")
  1298. if (dir != 0):
  1299. print "Found DirectX SDK March 2009"
  1300. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1301. if ("DX9" not in SDK):
  1302. exit("Couldn't find DirectX March 2009 SDK")
  1303. elif strMode == 'aug2006':
  1304. archStr = "x86"
  1305. if (is_64): archStr = "x64"
  1306. if ("DX9" not in SDK) or ("DX8" not in SDK):
  1307. uninstaller = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
  1308. for subdir in ListRegistryKeys(uninstaller):
  1309. if (subdir[0]=="{"):
  1310. dir = GetRegistryKey(uninstaller+"\\"+subdir, "InstallLocation")
  1311. if (dir != 0):
  1312. if (("DX8" not in SDK) and
  1313. (os.path.isfile(dir+"\\Include\\d3d8.h")) and
  1314. (os.path.isfile(dir+"\\Include\\d3dx8.h")) and
  1315. (os.path.isfile(dir+"\\Lib\\d3d8.lib")) and
  1316. (os.path.isfile(dir+"\\Lib\\d3dx8.lib"))):
  1317. SDK["DX8"] = dir.replace("\\", "/").rstrip("/")
  1318. if (("DX9" not in SDK) and
  1319. (os.path.isfile(dir+"\\Include\\d3d9.h")) and
  1320. (os.path.isfile(dir+"\\Include\\d3dx9.h")) and
  1321. (os.path.isfile(dir+"\\Include\\dxsdkver.h")) and
  1322. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3d9.lib")) and
  1323. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3dx9.lib"))):
  1324. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1325. if ("DX9" not in SDK):
  1326. exit("Couldn't find a DirectX Aug 2006 SDK")
  1327. if ("DX9" in SDK):
  1328. SDK["DIRECTCAM"] = SDK["DX9"]
  1329. def SdkLocateMaya():
  1330. for (ver,key) in MAYAVERSIONINFO:
  1331. if (PkgSkip(ver)==0 and ver not in SDK):
  1332. GetSdkDir(ver.lower().replace("x",""), ver)
  1333. if (not ver in SDK):
  1334. if (sys.platform == "win32"):
  1335. for dev in ["Alias|Wavefront","Alias","Autodesk"]:
  1336. fullkey="SOFTWARE\\"+dev+"\\Maya\\"+key+"\\Setup\\InstallPath"
  1337. res = GetRegistryKey(fullkey, "MAYA_INSTALL_LOCATION", override64=False)
  1338. if (res != 0):
  1339. res = res.replace("\\", "/").rstrip("/")
  1340. SDK[ver] = res
  1341. elif (sys.platform == "darwin"):
  1342. ddir = "/Applications/Autodesk/maya"+key
  1343. if (os.path.isdir(ddir)): SDK[ver] = ddir
  1344. else:
  1345. if (is_64):
  1346. ddir1 = "/usr/autodesk/maya"+key+"-x64"
  1347. ddir2 = "/usr/aw/maya"+key+"-x64"
  1348. else:
  1349. ddir1 = "/usr/autodesk/maya"+key
  1350. ddir2 = "/usr/aw/maya"+key
  1351. if (os.path.isdir(ddir1)): SDK[ver] = ddir1
  1352. elif (os.path.isdir(ddir2)): SDK[ver] = ddir2
  1353. def SdkLocateMax():
  1354. if (sys.platform != "win32"): return
  1355. for version,key1,key2,subdir in MAXVERSIONINFO:
  1356. if (PkgSkip(version)==0):
  1357. if (version not in SDK):
  1358. GetSdkDir("maxsdk"+version.lower()[3:], version)
  1359. GetSdkDir("maxsdk"+version.lower()[3:], version+"CS")
  1360. if (not version in SDK):
  1361. top = GetRegistryKey(key1,key2)
  1362. if (top != 0):
  1363. SDK[version] = top + "maxsdk"
  1364. if (os.path.isdir(top + "\\" + subdir)!=0):
  1365. SDK[version+"CS"] = top + subdir
  1366. def SdkLocatePython(force_use_sys_executable = False):
  1367. if (PkgSkip("PYTHON")==0):
  1368. if (sys.platform == "win32" and not force_use_sys_executable):
  1369. SDK["PYTHON"] = GetThirdpartyBase()+"/win-python"
  1370. if (GetOptimize() <= 2):
  1371. SDK["PYTHON"] += "-dbg"
  1372. if (is_64 and os.path.isdir(SDK["PYTHON"] + "-x64")):
  1373. SDK["PYTHON"] += "-x64"
  1374. SDK["PYTHONEXEC"] = SDK["PYTHON"] + "/python"
  1375. if (GetOptimize() <= 2): SDK["PYTHONEXEC"] += "_d.exe"
  1376. else: SDK["PYTHONEXEC"] += ".exe"
  1377. if (not os.path.isfile(SDK["PYTHONEXEC"])):
  1378. exit("Could not find %s!" % SDK["PYTHONEXEC"])
  1379. os.system(SDK["PYTHONEXEC"].replace("/", "\\") + " -V > "+OUTPUTDIR+"/tmp/pythonversion 2>&1")
  1380. pv=ReadFile(OUTPUTDIR+"/tmp/pythonversion")
  1381. if (pv.startswith("Python ")==0):
  1382. exit("python -V did not produce the expected output")
  1383. pv = pv[7:10]
  1384. SDK["PYTHONVERSION"]="python"+pv
  1385. elif (sys.platform == "win32"):
  1386. SDK["PYTHON"] = os.path.dirname(sysconfig.get_python_inc())
  1387. SDK["PYTHONVERSION"] = "python" + sysconfig.get_python_version()
  1388. SDK["PYTHONEXEC"] = sys.executable
  1389. else:
  1390. SDK["PYTHON"] = sysconfig.get_python_inc()
  1391. SDK["PYTHONVERSION"] = "python" + sysconfig.get_python_version()
  1392. if (os.path.islink(sys.executable)):
  1393. SDK["PYTHONEXEC"] = os.path.join(os.path.dirname(sys.executable), os.readlink(sys.executable))
  1394. else:
  1395. SDK["PYTHONEXEC"] = sys.executable
  1396. elif (os.path.islink(sys.executable)):
  1397. SDK["PYTHONEXEC"] = os.path.join(os.path.dirname(sys.executable), os.readlink(sys.executable))
  1398. else:
  1399. SDK["PYTHONEXEC"] = sys.executable
  1400. def SdkLocateVisualStudio():
  1401. if (sys.platform != "win32"): return
  1402. vcdir = GetRegistryKey("SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VC7", "9.0")
  1403. if (vcdir != 0) and (vcdir[-4:] == "\\VC\\"):
  1404. vcdir = vcdir[:-3]
  1405. SDK["VISUALSTUDIO"] = vcdir
  1406. elif "VCINSTALLDIR" in os.environ:
  1407. vcdir = os.environ["VCINSTALLDIR"]
  1408. if (vcdir[-3:] == "\\VC"):
  1409. vcdir = vcdir[:-2]
  1410. elif (vcdir[-4:] == "\\VC\\"):
  1411. vcdir = vcdir[:-3]
  1412. SDK["VISUALSTUDIO"] = vcdir
  1413. def SdkLocateMSPlatform( strMode = 'default'):
  1414. if (sys.platform != "win32"): return
  1415. platsdk = 0
  1416. if (strMode == 'default'):
  1417. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v7.1", "InstallationFolder")
  1418. if (platsdk and not os.path.isdir(platsdk)):
  1419. platsdk = 0
  1420. if (platsdk == 0):
  1421. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\MicrosoftSDK\\InstalledSDKs\\D2FF9F89-8AA2-4373-8A31-C838BF4DBBE1", "Install Dir")
  1422. if (platsdk and not os.path.isdir(platsdk)):
  1423. platsdk = 0
  1424. if (platsdk == 0):
  1425. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v6.1","InstallationFolder")
  1426. if (platsdk and not os.path.isdir(platsdk)):
  1427. platsdk = 0
  1428. if (platsdk == 0):
  1429. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v6.0A","InstallationFolder")
  1430. if (platsdk and not os.path.isdir(platsdk)):
  1431. platsdk = 0
  1432. if (platsdk == 0 and os.path.isdir(os.path.join(GetProgramFiles(), "Microsoft Platform SDK for Windows Server 2003 R2"))):
  1433. if (not is_64 or os.path.isdir(os.path.join(GetProgramFiles(), "Microsoft Platform SDK for Windows Server 2003 R2", "Lib", "AMD64"))):
  1434. platsdk = os.path.join(GetProgramFiles(), "Microsoft Platform SDK for Windows Server 2003 R2")
  1435. if (not os.path.isdir(platsdk)):
  1436. platsdk = 0
  1437. # Doesn't work with the Express versions, so we're checking for the "atlmfc" dir, which is not in the Express
  1438. if (platsdk == 0 and os.path.isdir(os.path.join(GetProgramFiles(), "Microsoft Visual Studio 9\\VC\\atlmfc"))
  1439. and os.path.isdir(os.path.join(GetProgramFiles(), "Microsoft Visual Studio 9\\VC\\PlatformSDK"))):
  1440. platsdk = os.path.join(GetProgramFiles(), "Microsoft Visual Studio 9\\VC\\PlatformSDK")
  1441. if (not os.path.isdir(platsdk)):
  1442. platsdk = 0
  1443. # This may not be the best idea but it does give a warning
  1444. if (platsdk == 0):
  1445. if ("WindowsSdkDir" in os.environ):
  1446. WARNINGS.append("Windows SDK directory not found in registry, found in Environment variables instead")
  1447. platsdk = os.environ["WindowsSdkDir"]
  1448. elif (strMode == 'win71'):
  1449. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v7.1", "InstallationFolder")
  1450. if (platsdk and not os.path.isdir(platsdk)):
  1451. platsdk = 0
  1452. if not platsdk:
  1453. exit("Couldn't find Win7.1 Platform SDK")
  1454. elif (strMode == 'win61'):
  1455. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v6.1","InstallationFolder")
  1456. if (platsdk and not os.path.isdir(platsdk)):
  1457. platsdk = 0
  1458. if not platsdk:
  1459. exit("Couldn't find Win6.1 Platform SDK")
  1460. elif (strMode == 'win60A'):
  1461. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v6.0A","InstallationFolder")
  1462. if (platsdk and not os.path.isdir(platsdk)):
  1463. platsdk = 0
  1464. if not platsdk:
  1465. exit("Couldn't find Win6.0 Platform SDK")
  1466. elif (strMode == 'winserver2003r2'):
  1467. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\MicrosoftSDK\\InstalledSDKs\\D2FF9F89-8AA2-4373-8A31-C838BF4DBBE1", "Install Dir")
  1468. if (platsdk and not os.path.isdir(platsdk)):
  1469. platsdk = 0
  1470. if (platsdk == 0 and os.path.isdir(os.path.join(GetProgramFiles(), "Microsoft Platform SDK for Windows Server 2003 R2"))):
  1471. if (not is_64 or os.path.isdir(os.path.join(GetProgramFiles(), "Microsoft Platform SDK for Windows Server 2003 R2", "Lib", "AMD64"))):
  1472. platsdk = os.path.join(GetProgramFiles(), "Microsoft Platform SDK for Windows Server 2003 R2")
  1473. if (not os.path.isdir(platsdk)):
  1474. platsdk = 0
  1475. if (platsdk == 0 and os.path.isdir("C:/Program Files/Microsoft Platform SDK for Windows Server 2003 R2")):
  1476. if (not is_64 or os.path.isdir(os.path.join("C:/Program Files/Microsoft Platform SDK for Windows Server 2003 R2", "Lib", "AMD64"))):
  1477. platsdk = os.path.join("C:/Program Files/Microsoft Platform SDK for Windows Server 2003 R2")
  1478. if (not os.path.isdir(platsdk)):
  1479. platsdk = 0
  1480. if not platsdk:
  1481. exit("Couldn't find Windows Server 2003 R2 PlatformSDK")
  1482. if (platsdk != 0):
  1483. if (not platsdk.endswith("\\")):
  1484. platsdk += "\\"
  1485. SDK["MSPLATFORM"] = platsdk
  1486. def SdkLocateMacOSX(osxtarget = None):
  1487. if (sys.platform != "darwin"): return
  1488. if (osxtarget != None):
  1489. if (os.path.exists("/Developer/SDKs/MacOSX%su.sdk" % osxtarget)):
  1490. SDK["MACOSX"] = "/Developer/SDKs/MacOSX%su.sdk" % osxtarget
  1491. elif (os.path.exists("/Developer/SDKs/MacOSX%s.sdk" % osxtarget)):
  1492. SDK["MACOSX"] = "/Developer/SDKs/MacOSX%s.sdk" % osxtarget
  1493. elif (os.path.exists("/Developer/SDKs/MacOSX%s.0.sdk" % osxtarget)):
  1494. SDK["MACOSX"] = "/Developer/SDKs/MacOSX%s.0.sdk" % osxtarget
  1495. else:
  1496. exit("Couldn't find any MacOSX SDK for OSX version %s!" % osxtarget)
  1497. else:
  1498. SDK["MACOSX"] = ""
  1499. # Latest first
  1500. PHYSXVERSIONINFO=[
  1501. ("PHYSX284","v2.8.4"),
  1502. ("PHYSX283","v2.8.3"),
  1503. ("PHYSX281","v2.8.1"),
  1504. ]
  1505. def SdkLocatePhysX():
  1506. # First check for a physx directory in sdks.
  1507. dir = GetSdkDir("physx")
  1508. if (dir and os.path.isdir(dir)):
  1509. SDK["PHYSX"] = dir
  1510. SDK["PHYSXLIBS"] = dir + "/lib"
  1511. return
  1512. # Try to find a PhysX installation on the system.
  1513. for (ver, key) in PHYSXVERSIONINFO:
  1514. if (sys.platform == "win32"):
  1515. folders = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\Folders"
  1516. for folder in ListRegistryValues(folders):
  1517. if folder.endswith("NVIDIA PhysX SDK\\%s\\SDKs\\" % key) or \
  1518. folder.endswith("NVIDIA PhysX SDK\\%s_win\\SDKs\\" % key):
  1519. SDK["PHYSX"] = folder
  1520. return
  1521. elif (sys.platform.startswith("linux")):
  1522. incpath = "/usr/include/PhysX/%s/SDKs" % key
  1523. libpath = "/usr/lib/PhysX/%s" % key
  1524. if (os.path.isdir(incpath) and os.path.isdir(libpath)):
  1525. SDK["PHYSX"] = incpath
  1526. SDK["PHYSXLIBS"] = libpath
  1527. return
  1528. def SdkLocateSpeedTree():
  1529. # Look for all of the SpeedTree SDK directories within the
  1530. # sdks/win32/speedtree dir, and pick the highest-numbered one.
  1531. dir = GetSdkDir("speedtree")
  1532. if not os.path.exists(dir):
  1533. return
  1534. speedtrees = []
  1535. for dirname in os.listdir(dir):
  1536. if dirname.startswith('SpeedTree SDK v'):
  1537. version = dirname[15:].split()[0]
  1538. version = map(int, version.split('.'))
  1539. speedtrees.append((version, dirname))
  1540. if not speedtrees:
  1541. # No installed SpeedTree SDK.
  1542. return
  1543. speedtrees.sort()
  1544. version, dirname = speedtrees[-1]
  1545. SDK["SPEEDTREE"] = os.path.join(dir, dirname)
  1546. SDK["SPEEDTREEAPI"] = "OpenGL"
  1547. SDK["SPEEDTREEVERSION"] = '%s.%s' % (version[0], version[1])
  1548. ########################################################################
  1549. ##
  1550. ## SDK Auto-Disables
  1551. ##
  1552. ## Disable packages whose SDKs could not be found.
  1553. ##
  1554. ########################################################################
  1555. def SdkAutoDisableDirectX():
  1556. for ver in ["DX8","DX9","DIRECTCAM"]:
  1557. if (PkgSkip(ver)==0):
  1558. if (ver not in SDK):
  1559. if (sys.platform.startswith("win")):
  1560. WARNINGS.append("I cannot locate SDK for "+ver)
  1561. WARNINGS.append("I have automatically added this command-line option: --no-"+ver.lower())
  1562. PkgDisable(ver)
  1563. else:
  1564. WARNINGS.append("Using "+ver+" sdk: "+SDK[ver])
  1565. def SdkAutoDisableMaya():
  1566. for (ver,key) in MAYAVERSIONINFO:
  1567. if (ver not in SDK) and (PkgSkip(ver)==0):
  1568. if (sys.platform == "win32"):
  1569. WARNINGS.append("The registry does not appear to contain a pointer to the "+ver+" SDK.")
  1570. else:
  1571. WARNINGS.append("I cannot locate SDK for "+ver)
  1572. WARNINGS.append("I have automatically added this command-line option: --no-"+ver.lower())
  1573. PkgDisable(ver)
  1574. def SdkAutoDisableMax():
  1575. for version,key1,key2,subdir in MAXVERSIONINFO:
  1576. if (PkgSkip(version)==0) and ((version not in SDK) or (version+"CS" not in SDK)):
  1577. if (sys.platform.startswith("win")):
  1578. if (version in SDK):
  1579. WARNINGS.append("Your copy of "+version+" does not include the character studio SDK")
  1580. else:
  1581. WARNINGS.append("The registry does not appear to contain a pointer to "+version)
  1582. WARNINGS.append("I have automatically added this command-line option: --no-"+version.lower())
  1583. PkgDisable(version)
  1584. def SdkAutoDisablePhysX():
  1585. if ("PHYSX" not in SDK) and (PkgSkip("PHYSX")==0):
  1586. PkgDisable("PHYSX")
  1587. WARNINGS.append("I cannot locate SDK for PhysX")
  1588. WARNINGS.append("I have automatically added this command-line option: --no-physx")
  1589. def SdkAutoDisableSpeedTree():
  1590. if ("SPEEDTREE" not in SDK) and (PkgSkip("SPEEDTREE")==0):
  1591. PkgDisable("SPEEDTREE")
  1592. WARNINGS.append("I cannot locate SDK for SpeedTree")
  1593. WARNINGS.append("I have automatically added this command-line option: --no-speedtree")
  1594. ########################################################################
  1595. ##
  1596. ## Visual Studio comes with a script called VSVARS32.BAT, which
  1597. ## you need to run before using visual studio command-line tools.
  1598. ## The following python subroutine serves the same purpose.
  1599. ##
  1600. ########################################################################
  1601. def AddToPathEnv(path,add):
  1602. if (path in os.environ):
  1603. if (sys.platform.startswith("win")):
  1604. os.environ[path] = add + ";" + os.environ[path]
  1605. else:
  1606. os.environ[path] = add + ":" + os.environ[path]
  1607. else:
  1608. os.environ[path] = add
  1609. def SetupVisualStudioEnviron():
  1610. if ("VISUALSTUDIO" not in SDK):
  1611. exit("Could not find Visual Studio install directory")
  1612. if ("MSPLATFORM" not in SDK):
  1613. exit("Could not find the Microsoft Platform SDK")
  1614. os.environ["VCINSTALLDIR"] = SDK["VISUALSTUDIO"] + "VC"
  1615. os.environ["WindowsSdkDir"] = SDK["MSPLATFORM"]
  1616. suffix=""
  1617. if (is_64): suffix = "\\amd64"
  1618. AddToPathEnv("PATH", SDK["VISUALSTUDIO"] + "VC\\bin"+suffix)
  1619. AddToPathEnv("PATH", SDK["VISUALSTUDIO"] + "Common7\\IDE")
  1620. AddToPathEnv("INCLUDE", SDK["VISUALSTUDIO"] + "VC\\include")
  1621. AddToPathEnv("INCLUDE", SDK["VISUALSTUDIO"] + "VC\\atlmfc\\include")
  1622. AddToPathEnv("LIB", SDK["VISUALSTUDIO"] + "VC\\lib"+suffix)
  1623. AddToPathEnv("LIB", SDK["VISUALSTUDIO"] + "VC\\atlmfc\\lib")
  1624. AddToPathEnv("PATH", SDK["MSPLATFORM"] + "bin")
  1625. AddToPathEnv("INCLUDE", SDK["MSPLATFORM"] + "include")
  1626. AddToPathEnv("INCLUDE", SDK["MSPLATFORM"] + "include\\atl")
  1627. AddToPathEnv("INCLUDE", SDK["MSPLATFORM"] + "include\\mfc")
  1628. if (not is_64):
  1629. AddToPathEnv("LIB", SDK["MSPLATFORM"] + "lib")
  1630. AddToPathEnv("PATH",SDK["VISUALSTUDIO"] + "VC\\redist\\x86\\Microsoft.VC90.CRT")
  1631. AddToPathEnv("PATH",SDK["VISUALSTUDIO"] + "VC\\redist\\x86\\Microsoft.VC90.MFC")
  1632. elif (os.path.isdir(SDK["MSPLATFORM"] + "lib\\x64")):
  1633. AddToPathEnv("LIB", SDK["MSPLATFORM"] + "lib\\x64")
  1634. elif (os.path.isdir(SDK["MSPLATFORM"] + "lib\\amd64")):
  1635. AddToPathEnv("LIB", SDK["MSPLATFORM"] + "lib\\amd64")
  1636. else:
  1637. exit("Could not locate 64-bits libraries in Platform SDK!")
  1638. ########################################################################
  1639. #
  1640. # Include and Lib directories.
  1641. #
  1642. # These allow you to add include and lib directories to the
  1643. # compiler search paths. These methods accept a "package"
  1644. # parameter, which specifies which package the directory is
  1645. # associated with. The include/lib directory is not used
  1646. # if the package is not selected. The package can be 'ALWAYS'.
  1647. #
  1648. ########################################################################
  1649. INCDIRECTORIES = []
  1650. LIBDIRECTORIES = []
  1651. LIBNAMES = []
  1652. DEFSYMBOLS = []
  1653. def IncDirectory(opt, dir):
  1654. INCDIRECTORIES.append((opt, dir))
  1655. def LibDirectory(opt, dir):
  1656. LIBDIRECTORIES.append((opt, dir))
  1657. def LibName(opt, name):
  1658. # Check to see if the lib file actually exists for the thirdparty library given
  1659. # Are we a thirdparty library?
  1660. if name.startswith(GetThirdpartyDir()):
  1661. # Does this lib exist?
  1662. if not os.path.exists(name):
  1663. WARNINGS.append(name + " not found. Skipping Package " + opt)
  1664. if (opt in PkgListGet()):
  1665. print "%sWARNING:%s Could not locate thirdparty package %s, excluding from build" % (GetColor("red"), GetColor(), opt.lower())
  1666. PkgDisable(opt)
  1667. return
  1668. else:
  1669. print "%sERROR:%s Could not locate thirdparty package %s, aborting build" % (GetColor("red"), GetColor(), opt.lower())
  1670. exit()
  1671. LIBNAMES.append((opt, name))
  1672. def DefSymbol(opt, sym, val):
  1673. DEFSYMBOLS.append((opt, sym, val))
  1674. ########################################################################
  1675. #
  1676. # On Linux/OSX, to run panda, the dynamic linker needs to know how to
  1677. # find the shared libraries. This subroutine verifies that the dynamic
  1678. # linker is properly configured. If not, it sets it up on a temporary
  1679. # basis and issues a warning.
  1680. #
  1681. ########################################################################
  1682. def CheckLinkerLibraryPath():
  1683. if (sys.platform == "win32"): return
  1684. builtlib = os.path.abspath(os.path.join(OUTPUTDIR,"lib"))
  1685. dyldpath = []
  1686. try:
  1687. ldpath = []
  1688. f = file("/etc/ld.so.conf","r")
  1689. for line in f: ldpath.append(line.rstrip())
  1690. f.close()
  1691. except: ldpath = []
  1692. # Get the current
  1693. if ("LD_LIBRARY_PATH" in os.environ):
  1694. ldpath = ldpath + os.environ["LD_LIBRARY_PATH"].split(":")
  1695. if (sys.platform == "darwin" and "DYLD_LIBRARY_PATH" in os.environ):
  1696. dyldpath = os.environ["DYLD_LIBRARY_PATH"].split(":")
  1697. # Remove any potential current Panda installation lib dirs
  1698. for i in ldpath:
  1699. if i.startswith("/usr/lib/panda"): ldpath.remove(i)
  1700. for i in ldpath:
  1701. if i.startswith("/usr/local/panda"): ldpath.remove(i)
  1702. for i in dyldpath:
  1703. if i.startswith("/Applications/Panda3D"): dyldpath.remove(i)
  1704. if i.startswith("/Developer/Panda3D"): dyldpath.remove(i)
  1705. # Add built/lib/ to (DY)LD_LIBRARY_PATH if it's not already there
  1706. if (ldpath.count(builtlib)==0):
  1707. if ("LD_LIBRARY_PATH" in os.environ):
  1708. os.environ["LD_LIBRARY_PATH"] = builtlib + ":" + os.environ["LD_LIBRARY_PATH"]
  1709. else:
  1710. os.environ["LD_LIBRARY_PATH"] = builtlib
  1711. if (sys.platform == "darwin" and dyldpath.count(builtlib)==0):
  1712. if ("DYLD_LIBRARY_PATH" in os.environ):
  1713. os.environ["DYLD_LIBRARY_PATH"] = builtlib + ":" + os.environ["DYLD_LIBRARY_PATH"]
  1714. else:
  1715. os.environ["DYLD_LIBRARY_PATH"] = builtlib
  1716. # Workaround around compile issue on PCBSD
  1717. if (os.path.exists("/usr/PCBSD")):
  1718. os.environ["LD_LIBRARY_PATH"] += ":/usr/PCBSD/local/lib"
  1719. ########################################################################
  1720. ##
  1721. ## Routines to copy files into the build tree
  1722. ##
  1723. ########################################################################
  1724. def CopyFile(dstfile,srcfile):
  1725. if (dstfile[-1]=='/'):
  1726. dstdir = dstfile
  1727. fnl = srcfile.rfind("/")
  1728. if (fnl < 0): fn = srcfile
  1729. else: fn = srcfile[fnl+1:]
  1730. dstfile = dstdir + fn
  1731. if (NeedsBuild([dstfile],[srcfile])):
  1732. WriteFile(dstfile,ReadFile(srcfile))
  1733. JustBuilt([dstfile], [srcfile])
  1734. def CopyAllFiles(dstdir, srcdir, suffix=""):
  1735. for x in GetDirectoryContents(srcdir, ["*"+suffix]):
  1736. CopyFile(dstdir+x, srcdir+x)
  1737. def CopyAllHeaders(dir, skip=[]):
  1738. for filename in GetDirectoryContents(dir, ["*.h", "*.I", "*.T"], skip):
  1739. srcfile = dir + "/" + filename
  1740. dstfile = OUTPUTDIR+"/include/" + filename
  1741. if (NeedsBuild([dstfile],[srcfile])):
  1742. WriteFile(dstfile,ReadFile(srcfile))
  1743. JustBuilt([dstfile],[srcfile])
  1744. def CopyTree(dstdir,srcdir):
  1745. if (os.path.isdir(dstdir)): return 0
  1746. if (sys.platform == "win32"):
  1747. cmd = 'xcopy /I/Y/E/Q "' + srcdir + '" "' + dstdir + '"'
  1748. else:
  1749. cmd = 'cp -R -f ' + srcdir + ' ' + dstdir
  1750. oscmd(cmd)
  1751. ########################################################################
  1752. ##
  1753. ## Parse PandaVersion.pp to extract the version number.
  1754. ##
  1755. ########################################################################
  1756. def ParsePandaVersion(fn):
  1757. try:
  1758. f = file(fn, "r")
  1759. pattern = re.compile('^[ \t]*[#][ \t]*define[ \t]+PANDA_VERSION[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)')
  1760. for line in f:
  1761. match = pattern.match(line,0)
  1762. if (match):
  1763. f.close()
  1764. return match.group(1)+"."+match.group(2)+"."+match.group(3)
  1765. f.close()
  1766. except: pass
  1767. return "0.0.0"
  1768. def ParsePluginVersion(fn):
  1769. try:
  1770. f = file(fn, "r")
  1771. pattern = re.compile('^[ \t]*[#][ \t]*define[ \t]+P3D_PLUGIN_VERSION[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)')
  1772. for line in f:
  1773. match = pattern.match(line,0)
  1774. if (match):
  1775. f.close()
  1776. return match.group(1)+"."+match.group(2)+"."+match.group(3)
  1777. f.close()
  1778. except: pass
  1779. return "0.0.0"
  1780. def ParseCoreapiVersion(fn):
  1781. try:
  1782. f = file(fn, "r")
  1783. pattern = re.compile('^[ \t]*[#][ \t]*define[ \t]+P3D_COREAPI_VERSION.*([0-9]+)[ \t]*$')
  1784. for line in f:
  1785. match = pattern.match(line,0)
  1786. if (match):
  1787. f.close()
  1788. return match.group(1)
  1789. f.close()
  1790. except: pass
  1791. return "0"
  1792. ##########################################################################################
  1793. #
  1794. # Utility function to generate a resource file
  1795. #
  1796. ##########################################################################################
  1797. RESOURCE_FILE_TEMPLATE = """VS_VERSION_INFO VERSIONINFO
  1798. FILEVERSION %(commaversion)s
  1799. PRODUCTVERSION %(commaversion)s
  1800. FILEFLAGSMASK 0x3fL
  1801. FILEFLAGS %(debugflag)s
  1802. FILEOS 0x40004L
  1803. FILETYPE 0x2L
  1804. FILESUBTYPE 0x0L
  1805. BEGIN
  1806. BLOCK "StringFileInfo"
  1807. BEGIN
  1808. BLOCK "040904e4"
  1809. BEGIN
  1810. VALUE "FileDescription", "%(description)s\\0"
  1811. VALUE "FileVersion", "%(dotversion)s"
  1812. VALUE "LegalTrademarks", "\\0"
  1813. VALUE "MIMEType", "%(mimetype)s\\0"
  1814. VALUE "FileExtents", "%(extension)s\\0"
  1815. VALUE "FileOpenName", "%(filedesc)s\\0"
  1816. VALUE "OLESelfRegister", "\\0"
  1817. VALUE "OriginalFilename", "%(filename)s\\0"
  1818. VALUE "ProductName", "%(name)s %(version)s\\0"
  1819. VALUE "ProductVersion", "%(dotversion)s"
  1820. END
  1821. END
  1822. BLOCK "VarFileInfo"
  1823. BEGIN
  1824. VALUE "Translation", 0x409, 1252
  1825. END
  1826. END
  1827. """
  1828. def GenerateResourceFile(**kwargs):
  1829. if "debugflag" not in kwargs:
  1830. if GetOptimize() <= 2:
  1831. kwargs["debugflag"] = "0x1L"
  1832. else:
  1833. kwargs["debugflag"] = "0x0L"
  1834. kwargs["dotversion"] = kwargs["version"]
  1835. if len(kwargs["dotversion"].split(".")) == 3:
  1836. kwargs["dotversion"] += ".0"
  1837. if "commaversion" not in kwargs:
  1838. kwargs["commaversion"] = kwargs["dotversion"].replace(".", ",")
  1839. rcdata = ""
  1840. if not "noinclude" in kwargs:
  1841. rcdata += "#define APSTUDIO_READONLY_SYMBOLS\n"
  1842. rcdata += "#include \"winresrc.h\"\n"
  1843. rcdata += "#undef APSTUDIO_READONLY_SYMBOLS\n"
  1844. rcdata += RESOURCE_FILE_TEMPLATE % kwargs
  1845. if "icon" in kwargs:
  1846. rcdata += "\nICON_FILE ICON \"%s\"\n" % kwargs["icon"]
  1847. return rcdata
  1848. def WriteResourceFile(basename, **kwargs):
  1849. if not basename.endswith(".rc"):
  1850. basename += ".rc"
  1851. basename = GetOutputDir() + "/include/" + basename
  1852. ConditionalWriteFile(basename, GenerateResourceFile(**kwargs))
  1853. return basename
  1854. ########################################################################
  1855. ##
  1856. ## FindLocation
  1857. ##
  1858. ########################################################################
  1859. ORIG_EXT={}
  1860. def GetOrigExt(x):
  1861. return ORIG_EXT[x]
  1862. def SetOrigExt(x, v):
  1863. ORIG_EXT[x] = v
  1864. def CalcLocation(fn, ipath):
  1865. if (fn.count("/")): return fn
  1866. dllext = ""
  1867. if (GetOptimize() <= 2 and sys.platform.startswith("win")): dllext = "_d"
  1868. if (fn == "PandaModules.py"): return "pandac/" + fn
  1869. if (fn.endswith(".cxx")): return CxxFindSource(fn, ipath)
  1870. if (fn.endswith(".I")): return CxxFindSource(fn, ipath)
  1871. if (fn.endswith(".h")): return CxxFindSource(fn, ipath)
  1872. if (fn.endswith(".c")): return CxxFindSource(fn, ipath)
  1873. if (fn.endswith(".yxx")): return CxxFindSource(fn, ipath)
  1874. if (fn.endswith(".lxx")): return CxxFindSource(fn, ipath)
  1875. if (fn.endswith(".pdef")):return CxxFindSource(fn, ipath)
  1876. if (fn.endswith(".egg")): return OUTPUTDIR+"/models/"+fn
  1877. if (fn.endswith(".egg.pz")):return OUTPUTDIR+"/models/"+fn
  1878. if (sys.platform.startswith("win")):
  1879. if (fn.endswith(".def")): return CxxFindSource(fn, ipath)
  1880. if (fn.endswith(".rc")): return CxxFindSource(fn, ipath)
  1881. if (fn.endswith(".idl")): return CxxFindSource(fn, ipath)
  1882. if (fn.endswith(".obj")): return OUTPUTDIR+"/tmp/"+fn
  1883. if (fn.endswith(".res")): return OUTPUTDIR+"/tmp/"+fn
  1884. if (fn.endswith(".tlb")): return OUTPUTDIR+"/tmp/"+fn
  1885. if (fn.endswith(".dll")): return OUTPUTDIR+"/bin/"+fn[:-4]+dllext+".dll"
  1886. if (fn.endswith(".pyd")): return OUTPUTDIR+"/bin/"+fn[:-4]+dllext+".pyd"
  1887. if (fn.endswith(".ocx")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".ocx"
  1888. if (fn.endswith(".mll")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".mll"
  1889. if (fn.endswith(".dlo")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".dlo"
  1890. if (fn.endswith(".dli")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".dli"
  1891. if (fn.endswith(".dle")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".dle"
  1892. if (fn.endswith(".plugin")):return OUTPUTDIR+"/plugins/"+fn[:-7]+dllext+".dll"
  1893. if (fn.endswith(".exe")): return OUTPUTDIR+"/bin/"+fn
  1894. if (fn.endswith(".lib")): return OUTPUTDIR+"/lib/"+fn[:-4]+dllext+".lib"
  1895. if (fn.endswith(".ilb")): return OUTPUTDIR+"/tmp/"+fn[:-4]+dllext+".lib"
  1896. if (fn.endswith(".dat")): return OUTPUTDIR+"/tmp/"+fn
  1897. if (fn.endswith(".in")): return OUTPUTDIR+"/pandac/input/"+fn
  1898. elif (sys.platform == "darwin"):
  1899. if (fn.endswith(".mm")): return CxxFindSource(fn, ipath)
  1900. if (fn.endswith(".r")): return CxxFindSource(fn, ipath)
  1901. if (fn.endswith(".plist")): return CxxFindSource(fn, ipath)
  1902. if (fn.endswith(".obj")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".o"
  1903. if (fn.endswith(".dll")): return OUTPUTDIR+"/lib/"+fn[:-4]+".dylib"
  1904. if (fn.endswith(".pyd")): return OUTPUTDIR+"/lib/"+fn[:-4]+".dylib"
  1905. if (fn.endswith(".mll")): return OUTPUTDIR+"/plugins/"+fn
  1906. if (fn.endswith(".exe")): return OUTPUTDIR+"/bin/"+fn[:-4]
  1907. if (fn.endswith(".lib")): return OUTPUTDIR+"/lib/"+fn[:-4]+".a"
  1908. if (fn.endswith(".ilb")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".a"
  1909. if (fn.endswith(".dat")): return OUTPUTDIR+"/tmp/"+fn
  1910. if (fn.endswith(".rsrc")): return OUTPUTDIR+"/tmp/"+fn
  1911. if (fn.endswith(".plugin")):return OUTPUTDIR+"/plugins/"+fn
  1912. if (fn.endswith(".app")): return OUTPUTDIR+"/bin/"+fn
  1913. if (fn.endswith(".in")): return OUTPUTDIR+"/pandac/input/"+fn
  1914. else:
  1915. if (fn.endswith(".obj")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".o"
  1916. if (fn.endswith(".dll")): return OUTPUTDIR+"/lib/"+fn[:-4]+".so"
  1917. if (fn.endswith(".pyd")): return OUTPUTDIR+"/lib/"+fn[:-4]+".so"
  1918. if (fn.endswith(".mll")): return OUTPUTDIR+"/plugins/"+fn
  1919. if (fn.endswith(".plugin")):return OUTPUTDIR+"/plugins/"+fn[:-7]+dllext+".so"
  1920. if (fn.endswith(".exe")): return OUTPUTDIR+"/bin/"+fn[:-4]
  1921. if (fn.endswith(".lib")): return OUTPUTDIR+"/lib/"+fn[:-4]+".a"
  1922. if (fn.endswith(".ilb")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".a"
  1923. if (fn.endswith(".dat")): return OUTPUTDIR+"/tmp/"+fn
  1924. if (fn.endswith(".in")): return OUTPUTDIR+"/pandac/input/"+fn
  1925. return fn
  1926. def FindLocation(fn, ipath):
  1927. if (GetLinkAllStatic() and fn.endswith(".dll")):
  1928. fn = fn[:-4]+".lib"
  1929. loc = CalcLocation(fn, ipath)
  1930. (base,ext) = os.path.splitext(fn)
  1931. ORIG_EXT[loc] = ext
  1932. return loc
  1933. ########################################################################
  1934. ##
  1935. ## TargetAdd
  1936. ##
  1937. ## Makepanda maintains a list of make-targets. Each target has
  1938. ## these attributes:
  1939. ##
  1940. ## name - the name of the file being created.
  1941. ## ext - the original file extension, prior to OS-specific translation
  1942. ## inputs - the names of the input files to the compiler
  1943. ## deps - other input files that the target also depends on
  1944. ## opts - compiler options, a catch-all category
  1945. ##
  1946. ## TargetAdd will create the target if it does not exist. Then,
  1947. ## depending on what options you pass, it will push data onto these
  1948. ## various target attributes. This is cumulative: for example, if
  1949. ## you use TargetAdd to add compiler options, then use TargetAdd
  1950. ## again with more compiler options, both sets of options will be
  1951. ## included.
  1952. ##
  1953. ## TargetAdd does some automatic dependency generation on C++ files.
  1954. ## It will scan these files for include-files and automatically push
  1955. ## the include files onto the list of dependencies. In order to do
  1956. ## this, it needs an include-file search path. So if you supply
  1957. ## any C++ input, you also need to supply compiler options containing
  1958. ## include-directories, or alternately, a separate ipath parameter.
  1959. ##
  1960. ## The main body of 'makepanda' is a long list of TargetAdd
  1961. ## directives building up a giant list of make targets. Then,
  1962. ## finally, the targets are run and panda is built.
  1963. ##
  1964. ## Makepanda's dependency system does not understand multiple
  1965. ## outputs from a single build step. When a build step generates
  1966. ## a primary output file and a secondary output file, it is
  1967. ## necessary to trick the dependency system. Insert a dummy
  1968. ## build step that "generates" the secondary output file, using
  1969. ## the primary output file as an input. There is a special
  1970. ## compiler option DEPENDENCYONLY that creates such a dummy
  1971. ## build-step. There are two cases where dummy build steps must
  1972. ## be inserted: bison generates an OBJ and a secondary header
  1973. ## file, interrogate generates an IN and a secondary IGATE.OBJ.
  1974. ##
  1975. ########################################################################
  1976. class Target:
  1977. pass
  1978. TARGET_LIST=[]
  1979. TARGET_TABLE={}
  1980. def TargetAdd(target, dummy=0, opts=0, input=0, dep=0, ipath=0, winrc=0):
  1981. if (dummy != 0):
  1982. exit("Syntax error in TargetAdd "+target)
  1983. if (ipath == 0): ipath = opts
  1984. if (ipath == 0): ipath = []
  1985. if (type(input) == str): input = [input]
  1986. if (type(dep) == str): dep = [dep]
  1987. full = FindLocation(target,[OUTPUTDIR+"/include"])
  1988. if (full not in TARGET_TABLE):
  1989. t = Target()
  1990. t.name = full
  1991. t.inputs = []
  1992. t.deps = {}
  1993. t.opts = []
  1994. TARGET_TABLE[full] = t
  1995. TARGET_LIST.append(t)
  1996. else:
  1997. t = TARGET_TABLE[full]
  1998. ipath = [OUTPUTDIR+"/tmp"] + GetListOption(ipath, "DIR:") + [OUTPUTDIR+"/include"]
  1999. if (opts != 0):
  2000. for x in opts:
  2001. if (t.opts.count(x)==0):
  2002. t.opts.append(x)
  2003. if (input != 0):
  2004. for x in input:
  2005. fullinput = FindLocation(x, ipath)
  2006. t.inputs.append(fullinput)
  2007. # Don't re-link a library or binary if just it's dependency dll's have been altered.
  2008. # This should work out fine in most cases, and often reduces recompilation time.
  2009. if (os.path.splitext(x)[-1] not in SUFFIX_DLL):
  2010. t.deps[fullinput] = 1
  2011. (base,suffix) = os.path.splitext(x)
  2012. if (SUFFIX_INC.count(suffix)):
  2013. for d in CxxCalcDependencies(fullinput, ipath, []):
  2014. t.deps[d] = 1
  2015. if (dep != 0):
  2016. for x in dep:
  2017. fulldep = FindLocation(x, ipath)
  2018. t.deps[fulldep] = 1
  2019. if (winrc != 0 and sys.platform.startswith("win")):
  2020. TargetAdd(target, input=WriteResourceFile(target.split("/")[-1].split(".")[0], **winrc))
  2021. if (target.endswith(".in")):
  2022. t.deps[FindLocation("interrogate.exe",[])] = 1
  2023. t.deps[FindLocation("dtool_have_python.dat",[])] = 1
  2024. if (target.endswith(".pz")):
  2025. t.deps[FindLocation("pzip.exe",[])] = 1
  2026. if __name__ == '__main__':
  2027. ##Debug SDK search check
  2028. if sys.platform == "win32":
  2029. SdkLocateDirectX( 'aug2006' )
  2030. SdkLocateMSPlatform( 'winserver2003r2')