makepandacore.py 100 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764
  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 = ["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] + " -vv " + cmd.split(" ", 1)[1])
  456. else:
  457. os.system(cmd.split(" ", 1)[0] + " -vv " + 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("directx9", "DX9")
  1425. if ("DX9" not in SDK):
  1426. strMode = 'latest'
  1427. if strMode == 'latest':
  1428. ## We first try to locate the August SDK in 64 bits, then 32.
  1429. if ("DX9" not in SDK):
  1430. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1431. if (dir != 0):
  1432. print("Using DirectX SDK June 2010")
  1433. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1434. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1435. if ("DX9" not in SDK):
  1436. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1437. if (dir != 0):
  1438. print("Using DirectX SDK June 2010")
  1439. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1440. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1441. if ("DX9" not in SDK):
  1442. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1443. if (dir != 0):
  1444. print("Using DirectX SDK Aug 2009")
  1445. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1446. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1447. if ("DX9" not in SDK):
  1448. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1449. if (dir != 0):
  1450. print("Using DirectX SDK Aug 2009")
  1451. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1452. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1453. if ("DX9" not in SDK):
  1454. ## Try to locate the key within the "new" March 2009 location in the registry (yecch):
  1455. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (March 2009)", "InstallPath")
  1456. if (dir != 0):
  1457. print("Using DirectX SDK March 2009")
  1458. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1459. archStr = GetTargetArch()
  1460. if ("DX9" not in SDK):
  1461. uninstaller = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
  1462. for subdir in ListRegistryKeys(uninstaller):
  1463. if (subdir[0]=="{"):
  1464. dir = GetRegistryKey(uninstaller+"\\"+subdir, "InstallLocation")
  1465. if (dir != 0):
  1466. if (("DX9" not in SDK) and
  1467. (os.path.isfile(dir+"\\Include\\d3d9.h")) and
  1468. (os.path.isfile(dir+"\\Include\\d3dx9.h")) and
  1469. (os.path.isfile(dir+"\\Include\\dxsdkver.h")) and
  1470. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3d9.lib")) and
  1471. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3dx9.lib"))):
  1472. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1473. if ("DX9" not in SDK):
  1474. return
  1475. elif strMode == 'jun2010':
  1476. if ("DX9" not in SDK):
  1477. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1478. if (dir != 0):
  1479. print("Found DirectX SDK June 2010")
  1480. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1481. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1482. if ("DX9" not in SDK):
  1483. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1484. if (dir != 0):
  1485. print("Found DirectX SDK June 2010")
  1486. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1487. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1488. if ("DX9" not in SDK):
  1489. exit("Couldn't find DirectX June2010 SDK")
  1490. elif strMode == 'aug2009':
  1491. if ("DX9" not in SDK):
  1492. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1493. if (dir != 0):
  1494. print("Found DirectX SDK Aug 2009")
  1495. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1496. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1497. if ("DX9" not in SDK):
  1498. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1499. if (dir != 0):
  1500. print("Found DirectX SDK Aug 2009")
  1501. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1502. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1503. if ("DX9" not in SDK):
  1504. exit("Couldn't find DirectX Aug 2009 SDK")
  1505. elif strMode == 'mar2009':
  1506. if ("DX9" not in SDK):
  1507. ## Try to locate the key within the "new" March 2009 location in the registry (yecch):
  1508. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (March 2009)", "InstallPath")
  1509. if (dir != 0):
  1510. print("Found DirectX SDK March 2009")
  1511. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1512. if ("DX9" not in SDK):
  1513. exit("Couldn't find DirectX March 2009 SDK")
  1514. elif strMode == 'aug2006':
  1515. archStr = GetTargetArch()
  1516. if ("DX9" not in SDK):
  1517. uninstaller = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
  1518. for subdir in ListRegistryKeys(uninstaller):
  1519. if (subdir[0]=="{"):
  1520. dir = GetRegistryKey(uninstaller+"\\"+subdir, "InstallLocation")
  1521. if (dir != 0):
  1522. if (("DX9" not in SDK) and
  1523. (os.path.isfile(dir+"\\Include\\d3d9.h")) and
  1524. (os.path.isfile(dir+"\\Include\\d3dx9.h")) and
  1525. (os.path.isfile(dir+"\\Include\\dxsdkver.h")) and
  1526. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3d9.lib")) and
  1527. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3dx9.lib"))):
  1528. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1529. if ("DX9" not in SDK):
  1530. exit("Couldn't find a DirectX Aug 2006 SDK")
  1531. if ("DX9" in SDK):
  1532. SDK["DIRECTCAM"] = SDK["DX9"]
  1533. def SdkLocateMaya():
  1534. for (ver, key) in MAYAVERSIONINFO:
  1535. if (PkgSkip(ver)==0 and ver not in SDK):
  1536. GetSdkDir(ver.lower().replace("x",""), ver)
  1537. if (not ver in SDK):
  1538. if (GetHost() == "windows"):
  1539. for dev in ["Alias|Wavefront","Alias","Autodesk"]:
  1540. fullkey="SOFTWARE\\"+dev+"\\Maya\\"+key+"\\Setup\\InstallPath"
  1541. res = GetRegistryKey(fullkey, "MAYA_INSTALL_LOCATION", override64=False)
  1542. if (res != 0):
  1543. res = res.replace("\\", "/").rstrip("/")
  1544. SDK[ver] = res
  1545. elif (GetHost() == "darwin"):
  1546. ddir = "/Applications/Autodesk/maya"+key
  1547. if (os.path.isdir(ddir)): SDK[ver] = ddir
  1548. else:
  1549. if (GetTargetArch() in ("x86_64", "amd64")):
  1550. ddir1 = "/usr/autodesk/maya"+key+"-x64"
  1551. ddir2 = "/usr/aw/maya"+key+"-x64"
  1552. else:
  1553. ddir1 = "/usr/autodesk/maya"+key
  1554. ddir2 = "/usr/aw/maya"+key
  1555. if (os.path.isdir(ddir1)): SDK[ver] = ddir1
  1556. elif (os.path.isdir(ddir2)): SDK[ver] = ddir2
  1557. def SdkLocateMax():
  1558. if (GetHost() != "windows"): return
  1559. for version,key1,key2,subdir in MAXVERSIONINFO:
  1560. if (PkgSkip(version)==0):
  1561. if (version not in SDK):
  1562. GetSdkDir("maxsdk"+version.lower()[3:], version)
  1563. GetSdkDir("maxsdk"+version.lower()[3:], version+"CS")
  1564. if (not version in SDK):
  1565. top = GetRegistryKey(key1,key2)
  1566. if (top != 0):
  1567. SDK[version] = top + "maxsdk"
  1568. if (os.path.isdir(top + "\\" + subdir)!=0):
  1569. SDK[version+"CS"] = top + subdir
  1570. def SdkLocatePython(force_use_sys_executable = False):
  1571. if PkgSkip("PYTHON"):
  1572. SDK["PYTHONEXEC"] = os.path.realpath(sys.executable)
  1573. return
  1574. if CrossCompiling():
  1575. force_use_sys_executable = False
  1576. if (GetTarget() == 'windows' and not force_use_sys_executable):
  1577. SDK["PYTHON"] = GetThirdpartyBase() + "/win-python"
  1578. if (GetOptimize() <= 2):
  1579. SDK["PYTHON"] += "-dbg"
  1580. if (GetTargetArch() == 'x64' and os.path.isdir(SDK["PYTHON"] + "-x64")):
  1581. SDK["PYTHON"] += "-x64"
  1582. SDK["PYTHONEXEC"] = SDK["PYTHON"].replace('/', '\\') + "\\python"
  1583. if (GetOptimize() <= 2):
  1584. SDK["PYTHONEXEC"] += "_d.exe"
  1585. else:
  1586. SDK["PYTHONEXEC"] += ".exe"
  1587. if (not os.path.isfile(SDK["PYTHONEXEC"])):
  1588. exit("Could not find %s!" % SDK["PYTHONEXEC"])
  1589. # Determine which version it is by checking which dll is in the directory.
  1590. if (GetOptimize() <= 2):
  1591. py_dlls = glob.glob(SDK["PYTHON"] + "/python[0-9][0-9]_d.dll")
  1592. else:
  1593. py_dlls = glob.glob(SDK["PYTHON"] + "/python[0-9][0-9].dll")
  1594. if len(py_dlls) == 0:
  1595. exit("Could not find the Python dll in %s." % (SDK["PYTHON"]))
  1596. elif len(py_dlls) > 1:
  1597. exit("Found multiple Python dlls in %s." % (SDK["PYTHON"]))
  1598. py_dll = os.path.basename(py_dlls[0])
  1599. SDK["PYTHONVERSION"] = "python" + py_dll[6] + "." + py_dll[7]
  1600. os.environ["PYTHONHOME"] = SDK["PYTHON"]
  1601. elif CrossCompiling():
  1602. tp_python = os.path.join(GetThirdpartyDir(), "python")
  1603. SDK["PYTHON"] = tp_python + "/include"
  1604. if GetTarget() == 'darwin':
  1605. py_libs = glob.glob(tp_python + "/lib/libpython[0-9].[0-9].dylib")
  1606. else:
  1607. py_libs = glob.glob(tp_python + "/lib/libpython[0-9].[0-9].so")
  1608. if len(py_libs) == 0:
  1609. py_libs = glob.glob(tp_python + "/lib/libpython[0-9].[0-9].a")
  1610. if len(py_libs) == 0:
  1611. exit("Could not find the Python library in %s." % (tp_python))
  1612. elif len(py_libs) > 1:
  1613. exit("Found multiple Python libraries in %s." % (tp_python))
  1614. py_lib = os.path.basename(py_libs[0])
  1615. SDK["PYTHONVERSION"] = "python" + py_lib[9] + "." + py_lib[11]
  1616. elif (GetTarget() == 'windows'):
  1617. SDK["PYTHON"] = os.path.dirname(sysconfig.get_python_inc())
  1618. SDK["PYTHONVERSION"] = "python" + sysconfig.get_python_version()
  1619. SDK["PYTHONEXEC"] = sys.executable
  1620. else:
  1621. SDK["PYTHON"] = sysconfig.get_python_inc()
  1622. SDK["PYTHONVERSION"] = "python" + sysconfig.get_python_version()
  1623. SDK["PYTHONEXEC"] = os.path.realpath(sys.executable)
  1624. if CrossCompiling():
  1625. SDK["PYTHONEXEC"] = sys.executable
  1626. host_version = "python" + sysconfig.get_python_version()
  1627. if SDK["PYTHONVERSION"] != host_version:
  1628. exit("Host Python version (%s) must be the same as target Python version (%s)!" % (host_version, SDK["PYTHONVERSION"]))
  1629. if GetVerbose():
  1630. print("Using Python %s build located at %s" % (SDK["PYTHONVERSION"][6:9], SDK["PYTHON"]))
  1631. def SdkLocateVisualStudio():
  1632. if (GetHost() != "windows"): return
  1633. vcdir = GetRegistryKey("SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VC7", "10.0")
  1634. if (vcdir != 0) and (vcdir[-4:] == "\\VC\\"):
  1635. vcdir = vcdir[:-3]
  1636. SDK["VISUALSTUDIO"] = vcdir
  1637. elif (os.path.isfile("C:\\Program Files\\Microsoft Visual Studio 10.0\\VC\\bin\\cl.exe")):
  1638. SDK["VISUALSTUDIO"] = "C:\\Program Files\\Microsoft Visual Studio 10.0\\"
  1639. elif (os.path.isfile("C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\bin\\cl.exe")):
  1640. SDK["VISUALSTUDIO"] = "C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\"
  1641. elif "VCINSTALLDIR" in os.environ:
  1642. vcdir = os.environ["VCINSTALLDIR"]
  1643. if (vcdir[-3:] == "\\VC"):
  1644. vcdir = vcdir[:-2]
  1645. elif (vcdir[-4:] == "\\VC\\"):
  1646. vcdir = vcdir[:-3]
  1647. SDK["VISUALSTUDIO"] = vcdir
  1648. def SdkLocateMSPlatform(strMode = 'default'):
  1649. if (GetHost() != "windows"): return
  1650. platsdk = None
  1651. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v7.1", "InstallationFolder")
  1652. if (platsdk and not os.path.isdir(platsdk)):
  1653. platsdk = None
  1654. if not platsdk:
  1655. # Most common location. Worth a try.
  1656. platsdk = "C:\\Program Files\\Microsoft SDKs\\Windows\\v7.1"
  1657. if not os.path.isdir(platsdk):
  1658. platsdk = None
  1659. if not platsdk:
  1660. exit("Couldn't find Windows SDK v7.1")
  1661. if not platsdk.endswith("\\"):
  1662. platsdk += "\\"
  1663. SDK["MSPLATFORM"] = platsdk
  1664. def SdkLocateMacOSX(osxtarget = None):
  1665. if (GetHost() != "darwin"): return
  1666. if (osxtarget != None):
  1667. if (os.path.exists("/Developer/SDKs/MacOSX%su.sdk" % osxtarget)):
  1668. SDK["MACOSX"] = "/Developer/SDKs/MacOSX%su.sdk" % osxtarget
  1669. elif (os.path.exists("/Developer/SDKs/MacOSX%s.sdk" % osxtarget)):
  1670. SDK["MACOSX"] = "/Developer/SDKs/MacOSX%s.sdk" % osxtarget
  1671. elif (os.path.exists("/Developer/SDKs/MacOSX%s.0.sdk" % osxtarget)):
  1672. SDK["MACOSX"] = "/Developer/SDKs/MacOSX%s.0.sdk" % osxtarget
  1673. elif (os.path.exists("/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX%s.sdk" % osxtarget)):
  1674. SDK["MACOSX"] = "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX%s.sdk" % osxtarget
  1675. else:
  1676. handle = os.popen("xcode-select -print-path")
  1677. result = handle.read().strip().rstrip('/')
  1678. handle.close()
  1679. if (os.path.exists("%s/Platforms/MacOSX.platform/Developer/SDKs/MacOSX%s.sdk" % (result, osxtarget))):
  1680. SDK["MACOSX"] = "%s/Platforms/MacOSX.platform/Developer/SDKs/MacOSX%s.sdk" % (result, osxtarget)
  1681. else:
  1682. exit("Couldn't find any MacOSX SDK for OSX version %s!" % osxtarget)
  1683. else:
  1684. SDK["MACOSX"] = ""
  1685. # Latest first
  1686. PHYSXVERSIONINFO = [
  1687. ("PHYSX284", "v2.8.4"),
  1688. ("PHYSX283", "v2.8.3"),
  1689. ("PHYSX281", "v2.8.1"),
  1690. ]
  1691. def SdkLocatePhysX():
  1692. # First check for a physx directory in sdks.
  1693. dir = GetSdkDir("physx")
  1694. if (dir and os.path.isdir(dir)):
  1695. SDK["PHYSX"] = dir
  1696. SDK["PHYSXLIBS"] = dir + "/lib"
  1697. return
  1698. if CrossCompiling():
  1699. return
  1700. # Try to find a PhysX installation on the system.
  1701. for (ver, key) in PHYSXVERSIONINFO:
  1702. if (GetHost() == "windows"):
  1703. folders = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\Folders"
  1704. for folder in ListRegistryValues(folders):
  1705. if folder.endswith("NVIDIA PhysX SDK\\%s\\SDKs\\" % key) or \
  1706. folder.endswith("NVIDIA PhysX SDK\\%s_win\\SDKs\\" % key):
  1707. SDK["PHYSX"] = folder
  1708. if GetTargetArch() == 'x64':
  1709. SDK["PHYSXLIBS"] = folder + "/lib/win64"
  1710. AddToPathEnv("PATH", folder + "/../Bin/win64/")
  1711. else:
  1712. SDK["PHYSXLIBS"] = folder + "/lib/win32"
  1713. AddToPathEnv("PATH", folder + "/../Bin/win32/")
  1714. return
  1715. elif (GetHost() == "linux"):
  1716. incpath = "/usr/include/PhysX/%s/SDKs" % key
  1717. libpath = "/usr/lib/PhysX/%s" % key
  1718. if (os.path.isdir(incpath) and os.path.isdir(libpath)):
  1719. SDK["PHYSX"] = incpath
  1720. SDK["PHYSXLIBS"] = libpath
  1721. return
  1722. def SdkLocateSpeedTree():
  1723. # Look for all of the SpeedTree SDK directories within the
  1724. # sdks/win32/speedtree dir, and pick the highest-numbered one.
  1725. dir = GetSdkDir("speedtree")
  1726. if not os.path.exists(dir):
  1727. return
  1728. speedtrees = []
  1729. for dirname in os.listdir(dir):
  1730. if dirname.startswith('SpeedTree SDK v'):
  1731. version = dirname[15:].split()[0]
  1732. version = tuple(map(int, version.split('.')))
  1733. speedtrees.append((version, dirname))
  1734. if not speedtrees:
  1735. # No installed SpeedTree SDK.
  1736. return
  1737. speedtrees.sort()
  1738. version, dirname = speedtrees[-1]
  1739. SDK["SPEEDTREE"] = os.path.join(dir, dirname)
  1740. SDK["SPEEDTREEAPI"] = "OpenGL"
  1741. SDK["SPEEDTREEVERSION"] = '%s.%s' % (version[0], version[1])
  1742. def SdkLocateAndroid():
  1743. """This actually locates the Android NDK, not the Android SDK.
  1744. NDK_ROOT must be set to its root directory."""
  1745. if GetTarget() != 'android':
  1746. return
  1747. # Determine the NDK installation directory.
  1748. if 'NDK_ROOT' not in os.environ:
  1749. exit('NDK_ROOT must be set when compiling for Android!')
  1750. ndk_root = os.environ["NDK_ROOT"]
  1751. if not os.path.isdir(ndk_root):
  1752. exit("Cannot find %s. Please install Android NDK and set NDK_ROOT." % (ndk_root))
  1753. SDK["ANDROID_NDK"] = ndk_root
  1754. # Determine the toolchain location.
  1755. gcc_ver = '4.8'
  1756. arch = GetTargetArch()
  1757. if arch == 'armv7a' or arch == 'arm':
  1758. arch = 'arm'
  1759. toolchain = 'arm-linux-androideabi-' + gcc_ver
  1760. elif arch == 'x86':
  1761. toolchain = 'x86-' + gcc_ver
  1762. elif arch == 'mips':
  1763. toolchain = 'mipsel-linux-android-' + gcc_ver
  1764. SDK["ANDROID_TOOLCHAIN"] = os.path.join(ndk_root, 'toolchains', toolchain)
  1765. # Allow ANDROID_ABI to be used in makepanda.py.
  1766. abi = ANDROID_ABI
  1767. SDK["ANDROID_ABI"] = abi
  1768. # Determine the sysroot directory.
  1769. SDK["SYSROOT"] = os.path.join(ndk_root, 'platforms', 'android-9', 'arch-%s' % (arch))
  1770. #IncDirectory("ALWAYS", os.path.join(SDK["SYSROOT"], 'usr', 'include'))
  1771. stdlibc = os.path.join(ndk_root, 'sources', 'cxx-stl', 'gnu-libstdc++', gcc_ver)
  1772. SDK["ANDROID_STL"] = stdlibc
  1773. #IncDirectory("ALWAYS", os.path.join(stdlibc, 'include'))
  1774. #IncDirectory("ALWAYS", os.path.join(stdlibc, 'libs', abi, 'include'))
  1775. stl_lib = os.path.join(stdlibc, 'libs', abi, 'libgnustl_shared.so')
  1776. LibName("ALWAYS", stl_lib)
  1777. CopyFile(os.path.join(GetOutputDir(), 'libs', abi, 'libgnustl_shared.so'), stl_lib)
  1778. ########################################################################
  1779. ##
  1780. ## SDK Auto-Disables
  1781. ##
  1782. ## Disable packages whose SDKs could not be found.
  1783. ##
  1784. ########################################################################
  1785. def SdkAutoDisableDirectX():
  1786. for ver in ["DX9", "DIRECTCAM"]:
  1787. if (PkgSkip(ver)==0):
  1788. if (ver not in SDK):
  1789. if (GetHost() == "windows"):
  1790. WARNINGS.append("I cannot locate SDK for "+ver)
  1791. WARNINGS.append("I have automatically added this command-line option: --no-"+ver.lower())
  1792. PkgDisable(ver)
  1793. else:
  1794. WARNINGS.append("Using "+ver+" sdk: "+SDK[ver])
  1795. def SdkAutoDisableMaya():
  1796. for (ver,key) in MAYAVERSIONINFO:
  1797. if (ver not in SDK) and (PkgSkip(ver)==0):
  1798. if (GetHost() == "windows"):
  1799. WARNINGS.append("The registry does not appear to contain a pointer to the "+ver+" SDK.")
  1800. else:
  1801. WARNINGS.append("I cannot locate SDK for "+ver)
  1802. WARNINGS.append("I have automatically added this command-line option: --no-"+ver.lower())
  1803. PkgDisable(ver)
  1804. def SdkAutoDisableMax():
  1805. for version,key1,key2,subdir in MAXVERSIONINFO:
  1806. if (PkgSkip(version)==0) and ((version not in SDK) or (version+"CS" not in SDK)):
  1807. if (GetHost() == "windows"):
  1808. if (version in SDK):
  1809. WARNINGS.append("Your copy of "+version+" does not include the character studio SDK")
  1810. else:
  1811. WARNINGS.append("The registry does not appear to contain a pointer to "+version)
  1812. WARNINGS.append("I have automatically added this command-line option: --no-"+version.lower())
  1813. PkgDisable(version)
  1814. def SdkAutoDisablePhysX():
  1815. if ("PHYSX" not in SDK) and (PkgSkip("PHYSX")==0):
  1816. PkgDisable("PHYSX")
  1817. WARNINGS.append("I cannot locate SDK for PhysX")
  1818. WARNINGS.append("I have automatically added this command-line option: --no-physx")
  1819. def SdkAutoDisableSpeedTree():
  1820. if ("SPEEDTREE" not in SDK) and (PkgSkip("SPEEDTREE")==0):
  1821. PkgDisable("SPEEDTREE")
  1822. WARNINGS.append("I cannot locate SDK for SpeedTree")
  1823. WARNINGS.append("I have automatically added this command-line option: --no-speedtree")
  1824. ########################################################################
  1825. ##
  1826. ## Visual Studio comes with a script called VSVARS32.BAT, which
  1827. ## you need to run before using visual studio command-line tools.
  1828. ## The following python subroutine serves the same purpose.
  1829. ##
  1830. ########################################################################
  1831. def AddToPathEnv(path,add):
  1832. if path in os.environ:
  1833. os.environ[path] = add + os.pathsep + os.environ[path]
  1834. else:
  1835. os.environ[path] = add
  1836. def SetupVisualStudioEnviron():
  1837. if ("VISUALSTUDIO" not in SDK):
  1838. exit("Could not find Visual Studio install directory")
  1839. if ("MSPLATFORM" not in SDK):
  1840. exit("Could not find the Microsoft Platform SDK")
  1841. os.environ["VCINSTALLDIR"] = SDK["VISUALSTUDIO"] + "VC"
  1842. os.environ["WindowsSdkDir"] = SDK["MSPLATFORM"]
  1843. # Determine the directories to look in based on the architecture.
  1844. arch = GetTargetArch()
  1845. bindir = ""
  1846. libdir = ""
  1847. if (arch == 'x64'):
  1848. bindir = 'amd64'
  1849. libdir = 'amd64'
  1850. elif (arch != 'x86'):
  1851. bindir = arch
  1852. libdir = arch
  1853. if (arch != 'x86' and GetHostArch() == 'x86'):
  1854. # Special version of the tools that run on x86.
  1855. bindir = 'x86_' + bindir
  1856. binpath = SDK["VISUALSTUDIO"] + "VC\\bin\\" + bindir
  1857. if not os.path.isdir(binpath):
  1858. 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.")
  1859. AddToPathEnv("PATH", binpath)
  1860. AddToPathEnv("PATH", SDK["VISUALSTUDIO"] + "Common7\\IDE")
  1861. AddToPathEnv("INCLUDE", SDK["VISUALSTUDIO"] + "VC\\include")
  1862. AddToPathEnv("INCLUDE", SDK["VISUALSTUDIO"] + "VC\\atlmfc\\include")
  1863. AddToPathEnv("LIB", SDK["VISUALSTUDIO"] + "VC\\lib\\" + libdir)
  1864. AddToPathEnv("LIB", SDK["VISUALSTUDIO"] + "VC\\atlmfc\\lib\\" + libdir)
  1865. AddToPathEnv("PATH", SDK["MSPLATFORM"] + "bin")
  1866. AddToPathEnv("INCLUDE", SDK["MSPLATFORM"] + "include")
  1867. AddToPathEnv("INCLUDE", SDK["MSPLATFORM"] + "include\\atl")
  1868. AddToPathEnv("INCLUDE", SDK["MSPLATFORM"] + "include\\mfc")
  1869. if (arch != 'x64'):
  1870. AddToPathEnv("LIB", SDK["MSPLATFORM"] + "lib")
  1871. AddToPathEnv("PATH",SDK["VISUALSTUDIO"] + "VC\\redist\\x86\\Microsoft.VC100.CRT")
  1872. AddToPathEnv("PATH",SDK["VISUALSTUDIO"] + "VC\\redist\\x86\\Microsoft.VC100.MFC")
  1873. elif (os.path.isdir(SDK["MSPLATFORM"] + "lib\\x64")):
  1874. AddToPathEnv("LIB", SDK["MSPLATFORM"] + "lib\\x64")
  1875. elif (os.path.isdir(SDK["MSPLATFORM"] + "lib\\amd64")):
  1876. AddToPathEnv("LIB", SDK["MSPLATFORM"] + "lib\\amd64")
  1877. else:
  1878. exit("Could not locate 64-bits libraries in Platform SDK!")
  1879. ########################################################################
  1880. #
  1881. # Include and Lib directories.
  1882. #
  1883. # These allow you to add include and lib directories to the
  1884. # compiler search paths. These methods accept a "package"
  1885. # parameter, which specifies which package the directory is
  1886. # associated with. The include/lib directory is not used
  1887. # if the package is not selected. The package can be 'ALWAYS'.
  1888. #
  1889. ########################################################################
  1890. INCDIRECTORIES = []
  1891. LIBDIRECTORIES = []
  1892. LIBNAMES = []
  1893. DEFSYMBOLS = []
  1894. def IncDirectory(opt, dir):
  1895. INCDIRECTORIES.append((opt, dir))
  1896. def LibDirectory(opt, dir):
  1897. LIBDIRECTORIES.append((opt, dir))
  1898. def LibName(opt, name):
  1899. # Check to see if the lib file actually exists for the thirdparty library given
  1900. # Are we a thirdparty library?
  1901. if name.startswith(GetThirdpartyDir()):
  1902. # Does this lib exist?
  1903. if not os.path.exists(name):
  1904. WARNINGS.append(name + " not found. Skipping Package " + opt)
  1905. if (opt in PkgListGet()):
  1906. print("%sWARNING:%s Could not locate thirdparty package %s, excluding from build" % (GetColor("red"), GetColor(), opt.lower()))
  1907. PkgDisable(opt)
  1908. return
  1909. else:
  1910. print("%sERROR:%s Could not locate thirdparty package %s, aborting build" % (GetColor("red"), GetColor(), opt.lower()))
  1911. exit()
  1912. LIBNAMES.append((opt, name))
  1913. def DefSymbol(opt, sym, val=""):
  1914. DEFSYMBOLS.append((opt, sym, val))
  1915. ########################################################################
  1916. #
  1917. # This subroutine prepares the environment for the build.
  1918. #
  1919. ########################################################################
  1920. def SetupBuildEnvironment(compiler):
  1921. if GetVerbose():
  1922. print("Using compiler: %s" % compiler)
  1923. print("Host OS: %s" % GetHost())
  1924. print("Host arch: %s" % GetHostArch())
  1925. print("Target OS: %s" % GetTarget())
  1926. print("Target arch: %s" % GetTargetArch())
  1927. if compiler == "MSVC":
  1928. # Add the visual studio tools to PATH et al.
  1929. SetupVisualStudioEnviron()
  1930. if compiler == "GCC":
  1931. # Invoke gcc to determine the system library directories.
  1932. global SYS_LIB_DIRS
  1933. if sys.platform == "darwin":
  1934. # We need to add this one explicitly.
  1935. SYS_LIB_DIRS.append(SDK["MACOSX"] + "/usr/lib")
  1936. if not SDK.get("MACOSX"):
  1937. # gcc doesn't add this one, but we do want it:
  1938. local_lib = SDK.get("SYSROOT", "") + "/usr/local/lib"
  1939. if os.path.isdir(local_lib):
  1940. SYS_LIB_DIRS.append(local_lib)
  1941. cmd = GetCXX() + " -print-search-dirs"
  1942. if SDK.get("MACOSX"):
  1943. # The default compiler in Leopard does not respect --sysroot correctly.
  1944. cmd += " -isysroot " + SDK["MACOSX"]
  1945. if SDK.get("SYSROOT"):
  1946. cmd += ' --sysroot=%s -no-canonical-prefixes' % (SDK["SYSROOT"])
  1947. # Extract the dirs from the line that starts with 'libraries: ='.
  1948. handle = os.popen(cmd)
  1949. for line in handle:
  1950. if not line.startswith('libraries: ='):
  1951. continue
  1952. line = line[12:].strip()
  1953. SYS_LIB_DIRS += line.split(':')
  1954. returnval = handle.close()
  1955. if returnval != None and returnval != 0:
  1956. print("%sWARNING:%s %s failed" % (GetColor("red"), GetColor(), cmd))
  1957. SYS_LIB_DIRS += [SDK.get("SYSROOT", "") + "/usr/lib"]
  1958. elif GetVerbose():
  1959. print("System library search path: %s" % ':'.join(SYS_LIB_DIRS))
  1960. # In the case of Android, we have to put the toolchain on the PATH in order to use it.
  1961. if GetTarget() == 'android':
  1962. # Locate the directory where the toolchain binaries reside.
  1963. prebuilt_dir = os.path.join(SDK['ANDROID_TOOLCHAIN'], 'prebuilt')
  1964. if not os.path.isdir(prebuilt_dir):
  1965. exit('Not found: %s' % (prebuilt_dir))
  1966. host_tag = GetHost() + '-x86'
  1967. if host_64:
  1968. host_tag += '_64'
  1969. elif host_tag == 'windows-x86':
  1970. host_tag = 'windows'
  1971. prebuilt_dir = os.path.join(prebuilt_dir, host_tag)
  1972. if host_64 and not os.path.isdir(prebuilt_dir):
  1973. # Try the 32-bits toolchain instead.
  1974. prebuilt_dir = os.path.join(prebuilt_dir, host_tag)
  1975. if not os.path.isdir(prebuilt_dir):
  1976. if host_64:
  1977. exit('Not found: %s or %s' % (prebuilt_dir, host_tag))
  1978. else:
  1979. exit('Not found: %s' % (prebuilt_dir))
  1980. # Then, add it to the PATH.
  1981. AddToPathEnv("PATH", os.path.join(prebuilt_dir, 'bin'))
  1982. # If we're cross-compiling, no point in putting our output dirs on the path.
  1983. if CrossCompiling():
  1984. return
  1985. # Add our output directories to the environment.
  1986. builtdir = os.path.join(os.path.abspath(GetOutputDir()))
  1987. AddToPathEnv("PYTHONPATH", builtdir)
  1988. AddToPathEnv("PANDA_PRC_DIR", os.path.join(builtdir, "etc"))
  1989. AddToPathEnv("PATH", os.path.join(builtdir, "bin"))
  1990. if (GetHost() == 'windows'):
  1991. AddToPathEnv("PATH", os.path.join(builtdir, "plugins"))
  1992. AddToPathEnv("PYTHONPATH", os.path.join(builtdir, "bin"))
  1993. else:
  1994. AddToPathEnv("PYTHONPATH", os.path.join(builtdir, "lib"))
  1995. # Now for the special (DY)LD_LIBRARY_PATH on Unix-esque systems.
  1996. if GetHost() != 'windows':
  1997. # Get the current
  1998. ldpath = os.environ.get("LD_LIBRARY_PATH", "").split(os.pathsep)
  1999. if GetHost() == 'darwin':
  2000. dyldpath = os.environ.get("DYLD_LIBRARY_PATH", "").split(os.pathsep)
  2001. # Remove any potential current Panda installation lib dirs
  2002. for i in ldpath[:]:
  2003. if i.startswith("/usr/lib/panda3d") or \
  2004. i.startswith("/usr/local/panda"):
  2005. ldpath.remove(i)
  2006. if GetHost() == 'darwin':
  2007. for i in dyldpath[:]:
  2008. if i.startswith("/Applications/Panda3D") or \
  2009. i.startswith("/Developer/Panda3D"):
  2010. dyldpath.remove(i)
  2011. # Add built/lib/ to (DY)LD_LIBRARY_PATH
  2012. ldpath.insert(0, os.path.join(builtdir, 'lib'))
  2013. os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(ldpath)
  2014. if GetHost() == 'darwin':
  2015. dyldpath.insert(0, os.path.join(builtdir, 'lib'))
  2016. os.environ["DYLD_LIBRARY_PATH"] = os.pathsep.join(dyldpath)
  2017. # Workaround around compile issue on PCBSD
  2018. if (os.path.exists("/usr/PCBSD")):
  2019. os.environ["LD_LIBRARY_PATH"] += os.pathsep + "/usr/PCBSD/local/lib"
  2020. ########################################################################
  2021. ##
  2022. ## Routines to copy files into the build tree
  2023. ##
  2024. ########################################################################
  2025. def CopyFile(dstfile, srcfile):
  2026. if dstfile[-1] == '/':
  2027. dstdir = dstfile
  2028. fnl = srcfile.rfind("/")
  2029. if fnl < 0:
  2030. fn = srcfile
  2031. else:
  2032. fn = srcfile[fnl+1:]
  2033. dstfile = dstdir + fn
  2034. if NeedsBuild([dstfile], [srcfile]):
  2035. if os.path.islink(srcfile):
  2036. # Preserve symlinks
  2037. if os.path.exists(dstfile):
  2038. os.unlink(dstfile)
  2039. os.symlink(os.readlink(srcfile), dstfile)
  2040. else:
  2041. WriteBinaryFile(dstfile, ReadBinaryFile(srcfile))
  2042. JustBuilt([dstfile], [srcfile])
  2043. def CopyAllFiles(dstdir, srcdir, suffix=""):
  2044. for x in GetDirectoryContents(srcdir, ["*"+suffix]):
  2045. CopyFile(dstdir + x, srcdir + x)
  2046. def CopyAllHeaders(dir, skip=[]):
  2047. for filename in GetDirectoryContents(dir, ["*.h", "*.I", "*.T"], skip):
  2048. srcfile = dir + "/" + filename
  2049. dstfile = OUTPUTDIR + "/include/" + filename
  2050. if (NeedsBuild([dstfile], [srcfile])):
  2051. WriteBinaryFile(dstfile, ReadBinaryFile(srcfile))
  2052. JustBuilt([dstfile], [srcfile])
  2053. def CopyAllJavaSources(dir, skip=[]):
  2054. for filename in GetDirectoryContents(dir, ["*.java"], skip):
  2055. srcfile = dir + "/" + filename
  2056. dstfile = OUTPUTDIR + "/src/org/panda3d/android/" + filename
  2057. if (NeedsBuild([dstfile], [srcfile])):
  2058. WriteBinaryFile(dstfile, ReadBinaryFile(srcfile))
  2059. JustBuilt([dstfile], [srcfile])
  2060. def CopyTree(dstdir, srcdir, omitVCS=True):
  2061. if (os.path.isdir(dstdir)):
  2062. for entry in os.listdir(srcdir):
  2063. srcpth = os.path.join(srcdir, entry)
  2064. dstpth = os.path.join(dstdir, entry)
  2065. if (os.path.isfile(srcpth)):
  2066. if not omitVCS or entry not in VCS_FILES:
  2067. CopyFile(dstpth, srcpth)
  2068. else:
  2069. if not omitVCS or entry not in VCS_DIRS:
  2070. CopyTree(dstpth, srcpth)
  2071. else:
  2072. if sys.platform == 'win32':
  2073. cmd = 'xcopy /I/Y/E/Q "' + srcdir + '" "' + dstdir + '"'
  2074. else:
  2075. cmd = 'cp -R -f ' + srcdir + ' ' + dstdir
  2076. oscmd(cmd)
  2077. if omitVCS:
  2078. DeleteVCS(dstdir)
  2079. def CopyPythonTree(dstdir, srcdir, lib2to3_fixers=[]):
  2080. if (not os.path.isdir(dstdir)):
  2081. os.mkdir(dstdir)
  2082. lib2to3 = None
  2083. if len(lib2to3_fixers) > 0 and sys.version_info >= (3, 0):
  2084. from lib2to3.main import main as lib2to3
  2085. lib2to3_args = ['-w', '-n', '--no-diffs', '-x', 'buffer', '-x', 'idioms', '-x', 'set_literal', '-x', 'ws_comma']
  2086. if lib2to3_fixers != ['all']:
  2087. for fixer in lib2to3_fixers:
  2088. lib2to3_args += ['-f', fixer]
  2089. refactor = []
  2090. for entry in os.listdir(srcdir):
  2091. srcpth = os.path.join(srcdir, entry)
  2092. dstpth = os.path.join(dstdir, entry)
  2093. if (os.path.isfile(srcpth)):
  2094. base, ext = os.path.splitext(entry)
  2095. if entry not in VCS_FILES and ext not in SUFFIX_INC + ['.pyc', '.pyo']:
  2096. if (NeedsBuild([dstpth], [srcpth])):
  2097. WriteBinaryFile(dstpth, ReadBinaryFile(srcpth))
  2098. if ext == '.py' and not entry.endswith('-extensions.py'):
  2099. refactor.append((dstpth, srcpth))
  2100. else:
  2101. JustBuilt([dstpth], [srcpth])
  2102. elif entry not in VCS_DIRS:
  2103. CopyPythonTree(dstpth, srcpth, lib2to3_fixers)
  2104. for dstpth, srcpth in refactor:
  2105. if lib2to3 is not None:
  2106. ret = lib2to3("lib2to3.fixes", lib2to3_args + [dstpth])
  2107. if ret != 0:
  2108. os.remove(dstpth)
  2109. exit("Error in lib2to3.")
  2110. JustBuilt([dstpth], [srcpth])
  2111. ########################################################################
  2112. ##
  2113. ## Parse PandaVersion.pp to extract the version number.
  2114. ##
  2115. ########################################################################
  2116. def ParsePandaVersion(fn):
  2117. try:
  2118. f = open(fn, "r")
  2119. pattern = re.compile('^[ \t]*[#][ \t]*define[ \t]+PANDA_VERSION[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)')
  2120. for line in f:
  2121. match = pattern.match(line, 0)
  2122. if (match):
  2123. f.close()
  2124. return match.group(1) + "." + match.group(2) + "." + match.group(3)
  2125. f.close()
  2126. except: pass
  2127. return "0.0.0"
  2128. def ParsePluginVersion(fn):
  2129. try:
  2130. f = open(fn, "r")
  2131. pattern = re.compile('^[ \t]*[#][ \t]*define[ \t]+P3D_PLUGIN_VERSION[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)')
  2132. for line in f:
  2133. match = pattern.match(line,0)
  2134. if (match):
  2135. f.close()
  2136. return match.group(1) + "." + match.group(2) + "." + match.group(3)
  2137. f.close()
  2138. except: pass
  2139. return "0.0.0"
  2140. def ParseCoreapiVersion(fn):
  2141. try:
  2142. f = open(fn, "r")
  2143. pattern = re.compile('^[ \t]*[#][ \t]*define[ \t]+P3D_COREAPI_VERSION.*([0-9]+)[ \t]*$')
  2144. for line in f:
  2145. match = pattern.match(line,0)
  2146. if (match):
  2147. f.close()
  2148. return match.group(1)
  2149. f.close()
  2150. except: pass
  2151. return "0"
  2152. ##########################################################################################
  2153. #
  2154. # Utility function to generate a resource file
  2155. #
  2156. ##########################################################################################
  2157. RESOURCE_FILE_TEMPLATE = """VS_VERSION_INFO VERSIONINFO
  2158. FILEVERSION %(commaversion)s
  2159. PRODUCTVERSION %(commaversion)s
  2160. FILEFLAGSMASK 0x3fL
  2161. FILEFLAGS %(debugflag)s
  2162. FILEOS 0x40004L
  2163. FILETYPE 0x2L
  2164. FILESUBTYPE 0x0L
  2165. BEGIN
  2166. BLOCK "StringFileInfo"
  2167. BEGIN
  2168. BLOCK "040904e4"
  2169. BEGIN
  2170. VALUE "FileDescription", "%(description)s\\0"
  2171. VALUE "FileVersion", "%(dotversion)s"
  2172. VALUE "LegalTrademarks", "\\0"
  2173. VALUE "MIMEType", "%(mimetype)s\\0"
  2174. VALUE "FileExtents", "%(extension)s\\0"
  2175. VALUE "FileOpenName", "%(filedesc)s\\0"
  2176. VALUE "OLESelfRegister", "\\0"
  2177. VALUE "OriginalFilename", "%(filename)s\\0"
  2178. VALUE "ProductName", "%(name)s %(version)s\\0"
  2179. VALUE "ProductVersion", "%(dotversion)s"
  2180. END
  2181. END
  2182. BLOCK "VarFileInfo"
  2183. BEGIN
  2184. VALUE "Translation", 0x409, 1252
  2185. END
  2186. END
  2187. """
  2188. def GenerateResourceFile(**kwargs):
  2189. if "debugflag" not in kwargs:
  2190. if GetOptimize() <= 2:
  2191. kwargs["debugflag"] = "0x1L"
  2192. else:
  2193. kwargs["debugflag"] = "0x0L"
  2194. kwargs["dotversion"] = kwargs["version"]
  2195. if len(kwargs["dotversion"].split(".")) == 3:
  2196. kwargs["dotversion"] += ".0"
  2197. if "commaversion" not in kwargs:
  2198. kwargs["commaversion"] = kwargs["dotversion"].replace(".", ",")
  2199. rcdata = ""
  2200. if not "noinclude" in kwargs:
  2201. rcdata += "#define APSTUDIO_READONLY_SYMBOLS\n"
  2202. rcdata += "#include \"winresrc.h\"\n"
  2203. rcdata += "#undef APSTUDIO_READONLY_SYMBOLS\n"
  2204. rcdata += RESOURCE_FILE_TEMPLATE % kwargs
  2205. if "icon" in kwargs:
  2206. rcdata += "\nICON_FILE ICON \"%s\"\n" % kwargs["icon"]
  2207. return rcdata
  2208. def WriteResourceFile(basename, **kwargs):
  2209. if not basename.endswith(".rc"):
  2210. basename += ".rc"
  2211. basename = GetOutputDir() + "/include/" + basename
  2212. ConditionalWriteFile(basename, GenerateResourceFile(**kwargs))
  2213. return basename
  2214. ########################################################################
  2215. ##
  2216. ## FindLocation
  2217. ##
  2218. ########################################################################
  2219. ORIG_EXT = {}
  2220. def GetOrigExt(x):
  2221. return ORIG_EXT[x]
  2222. def SetOrigExt(x, v):
  2223. ORIG_EXT[x] = v
  2224. def CalcLocation(fn, ipath):
  2225. if (fn.count("/")): return fn
  2226. dllext = ""
  2227. target = GetTarget()
  2228. if (GetOptimize() <= 2 and target == 'windows'): dllext = "_d"
  2229. if (fn == "PandaModules.py"): return OUTPUTDIR+"/pandac/" + fn
  2230. if (fn == "AndroidManifest.xml"): return OUTPUTDIR+"/"+fn
  2231. if (fn.endswith(".cxx")): return CxxFindSource(fn, ipath)
  2232. if (fn.endswith(".I")): return CxxFindSource(fn, ipath)
  2233. if (fn.endswith(".h")): return CxxFindSource(fn, ipath)
  2234. if (fn.endswith(".c")): return CxxFindSource(fn, ipath)
  2235. if (fn.endswith(".yxx")): return CxxFindSource(fn, ipath)
  2236. if (fn.endswith(".lxx")): return CxxFindSource(fn, ipath)
  2237. if (fn.endswith(".pdef")):return CxxFindSource(fn, ipath)
  2238. if (fn.endswith(".xml")): return CxxFindSource(fn, ipath)
  2239. if (fn.endswith(".egg")): return OUTPUTDIR+"/models/"+fn
  2240. if (fn.endswith(".egg.pz")):return OUTPUTDIR+"/models/"+fn
  2241. if (target == 'windows'):
  2242. if (fn.endswith(".def")): return CxxFindSource(fn, ipath)
  2243. if (fn.endswith(".rc")): return CxxFindSource(fn, ipath)
  2244. if (fn.endswith(".idl")): return CxxFindSource(fn, ipath)
  2245. if (fn.endswith(".obj")): return OUTPUTDIR+"/tmp/"+fn
  2246. if (fn.endswith(".res")): return OUTPUTDIR+"/tmp/"+fn
  2247. if (fn.endswith(".tlb")): return OUTPUTDIR+"/tmp/"+fn
  2248. if (fn.endswith(".dll")): return OUTPUTDIR+"/bin/"+fn[:-4]+dllext+".dll"
  2249. if (fn.endswith(".pyd")): return OUTPUTDIR+"/panda3d/"+fn[:-4]+".pyd"
  2250. if (fn.endswith(".ocx")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".ocx"
  2251. if (fn.endswith(".mll")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".mll"
  2252. if (fn.endswith(".dlo")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".dlo"
  2253. if (fn.endswith(".dli")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".dli"
  2254. if (fn.endswith(".dle")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".dle"
  2255. if (fn.endswith(".plugin")):return OUTPUTDIR+"/plugins/"+fn[:-7]+dllext+".dll"
  2256. if (fn.endswith(".exe")): return OUTPUTDIR+"/bin/"+fn
  2257. if (fn.endswith(".lib")): return OUTPUTDIR+"/lib/"+fn[:-4]+dllext+".lib"
  2258. if (fn.endswith(".ilb")): return OUTPUTDIR+"/tmp/"+fn[:-4]+dllext+".lib"
  2259. elif (target == 'darwin'):
  2260. if (fn.endswith(".mm")): return CxxFindSource(fn, ipath)
  2261. if (fn.endswith(".r")): return CxxFindSource(fn, ipath)
  2262. if (fn.endswith(".plist")): return CxxFindSource(fn, ipath)
  2263. if (fn.endswith(".obj")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".o"
  2264. if (fn.endswith(".dll")): return OUTPUTDIR+"/lib/"+fn[:-4]+".dylib"
  2265. if (fn.endswith(".pyd")): return OUTPUTDIR+"/panda3d/"+fn[:-4]+".so"
  2266. if (fn.endswith(".mll")): return OUTPUTDIR+"/plugins/"+fn
  2267. if (fn.endswith(".exe")): return OUTPUTDIR+"/bin/"+fn[:-4]
  2268. if (fn.endswith(".lib")): return OUTPUTDIR+"/lib/"+fn[:-4]+".a"
  2269. if (fn.endswith(".ilb")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".a"
  2270. if (fn.endswith(".rsrc")): return OUTPUTDIR+"/tmp/"+fn
  2271. if (fn.endswith(".plugin")):return OUTPUTDIR+"/plugins/"+fn
  2272. if (fn.endswith(".app")): return OUTPUTDIR+"/bin/"+fn
  2273. elif (target == 'android'):
  2274. # On Android, we build the libraries into built/tmp, then copy them.
  2275. if (fn.endswith(".obj")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".o"
  2276. if (fn.endswith(".dll")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".so"
  2277. if (fn.endswith(".pyd")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".so"
  2278. if (fn.endswith(".mll")): return OUTPUTDIR+"/plugins/"+fn
  2279. if (fn.endswith(".plugin")):return OUTPUTDIR+"/plugins/"+fn[:-7]+dllext+".so"
  2280. if (fn.endswith(".exe")): return OUTPUTDIR+"/tmp/lib"+fn[:-4]+".so"
  2281. if (fn.endswith(".lib")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".a"
  2282. if (fn.endswith(".ilb")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".a"
  2283. else:
  2284. if (fn.endswith(".obj")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".o"
  2285. if (fn.endswith(".dll")): return OUTPUTDIR+"/lib/"+fn[:-4]+".so"
  2286. if (fn.endswith(".pyd")): return OUTPUTDIR+"/panda3d/"+fn[:-4]+".so"
  2287. if (fn.endswith(".mll")): return OUTPUTDIR+"/plugins/"+fn
  2288. if (fn.endswith(".plugin")):return OUTPUTDIR+"/plugins/"+fn[:-7]+dllext+".so"
  2289. if (fn.endswith(".exe")): return OUTPUTDIR+"/bin/"+fn[:-4]
  2290. if (fn.endswith(".lib")): return OUTPUTDIR+"/lib/"+fn[:-4]+".a"
  2291. if (fn.endswith(".ilb")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".a"
  2292. if (fn.endswith(".dat")): return OUTPUTDIR+"/tmp/"+fn
  2293. if (fn.endswith(".in")): return OUTPUTDIR+"/pandac/input/"+fn
  2294. return fn
  2295. def FindLocation(fn, ipath):
  2296. if (GetLinkAllStatic() and fn.endswith(".dll")):
  2297. fn = fn[:-4] + ".lib"
  2298. loc = CalcLocation(fn, ipath)
  2299. base, ext = os.path.splitext(fn)
  2300. ORIG_EXT[loc] = ext
  2301. return loc
  2302. ########################################################################
  2303. ##
  2304. ## TargetAdd
  2305. ##
  2306. ## Makepanda maintains a list of make-targets. Each target has
  2307. ## these attributes:
  2308. ##
  2309. ## name - the name of the file being created.
  2310. ## ext - the original file extension, prior to OS-specific translation
  2311. ## inputs - the names of the input files to the compiler
  2312. ## deps - other input files that the target also depends on
  2313. ## opts - compiler options, a catch-all category
  2314. ##
  2315. ## TargetAdd will create the target if it does not exist. Then,
  2316. ## depending on what options you pass, it will push data onto these
  2317. ## various target attributes. This is cumulative: for example, if
  2318. ## you use TargetAdd to add compiler options, then use TargetAdd
  2319. ## again with more compiler options, both sets of options will be
  2320. ## included.
  2321. ##
  2322. ## TargetAdd does some automatic dependency generation on C++ files.
  2323. ## It will scan these files for include-files and automatically push
  2324. ## the include files onto the list of dependencies. In order to do
  2325. ## this, it needs an include-file search path. So if you supply
  2326. ## any C++ input, you also need to supply compiler options containing
  2327. ## include-directories, or alternately, a separate ipath parameter.
  2328. ##
  2329. ## The main body of 'makepanda' is a long list of TargetAdd
  2330. ## directives building up a giant list of make targets. Then,
  2331. ## finally, the targets are run and panda is built.
  2332. ##
  2333. ## Makepanda's dependency system does not understand multiple
  2334. ## outputs from a single build step. When a build step generates
  2335. ## a primary output file and a secondary output file, it is
  2336. ## necessary to trick the dependency system. Insert a dummy
  2337. ## build step that "generates" the secondary output file, using
  2338. ## the primary output file as an input. There is a special
  2339. ## compiler option DEPENDENCYONLY that creates such a dummy
  2340. ## build-step. There are two cases where dummy build steps must
  2341. ## be inserted: bison generates an OBJ and a secondary header
  2342. ## file, interrogate generates an IN and a secondary IGATE.OBJ.
  2343. ##
  2344. ########################################################################
  2345. class Target:
  2346. pass
  2347. TARGET_LIST = []
  2348. TARGET_TABLE = {}
  2349. def TargetAdd(target, dummy=0, opts=0, input=0, dep=0, ipath=0, winrc=0):
  2350. if (dummy != 0):
  2351. exit("Syntax error in TargetAdd "+target)
  2352. if (ipath == 0): ipath = opts
  2353. if (ipath == 0): ipath = []
  2354. if (type(input) == str): input = [input]
  2355. if (type(dep) == str): dep = [dep]
  2356. if os.path.splitext(target)[1] == '.pyd' and PkgSkip("PYTHON"):
  2357. # It makes no sense to build Python modules with python disabled.
  2358. return
  2359. full = FindLocation(target, [OUTPUTDIR + "/include"])
  2360. if (full not in TARGET_TABLE):
  2361. t = Target()
  2362. t.name = full
  2363. t.inputs = []
  2364. t.deps = {}
  2365. t.opts = []
  2366. TARGET_TABLE[full] = t
  2367. TARGET_LIST.append(t)
  2368. else:
  2369. t = TARGET_TABLE[full]
  2370. if opts != 0:
  2371. for x in opts:
  2372. if (t.opts.count(x)==0):
  2373. t.opts.append(x)
  2374. ipath = [OUTPUTDIR + "/tmp"] + GetListOption(ipath, "DIR:") + [OUTPUTDIR+"/include"]
  2375. if input != 0:
  2376. for x in input:
  2377. fullinput = FindLocation(x, ipath)
  2378. t.inputs.append(fullinput)
  2379. # Don't re-link a library or binary if just its dependency dlls have been altered.
  2380. # This should work out fine in most cases, and often reduces recompilation time.
  2381. if (os.path.splitext(x)[-1] not in SUFFIX_DLL):
  2382. t.deps[fullinput] = 1
  2383. (base,suffix) = os.path.splitext(x)
  2384. if (SUFFIX_INC.count(suffix)):
  2385. for d in CxxCalcDependencies(fullinput, ipath, []):
  2386. t.deps[d] = 1
  2387. if dep != 0:
  2388. for x in dep:
  2389. fulldep = FindLocation(x, ipath)
  2390. t.deps[fulldep] = 1
  2391. if winrc != 0 and GetTarget() == 'windows':
  2392. TargetAdd(target, input=WriteResourceFile(target.split("/")[-1].split(".")[0], **winrc))
  2393. if target.endswith(".in"):
  2394. if not CrossCompiling():
  2395. t.deps[FindLocation("interrogate.exe", [])] = 1
  2396. t.deps[FindLocation("dtool_have_python.dat", [])] = 1
  2397. if target.endswith(".pz") and not CrossCompiling():
  2398. t.deps[FindLocation("pzip.exe", [])] = 1