makepandacore.py 101 KB

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