makepandacore.py 73 KB

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