makepandacore.py 89 KB

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