makepandacore.py 78 KB

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