makepandacore.py 77 KB

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