makepandacore.py 134 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715
  1. ########################################################################
  2. ##
  3. ## This file, makepandacore, contains all the global state and
  4. ## global functions for the makepanda system.
  5. ##
  6. ########################################################################
  7. import configparser
  8. from distutils import sysconfig
  9. import fnmatch
  10. import getpass
  11. import glob
  12. import os
  13. import pickle
  14. import platform
  15. import re
  16. import shutil
  17. import signal
  18. import subprocess
  19. import sys
  20. import threading
  21. import _thread as thread
  22. import time
  23. SUFFIX_INC = [".cxx",".cpp",".c",".h",".I",".yxx",".lxx",".mm",".rc",".r"]
  24. SUFFIX_DLL = [".dll",".dlo",".dle",".dli",".dlm",".mll",".exe",".pyd",".ocx"]
  25. SUFFIX_LIB = [".lib",".ilb"]
  26. VCS_DIRS = set(["CVS", "CVSROOT", ".git", ".hg", "__pycache__"])
  27. VCS_FILES = set([".cvsignore", ".gitignore", ".gitmodules", ".hgignore"])
  28. STARTTIME = time.time()
  29. MAINTHREAD = threading.current_thread()
  30. OUTPUTDIR = "built"
  31. CUSTOM_OUTPUTDIR = False
  32. THIRDPARTYBASE = None
  33. THIRDPARTYDIR = None
  34. OPTIMIZE = "3"
  35. VERBOSE = False
  36. LINK_ALL_STATIC = False
  37. TARGET = None
  38. TARGET_ARCH = None
  39. HAS_TARGET_ARCH = False
  40. TOOLCHAIN_PREFIX = ""
  41. ANDROID_ABI = None
  42. ANDROID_TRIPLE = None
  43. ANDROID_API = None
  44. SYS_LIB_DIRS = []
  45. SYS_INC_DIRS = []
  46. DEBUG_DEPENDENCIES = False
  47. # Is the current Python a 32-bit or 64-bit build? There doesn't
  48. # appear to be a universal test for this.
  49. if sys.platform == 'darwin':
  50. # On macOS, platform.architecture reports '64bit' even if it is
  51. # currently running in 32-bit mode. But sys.maxint is a reliable
  52. # indicator.
  53. host_64 = (sys.maxsize > 0x100000000)
  54. else:
  55. # On Windows (and Linux?) sys.maxint reports 0x7fffffff even on a
  56. # 64-bit build. So we stick with platform.architecture in that
  57. # case.
  58. host_64 = (platform.architecture()[0] == '64bit')
  59. # On Android, get a list of all the public system libraries.
  60. ANDROID_SYS_LIBS = []
  61. if os.path.exists("/etc/public.libraries.txt"):
  62. for line in open("/etc/public.libraries.txt", "r"):
  63. line = line.strip()
  64. ANDROID_SYS_LIBS.append(line)
  65. ########################################################################
  66. ##
  67. ## Visual C++ Version (MSVC) and Visual Studio Information Map
  68. ##
  69. ########################################################################
  70. MSVCVERSIONINFO = {
  71. (10,0): {"vsversion":(10,0), "vsname":"Visual Studio 2010"},
  72. (11,0): {"vsversion":(11,0), "vsname":"Visual Studio 2012"},
  73. (12,0): {"vsversion":(12,0), "vsname":"Visual Studio 2013"},
  74. (14,0): {"vsversion":(14,0), "vsname":"Visual Studio 2015"},
  75. (14,1): {"vsversion":(15,0), "vsname":"Visual Studio 2017"},
  76. (14,2): {"vsversion":(16,0), "vsname":"Visual Studio 2019"},
  77. (14,3): {"vsversion":(17,0), "vsname":"Visual Studio 2022"},
  78. }
  79. ########################################################################
  80. ##
  81. ## Maya and Max Version List (with registry keys)
  82. ##
  83. ########################################################################
  84. MAYAVERSIONINFO = [("MAYA6", "6.0"),
  85. ("MAYA65", "6.5"),
  86. ("MAYA7", "7.0"),
  87. ("MAYA8", "8.0"),
  88. ("MAYA85", "8.5"),
  89. ("MAYA2008","2008"),
  90. ("MAYA2009","2009"),
  91. ("MAYA2010","2010"),
  92. ("MAYA2011","2011"),
  93. ("MAYA2012","2012"),
  94. ("MAYA2013","2013"),
  95. ("MAYA20135","2013.5"),
  96. ("MAYA2014","2014"),
  97. ("MAYA2015","2015"),
  98. ("MAYA2016","2016"),
  99. ("MAYA20165","2016.5"),
  100. ("MAYA2017","2017"),
  101. ("MAYA2018","2018"),
  102. ("MAYA2019","2019"),
  103. ("MAYA2020","2020"),
  104. ("MAYA2022","2022"),
  105. ]
  106. MAXVERSIONINFO = [("MAX6", "SOFTWARE\\Autodesk\\3DSMAX\\6.0", "installdir", "maxsdk\\cssdk\\include"),
  107. ("MAX7", "SOFTWARE\\Autodesk\\3DSMAX\\7.0", "Installdir", "maxsdk\\include\\CS"),
  108. ("MAX8", "SOFTWARE\\Autodesk\\3DSMAX\\8.0", "Installdir", "maxsdk\\include\\CS"),
  109. ("MAX9", "SOFTWARE\\Autodesk\\3DSMAX\\9.0", "Installdir", "maxsdk\\include\\CS"),
  110. ("MAX2009", "SOFTWARE\\Autodesk\\3DSMAX\\11.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  111. ("MAX2010", "SOFTWARE\\Autodesk\\3DSMAX\\12.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  112. ("MAX2011", "SOFTWARE\\Autodesk\\3DSMAX\\13.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  113. ("MAX2012", "SOFTWARE\\Autodesk\\3DSMAX\\14.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  114. ("MAX2013", "SOFTWARE\\Autodesk\\3DSMAX\\15.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  115. ("MAX2014", "SOFTWARE\\Autodesk\\3DSMAX\\16.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  116. ]
  117. MAYAVERSIONS = []
  118. MAXVERSIONS = []
  119. DXVERSIONS = ["DX9"]
  120. for (ver,key) in MAYAVERSIONINFO:
  121. MAYAVERSIONS.append(ver)
  122. for (ver,key1,key2,subdir) in MAXVERSIONINFO:
  123. MAXVERSIONS.append(ver)
  124. ########################################################################
  125. ##
  126. ## Potentially Conflicting Files
  127. ##
  128. ## The next function can warn about the existence of files that are
  129. ## commonly generated by ppremake that may conflict with the build.
  130. ##
  131. ########################################################################
  132. CONFLICTING_FILES=["dtool/src/dtoolutil/pandaVersion.h",
  133. "dtool/src/dtoolutil/checkPandaVersion.h",
  134. "dtool/src/dtoolutil/checkPandaVersion.cxx",
  135. "dtool/src/prc/prc_parameters.h",
  136. "contrib/src/speedtree/speedtree_parameters.h",
  137. "direct/src/plugin/p3d_plugin_config.h",
  138. "direct/src/plugin_activex/P3DActiveX.rc",
  139. "direct/src/plugin_npapi/nppanda3d.rc",
  140. "direct/src/plugin_standalone/panda3d.rc"]
  141. def WarnConflictingFiles(delete = False):
  142. for cfile in CONFLICTING_FILES:
  143. if os.path.exists(cfile):
  144. Warn("file may conflict with build:", cfile)
  145. if delete:
  146. os.unlink(cfile)
  147. print("Deleted.")
  148. ########################################################################
  149. ##
  150. ## The exit routine will normally
  151. ##
  152. ## - print a message
  153. ## - save the dependency cache
  154. ## - exit
  155. ##
  156. ## However, if it is invoked inside a thread, it instead:
  157. ##
  158. ## - prints a message
  159. ## - raises the "initiate-exit" exception
  160. ##
  161. ## If you create a thread, you must be prepared to catch this
  162. ## exception, save the dependency cache, and exit.
  163. ##
  164. ########################################################################
  165. WARNINGS = []
  166. THREADS = {}
  167. HAVE_COLORS = False
  168. SETF = ""
  169. try:
  170. import curses
  171. curses.setupterm()
  172. SETF = curses.tigetstr("setf")
  173. if SETF is None:
  174. SETF = curses.tigetstr("setaf")
  175. assert SETF is not None
  176. HAVE_COLORS = sys.stdout.isatty()
  177. except:
  178. pass
  179. def DisableColors():
  180. global HAVE_COLORS
  181. HAVE_COLORS = False
  182. def GetColor(color = None):
  183. if not HAVE_COLORS:
  184. return ""
  185. if color is not None:
  186. color = color.lower()
  187. if color == "blue":
  188. token = curses.tparm(SETF, 1)
  189. elif color == "green":
  190. token = curses.tparm(SETF, 2)
  191. elif color == "cyan":
  192. token = curses.tparm(SETF, 3)
  193. elif color == "red":
  194. token = curses.tparm(SETF, 4)
  195. elif color == "magenta":
  196. token = curses.tparm(SETF, 5)
  197. elif color == "yellow":
  198. token = curses.tparm(SETF, 6)
  199. else:
  200. token = curses.tparm(curses.tigetstr("sgr0"))
  201. return token.decode('ascii')
  202. def ColorText(color, text, reset=True):
  203. if reset is True:
  204. return ''.join((GetColor(color), text, GetColor()))
  205. else:
  206. return ''.join((GetColor(color), text))
  207. def PrettyTime(t):
  208. t = int(t)
  209. hours = t // 3600
  210. t -= hours * 3600
  211. minutes = t // 60
  212. t -= minutes * 60
  213. seconds = t
  214. if hours:
  215. return "%d hours %d min" % (hours, minutes)
  216. if minutes:
  217. return "%d min %d sec" % (minutes, seconds)
  218. return "%d sec" % (seconds)
  219. def ProgressOutput(progress, msg, target = None):
  220. sys.stdout.flush()
  221. sys.stderr.flush()
  222. prefix = ""
  223. thisthread = threading.current_thread()
  224. if thisthread is MAINTHREAD:
  225. if progress is None:
  226. prefix = ""
  227. elif progress >= 100.0:
  228. prefix = "%s[%s%d%%%s] " % (GetColor("yellow"), GetColor("cyan"), progress, GetColor("yellow"))
  229. elif progress < 10.0:
  230. prefix = "%s[%s %d%%%s] " % (GetColor("yellow"), GetColor("cyan"), progress, GetColor("yellow"))
  231. else:
  232. prefix = "%s[%s %d%%%s] " % (GetColor("yellow"), GetColor("cyan"), progress, GetColor("yellow"))
  233. else:
  234. global THREADS
  235. ident = thread.get_ident()
  236. if ident not in THREADS:
  237. THREADS[ident] = len(THREADS) + 1
  238. prefix = "%s[%sT%d%s] " % (GetColor("yellow"), GetColor("cyan"), THREADS[ident], GetColor("yellow"))
  239. if target is not None:
  240. suffix = ' ' + ColorText("green", target)
  241. else:
  242. suffix = GetColor()
  243. print(''.join((prefix, msg, suffix)))
  244. sys.stdout.flush()
  245. sys.stderr.flush()
  246. def exit(msg = ""):
  247. sys.stdout.flush()
  248. sys.stderr.flush()
  249. if threading.current_thread() == MAINTHREAD:
  250. SaveDependencyCache()
  251. print("Elapsed Time: " + PrettyTime(time.time() - STARTTIME))
  252. print(msg)
  253. print(ColorText("red", "Build terminated."))
  254. sys.stdout.flush()
  255. sys.stderr.flush()
  256. ##Don't quit the interperter if I'm running this file directly (debugging)
  257. if __name__ != '__main__':
  258. os._exit(1)
  259. else:
  260. print(msg)
  261. raise "initiate-exit"
  262. def Warn(msg, extra=None):
  263. if extra is not None:
  264. print("%sWARNING:%s %s %s%s%s" % (GetColor("red"), GetColor(), msg, GetColor("green"), extra, GetColor()))
  265. else:
  266. print("%sWARNING:%s %s" % (GetColor("red"), GetColor(), msg))
  267. sys.stdout.flush()
  268. def Error(msg, extra=None):
  269. if extra is not None:
  270. print("%sERROR:%s %s %s%s%s" % (GetColor("red"), GetColor(), msg, GetColor("green"), extra, GetColor()))
  271. else:
  272. print("%sERROR:%s %s" % (GetColor("red"), GetColor(), msg))
  273. exit()
  274. ########################################################################
  275. ##
  276. ## SetTarget, GetTarget, GetHost
  277. ##
  278. ## These functions control cross-compilation.
  279. ##
  280. ########################################################################
  281. def GetHost():
  282. """Returns the host platform, ie. the one we're compiling on."""
  283. if sys.platform == 'win32' or sys.platform == 'cygwin':
  284. # sys.platform is win32 on 64-bits Windows as well.
  285. return 'windows'
  286. elif sys.platform == 'darwin':
  287. return 'darwin'
  288. elif sys.platform.startswith('linux'):
  289. try:
  290. # Python seems to offer no built-in way to check this.
  291. osname = subprocess.check_output(["uname", "-o"])
  292. if osname.strip().lower() == b'android':
  293. return 'android'
  294. else:
  295. return 'linux'
  296. except:
  297. return 'linux'
  298. elif sys.platform.startswith('freebsd'):
  299. return 'freebsd'
  300. else:
  301. exit('Unrecognized sys.platform: %s' % (sys.platform))
  302. def GetHostArch():
  303. """Returns the architecture we're compiling on.
  304. Its value is also platform-dependent, as different platforms
  305. have different architecture naming."""
  306. target = GetTarget()
  307. if target == 'windows':
  308. return 'x64' if host_64 else 'x86'
  309. machine = platform.machine()
  310. if machine.startswith('armv7'):
  311. return 'armv7a'
  312. else:
  313. return machine
  314. def SetTarget(target, arch=None):
  315. """Sets the target platform; the one we're compiling for. Also
  316. sets the target architecture (None for default, if any). Should
  317. be called *before* any calls are made to GetOutputDir, GetCC, etc."""
  318. global TARGET, TARGET_ARCH, HAS_TARGET_ARCH
  319. global TOOLCHAIN_PREFIX
  320. host = GetHost()
  321. host_arch = GetHostArch()
  322. if target is None:
  323. target = host
  324. else:
  325. target = target.lower()
  326. if arch is not None:
  327. HAS_TARGET_ARCH = True
  328. TOOLCHAIN_PREFIX = ''
  329. if target == 'windows':
  330. if arch == 'i386':
  331. arch = 'x86'
  332. elif arch == 'amd64':
  333. arch = 'x64'
  334. if arch is not None and arch != 'x86' and arch != 'x64':
  335. exit("Windows architecture must be x86 or x64")
  336. elif target == 'darwin':
  337. if arch == 'amd64':
  338. arch = 'x86_64'
  339. if arch == 'aarch64':
  340. arch = 'arm64'
  341. if arch is not None:
  342. choices = ('i386', 'x86_64', 'ppc', 'ppc64', 'arm64')
  343. if arch not in choices:
  344. exit('macOS architecture must be one of %s' % (', '.join(choices)))
  345. elif target == 'android' or target.startswith('android-'):
  346. if arch is None:
  347. # If compiling on Android, default to same architecture. Otherwise, arm.
  348. if host == 'android':
  349. arch = host_arch
  350. else:
  351. arch = 'armv7a'
  352. if arch == 'aarch64':
  353. arch = 'arm64'
  354. # Did we specify an API level?
  355. global ANDROID_API
  356. target, _, api = target.partition('-')
  357. if api:
  358. ANDROID_API = int(api)
  359. elif arch in ('mips64', 'arm64', 'x86_64'):
  360. # 64-bit platforms were introduced in Android 21.
  361. ANDROID_API = 21
  362. else:
  363. # Default to the lowest API level still supported by Google.
  364. ANDROID_API = 19
  365. # Determine the prefix for our gcc tools, eg. arm-linux-androideabi-gcc
  366. global ANDROID_ABI, ANDROID_TRIPLE
  367. if arch == 'armv7a':
  368. ANDROID_ABI = 'armeabi-v7a'
  369. ANDROID_TRIPLE = 'armv7a-linux-androideabi'
  370. elif arch == 'arm':
  371. ANDROID_ABI = 'armeabi'
  372. ANDROID_TRIPLE = 'arm-linux-androideabi'
  373. elif arch == 'arm64':
  374. ANDROID_ABI = 'arm64-v8a'
  375. ANDROID_TRIPLE = 'aarch64-linux-android'
  376. elif arch == 'mips':
  377. ANDROID_ABI = 'mips'
  378. ANDROID_TRIPLE = 'mipsel-linux-android'
  379. elif arch == 'mips64':
  380. ANDROID_ABI = 'mips64'
  381. ANDROID_TRIPLE = 'mips64el-linux-android'
  382. elif arch == 'x86':
  383. ANDROID_ABI = 'x86'
  384. ANDROID_TRIPLE = 'i686-linux-android'
  385. elif arch == 'x86_64':
  386. ANDROID_ABI = 'x86_64'
  387. ANDROID_TRIPLE = 'x86_64-linux-android'
  388. else:
  389. exit('Android architecture must be arm, armv7a, arm64, mips, mips64, x86 or x86_64')
  390. ANDROID_TRIPLE += str(ANDROID_API)
  391. TOOLCHAIN_PREFIX = ANDROID_TRIPLE + '-'
  392. elif target == 'linux':
  393. if arch is not None:
  394. TOOLCHAIN_PREFIX = '%s-linux-gnu-' % arch
  395. elif host != 'linux':
  396. exit('Should specify an architecture when building for Linux')
  397. elif target == host:
  398. if arch is None or arch == host_arch:
  399. # Not a cross build.
  400. pass
  401. else:
  402. exit('Cannot cross-compile for %s-%s from %s-%s' % (target, arch, host, host_arch))
  403. else:
  404. exit('Cannot cross-compile for %s from %s' % (target, host))
  405. if arch is None:
  406. arch = host_arch
  407. TARGET = target
  408. TARGET_ARCH = arch
  409. def GetTarget():
  410. """Returns the platform we're compiling for. Defaults to GetHost()."""
  411. global TARGET
  412. if TARGET is None:
  413. TARGET = GetHost()
  414. return TARGET
  415. def HasTargetArch():
  416. """Returns True if the user specified an architecture to compile for."""
  417. return HAS_TARGET_ARCH
  418. def GetTargetArch():
  419. """Returns the architecture we're compiling for. Defaults to GetHostArch().
  420. Its value is also dependent on that of GetTarget(), as different platforms
  421. use a different architecture naming."""
  422. global TARGET_ARCH
  423. if TARGET_ARCH is None:
  424. TARGET_ARCH = GetHostArch()
  425. return TARGET_ARCH
  426. def CrossCompiling():
  427. """Returns True if we're cross-compiling."""
  428. return GetTarget() != GetHost()
  429. def GetCC():
  430. if TARGET in ('darwin', 'freebsd', 'android'):
  431. return os.environ.get('CC', TOOLCHAIN_PREFIX + 'clang')
  432. else:
  433. return os.environ.get('CC', TOOLCHAIN_PREFIX + 'gcc')
  434. def GetCXX():
  435. if TARGET in ('darwin', 'freebsd', 'android'):
  436. return os.environ.get('CXX', TOOLCHAIN_PREFIX + 'clang++')
  437. else:
  438. return os.environ.get('CXX', TOOLCHAIN_PREFIX + 'g++')
  439. def GetStrip():
  440. # Hack
  441. if TARGET == 'android':
  442. return 'llvm-strip'
  443. else:
  444. return 'strip'
  445. def GetAR():
  446. # Hack
  447. if TARGET == 'android':
  448. return TOOLCHAIN_PREFIX + 'ar'
  449. else:
  450. return 'ar'
  451. def GetRanlib():
  452. # Hack
  453. if TARGET == 'android':
  454. return TOOLCHAIN_PREFIX + 'ranlib'
  455. else:
  456. return 'ranlib'
  457. BISON = None
  458. def GetBison():
  459. global BISON
  460. if BISON is not None:
  461. return BISON
  462. # We now require a newer version of Bison than the one we previously
  463. # shipped in the win-util dir. The new version has a 'data'
  464. # subdirectory, so check for that.
  465. win_util_data = os.path.join(GetThirdpartyBase(), 'win-util', 'data')
  466. if GetHost() == 'windows' and os.path.isdir(win_util_data):
  467. BISON = os.path.join(GetThirdpartyBase(), 'win-util', 'bison.exe')
  468. elif LocateBinary('bison'):
  469. BISON = 'bison'
  470. else:
  471. # We don't strictly need it, so don't give an error
  472. return None
  473. return BISON
  474. FLEX = None
  475. def GetFlex():
  476. global FLEX
  477. if FLEX is not None:
  478. return FLEX
  479. win_util = os.path.join(GetThirdpartyBase(), 'win-util')
  480. if GetHost() == 'windows' and os.path.isdir(win_util):
  481. FLEX = GetThirdpartyBase() + "/win-util/flex.exe"
  482. elif LocateBinary('flex'):
  483. FLEX = 'flex'
  484. else:
  485. # We don't strictly need it, so don't give an error
  486. return None
  487. return FLEX
  488. def GetFlexVersion():
  489. flex = GetFlex()
  490. if not flex:
  491. return (0, 0, 0)
  492. try:
  493. handle = subprocess.Popen(["flex", "--version"], executable=flex, stdout=subprocess.PIPE)
  494. words = handle.communicate()[0].strip().splitlines()[0].split(b' ')
  495. if words[1] != "version":
  496. version = words[1]
  497. else:
  498. version = words[2]
  499. return tuple(map(int, version.split(b'.')))
  500. except:
  501. Warn("Unable to detect flex version")
  502. return (0, 0, 0)
  503. ########################################################################
  504. ##
  505. ## LocateBinary
  506. ##
  507. ## This function searches the system PATH for the binary. Returns its
  508. ## full path when it is found, or None when it was not found.
  509. ##
  510. ########################################################################
  511. def LocateBinary(binary):
  512. if os.path.isfile(binary):
  513. return binary
  514. if "PATH" not in os.environ or os.environ["PATH"] == "":
  515. p = os.defpath
  516. else:
  517. p = os.environ["PATH"]
  518. pathList = p.split(os.pathsep)
  519. suffixes = ['']
  520. if GetHost() == 'windows':
  521. if not binary.lower().endswith('.exe') and not binary.lower().endswith('.bat'):
  522. # Append .exe if necessary
  523. suffixes = ['.exe', '.bat']
  524. # On Windows the current directory is always implicitly
  525. # searched before anything else on PATH.
  526. pathList = ['.'] + pathList
  527. for path in pathList:
  528. binpath = os.path.join(os.path.expanduser(path), binary)
  529. for suffix in suffixes:
  530. if os.access(binpath + suffix, os.X_OK):
  531. return os.path.abspath(os.path.realpath(binpath + suffix))
  532. return None
  533. ########################################################################
  534. ##
  535. ## Run a command.
  536. ##
  537. ########################################################################
  538. def oscmd(cmd, ignoreError = False, cwd=None):
  539. if VERBOSE:
  540. print(GetColor("blue") + cmd.split(" ", 1)[0] + " " + GetColor("magenta") + cmd.split(" ", 1)[1] + GetColor())
  541. sys.stdout.flush()
  542. if sys.platform == "win32":
  543. if cmd[0] == '"':
  544. exe = cmd[1 : cmd.index('"', 1)]
  545. else:
  546. exe = cmd.split()[0]
  547. exe_path = LocateBinary(exe)
  548. if exe_path is None:
  549. exit("Cannot find "+exe+" on search path")
  550. if cwd is not None:
  551. pwd = os.getcwd()
  552. os.chdir(cwd)
  553. res = os.spawnl(os.P_WAIT, exe_path, cmd)
  554. if cwd is not None:
  555. os.chdir(pwd)
  556. else:
  557. cmd = cmd.replace(';', '\\;')
  558. cmd = cmd.replace('$', '\\$')
  559. res = subprocess.call(cmd, cwd=cwd, shell=True)
  560. sig = res & 0x7F
  561. if (GetVerbose() and res != 0):
  562. print(ColorText("red", "Process exited with exit status %d and signal code %d" % ((res & 0xFF00) >> 8, sig)))
  563. if (sig == signal.SIGINT):
  564. exit("keyboard interrupt")
  565. # Don't ask me where the 35584 or 34304 come from...
  566. if (sig == signal.SIGSEGV or res == 35584 or res == 34304):
  567. if (LocateBinary("gdb") and GetVerbose() and GetHost() != "windows"):
  568. print(ColorText("red", "Received SIGSEGV, retrieving traceback..."))
  569. 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)
  570. else:
  571. print(ColorText("red", "Received SIGSEGV"))
  572. exit("")
  573. if res != 0 and not ignoreError:
  574. if "interrogate" in cmd.split(" ", 1)[0] and GetVerbose():
  575. print(ColorText("red", "Interrogate failed, retrieving debug output..."))
  576. sys.stdout.flush()
  577. verbose_cmd = cmd.split(" ", 1)[0] + " -vv " + cmd.split(" ", 1)[1]
  578. if sys.platform == "win32":
  579. os.spawnl(os.P_WAIT, exe_path, verbose_cmd)
  580. else:
  581. subprocess.call(verbose_cmd, shell=True)
  582. exit("The following command returned a non-zero value: " + str(cmd))
  583. return res
  584. ########################################################################
  585. ##
  586. ## GetDirectoryContents
  587. ##
  588. ########################################################################
  589. def GetDirectoryContents(dir, filters="*", skip=[]):
  590. if isinstance(filters, str):
  591. filters = [filters]
  592. actual = {}
  593. files = os.listdir(dir)
  594. for filter in filters:
  595. for file in fnmatch.filter(files, filter):
  596. if (skip.count(file)==0) and (os.path.isfile(dir + "/" + file)):
  597. actual[file] = 1
  598. results = list(actual.keys())
  599. results.sort()
  600. return results
  601. def GetDirectorySize(dir):
  602. if not os.path.isdir(dir):
  603. return 0
  604. size = 0
  605. for (path, dirs, files) in os.walk(dir):
  606. for file in files:
  607. try:
  608. size += os.path.getsize(os.path.join(path, file))
  609. except:
  610. pass
  611. return size
  612. ########################################################################
  613. ##
  614. ## The Timestamp Cache
  615. ##
  616. ## The make utility is constantly fetching the timestamps of files.
  617. ## This can represent the bulk of the file accesses during the make
  618. ## process. The timestamp cache eliminates redundant checks.
  619. ##
  620. ########################################################################
  621. TIMESTAMPCACHE = {}
  622. def GetTimestamp(path):
  623. if path in TIMESTAMPCACHE:
  624. return TIMESTAMPCACHE[path]
  625. try:
  626. date = os.path.getmtime(path)
  627. except:
  628. date = 0
  629. TIMESTAMPCACHE[path] = date
  630. return date
  631. def ClearTimestamp(path):
  632. del TIMESTAMPCACHE[path]
  633. ########################################################################
  634. ##
  635. ## The Dependency cache.
  636. ##
  637. ## Makepanda's strategy for file dependencies is different from most
  638. ## make-utilities. Whenever a file is built, makepanda records
  639. ## that the file was built, and it records what the input files were,
  640. ## and what their dates were. Whenever a file is about to be built,
  641. ## panda compares the current list of input files and their dates,
  642. ## to the previous list of input files and their dates. If they match,
  643. ## there is no need to build the file.
  644. ##
  645. ########################################################################
  646. BUILTFROMCACHE = {}
  647. def JustBuilt(files, others):
  648. dates = {}
  649. for file in files:
  650. del TIMESTAMPCACHE[file]
  651. dates[file] = GetTimestamp(file)
  652. for file in others:
  653. dates[file] = GetTimestamp(file)
  654. key = tuple(files)
  655. BUILTFROMCACHE[key] = dates
  656. def NeedsBuild(files, others):
  657. dates = {}
  658. for file in files:
  659. dates[file] = GetTimestamp(file)
  660. if not os.path.exists(file):
  661. if DEBUG_DEPENDENCIES:
  662. print("rebuilding %s because it does not exist" % (file))
  663. return True
  664. for file in others:
  665. dates[file] = GetTimestamp(file)
  666. key = tuple(files)
  667. if key in BUILTFROMCACHE:
  668. cached = BUILTFROMCACHE[key]
  669. if cached == dates:
  670. return False
  671. elif DEBUG_DEPENDENCIES:
  672. print("rebuilding %s because:" % (key))
  673. for key in frozenset(cached.keys()) | frozenset(dates.keys()):
  674. if key not in cached:
  675. print(" new dependency: %s" % (key))
  676. elif key not in dates:
  677. print(" removed dependency: %s" % (key))
  678. elif cached[key] != dates[key]:
  679. print(" dependency changed: %s" % (key))
  680. if VERBOSE and frozenset(cached) != frozenset(dates):
  681. Warn("file dependencies changed:", files)
  682. return True
  683. ########################################################################
  684. ##
  685. ## The CXX include cache:
  686. ##
  687. ## The following routine scans a CXX file and returns a list of
  688. ## the include-directives inside that file. It's not recursive:
  689. ## it just returns the includes that are textually inside the
  690. ## file. If you need recursive dependencies, you need the higher-level
  691. ## routine CxxCalcDependencies, defined elsewhere.
  692. ##
  693. ## Since scanning a CXX file is slow, we cache the result. It records
  694. ## the date of the source file and the list of includes that it
  695. ## contains. It assumes that if the file date hasn't changed, that
  696. ## the list of include-statements inside the file has not changed
  697. ## either. Once again, this particular routine does not return
  698. ## recursive dependencies --- it only returns an explicit list of
  699. ## include statements that are textually inside the file. That
  700. ## is what the cache stores, as well.
  701. ##
  702. ########################################################################
  703. CXXINCLUDECACHE = {}
  704. CxxIncludeRegex = re.compile('^[ \t]*[#][ \t]*include[ \t]+"([^"]+)"[ \t\r\n]*$')
  705. def CxxGetIncludes(path):
  706. date = GetTimestamp(path)
  707. if path in CXXINCLUDECACHE:
  708. cached = CXXINCLUDECACHE[path]
  709. if cached[0] == date:
  710. return cached[1]
  711. try:
  712. sfile = open(path, 'r')
  713. except:
  714. exit("Cannot open source file \""+path+"\" for reading.")
  715. include = []
  716. try:
  717. for line in sfile:
  718. match = CxxIncludeRegex.match(line,0)
  719. if match:
  720. incname = match.group(1)
  721. include.append(incname)
  722. except:
  723. print("Failed to determine dependencies of \""+path+"\".")
  724. raise
  725. sfile.close()
  726. CXXINCLUDECACHE[path] = [date, include]
  727. return include
  728. JAVAIMPORTCACHE = {}
  729. JavaImportRegex = re.compile('[ \t\r\n;]import[ \t]+([a-zA-Z][^;]+)[ \t\r\n]*;')
  730. def JavaGetImports(path):
  731. date = GetTimestamp(path)
  732. if path in JAVAIMPORTCACHE:
  733. cached = JAVAIMPORTCACHE[path]
  734. if cached[0] == date:
  735. return cached[1]
  736. try:
  737. source = open(path, 'r').read()
  738. except:
  739. exit("Cannot open source file \"" + path + "\" for reading.")
  740. imports = []
  741. try:
  742. for match in JavaImportRegex.finditer(source, 0):
  743. impname = match.group(1)
  744. imports.append(impname.strip())
  745. except:
  746. print("Failed to determine dependencies of \"" + path +"\".")
  747. raise
  748. JAVAIMPORTCACHE[path] = [date, imports]
  749. return imports
  750. ########################################################################
  751. ##
  752. ## SaveDependencyCache / LoadDependencyCache
  753. ##
  754. ## This actually saves both the dependency and cxx-include caches.
  755. ##
  756. ########################################################################
  757. DCACHE_VERSION = 2
  758. DCACHE_BACKED_UP = False
  759. def SaveDependencyCache():
  760. global DCACHE_BACKED_UP
  761. if not DCACHE_BACKED_UP:
  762. try:
  763. if os.path.exists(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache")):
  764. os.rename(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"),
  765. os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache-backup"))
  766. except:
  767. pass
  768. DCACHE_BACKED_UP = True
  769. try:
  770. icache = open(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"),'wb')
  771. except:
  772. icache = None
  773. if icache is not None:
  774. print("Storing dependency cache.")
  775. pickle.dump(DCACHE_VERSION, icache, 0)
  776. pickle.dump(CXXINCLUDECACHE, icache, 2)
  777. pickle.dump(BUILTFROMCACHE, icache, 2)
  778. icache.close()
  779. def LoadDependencyCache():
  780. global CXXINCLUDECACHE
  781. global BUILTFROMCACHE
  782. try:
  783. icache = open(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"), 'rb')
  784. except:
  785. icache = None
  786. if icache is not None:
  787. ver = pickle.load(icache)
  788. if ver == DCACHE_VERSION:
  789. CXXINCLUDECACHE = pickle.load(icache)
  790. BUILTFROMCACHE = pickle.load(icache)
  791. icache.close()
  792. else:
  793. print("Cannot load dependency cache, version is too old!")
  794. ########################################################################
  795. ##
  796. ## CxxFindSource: given a source file name and a directory list,
  797. ## searches the directory list for the given source file. Returns
  798. ## the full pathname of the located file.
  799. ##
  800. ## CxxFindHeader: given a source file, an include directive, and a
  801. ## directory list, searches the directory list for the given header
  802. ## file. Returns the full pathname of the located file.
  803. ##
  804. ## Of course, CxxFindSource and CxxFindHeader cannot find a source
  805. ## file that has not been created yet. This can cause dependency
  806. ## problems. So the function CreateStubHeader can be used to create
  807. ## a file that CxxFindSource or CxxFindHeader can subsequently find.
  808. ##
  809. ########################################################################
  810. def CxxFindSource(name, ipath):
  811. for dir in ipath:
  812. if (dir == "."): full = name
  813. else: full = dir + "/" + name
  814. if GetTimestamp(full) > 0: return full
  815. exit("Could not find source file: "+name)
  816. def CxxFindHeader(srcfile, incfile, ipath):
  817. if (incfile.startswith(".")):
  818. last = srcfile.rfind("/")
  819. if (last < 0): exit("CxxFindHeader cannot handle this case #1")
  820. srcdir = srcfile[:last+1]
  821. while (incfile[:1]=="."):
  822. if (incfile[:2]=="./"):
  823. incfile = incfile[2:]
  824. elif (incfile[:3]=="../"):
  825. incfile = incfile[3:]
  826. last = srcdir[:-1].rfind("/")
  827. if (last < 0): exit("CxxFindHeader cannot handle this case #2")
  828. srcdir = srcdir[:last+1]
  829. else: exit("CxxFindHeader cannot handle this case #3")
  830. full = srcdir + incfile
  831. if GetTimestamp(full) > 0: return full
  832. return 0
  833. else:
  834. for dir in ipath:
  835. full = dir + "/" + incfile
  836. if GetTimestamp(full) > 0: return full
  837. return 0
  838. def JavaFindClasses(impspec, clspath):
  839. path = clspath + '/' + impspec.replace('.', '/') + '.class'
  840. if '*' in path:
  841. return glob.glob(path)
  842. else:
  843. return [path]
  844. ########################################################################
  845. ##
  846. ## CxxCalcDependencies(srcfile, ipath, ignore)
  847. ##
  848. ## Calculate the dependencies of a source file given a
  849. ## particular include-path. Any file in the list of files to
  850. ## ignore is not considered.
  851. ##
  852. ########################################################################
  853. CxxIgnoreHeader = {}
  854. CxxDependencyCache = {}
  855. def CxxCalcDependencies(srcfile, ipath, ignore):
  856. if srcfile in CxxDependencyCache:
  857. return CxxDependencyCache[srcfile]
  858. if ignore.count(srcfile):
  859. return []
  860. dep = {}
  861. dep[srcfile] = 1
  862. includes = CxxGetIncludes(srcfile)
  863. for include in includes:
  864. header = CxxFindHeader(srcfile, include, ipath)
  865. if header != 0:
  866. if ignore.count(header) == 0:
  867. hdeps = CxxCalcDependencies(header, ipath, [srcfile]+ignore)
  868. for x in hdeps:
  869. dep[x] = 1
  870. result = list(dep.keys())
  871. CxxDependencyCache[srcfile] = result
  872. return result
  873. global JavaDependencyCache
  874. JavaDependencyCache = {}
  875. def JavaCalcDependencies(srcfile, clspath):
  876. if srcfile in JavaDependencyCache:
  877. return JavaDependencyCache[srcfile]
  878. deps = set((srcfile,))
  879. JavaDependencyCache[srcfile] = deps
  880. imports = JavaGetImports(srcfile)
  881. for impspec in imports:
  882. for cls in JavaFindClasses(impspec, clspath):
  883. deps.add(cls)
  884. return deps
  885. ########################################################################
  886. ##
  887. ## Registry Key Handling
  888. ##
  889. ## Of course, these routines will fail if you call them on a
  890. ## non win32 platform. If you use them on a win64 platform, they
  891. ## will look in the win32 private hive first, then look in the
  892. ## win64 hive.
  893. ##
  894. ########################################################################
  895. if sys.platform == "win32":
  896. # Note: not supported on cygwin.
  897. import winreg
  898. def TryRegistryKey(path):
  899. try:
  900. key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path, 0, winreg.KEY_READ)
  901. return key
  902. except:
  903. pass
  904. try:
  905. key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path, 0, winreg.KEY_READ | 256)
  906. return key
  907. except:
  908. pass
  909. return 0
  910. def ListRegistryKeys(path):
  911. result=[]
  912. index=0
  913. key = TryRegistryKey(path)
  914. if (key != 0):
  915. try:
  916. while (1):
  917. result.append(winreg.EnumKey(key, index))
  918. index = index + 1
  919. except:
  920. pass
  921. winreg.CloseKey(key)
  922. return result
  923. def ListRegistryValues(path):
  924. result = []
  925. index = 0
  926. key = TryRegistryKey(path)
  927. if (key != 0):
  928. try:
  929. while (1):
  930. result.append(winreg.EnumValue(key, index)[0])
  931. index = index + 1
  932. except:
  933. pass
  934. winreg.CloseKey(key)
  935. return result
  936. def GetRegistryKey(path, subkey, override64=True):
  937. if (host_64 and override64):
  938. path = path.replace("SOFTWARE\\", "SOFTWARE\\Wow6432Node\\")
  939. k1=0
  940. key = TryRegistryKey(path)
  941. if (key != 0):
  942. try:
  943. k1, k2 = winreg.QueryValueEx(key, subkey)
  944. except:
  945. pass
  946. winreg.CloseKey(key)
  947. return k1
  948. def GetProgramFiles():
  949. if ("PROGRAMFILES" in os.environ):
  950. return os.environ["PROGRAMFILES"]
  951. elif (os.path.isdir("C:\\Program Files")):
  952. return "C:\\Program Files"
  953. elif (os.path.isdir("D:\\Program Files")):
  954. return "D:\\Program Files"
  955. elif (os.path.isdir("E:\\Program Files")):
  956. return "E:\\Program Files"
  957. return 0
  958. def GetProgramFiles_x86():
  959. if ("ProgramFiles(x86)" in os.environ):
  960. return os.environ["ProgramFiles(x86)"]
  961. elif (os.path.isdir("C:\\Program Files (x86)")):
  962. return "C:\\Program Files (x86)"
  963. elif (os.path.isdir("D:\\Program Files (x86)")):
  964. return "D:\\Program Files (x86)"
  965. elif (os.path.isdir("E:\\Program Files (x86)")):
  966. return "E:\\Program Files (x86)"
  967. return GetProgramFiles()
  968. ########################################################################
  969. ##
  970. ## Parsing Compiler Option Lists
  971. ##
  972. ########################################################################
  973. def GetListOption(opts, prefix):
  974. res=[]
  975. for x in opts:
  976. if (x.startswith(prefix)):
  977. res.append(x[len(prefix):])
  978. return res
  979. def GetValueOption(opts, prefix):
  980. for x in opts:
  981. if (x.startswith(prefix)):
  982. return x[len(prefix):]
  983. return 0
  984. def GetOptimizeOption(opts):
  985. val = GetValueOption(opts, "OPT:")
  986. if (val == 0):
  987. return OPTIMIZE
  988. return val
  989. ########################################################################
  990. ##
  991. ## General File Manipulation
  992. ##
  993. ########################################################################
  994. def MakeDirectory(path, mode=None, recursive=False):
  995. if os.path.isdir(path):
  996. return
  997. if recursive:
  998. parent = os.path.dirname(path)
  999. if parent and not os.path.isdir(parent):
  1000. MakeDirectory(parent, mode=mode, recursive=True)
  1001. if mode is not None:
  1002. os.mkdir(path, mode)
  1003. else:
  1004. os.mkdir(path)
  1005. def ReadFile(wfile):
  1006. try:
  1007. srchandle = open(wfile, "r")
  1008. data = srchandle.read()
  1009. srchandle.close()
  1010. return data
  1011. except:
  1012. ex = sys.exc_info()[1]
  1013. exit("Cannot read %s: %s" % (wfile, ex))
  1014. def ReadBinaryFile(wfile):
  1015. try:
  1016. srchandle = open(wfile, "rb")
  1017. data = srchandle.read()
  1018. srchandle.close()
  1019. return data
  1020. except:
  1021. ex = sys.exc_info()[1]
  1022. exit("Cannot read %s: %s" % (wfile, ex))
  1023. def WriteFile(wfile, data, newline=None):
  1024. if newline is not None:
  1025. data = data.replace('\r\n', '\n')
  1026. data = data.replace('\r', '\n')
  1027. data = data.replace('\n', newline)
  1028. try:
  1029. dsthandle = open(wfile, "w", newline='')
  1030. dsthandle.write(data)
  1031. dsthandle.close()
  1032. except:
  1033. ex = sys.exc_info()[1]
  1034. exit("Cannot write to %s: %s" % (wfile, ex))
  1035. def WriteBinaryFile(wfile, data):
  1036. try:
  1037. dsthandle = open(wfile, "wb")
  1038. dsthandle.write(data)
  1039. dsthandle.close()
  1040. except:
  1041. ex = sys.exc_info()[1]
  1042. exit("Cannot write to %s: %s" % (wfile, ex))
  1043. def ConditionalWriteFile(dest, data, newline=None):
  1044. if newline is not None:
  1045. data = data.replace('\r\n', '\n')
  1046. data = data.replace('\r', '\n')
  1047. data = data.replace('\n', newline)
  1048. try:
  1049. rfile = open(dest, 'r')
  1050. contents = rfile.read(-1)
  1051. rfile.close()
  1052. except:
  1053. contents = 0
  1054. if contents != data:
  1055. if VERBOSE:
  1056. print("Writing %s" % (dest))
  1057. sys.stdout.flush()
  1058. WriteFile(dest, data)
  1059. def DeleteVCS(dir):
  1060. if dir == "": dir = "."
  1061. for entry in os.listdir(dir):
  1062. subdir = os.path.join(dir, entry)
  1063. if (os.path.isdir(subdir)):
  1064. if entry in VCS_DIRS:
  1065. shutil.rmtree(subdir)
  1066. else:
  1067. DeleteVCS(subdir)
  1068. elif (os.path.isfile(subdir) and (entry in VCS_FILES or entry.startswith(".#"))):
  1069. os.remove(subdir)
  1070. def DeleteBuildFiles(dir):
  1071. if dir == "": dir = "."
  1072. for entry in os.listdir(dir):
  1073. subdir = os.path.join(dir, entry)
  1074. if (os.path.isfile(subdir) and os.path.splitext(subdir)[-1] in [".pp", ".moved"]):
  1075. os.remove(subdir)
  1076. elif (os.path.isdir(subdir)):
  1077. if (os.path.basename(subdir)[:3] == "Opt" and os.path.basename(subdir)[4] == "-"):
  1078. shutil.rmtree(subdir)
  1079. else:
  1080. DeleteBuildFiles(subdir)
  1081. def DeleteEmptyDirs(dir):
  1082. if dir == "": dir = "."
  1083. entries = os.listdir(dir)
  1084. if not entries:
  1085. os.rmdir(dir)
  1086. return
  1087. for entry in entries:
  1088. subdir = os.path.join(dir, entry)
  1089. if (os.path.isdir(subdir)):
  1090. if (not os.listdir(subdir)):
  1091. os.rmdir(subdir)
  1092. else:
  1093. DeleteEmptyDirs(subdir)
  1094. def CreateFile(file):
  1095. if (os.path.exists(file)==0):
  1096. WriteFile(file, "")
  1097. ########################################################################
  1098. #
  1099. # Create the panda build tree.
  1100. #
  1101. ########################################################################
  1102. def MakeBuildTree():
  1103. MakeDirectory(OUTPUTDIR)
  1104. MakeDirectory(OUTPUTDIR + "/bin")
  1105. MakeDirectory(OUTPUTDIR + "/lib")
  1106. MakeDirectory(OUTPUTDIR + "/tmp")
  1107. MakeDirectory(OUTPUTDIR + "/etc")
  1108. MakeDirectory(OUTPUTDIR + "/plugins")
  1109. MakeDirectory(OUTPUTDIR + "/include")
  1110. MakeDirectory(OUTPUTDIR + "/models")
  1111. MakeDirectory(OUTPUTDIR + "/models/audio")
  1112. MakeDirectory(OUTPUTDIR + "/models/audio/sfx")
  1113. MakeDirectory(OUTPUTDIR + "/models/icons")
  1114. MakeDirectory(OUTPUTDIR + "/models/maps")
  1115. MakeDirectory(OUTPUTDIR + "/models/misc")
  1116. MakeDirectory(OUTPUTDIR + "/models/gui")
  1117. MakeDirectory(OUTPUTDIR + "/pandac")
  1118. MakeDirectory(OUTPUTDIR + "/pandac/input")
  1119. MakeDirectory(OUTPUTDIR + "/panda3d")
  1120. if GetTarget() == 'android':
  1121. MakeDirectory(OUTPUTDIR + "/classes")
  1122. ########################################################################
  1123. #
  1124. # Make sure that you are in the root of the panda tree.
  1125. #
  1126. ########################################################################
  1127. def CheckPandaSourceTree():
  1128. dir = os.getcwd()
  1129. if ((os.path.exists(os.path.join(dir, "makepanda/makepanda.py"))==0) or
  1130. (os.path.exists(os.path.join(dir, "dtool", "src", "dtoolbase", "dtoolbase.h"))==0) or
  1131. (os.path.exists(os.path.join(dir, "panda", "src", "pandabase", "pandabase.h"))==0)):
  1132. exit("Current directory is not the root of the panda tree.")
  1133. ########################################################################
  1134. ##
  1135. ## Thirdparty libraries paths
  1136. ##
  1137. ########################################################################
  1138. def GetThirdpartyBase():
  1139. """Returns the location of the 'thirdparty' directory.
  1140. Normally, this is simply the thirdparty directory relative
  1141. to the root of the source root, but if a MAKEPANDA_THIRDPARTY
  1142. environment variable was set, it is used as the location of the
  1143. thirdparty directory. This is useful when wanting to use a single
  1144. system-wide thirdparty directory, for instance on a build machine."""
  1145. global THIRDPARTYBASE
  1146. if (THIRDPARTYBASE is not None):
  1147. return THIRDPARTYBASE
  1148. THIRDPARTYBASE = "thirdparty"
  1149. if "MAKEPANDA_THIRDPARTY" in os.environ:
  1150. THIRDPARTYBASE = os.environ["MAKEPANDA_THIRDPARTY"]
  1151. return THIRDPARTYBASE
  1152. def GetThirdpartyDir():
  1153. """Returns the thirdparty directory for the target platform,
  1154. ie. thirdparty/win-libs-vc10/. May return None in the future."""
  1155. global THIRDPARTYDIR
  1156. if THIRDPARTYDIR is not None:
  1157. return THIRDPARTYDIR
  1158. base = GetThirdpartyBase()
  1159. target = GetTarget()
  1160. target_arch = GetTargetArch()
  1161. if (target == 'windows'):
  1162. vc = str(SDK["MSVC_VERSION"][0])
  1163. if target_arch == 'x64':
  1164. THIRDPARTYDIR = base + "/win-libs-vc" + vc + "-x64/"
  1165. else:
  1166. THIRDPARTYDIR = base + "/win-libs-vc" + vc + "/"
  1167. elif (target == 'darwin'):
  1168. # macOS thirdparty binaries are universal, where possible.
  1169. THIRDPARTYDIR = base + "/darwin-libs-a/"
  1170. elif (target == 'linux'):
  1171. if target_arch in ("aarch64", "arm64"):
  1172. THIRDPARTYDIR = base + "/linux-libs-arm64/"
  1173. elif target_arch.startswith("arm"):
  1174. THIRDPARTYDIR = base + "/linux-libs-arm/"
  1175. elif (target_arch in ("x86_64", "amd64")):
  1176. THIRDPARTYDIR = base + "/linux-libs-x64/"
  1177. else:
  1178. THIRDPARTYDIR = base + "/linux-libs-a/"
  1179. elif (target == 'freebsd'):
  1180. if target_arch in ("aarch64", "arm64"):
  1181. THIRDPARTYDIR = base + "/freebsd-libs-arm64/"
  1182. elif target_arch.startswith("arm"):
  1183. THIRDPARTYDIR = base + "/freebsd-libs-arm/"
  1184. elif (target_arch in ("x86_64", "amd64")):
  1185. THIRDPARTYDIR = base + "/freebsd-libs-x64/"
  1186. else:
  1187. THIRDPARTYDIR = base + "/freebsd-libs-a/"
  1188. elif (target == 'android'):
  1189. THIRDPARTYDIR = base + "/android-libs-%s/" % (target_arch)
  1190. else:
  1191. Warn("Unsupported platform:", target)
  1192. return
  1193. if (GetVerbose()):
  1194. print("Using thirdparty directory: %s" % THIRDPARTYDIR)
  1195. return THIRDPARTYDIR
  1196. ########################################################################
  1197. ##
  1198. ## Gets or sets the output directory, by default "built".
  1199. ## Gets or sets the optimize level.
  1200. ## Gets or sets the verbose flag.
  1201. ##
  1202. ########################################################################
  1203. def GetOutputDir():
  1204. return OUTPUTDIR
  1205. def IsCustomOutputDir():
  1206. return CUSTOM_OUTPUTDIR
  1207. def SetOutputDir(outputdir):
  1208. global OUTPUTDIR, CUSTOM_OUTPUTDIR
  1209. OUTPUTDIR = outputdir
  1210. CUSTOM_OUTPUTDIR = True
  1211. def GetOptimize():
  1212. return int(OPTIMIZE)
  1213. def SetOptimize(optimize):
  1214. global OPTIMIZE
  1215. OPTIMIZE = optimize
  1216. def GetVerbose():
  1217. return VERBOSE
  1218. def SetVerbose(verbose):
  1219. global VERBOSE
  1220. VERBOSE = verbose
  1221. def SetDebugDependencies(dd = True):
  1222. global DEBUG_DEPENDENCIES
  1223. DEBUG_DEPENDENCIES = dd
  1224. def GetLinkAllStatic():
  1225. return LINK_ALL_STATIC
  1226. def SetLinkAllStatic(val = True):
  1227. global LINK_ALL_STATIC
  1228. LINK_ALL_STATIC = val
  1229. def UnsetLinkAllStatic():
  1230. global LINK_ALL_STATIC
  1231. LINK_ALL_STATIC = False
  1232. ########################################################################
  1233. ##
  1234. ## Package Selection
  1235. ##
  1236. ## This facility enables makepanda to keep a list of packages selected
  1237. ## by the user for inclusion or omission.
  1238. ##
  1239. ########################################################################
  1240. PKG_LIST_ALL = []
  1241. PKG_LIST_OMIT = {}
  1242. PKG_LIST_CUSTOM = set()
  1243. def PkgListSet(pkgs):
  1244. global PKG_LIST_ALL
  1245. global PKG_LIST_OMIT
  1246. PKG_LIST_ALL=pkgs
  1247. PKG_LIST_OMIT={}
  1248. PkgEnableAll()
  1249. def PkgListGet():
  1250. return PKG_LIST_ALL
  1251. def PkgEnableAll():
  1252. for x in PKG_LIST_ALL:
  1253. PKG_LIST_OMIT[x] = 0
  1254. def PkgDisableAll():
  1255. for x in PKG_LIST_ALL:
  1256. PKG_LIST_OMIT[x] = 1
  1257. def PkgEnable(pkg):
  1258. PKG_LIST_OMIT[pkg] = 0
  1259. def PkgDisable(pkg):
  1260. PKG_LIST_OMIT[pkg] = 1
  1261. def PkgSetCustomLocation(pkg):
  1262. PKG_LIST_CUSTOM.add(pkg)
  1263. def PkgHasCustomLocation(pkg):
  1264. return pkg in PKG_LIST_CUSTOM
  1265. def PkgSkip(pkg):
  1266. return PKG_LIST_OMIT[pkg]
  1267. def PkgSelected(pkglist, pkg):
  1268. if (pkglist.count(pkg)==0): return 0
  1269. if (PKG_LIST_OMIT[pkg]): return 0
  1270. return 1
  1271. ########################################################################
  1272. ##
  1273. ## DTOOL/PRC Option value override
  1274. ##
  1275. ## This facility enables makepanda to keep a list of parameters
  1276. ## overriden by the command line.
  1277. ##
  1278. ########################################################################
  1279. OVERRIDES_LIST={}
  1280. def AddOverride(spec):
  1281. if (spec.find("=")==-1):return
  1282. pair = spec.split("=",1)
  1283. OVERRIDES_LIST[pair[0]] = pair[1]
  1284. def OverrideValue(parameter, value):
  1285. if parameter in OVERRIDES_LIST:
  1286. print("Overriding value of key \"" + parameter + "\" with value \"" + OVERRIDES_LIST[parameter] + "\"")
  1287. return OVERRIDES_LIST[parameter]
  1288. else:
  1289. return value
  1290. ########################################################################
  1291. ##
  1292. ## These functions are for libraries which use pkg-config.
  1293. ##
  1294. ########################################################################
  1295. def PkgConfigHavePkg(pkgname, tool = "pkg-config"):
  1296. """Returns a bool whether the pkg-config package is installed."""
  1297. if (sys.platform == "win32" or CrossCompiling() or not LocateBinary(tool)):
  1298. return False
  1299. if (tool == "pkg-config"):
  1300. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --modversion " + pkgname)
  1301. else:
  1302. return bool(LocateBinary(tool) is not None)
  1303. result = handle.read().strip()
  1304. returnval = handle.close()
  1305. if returnval is not None and returnval != 0:
  1306. return False
  1307. return bool(len(result) > 0)
  1308. def PkgConfigGetLibs(pkgname, tool = "pkg-config"):
  1309. """Returns a list of libs for the package, prefixed by -l."""
  1310. if (sys.platform == "win32" or CrossCompiling() or not LocateBinary(tool)):
  1311. return []
  1312. if (tool == "pkg-config"):
  1313. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --libs-only-l " + pkgname)
  1314. elif (tool == "fltk-config"):
  1315. handle = os.popen(LocateBinary("fltk-config") + " --ldstaticflags")
  1316. else:
  1317. handle = os.popen(LocateBinary(tool) + " --libs")
  1318. result = handle.read().strip()
  1319. handle.close()
  1320. libs = []
  1321. # Walk through the result arguments carefully. Look for -lname as
  1322. # well as -framework name.
  1323. r = result.split(' ')
  1324. ri = 0
  1325. while ri < len(r):
  1326. l = r[ri]
  1327. if l.startswith("-l") or l.startswith("/"):
  1328. libs.append(l)
  1329. elif l == '-framework':
  1330. libs.append(l)
  1331. ri += 1
  1332. libs.append(r[ri])
  1333. ri += 1
  1334. return libs
  1335. def PkgConfigGetIncDirs(pkgname, tool = "pkg-config"):
  1336. """Returns a list of includes for the package, NOT prefixed by -I."""
  1337. if (sys.platform == "win32" or CrossCompiling() or not LocateBinary(tool)):
  1338. return []
  1339. if (tool == "pkg-config"):
  1340. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --cflags-only-I " + pkgname)
  1341. else:
  1342. handle = os.popen(LocateBinary(tool) + " --cflags")
  1343. result = handle.read().strip()
  1344. handle.close()
  1345. if len(result) == 0: return []
  1346. dirs = []
  1347. for opt in result.split(" "):
  1348. if (opt.startswith("-I")):
  1349. inc_dir = opt.replace("-I", "").replace("\"", "").strip()
  1350. # Hack for ODE, otherwise -S/usr/include gets added to interrogate
  1351. if inc_dir != '/usr/include' and inc_dir != '/usr/include/':
  1352. dirs.append(inc_dir)
  1353. return dirs
  1354. def PkgConfigGetLibDirs(pkgname, tool = "pkg-config"):
  1355. """Returns a list of library paths for the package, NOT prefixed by -L."""
  1356. if (sys.platform == "win32" or CrossCompiling() or not LocateBinary(tool)):
  1357. return []
  1358. if (tool == "pkg-config"):
  1359. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --libs-only-L " + pkgname)
  1360. elif (tool == "wx-config" or tool == "ode-config"):
  1361. return []
  1362. else:
  1363. handle = os.popen(LocateBinary(tool) + " --ldflags")
  1364. result = handle.read().strip()
  1365. handle.close()
  1366. if len(result) == 0: return []
  1367. libs = []
  1368. for l in result.split(" "):
  1369. if (l.startswith("-L")):
  1370. libs.append(l.replace("-L", "").replace("\"", "").strip())
  1371. return libs
  1372. def PkgConfigGetDefSymbols(pkgname, tool = "pkg-config"):
  1373. """Returns a dictionary of preprocessor definitions."""
  1374. if (sys.platform == "win32" or CrossCompiling() or not LocateBinary(tool)):
  1375. return []
  1376. if (tool == "pkg-config"):
  1377. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --cflags " + pkgname)
  1378. else:
  1379. handle = os.popen(LocateBinary(tool) + " --cflags")
  1380. result = handle.read().strip()
  1381. handle.close()
  1382. if len(result) == 0: return {}
  1383. defs = {}
  1384. for l in result.split(" "):
  1385. if (l.startswith("-D")):
  1386. d = l.replace("-D", "").replace("\"", "").strip().split("=")
  1387. if d[0] in ('NDEBUG', '_DEBUG'):
  1388. # Setting one of these flags by accident could cause serious harm.
  1389. if GetVerbose():
  1390. print("Ignoring %s flag provided by %s" % (l, tool))
  1391. elif len(d) == 1:
  1392. defs[d[0]] = ""
  1393. else:
  1394. defs[d[0]] = d[1]
  1395. return defs
  1396. def PkgConfigEnable(opt, pkgname, tool = "pkg-config"):
  1397. """Adds the libraries and includes to IncDirectory, LibName and LibDirectory."""
  1398. for i in PkgConfigGetIncDirs(pkgname, tool):
  1399. IncDirectory(opt, i)
  1400. for i in PkgConfigGetLibDirs(pkgname, tool):
  1401. LibDirectory(opt, i)
  1402. for i in PkgConfigGetLibs(pkgname, tool):
  1403. LibName(opt, i)
  1404. for i, j in PkgConfigGetDefSymbols(pkgname, tool).items():
  1405. DefSymbol(opt, i, j)
  1406. def LocateLibrary(lib, lpath=[], prefer_static=False):
  1407. """Searches for the library in the search path, returning its path if found,
  1408. or None if it was not found."""
  1409. target = GetTarget()
  1410. if prefer_static and target != 'windows':
  1411. for dir in lpath:
  1412. if os.path.isfile(os.path.join(dir, 'lib%s.a' % lib)):
  1413. return os.path.join(dir, 'lib%s.a' % lib)
  1414. for dir in lpath:
  1415. if target == 'darwin' and os.path.isfile(os.path.join(dir, 'lib%s.dylib' % lib)):
  1416. return os.path.join(dir, 'lib%s.dylib' % lib)
  1417. elif target != 'darwin' and os.path.isfile(os.path.join(dir, 'lib%s.so' % lib)):
  1418. return os.path.join(dir, 'lib%s.so' % lib)
  1419. elif os.path.isfile(os.path.join(dir, 'lib%s.a' % lib)):
  1420. return os.path.join(dir, 'lib%s.a' % lib)
  1421. return None
  1422. def SystemLibraryExists(lib):
  1423. result = LocateLibrary(lib, SYS_LIB_DIRS)
  1424. if result is not None:
  1425. return True
  1426. if GetHost() == "android" and GetTarget() == "android":
  1427. return ('lib%s.so' % lib) in ANDROID_SYS_LIBS
  1428. return False
  1429. def ChooseLib(libs, thirdparty=None):
  1430. """ Chooses a library from the parameters, in order of preference. Returns the first if none of them were found. """
  1431. lpath = []
  1432. if thirdparty is not None:
  1433. lpath.append(os.path.join(GetThirdpartyDir(), thirdparty.lower(), "lib"))
  1434. lpath += SYS_LIB_DIRS
  1435. for l in libs:
  1436. libname = l
  1437. if l.startswith("lib"):
  1438. libname = l[3:]
  1439. if LocateLibrary(libname, lpath):
  1440. return libname
  1441. if len(libs) > 0:
  1442. if VERBOSE:
  1443. print(ColorText("cyan", "Couldn't find any of the libraries " + ", ".join(libs)))
  1444. return libs[0]
  1445. def SmartPkgEnable(pkg, pkgconfig = None, libs = None, incs = None, defs = None, framework = None, target_pkg = None, tool = "pkg-config", thirdparty_dir = None):
  1446. global PKG_LIST_ALL
  1447. if (pkg in PkgListGet() and PkgSkip(pkg)):
  1448. return
  1449. if (target_pkg == "" or target_pkg is None):
  1450. target_pkg = pkg
  1451. if (pkgconfig == ""):
  1452. pkgconfig = None
  1453. if (framework == ""):
  1454. framework = None
  1455. if (libs is None or libs == ""):
  1456. libs = ()
  1457. elif (isinstance(libs, str)):
  1458. libs = (libs, )
  1459. if (incs is None or incs == ""):
  1460. incs = ()
  1461. elif (isinstance(incs, str)):
  1462. incs = (incs, )
  1463. if (defs is None or defs == "" or len(defs) == 0):
  1464. defs = {}
  1465. elif (isinstance(incs, str)):
  1466. defs = {defs : ""}
  1467. elif (isinstance(incs, list) or isinstance(incs, tuple) or isinstance(incs, set)):
  1468. olddefs = defs
  1469. defs = {}
  1470. for d in olddefs:
  1471. defs[d] = ""
  1472. custom_loc = PkgHasCustomLocation(pkg)
  1473. # Determine the location of the thirdparty directory.
  1474. if not thirdparty_dir:
  1475. thirdparty_dir = pkg.lower()
  1476. pkg_dir = os.path.join(GetThirdpartyDir(), thirdparty_dir)
  1477. # First check if the library can be found in the thirdparty directory.
  1478. if not custom_loc and os.path.isdir(pkg_dir):
  1479. if framework and os.path.isdir(os.path.join(pkg_dir, framework + ".framework")):
  1480. FrameworkDirectory(target_pkg, pkg_dir)
  1481. LibName(target_pkg, "-framework " + framework)
  1482. return
  1483. inc_dir = os.path.join(pkg_dir, "include")
  1484. if os.path.isdir(inc_dir):
  1485. IncDirectory(target_pkg, inc_dir)
  1486. # Handle cases like freetype2 where the include dir is a subdir under "include"
  1487. for i in incs:
  1488. if os.path.isdir(os.path.join(inc_dir, i)):
  1489. IncDirectory(target_pkg, os.path.join(inc_dir, i))
  1490. lib_dir = os.path.join(pkg_dir, "lib")
  1491. lpath = [lib_dir]
  1492. if not PkgSkip("PYTHON"):
  1493. py_lib_dir = os.path.join(lib_dir, SDK["PYTHONVERSION"])
  1494. if os.path.isdir(py_lib_dir):
  1495. lpath.append(py_lib_dir)
  1496. # TODO: check for a .pc file in the lib/pkgconfig/ dir
  1497. if (tool is not None and os.path.isfile(os.path.join(pkg_dir, "bin", tool))):
  1498. tool = os.path.join(pkg_dir, "bin", tool)
  1499. for i in PkgConfigGetLibs(None, tool):
  1500. if i.startswith('-l'):
  1501. # To make sure we don't pick up the system copy, write out
  1502. # the full path instead.
  1503. libname = i[2:]
  1504. location = LocateLibrary(libname, lpath, prefer_static=True)
  1505. if location is not None:
  1506. LibName(target_pkg, location)
  1507. else:
  1508. print(GetColor("cyan") + "Couldn't find library lib" + libname + " in thirdparty directory " + pkg.lower() + GetColor())
  1509. LibName(target_pkg, i)
  1510. else:
  1511. LibName(target_pkg, i)
  1512. for i, j in PkgConfigGetDefSymbols(None, tool).items():
  1513. DefSymbol(target_pkg, i, j)
  1514. return
  1515. # Now search for the libraries in the package's lib directories.
  1516. for l in libs:
  1517. libname = l
  1518. if l.startswith("lib"):
  1519. libname = l[3:]
  1520. location = LocateLibrary(libname, lpath, prefer_static=True)
  1521. if location is not None:
  1522. # If it's a .so or .dylib we may have changed it and copied it to the built/lib dir.
  1523. if location.endswith('.so') or location.endswith('.dylib'):
  1524. location = os.path.join(GetOutputDir(), "lib", os.path.basename(location))
  1525. LibName(target_pkg, location)
  1526. else:
  1527. # This is for backward compatibility - in the thirdparty dir,
  1528. # we kept some libs with "panda" prefix, like libpandatiff.
  1529. location = LocateLibrary("panda" + libname, lpath, prefer_static=True)
  1530. if location is not None:
  1531. if location.endswith('.so') or location.endswith('.dylib'):
  1532. location = os.path.join(GetOutputDir(), "lib", os.path.basename(location))
  1533. LibName(target_pkg, location)
  1534. else:
  1535. print(GetColor("cyan") + "Couldn't find library lib" + libname + " in thirdparty directory " + thirdparty_dir + GetColor())
  1536. for d, v in defs.values():
  1537. DefSymbol(target_pkg, d, v)
  1538. return
  1539. elif not custom_loc and GetHost() == "darwin" and framework is not None:
  1540. prefix = SDK["MACOSX"]
  1541. if (os.path.isdir(prefix + "/Library/Frameworks/%s.framework" % framework) or
  1542. os.path.isdir(prefix + "/System/Library/Frameworks/%s.framework" % framework) or
  1543. os.path.isdir(prefix + "/Developer/Library/Frameworks/%s.framework" % framework) or
  1544. os.path.isdir(prefix + "/Users/%s/System/Library/Frameworks/%s.framework" % (getpass.getuser(), framework))):
  1545. LibName(target_pkg, "-framework " + framework)
  1546. for d, v in defs.values():
  1547. DefSymbol(target_pkg, d, v)
  1548. return
  1549. elif VERBOSE:
  1550. print(ColorText("cyan", "Couldn't find the framework %s" % (framework)))
  1551. elif not custom_loc and LocateBinary(tool) is not None and (tool != "pkg-config" or pkgconfig is not None):
  1552. if (isinstance(pkgconfig, str) or tool != "pkg-config"):
  1553. if (PkgConfigHavePkg(pkgconfig, tool)):
  1554. return PkgConfigEnable(target_pkg, pkgconfig, tool)
  1555. else:
  1556. have_all_pkgs = True
  1557. for pc in pkgconfig:
  1558. if (PkgConfigHavePkg(pc, tool)):
  1559. PkgConfigEnable(target_pkg, pc, tool)
  1560. else:
  1561. have_all_pkgs = False
  1562. if (have_all_pkgs):
  1563. return
  1564. if not custom_loc and pkgconfig is not None and not libs:
  1565. # pkg-config is all we can do, abort if it wasn't found.
  1566. if pkg in PkgListGet():
  1567. Warn("Could not locate pkg-config package %s, excluding from build" % (pkgconfig))
  1568. PkgDisable(pkg)
  1569. else:
  1570. Error("Could not locate pkg-config package %s, aborting build" % (pkgconfig))
  1571. else:
  1572. # Okay, our pkg-config attempts failed. Let's try locating the libs by ourselves.
  1573. have_pkg = True
  1574. for l in libs:
  1575. libname = l
  1576. if l.startswith("lib"):
  1577. libname = l[3:]
  1578. if custom_loc:
  1579. # Try searching in the package's LibDirectories.
  1580. lpath = [dir for ppkg, dir in LIBDIRECTORIES if pkg == ppkg]
  1581. location = LocateLibrary(libname, lpath)
  1582. if location is not None:
  1583. LibName(target_pkg, location)
  1584. else:
  1585. have_pkg = False
  1586. print(GetColor("cyan") + "Couldn't find library lib" + libname + GetColor())
  1587. elif SystemLibraryExists(libname):
  1588. # It exists in a system library directory.
  1589. LibName(target_pkg, "-l" + libname)
  1590. else:
  1591. # Try searching in the package's LibDirectories.
  1592. lpath = [dir for ppkg, dir in LIBDIRECTORIES if pkg == ppkg or ppkg == "ALWAYS"]
  1593. location = LocateLibrary(libname, lpath)
  1594. if location is not None:
  1595. LibName(target_pkg, "-l" + libname)
  1596. else:
  1597. have_pkg = False
  1598. if VERBOSE or custom_loc:
  1599. print(GetColor("cyan") + "Couldn't find library lib" + libname + GetColor())
  1600. # Determine which include directories to look in.
  1601. incdirs = []
  1602. if not custom_loc:
  1603. incdirs += list(SYS_INC_DIRS)
  1604. for ppkg, pdir in INCDIRECTORIES[:]:
  1605. if pkg == ppkg or (ppkg == "ALWAYS" and not custom_loc):
  1606. incdirs.append(pdir)
  1607. if custom_loc and pkg != target_pkg:
  1608. IncDirectory(target_pkg, pdir)
  1609. # The incs list contains both subdirectories to explicitly add to
  1610. # the include path and header files to check the existence of.
  1611. for i in incs:
  1612. incdir = None
  1613. for dir in incdirs:
  1614. if len(glob.glob(os.path.join(dir, i))) > 0:
  1615. incdir = sorted(glob.glob(os.path.join(dir, i)))[-1]
  1616. # Note: It's possible to specify a file instead of a dir, for the sake of checking if it exists.
  1617. if incdir is None and (i.endswith('/Dense') or i.endswith(".h")):
  1618. have_pkg = False
  1619. if VERBOSE or custom_loc:
  1620. print(GetColor("cyan") + "Couldn't find header file " + i + GetColor())
  1621. if incdir is not None and os.path.isdir(incdir):
  1622. IncDirectory(target_pkg, incdir)
  1623. if not have_pkg:
  1624. if custom_loc:
  1625. Error("Could not locate thirdparty package %s in specified directory, aborting build" % (pkg.lower()))
  1626. elif pkg in PkgListGet():
  1627. Warn("Could not locate thirdparty package %s, excluding from build" % (pkg.lower()))
  1628. PkgDisable(pkg)
  1629. else:
  1630. Error("Could not locate thirdparty package %s, aborting build" % (pkg.lower()))
  1631. ########################################################################
  1632. ##
  1633. ## SDK Location
  1634. ##
  1635. ## This section is concerned with locating the install directories
  1636. ## for various third-party packages. The results are stored in the
  1637. ## SDK table.
  1638. ##
  1639. ## Microsoft keeps changing the &*#$*& registry key for the DirectX SDK.
  1640. ## The only way to reliably find it is to search through the installer's
  1641. ## uninstall-directories, look in each one, and see if it contains the
  1642. ## relevant files.
  1643. ##
  1644. ########################################################################
  1645. SDK = {}
  1646. def GetSdkDir(sdkname, sdkkey = None):
  1647. # Returns the default SDK directory. If it exists,
  1648. # and sdkkey is not None, it is put in SDK[sdkkey].
  1649. # Note: return value may not be an existing path.
  1650. sdkbase = "sdks"
  1651. if "MAKEPANDA_SDKS" in os.environ:
  1652. sdkbase = os.environ["MAKEPANDA_SDKS"]
  1653. sdir = sdkbase[:]
  1654. target = GetTarget()
  1655. target_arch = GetTargetArch()
  1656. if target == 'windows':
  1657. if target_arch == 'x64':
  1658. sdir += "/win64"
  1659. else:
  1660. sdir += "/win32"
  1661. elif target == 'linux':
  1662. sdir += "/linux"
  1663. sdir += platform.architecture()[0][:2]
  1664. elif target == 'darwin':
  1665. sdir += "/macosx"
  1666. sdir += "/" + sdkname
  1667. # If it does not exist, try the old location.
  1668. if (not os.path.isdir(sdir)):
  1669. sdir = sdkbase + "/" + sdir
  1670. if (target == 'linux'):
  1671. sdir += "-linux"
  1672. sdir += platform.architecture()[0][:2]
  1673. elif (target == "darwin"):
  1674. sdir += "-osx"
  1675. if (sdkkey and os.path.isdir(sdir)):
  1676. SDK[sdkkey] = sdir
  1677. return sdir
  1678. def SdkLocateDirectX( strMode = 'default' ):
  1679. if (GetHost() != "windows"): return
  1680. if strMode == 'default':
  1681. GetSdkDir("directx9", "DX9")
  1682. if ("DX9" not in SDK):
  1683. strMode = 'latest'
  1684. if strMode == 'latest':
  1685. ## We first try to locate the August SDK in 64 bits, then 32.
  1686. if ("DX9" not in SDK):
  1687. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1688. if (dir != 0):
  1689. print("Using DirectX SDK June 2010")
  1690. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1691. if ("DX9" not in SDK):
  1692. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1693. if (dir != 0):
  1694. print("Using DirectX SDK June 2010")
  1695. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1696. if ("DX9" not in SDK):
  1697. dir = "C:/Program Files (x86)/Microsoft DirectX SDK (June 2010)"
  1698. if os.path.isdir(dir):
  1699. print("Using DirectX SDK June 2010")
  1700. SDK["DX9"] = dir
  1701. if ("DX9" not in SDK):
  1702. dir = "C:/Program Files/Microsoft DirectX SDK (June 2010)"
  1703. if os.path.isdir(dir):
  1704. print("Using DirectX SDK June 2010")
  1705. SDK["DX9"] = dir
  1706. if ("DX9" not in SDK):
  1707. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1708. if (dir != 0):
  1709. print("Using DirectX SDK Aug 2009")
  1710. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1711. if ("DX9" not in SDK):
  1712. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1713. if (dir != 0):
  1714. print("Using DirectX SDK Aug 2009")
  1715. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1716. archStr = GetTargetArch()
  1717. if ("DX9" not in SDK):
  1718. uninstaller = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
  1719. for subdir in ListRegistryKeys(uninstaller):
  1720. if (subdir[0]=="{"):
  1721. dir = GetRegistryKey(uninstaller+"\\"+subdir, "InstallLocation")
  1722. if (dir != 0):
  1723. if (("DX9" not in SDK) and
  1724. (os.path.isfile(dir+"\\Include\\d3d9.h")) and
  1725. (os.path.isfile(dir+"\\Include\\d3dx9.h")) and
  1726. (os.path.isfile(dir+"\\Include\\dxsdkver.h")) and
  1727. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3d9.lib")) and
  1728. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3dx9.lib"))):
  1729. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1730. if ("DX9" not in SDK):
  1731. return
  1732. elif strMode == 'jun2010':
  1733. if ("DX9" not in SDK):
  1734. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1735. if (dir != 0):
  1736. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1737. if ("DX9" not in SDK):
  1738. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1739. if (dir != 0):
  1740. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1741. if ("DX9" not in SDK):
  1742. dir = "C:/Program Files (x86)/Microsoft DirectX SDK (June 2010)"
  1743. if os.path.isdir(dir):
  1744. SDK["DX9"] = dir
  1745. if ("DX9" not in SDK):
  1746. dir = "C:/Program Files/Microsoft DirectX SDK (June 2010)"
  1747. if os.path.isdir(dir):
  1748. SDK["DX9"] = dir
  1749. if ("DX9" not in SDK):
  1750. exit("Couldn't find DirectX June2010 SDK")
  1751. else:
  1752. print("Found DirectX SDK June 2010")
  1753. elif strMode == 'aug2009':
  1754. if ("DX9" not in SDK):
  1755. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1756. if (dir != 0):
  1757. print("Found DirectX SDK Aug 2009")
  1758. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1759. if ("DX9" not in SDK):
  1760. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1761. if (dir != 0):
  1762. print("Found DirectX SDK Aug 2009")
  1763. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1764. if ("DX9" not in SDK):
  1765. exit("Couldn't find DirectX Aug 2009 SDK")
  1766. if ("DX9" in SDK):
  1767. SDK["DIRECTCAM"] = SDK["DX9"]
  1768. def SdkLocateMaya():
  1769. for (ver, key) in MAYAVERSIONINFO:
  1770. if (PkgSkip(ver)==0 and ver not in SDK):
  1771. GetSdkDir(ver.lower().replace("x",""), ver)
  1772. if (not ver in SDK):
  1773. if (GetHost() == "windows"):
  1774. for dev in ["Alias|Wavefront","Alias","Autodesk"]:
  1775. fullkey="SOFTWARE\\"+dev+"\\Maya\\"+key+"\\Setup\\InstallPath"
  1776. res = GetRegistryKey(fullkey, "MAYA_INSTALL_LOCATION", override64=False)
  1777. if (res != 0):
  1778. res = res.replace("\\", "/").rstrip("/")
  1779. SDK[ver] = res
  1780. elif (GetHost() == "darwin"):
  1781. ddir = "/Applications/Autodesk/maya"+key
  1782. if (os.path.isdir(ddir)): SDK[ver] = ddir
  1783. else:
  1784. if (GetTargetArch() in ("x86_64", "amd64")):
  1785. ddir1 = "/usr/autodesk/maya"+key+"-x64"
  1786. ddir2 = "/usr/aw/maya"+key+"-x64"
  1787. else:
  1788. ddir1 = "/usr/autodesk/maya"+key
  1789. ddir2 = "/usr/aw/maya"+key
  1790. if (os.path.isdir(ddir1)): SDK[ver] = ddir1
  1791. elif (os.path.isdir(ddir2)): SDK[ver] = ddir2
  1792. def SdkLocateMax():
  1793. if (GetHost() != "windows"): return
  1794. for version,key1,key2,subdir in MAXVERSIONINFO:
  1795. if (PkgSkip(version)==0):
  1796. if (version not in SDK):
  1797. GetSdkDir("maxsdk"+version.lower()[3:], version)
  1798. GetSdkDir("maxsdk"+version.lower()[3:], version+"CS")
  1799. if (not version in SDK):
  1800. top = GetRegistryKey(key1,key2)
  1801. if (top != 0):
  1802. SDK[version] = top + "maxsdk"
  1803. if (os.path.isdir(top + "\\" + subdir)!=0):
  1804. SDK[version+"CS"] = top + subdir
  1805. def SdkLocatePython(prefer_thirdparty_python=False):
  1806. if PkgSkip("PYTHON"):
  1807. # We're not compiling with Python support. We still need to set this
  1808. # in case we want to run any scripts that use Python, though.
  1809. SDK["PYTHONEXEC"] = os.path.realpath(sys.executable)
  1810. return
  1811. abiflags = getattr(sys, 'abiflags', '')
  1812. if GetTarget() == 'windows':
  1813. if PkgHasCustomLocation("PYTHON"):
  1814. # Check our custom location instead (--python-libdir, --python-incdir)
  1815. sdkdir = FindOptDirectory("PYTHON")
  1816. if sdkdir is None:
  1817. exit("Could not find a Python installation using these command line options.")
  1818. else:
  1819. sdkdir = GetThirdpartyBase() + "/win-python"
  1820. sdkdir += "%d.%d" % sys.version_info[:2]
  1821. if GetOptimize() <= 2:
  1822. sdkdir += "-dbg"
  1823. if GetTargetArch() == 'x64':
  1824. sdkdir += "-x64"
  1825. sdkdir = sdkdir.replace('\\', '/')
  1826. SDK["PYTHON"] = sdkdir
  1827. SDK["PYTHONEXEC"] = SDK["PYTHON"] + "/python"
  1828. if (GetOptimize() <= 2):
  1829. SDK["PYTHONEXEC"] += "_d.exe"
  1830. else:
  1831. SDK["PYTHONEXEC"] += ".exe"
  1832. if (not os.path.isfile(SDK["PYTHONEXEC"])):
  1833. exit("Could not find %s!" % SDK["PYTHONEXEC"])
  1834. # Determine which version it is by checking which dll is in the directory.
  1835. if (GetOptimize() <= 2):
  1836. py_dlls = glob.glob(SDK["PYTHON"] + "/python[0-9][0-9]_d.dll") + \
  1837. glob.glob(SDK["PYTHON"] + "/python[0-9][0-9][0-9]_d.dll")
  1838. else:
  1839. py_dlls = glob.glob(SDK["PYTHON"] + "/python[0-9][0-9].dll") + \
  1840. glob.glob(SDK["PYTHON"] + "/python[0-9][0-9][0-9].dll")
  1841. if len(py_dlls) == 0:
  1842. exit("Could not find the Python dll in %s." % (SDK["PYTHON"]))
  1843. elif len(py_dlls) > 1:
  1844. exit("Found multiple Python dlls in %s." % (SDK["PYTHON"]))
  1845. py_dll = os.path.basename(py_dlls[0])
  1846. py_dllver = py_dll.strip(".DHLNOPTY_dhlnopty")
  1847. ver = py_dllver[0] + '.' + py_dllver[1:]
  1848. SDK["PYTHONVERSION"] = "python" + ver
  1849. os.environ["PYTHONHOME"] = SDK["PYTHON"]
  1850. running_ver = '%d.%d' % sys.version_info[:2]
  1851. if ver != running_ver:
  1852. Warn("running makepanda with Python %s, but building Panda3D with Python %s." % (running_ver, ver))
  1853. elif CrossCompiling() or (prefer_thirdparty_python and os.path.isdir(os.path.join(GetThirdpartyDir(), "python"))):
  1854. tp_python = os.path.join(GetThirdpartyDir(), "python")
  1855. if GetTarget() == 'darwin':
  1856. py_libs = glob.glob(tp_python + "/lib/libpython[0-9].[0-9].dylib") + \
  1857. glob.glob(tp_python + "/lib/libpython[0-9].[0-9][0-9].dylib")
  1858. else:
  1859. py_libs = glob.glob(tp_python + "/lib/libpython[0-9].[0-9].so") + \
  1860. glob.glob(tp_python + "/lib/libpython[0-9].[0-9][0-9].so")
  1861. if len(py_libs) == 0:
  1862. py_libs = glob.glob(tp_python + "/lib/libpython[0-9].[0-9].a") + \
  1863. glob.glob(tp_python + "/lib/libpython[0-9].[0-9][0-9].a")
  1864. if len(py_libs) == 0:
  1865. exit("Could not find the Python library in %s." % (tp_python))
  1866. elif len(py_libs) > 1:
  1867. exit("Found multiple Python libraries in %s." % (tp_python))
  1868. py_lib = os.path.basename(py_libs[0])
  1869. py_libver = py_lib.strip('.abdhilnopsty')
  1870. SDK["PYTHONVERSION"] = "python" + py_libver
  1871. SDK["PYTHONEXEC"] = tp_python + "/bin/" + SDK["PYTHONVERSION"]
  1872. SDK["PYTHON"] = tp_python + "/include/" + SDK["PYTHONVERSION"]
  1873. elif GetTarget() == 'darwin' and not PkgHasCustomLocation("PYTHON"):
  1874. # On macOS, search for the Python framework directory matching the
  1875. # version number of our current Python version.
  1876. sysroot = SDK.get("MACOSX", "")
  1877. version = sysconfig.get_python_version()
  1878. py_fwx = "{0}/System/Library/Frameworks/Python.framework/Versions/{1}".format(sysroot, version)
  1879. if not os.path.exists(py_fwx):
  1880. # Fall back to looking on the system.
  1881. py_fwx = "/Library/Frameworks/Python.framework/Versions/" + version
  1882. if not os.path.exists(py_fwx):
  1883. exit("Could not locate Python installation at %s" % (py_fwx))
  1884. SDK["PYTHON"] = py_fwx + "/Headers"
  1885. SDK["PYTHONVERSION"] = "python" + version + abiflags
  1886. SDK["PYTHONEXEC"] = py_fwx + "/bin/python" + version
  1887. # Avoid choosing the one in the thirdparty package dir.
  1888. PkgSetCustomLocation("PYTHON")
  1889. IncDirectory("PYTHON", py_fwx + "/include")
  1890. LibDirectory("PYTHON", py_fwx + "/lib")
  1891. #elif GetTarget() == 'windows':
  1892. # SDK["PYTHON"] = os.path.dirname(sysconfig.get_python_inc())
  1893. # SDK["PYTHONVERSION"] = "python" + sysconfig.get_python_version()
  1894. # SDK["PYTHONEXEC"] = sys.executable
  1895. else:
  1896. SDK["PYTHON"] = sysconfig.get_python_inc()
  1897. SDK["PYTHONVERSION"] = "python" + sysconfig.get_python_version() + abiflags
  1898. SDK["PYTHONEXEC"] = os.path.realpath(sys.executable)
  1899. if CrossCompiling():
  1900. # We need a version of Python we can run.
  1901. SDK["PYTHONEXEC"] = sys.executable
  1902. host_version = "python" + sysconfig.get_python_version() + abiflags
  1903. if SDK["PYTHONVERSION"] != host_version:
  1904. exit("Host Python version (%s) must be the same as target Python version (%s)!" % (host_version, SDK["PYTHONVERSION"]))
  1905. if GetVerbose():
  1906. print("Using Python %s build located at %s" % (SDK["PYTHONVERSION"][6:], SDK["PYTHON"]))
  1907. else:
  1908. print("Using Python %s" % (SDK["PYTHONVERSION"][6:]))
  1909. def SdkLocateVisualStudio(version=(10,0)):
  1910. if (GetHost() != "windows"): return
  1911. try:
  1912. msvcinfo = MSVCVERSIONINFO[version]
  1913. except:
  1914. exit("Couldn't get Visual Studio infomation with MSVC %s.%s version." % version)
  1915. vsversion = msvcinfo["vsversion"]
  1916. vsversion_str = "%s.%s" % vsversion
  1917. version_str = "%s.%s" % version
  1918. # try to use vswhere.exe
  1919. vswhere_path = LocateBinary("vswhere.exe")
  1920. if not vswhere_path:
  1921. if sys.platform == 'cygwin':
  1922. vswhere_path = "/cygdrive/c/Program Files/Microsoft Visual Studio/Installer/vswhere.exe"
  1923. else:
  1924. vswhere_path = "%s\\Microsoft Visual Studio\\Installer\\vswhere.exe" % GetProgramFiles()
  1925. if not os.path.isfile(vswhere_path):
  1926. vswhere_path = None
  1927. if not vswhere_path:
  1928. if sys.platform == 'cygwin':
  1929. vswhere_path = "/cygdrive/c/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe"
  1930. else:
  1931. vswhere_path = "%s\\Microsoft Visual Studio\\Installer\\vswhere.exe" % GetProgramFiles_x86()
  1932. if not os.path.isfile(vswhere_path):
  1933. vswhere_path = None
  1934. vsdir = 0
  1935. if vswhere_path:
  1936. min_vsversion = vsversion_str
  1937. max_vsversion = "%s.%s" % (vsversion[0]+1, 0)
  1938. vswhere_cmd = ["vswhere.exe", "-legacy", "-property", "installationPath",
  1939. "-version", "[{},{})".format(min_vsversion, max_vsversion)]
  1940. handle = subprocess.Popen(vswhere_cmd, executable=vswhere_path, stdout=subprocess.PIPE)
  1941. found_paths = handle.communicate()[0].splitlines()
  1942. if found_paths:
  1943. vsdir = found_paths[0].decode("utf-8") + "\\"
  1944. # try to use registry
  1945. if (vsdir == 0):
  1946. vsdir = GetRegistryKey("SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7", vsversion_str)
  1947. vcdir = GetRegistryKey("SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VC7", version_str)
  1948. if (vsdir != 0):
  1949. SDK["VISUALSTUDIO"] = vsdir
  1950. elif (vcdir != 0) and (vcdir[-4:] == "\\VC\\"):
  1951. vcdir = vcdir[:-3]
  1952. SDK["VISUALSTUDIO"] = vcdir
  1953. elif (os.path.isfile("C:\\Program Files\\Microsoft Visual Studio %s\\VC\\bin\\cl.exe" % (vsversion_str))):
  1954. SDK["VISUALSTUDIO"] = "C:\\Program Files\\Microsoft Visual Studio %s\\" % (vsversion_str)
  1955. elif (os.path.isfile("C:\\Program Files (x86)\\Microsoft Visual Studio %s\\VC\\bin\\cl.exe" % (vsversion_str))):
  1956. SDK["VISUALSTUDIO"] = "C:\\Program Files (x86)\\Microsoft Visual Studio %s\\" % (vsversion_str)
  1957. elif "VCINSTALLDIR" in os.environ:
  1958. vcdir = os.environ["VCINSTALLDIR"]
  1959. if (vcdir[-3:] == "\\VC"):
  1960. vcdir = vcdir[:-2]
  1961. elif (vcdir[-4:] == "\\VC\\"):
  1962. vcdir = vcdir[:-3]
  1963. SDK["VISUALSTUDIO"] = vcdir
  1964. else:
  1965. exit("Couldn't find %s. To use a different version, use the --msvc-version option." % msvcinfo["vsname"])
  1966. SDK["MSVC_VERSION"] = version
  1967. SDK["VISUALSTUDIO_VERSION"] = vsversion
  1968. if GetVerbose():
  1969. print("Using %s located at %s" % (msvcinfo["vsname"], SDK["VISUALSTUDIO"]))
  1970. else:
  1971. print("Using %s" % (msvcinfo["vsname"]))
  1972. print("Using MSVC %s" % version_str)
  1973. def SdkLocateWindows(version=None):
  1974. if GetTarget() != "windows" or GetHost() != "windows":
  1975. return
  1976. if version:
  1977. version = version.upper()
  1978. if version == '10':
  1979. version = '10.0'
  1980. if version and version.startswith('10.') and version.count('.') == 1:
  1981. # Choose the latest version of the Windows 10 SDK.
  1982. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10")
  1983. # Fallback in case we can't read the registry.
  1984. if not platsdk or not os.path.isdir(platsdk):
  1985. platsdk = "C:\\Program Files (x86)\\Windows Kits\\10\\"
  1986. if platsdk and os.path.isdir(platsdk):
  1987. incdirs = glob.glob(os.path.join(platsdk, 'Include', version + '.*.*'))
  1988. max_version = ()
  1989. for dir in incdirs:
  1990. verstring = os.path.basename(dir)
  1991. # Check that the important include directories exist.
  1992. if not os.path.isdir(os.path.join(dir, 'ucrt')):
  1993. continue
  1994. if not os.path.isdir(os.path.join(dir, 'shared')):
  1995. continue
  1996. if not os.path.isdir(os.path.join(dir, 'um')):
  1997. continue
  1998. if not os.path.isdir(os.path.join(platsdk, 'Lib', verstring, 'ucrt')):
  1999. continue
  2000. if not os.path.isdir(os.path.join(platsdk, 'Lib', verstring, 'um')):
  2001. continue
  2002. vertuple = tuple(map(int, verstring.split('.')))
  2003. if vertuple > max_version:
  2004. version = verstring
  2005. max_version = vertuple
  2006. if not max_version:
  2007. # No suitable version found.
  2008. platsdk = None
  2009. elif version and version.startswith('10.'):
  2010. # We chose a specific version of the Windows 10 SDK. Verify it exists.
  2011. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10")
  2012. # Fallback in case we can't read the registry.
  2013. if not platsdk or not os.path.isdir(platsdk):
  2014. platsdk = "C:\\Program Files (x86)\\Windows Kits\\10\\"
  2015. if version.count('.') == 2:
  2016. version += '.0'
  2017. if platsdk and not os.path.isdir(os.path.join(platsdk, 'Include', version)):
  2018. platsdk = None
  2019. elif version == '8.1' or not version:
  2020. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot81")
  2021. # Fallback in case we can't read the registry.
  2022. if not platsdk or not os.path.isdir(platsdk):
  2023. platsdk = "C:\\Program Files (x86)\\Windows Kits\\8.1\\"
  2024. if not version:
  2025. if not os.path.isdir(platsdk):
  2026. # Fall back to 7.1 SDK.
  2027. return SdkLocateWindows("7.1")
  2028. version = '8.1'
  2029. elif version == '8.0':
  2030. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot")
  2031. else:
  2032. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v" + version, "InstallationFolder")
  2033. DefSymbol("ALWAYS", "_USING_V110_SDK71_")
  2034. if not platsdk or not os.path.isdir(platsdk):
  2035. # Most common location. Worth a try.
  2036. platsdk = GetProgramFiles() + "\\Microsoft SDKs\\Windows\\v" + version
  2037. if not os.path.isdir(platsdk):
  2038. if not version.endswith('A'):
  2039. # Try the stripped-down version that is bundled with Visual Studio.
  2040. return SdkLocateWindows(version + 'A')
  2041. platsdk = None
  2042. if not platsdk or not os.path.isdir(platsdk):
  2043. exit("Couldn't find Windows SDK version %s. To use a different version, use the --windows-sdk option." % (version))
  2044. if not platsdk.endswith("\\"):
  2045. platsdk += "\\"
  2046. SDK["MSPLATFORM"] = platsdk
  2047. SDK["MSPLATFORM_VERSION"] = version
  2048. if GetVerbose():
  2049. print("Using Windows SDK %s located at %s" % (version, platsdk))
  2050. else:
  2051. print("Using Windows SDK %s" % (version))
  2052. def SdkLocateMacOSX(archs = []):
  2053. if (GetHost() != "darwin"): return
  2054. handle = os.popen("xcode-select -print-path")
  2055. xcode_dir = handle.read().strip().rstrip('/')
  2056. handle.close()
  2057. # Make a list of SDK versions that will work for us, then grab the latest.
  2058. sdk_versions = []
  2059. if 'arm64' not in archs:
  2060. # Prefer pre-10.14 for now so that we can keep building FMOD.
  2061. sdk_versions += ["10.13", "10.12", "10.11", "10.10", "10.9"]
  2062. sdk_versions += ["11.3", "11.1", "11.0"]
  2063. if 'arm64' not in archs:
  2064. sdk_versions += ["10.15", "10.14"]
  2065. for version in sdk_versions:
  2066. sdkname = "MacOSX" + version
  2067. if os.path.exists("/Library/Developer/CommandLineTools/SDKs/%s.sdk" % sdkname):
  2068. SDK["MACOSX"] = "/Library/Developer/CommandLineTools/SDKs/%s.sdk" % sdkname
  2069. return
  2070. elif os.path.exists("/Developer/SDKs/%s.sdk" % sdkname):
  2071. SDK["MACOSX"] = "/Developer/SDKs/%s.sdk" % sdkname
  2072. return
  2073. elif os.path.exists("/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/%s.sdk" % sdkname):
  2074. SDK["MACOSX"] = "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/%s.sdk" % sdkname
  2075. return
  2076. elif xcode_dir and os.path.exists("%s/Platforms/MacOSX.platform/Developer/SDKs/%s.sdk" % (xcode_dir, sdkname)):
  2077. SDK["MACOSX"] = "%s/Platforms/MacOSX.platform/Developer/SDKs/%s.sdk" % (xcode_dir, sdkname)
  2078. return
  2079. exit("Couldn't find any suitable MacOSX SDK!")
  2080. def SdkLocateSpeedTree():
  2081. # Look for all of the SpeedTree SDK directories within the
  2082. # sdks/win32/speedtree dir, and pick the highest-numbered one.
  2083. dir = GetSdkDir("speedtree")
  2084. if not os.path.exists(dir):
  2085. return
  2086. speedtrees = []
  2087. for dirname in os.listdir(dir):
  2088. if dirname.startswith('SpeedTree SDK v'):
  2089. version = dirname[15:].split()[0]
  2090. version = tuple(map(int, version.split('.')))
  2091. speedtrees.append((version, dirname))
  2092. if not speedtrees:
  2093. # No installed SpeedTree SDK.
  2094. return
  2095. speedtrees.sort()
  2096. version, dirname = speedtrees[-1]
  2097. SDK["SPEEDTREE"] = os.path.join(dir, dirname)
  2098. SDK["SPEEDTREEAPI"] = "OpenGL"
  2099. SDK["SPEEDTREEVERSION"] = '%s.%s' % (version[0], version[1])
  2100. def SdkLocateAndroid():
  2101. """This actually locates the Android NDK, not the Android SDK.
  2102. NDK_ROOT must be set to its root directory."""
  2103. global TOOLCHAIN_PREFIX
  2104. if GetTarget() != 'android':
  2105. return
  2106. # Allow ANDROID_API/ANDROID_ABI to be used in makepanda.py.
  2107. if ANDROID_API is None:
  2108. SetTarget('android')
  2109. api = ANDROID_API
  2110. SDK["ANDROID_API"] = api
  2111. abi = ANDROID_ABI
  2112. SDK["ANDROID_ABI"] = abi
  2113. SDK["ANDROID_TRIPLE"] = ANDROID_TRIPLE
  2114. if GetHost() == 'android':
  2115. # Assume we're compiling from termux.
  2116. prefix = os.environ.get("PREFIX", "/data/data/com.termux/files/usr")
  2117. SDK["ANDROID_JAR"] = prefix + "/share/aapt/android.jar"
  2118. return
  2119. # Find the location of the Android SDK.
  2120. sdk_root = os.environ.get('ANDROID_HOME')
  2121. if not sdk_root or not os.path.isdir(sdk_root):
  2122. sdk_root = os.environ.get('ANDROID_SDK_ROOT')
  2123. # Try the default installation location on Windows.
  2124. if not sdk_root and GetHost() == 'windows':
  2125. sdk_root = os.path.expanduser(os.path.join('~', 'AppData', 'Local', 'Android', 'Sdk'))
  2126. if not sdk_root:
  2127. exit('ANDROID_SDK_ROOT must be set when compiling for Android!')
  2128. elif not os.path.isdir(sdk_root):
  2129. exit('Cannot find %s. Please install Android SDK and set ANDROID_SDK_ROOT or ANDROID_HOME.' % (sdk_root))
  2130. # Determine the NDK installation directory.
  2131. if os.environ.get('NDK_ROOT') or os.environ.get('ANDROID_NDK_ROOT'):
  2132. # We have an explicit setting from an environment variable.
  2133. ndk_root = os.environ.get('ANDROID_NDK_ROOT')
  2134. if not ndk_root or not os.path.isdir(ndk_root):
  2135. ndk_root = os.environ.get('NDK_ROOT')
  2136. if not ndk_root or not os.path.isdir(ndk_root):
  2137. exit("Cannot find %s. Please install Android NDK and set ANDROID_NDK_ROOT." % (ndk_root))
  2138. else:
  2139. # Often, it's installed in the ndk-bundle subdirectory of the SDK.
  2140. ndk_root = os.path.join(sdk_root, 'ndk-bundle')
  2141. if not os.path.isdir(os.path.join(ndk_root, 'toolchains')):
  2142. exit('Cannot find the Android NDK. Install it via the SDK manager or set the ANDROID_NDK_ROOT variable if you have installed it in a different location.')
  2143. SDK["ANDROID_NDK"] = ndk_root
  2144. # Determine the toolchain location.
  2145. prebuilt_dir = os.path.join(ndk_root, 'toolchains', 'llvm', 'prebuilt')
  2146. if not os.path.isdir(prebuilt_dir):
  2147. exit('Not found: %s (is the Android NDK installed?)' % (prebuilt_dir))
  2148. host_tag = GetHost() + '-x86'
  2149. if host_64:
  2150. host_tag += '_64'
  2151. elif host_tag == 'windows-x86':
  2152. host_tag = 'windows'
  2153. prebuilt_dir = os.path.join(prebuilt_dir, host_tag)
  2154. if host_tag == 'windows-x86_64' and not os.path.isdir(prebuilt_dir):
  2155. # Try the 32-bits toolchain instead.
  2156. host_tag = 'windows'
  2157. prebuilt_dir = os.path.join(prebuilt_dir, host_tag)
  2158. SDK["ANDROID_TOOLCHAIN"] = prebuilt_dir
  2159. # And locate the GCC toolchain, which is needed for some tools (eg. as/ld)
  2160. arch = GetTargetArch()
  2161. for opt in (TOOLCHAIN_PREFIX + '4.9', arch + '-4.9', TOOLCHAIN_PREFIX + '4.8', arch + '-4.8'):
  2162. if os.path.isdir(os.path.join(ndk_root, 'toolchains', opt)):
  2163. SDK["ANDROID_GCC_TOOLCHAIN"] = os.path.join(ndk_root, 'toolchains', opt, 'prebuilt', host_tag)
  2164. break
  2165. # The prebuilt binaries have no toolchain prefix.
  2166. TOOLCHAIN_PREFIX = ''
  2167. # Determine the sysroot directory.
  2168. if arch == 'armv7a':
  2169. arch_dir = 'arch-arm'
  2170. elif arch == 'aarch64':
  2171. arch_dir = 'arch-arm64'
  2172. else:
  2173. arch_dir = 'arch-' + arch
  2174. SDK["SYSROOT"] = os.path.join(ndk_root, 'platforms', 'android-%s' % (api), arch_dir).replace('\\', '/')
  2175. #IncDirectory("ALWAYS", os.path.join(SDK["SYSROOT"], 'usr', 'include'))
  2176. # We need to redistribute the C++ standard library.
  2177. stdlibc = os.path.join(ndk_root, 'sources', 'cxx-stl', 'llvm-libc++')
  2178. stl_lib = os.path.join(stdlibc, 'libs', abi, 'libc++_shared.so')
  2179. CopyFile(os.path.join(GetOutputDir(), 'lib', 'libc++_shared.so'), stl_lib)
  2180. # The Android support library polyfills C++ features not available in the
  2181. # STL that ships with Android.
  2182. #support = os.path.join(ndk_root, 'sources', 'android', 'support', 'include')
  2183. #IncDirectory("ALWAYS", support.replace('\\', '/'))
  2184. if api < 21:
  2185. LibName("ALWAYS", "-landroid_support")
  2186. # Determine the location of android.jar.
  2187. SDK["ANDROID_JAR"] = os.path.join(sdk_root, 'platforms', 'android-%s' % (api), 'android.jar')
  2188. if not os.path.isfile(SDK["ANDROID_JAR"]):
  2189. exit("Cannot find %s. Install platform API level %s via the SDK manager or change the targeted API level with --target=android-#" % (SDK["ANDROID_JAR"], api))
  2190. # Which build tools versions do we have? Pick the latest.
  2191. versions = []
  2192. for version in os.listdir(os.path.join(sdk_root, "build-tools")):
  2193. match = re.match('([0-9]+)\\.([0-9]+)\\.([0-9]+)', version)
  2194. if match:
  2195. version_tuple = int(match.group(1)), int(match.group(2)), int(match.group(3))
  2196. versions.append(version_tuple)
  2197. versions.sort()
  2198. if versions:
  2199. version = versions[-1]
  2200. SDK["ANDROID_BUILD_TOOLS"] = os.path.join(sdk_root, "build-tools", "{0}.{1}.{2}".format(*version))
  2201. # And find the location of the Java compiler.
  2202. if GetHost() == "windows":
  2203. jdk_home = os.environ.get("JDK_HOME") or os.environ.get("JAVA_HOME")
  2204. if not jdk_home:
  2205. # Try to use the Java shipped with Android Studio.
  2206. studio_path = GetRegistryKey("SOFTWARE\\Android Studio", "Path", override64=False)
  2207. if studio_path and os.path.isdir(studio_path):
  2208. jdk_home = os.path.join(studio_path, "jre")
  2209. if not jdk_home or not os.path.isdir(jdk_home):
  2210. exit("Cannot find JDK. Please set JDK_HOME or JAVA_HOME.")
  2211. javac = os.path.join(jdk_home, "bin", "javac.exe")
  2212. if not os.path.isfile(javac):
  2213. exit("Cannot find %s. Install the JDK and set JDK_HOME or JAVA_HOME." % (javac))
  2214. SDK["JDK"] = jdk_home
  2215. ########################################################################
  2216. ##
  2217. ## SDK Auto-Disables
  2218. ##
  2219. ## Disable packages whose SDKs could not be found.
  2220. ##
  2221. ########################################################################
  2222. def SdkAutoDisableDirectX():
  2223. for ver in DXVERSIONS + ["DIRECTCAM"]:
  2224. if (PkgSkip(ver)==0):
  2225. if (ver not in SDK):
  2226. if (GetHost() == "windows"):
  2227. WARNINGS.append("I cannot locate SDK for "+ver)
  2228. WARNINGS.append("I have automatically added this command-line option: --no-"+ver.lower())
  2229. PkgDisable(ver)
  2230. else:
  2231. WARNINGS.append("Using "+ver+" sdk: "+SDK[ver])
  2232. def SdkAutoDisableMaya():
  2233. for (ver,key) in MAYAVERSIONINFO:
  2234. if (ver not in SDK) and (PkgSkip(ver)==0):
  2235. if (GetHost() == "windows"):
  2236. WARNINGS.append("The registry does not appear to contain a pointer to the "+ver+" SDK.")
  2237. else:
  2238. WARNINGS.append("I cannot locate SDK for "+ver)
  2239. WARNINGS.append("I have automatically added this command-line option: --no-"+ver.lower())
  2240. PkgDisable(ver)
  2241. def SdkAutoDisableMax():
  2242. for version,key1,key2,subdir in MAXVERSIONINFO:
  2243. if (PkgSkip(version)==0) and ((version not in SDK) or (version+"CS" not in SDK)):
  2244. if (GetHost() == "windows"):
  2245. if (version in SDK):
  2246. WARNINGS.append("Your copy of "+version+" does not include the character studio SDK")
  2247. else:
  2248. WARNINGS.append("The registry does not appear to contain a pointer to "+version)
  2249. WARNINGS.append("I have automatically added this command-line option: --no-"+version.lower())
  2250. PkgDisable(version)
  2251. def SdkAutoDisableSpeedTree():
  2252. if ("SPEEDTREE" not in SDK) and (PkgSkip("SPEEDTREE")==0):
  2253. PkgDisable("SPEEDTREE")
  2254. WARNINGS.append("I cannot locate SDK for SpeedTree")
  2255. WARNINGS.append("I have automatically added this command-line option: --no-speedtree")
  2256. ########################################################################
  2257. ##
  2258. ## Visual Studio comes with a script called VSVARS32.BAT, which
  2259. ## you need to run before using visual studio command-line tools.
  2260. ## The following python subroutine serves the same purpose.
  2261. ##
  2262. ########################################################################
  2263. def AddToPathEnv(path,add):
  2264. if path in os.environ:
  2265. if sys.platform == 'cygwin' and path != "PATH":
  2266. # INCLUDE, LIB, etc. must remain in Windows-style in cygwin.
  2267. os.environ[path] = add + ';' + os.environ[path]
  2268. else:
  2269. os.environ[path] = add + os.pathsep + os.environ[path]
  2270. else:
  2271. os.environ[path] = add
  2272. def SetupVisualStudioEnviron():
  2273. if ("VISUALSTUDIO" not in SDK):
  2274. exit("Could not find Visual Studio install directory")
  2275. if ("MSPLATFORM" not in SDK):
  2276. exit("Could not find the Microsoft Platform SDK")
  2277. if (SDK["VISUALSTUDIO_VERSION"] >= (15,0)):
  2278. try:
  2279. vsver_file = open(os.path.join(SDK["VISUALSTUDIO"],
  2280. "VC\\Auxiliary\\Build\\Microsoft.VCToolsVersion.default.txt"), "r")
  2281. SDK["VCTOOLSVERSION"] = vsver_file.readline().strip()
  2282. vcdir_suffix = "VC\\Tools\\MSVC\\%s\\" % SDK["VCTOOLSVERSION"]
  2283. except:
  2284. exit("Couldn't find tool version of %s." % MSVCVERSIONINFO[SDK["MSVC_VERSION"]]["vsname"])
  2285. else:
  2286. vcdir_suffix = "VC\\"
  2287. os.environ["VCINSTALLDIR"] = SDK["VISUALSTUDIO"] + vcdir_suffix
  2288. os.environ["WindowsSdkDir"] = SDK["MSPLATFORM"]
  2289. winsdk_ver = SDK["MSPLATFORM_VERSION"]
  2290. # Determine the directories to look in based on the architecture.
  2291. arch = GetTargetArch()
  2292. bindir = ""
  2293. libdir = ""
  2294. if ("VCTOOLSVERSION" in SDK):
  2295. bindir = "Host" + GetHostArch().upper() + "\\" + arch
  2296. libdir = arch
  2297. else:
  2298. if (arch == 'x64'):
  2299. bindir = 'amd64'
  2300. libdir = 'amd64'
  2301. elif (arch != 'x86'):
  2302. bindir = arch
  2303. libdir = arch
  2304. if (arch != 'x86' and GetHostArch() == 'x86'):
  2305. # Special version of the tools that run on x86.
  2306. bindir = 'x86_' + bindir
  2307. vc_binpath = SDK["VISUALSTUDIO"] + vcdir_suffix + "bin"
  2308. binpath = os.path.join(vc_binpath, bindir)
  2309. if not os.path.isfile(binpath + "\\cl.exe"):
  2310. # Try the x86 tools, those should work just as well.
  2311. if arch == 'x64' and os.path.isfile(vc_binpath + "\\x86_amd64\\cl.exe"):
  2312. binpath = "{0}\\x86_amd64;{0}".format(vc_binpath)
  2313. elif winsdk_ver.startswith('10.'):
  2314. 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." % binpath)
  2315. else:
  2316. exit("Couldn't find compilers in %s." % binpath)
  2317. AddToPathEnv("PATH", binpath)
  2318. AddToPathEnv("PATH", SDK["VISUALSTUDIO"] + "Common7\\IDE")
  2319. AddToPathEnv("INCLUDE", os.environ["VCINSTALLDIR"] + "include")
  2320. AddToPathEnv("INCLUDE", os.environ["VCINSTALLDIR"] + "atlmfc\\include")
  2321. AddToPathEnv("LIB", os.environ["VCINSTALLDIR"] + "lib\\" + libdir)
  2322. AddToPathEnv("LIB", os.environ["VCINSTALLDIR"] + "atlmfc\\lib\\" + libdir)
  2323. winsdk_ver = SDK["MSPLATFORM_VERSION"]
  2324. if winsdk_ver.startswith('10.'):
  2325. AddToPathEnv("PATH", SDK["MSPLATFORM"] + "bin\\" + arch)
  2326. AddToPathEnv("PATH", SDK["MSPLATFORM"] + "bin\\" + winsdk_ver + "\\" + arch)
  2327. # Windows Kit 10 introduces the "universal CRT".
  2328. inc_dir = SDK["MSPLATFORM"] + "Include\\" + winsdk_ver + "\\"
  2329. lib_dir = SDK["MSPLATFORM"] + "Lib\\" + winsdk_ver + "\\"
  2330. AddToPathEnv("INCLUDE", inc_dir + "shared")
  2331. AddToPathEnv("INCLUDE", inc_dir + "ucrt")
  2332. AddToPathEnv("INCLUDE", inc_dir + "um")
  2333. AddToPathEnv("LIB", lib_dir + "ucrt\\" + arch)
  2334. AddToPathEnv("LIB", lib_dir + "um\\" + arch)
  2335. elif winsdk_ver == '8.1':
  2336. AddToPathEnv("PATH", SDK["MSPLATFORM"] + "bin\\" + arch)
  2337. inc_dir = SDK["MSPLATFORM"] + "Include\\"
  2338. lib_dir = SDK["MSPLATFORM"] + "Lib\\winv6.3\\"
  2339. AddToPathEnv("INCLUDE", inc_dir + "shared")
  2340. AddToPathEnv("INCLUDE", inc_dir + "ucrt")
  2341. AddToPathEnv("INCLUDE", inc_dir + "um")
  2342. AddToPathEnv("LIB", lib_dir + "ucrt\\" + arch)
  2343. AddToPathEnv("LIB", lib_dir + "um\\" + arch)
  2344. else:
  2345. AddToPathEnv("PATH", SDK["MSPLATFORM"] + "bin")
  2346. AddToPathEnv("INCLUDE", SDK["MSPLATFORM"] + "include")
  2347. AddToPathEnv("INCLUDE", SDK["MSPLATFORM"] + "include\\atl")
  2348. AddToPathEnv("INCLUDE", SDK["MSPLATFORM"] + "include\\mfc")
  2349. if arch != 'x64':
  2350. AddToPathEnv("LIB", SDK["MSPLATFORM"] + "lib")
  2351. AddToPathEnv("PATH",SDK["VISUALSTUDIO"] + "VC\\redist\\x86\\Microsoft.VC100.CRT")
  2352. AddToPathEnv("PATH",SDK["VISUALSTUDIO"] + "VC\\redist\\x86\\Microsoft.VC100.MFC")
  2353. elif os.path.isdir(SDK["MSPLATFORM"] + "lib\\x64"):
  2354. AddToPathEnv("LIB", SDK["MSPLATFORM"] + "lib\\x64")
  2355. elif os.path.isdir(SDK["MSPLATFORM"] + "lib\\amd64"):
  2356. AddToPathEnv("LIB", SDK["MSPLATFORM"] + "lib\\amd64")
  2357. else:
  2358. exit("Could not locate 64-bits libraries in Windows SDK directory!\nUsing directory: %s" % SDK["MSPLATFORM"])
  2359. # Targeting the 7.1 SDK (which is the only way to have Windows XP support)
  2360. # with Visual Studio 2015+ requires use of the Universal CRT.
  2361. if winsdk_ver in ('7.1', '7.1A', '8.0', '8.1') and SDK["VISUALSTUDIO_VERSION"] >= (14,0):
  2362. win_kit = GetRegistryKey("SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10")
  2363. # Fallback in case we can't read the registry.
  2364. if not win_kit or not os.path.isdir(win_kit):
  2365. win_kit = "C:\\Program Files (x86)\\Windows Kits\\10\\"
  2366. elif not win_kit.endswith('\\'):
  2367. win_kit += '\\'
  2368. for vnum in 10150, 10240, 10586, 14393, 15063, 16299, 17134, 17763, 18362, 19041:
  2369. version = "10.0.{0}.0".format(vnum)
  2370. if os.path.isfile(win_kit + "Include\\" + version + "\\ucrt\\assert.h"):
  2371. print("Using Universal CRT %s" % (version))
  2372. break
  2373. AddToPathEnv("LIB", "%s\\Lib\\%s\\ucrt\\%s" % (win_kit, version, arch))
  2374. AddToPathEnv("INCLUDE", "%s\\Include\\%s\\ucrt" % (win_kit, version))
  2375. # Copy the DLLs to the bin directory.
  2376. CopyAllFiles(GetOutputDir() + "/bin/", win_kit + "Redist\\ucrt\\DLLs\\" + arch + "\\")
  2377. ########################################################################
  2378. #
  2379. # Include and Lib directories.
  2380. #
  2381. # These allow you to add include and lib directories to the
  2382. # compiler search paths. These methods accept a "package"
  2383. # parameter, which specifies which package the directory is
  2384. # associated with. The include/lib directory is not used
  2385. # if the package is not selected. The package can be 'ALWAYS'.
  2386. #
  2387. ########################################################################
  2388. INCDIRECTORIES = []
  2389. LIBDIRECTORIES = []
  2390. FRAMEWORKDIRECTORIES = []
  2391. LIBNAMES = []
  2392. DEFSYMBOLS = []
  2393. def IncDirectory(opt, dir):
  2394. INCDIRECTORIES.append((opt, dir))
  2395. def LibDirectory(opt, dir):
  2396. LIBDIRECTORIES.append((opt, dir))
  2397. def FrameworkDirectory(opt, dir):
  2398. FRAMEWORKDIRECTORIES.append((opt, dir))
  2399. def FindIncDirectory(opt):
  2400. # Find the include directory associated with this module
  2401. for mod, dir in INCDIRECTORIES:
  2402. if mod == opt:
  2403. return os.path.abspath(dir)
  2404. def FindLibDirectory(opt):
  2405. # Find the library directory associated with this module
  2406. for mod, dir in LIBDIRECTORIES:
  2407. if mod == opt:
  2408. return os.path.abspath(dir)
  2409. def FindOptDirectory(opt):
  2410. # Find the common directory associated with this module
  2411. # using the include and library directories as a guide
  2412. include_dir = FindIncDirectory(opt)
  2413. lib_dir = FindLibDirectory(opt)
  2414. if include_dir and lib_dir:
  2415. # The module's common directory is the common prefix of
  2416. # its include and library directory
  2417. common_dir = os.path.commonprefix([include_dir, lib_dir])
  2418. if common_dir:
  2419. return os.path.abspath(common_dir)
  2420. elif include_dir:
  2421. # The module's common directory is the parent of the include
  2422. # directory
  2423. return os.path.abspath(os.path.join(include_dir, os.pardir))
  2424. elif lib_dir:
  2425. # The module's common directory is the parent of the library
  2426. # directory
  2427. return os.path.abspath(os.path.join(lib_dir, os.pardir))
  2428. def LibName(opt, name):
  2429. # Check to see if the lib file actually exists for the thirdparty library given
  2430. # Are we a thirdparty library?
  2431. if name.startswith(GetThirdpartyDir()):
  2432. # Does this lib exist?
  2433. if not os.path.exists(name):
  2434. WARNINGS.append(name + " not found. Skipping Package " + opt)
  2435. if (opt in PkgListGet()):
  2436. if not PkgSkip(opt):
  2437. Warn("Could not locate thirdparty package %s, excluding from build" % (opt.lower()))
  2438. PkgDisable(opt)
  2439. return
  2440. else:
  2441. Error("Could not locate thirdparty package %s, aborting build" % (opt.lower()))
  2442. LIBNAMES.append((opt, name))
  2443. def DefSymbol(opt, sym, val=""):
  2444. DEFSYMBOLS.append((opt, sym, val))
  2445. ########################################################################
  2446. #
  2447. # This subroutine prepares the environment for the build.
  2448. #
  2449. ########################################################################
  2450. def SetupBuildEnvironment(compiler):
  2451. if GetVerbose():
  2452. print("Using compiler: %s" % compiler)
  2453. print("Host OS: %s" % GetHost())
  2454. print("Host arch: %s" % GetHostArch())
  2455. target = GetTarget()
  2456. if target != 'android':
  2457. print("Target OS: %s" % GetTarget())
  2458. else:
  2459. print("Target OS: %s (API level %d)" % (GetTarget(), ANDROID_API))
  2460. print("Target arch: %s" % GetTargetArch())
  2461. # Set to English so we can safely parse the result of gcc commands.
  2462. # Setting it to UTF-8 is necessary for Python 3 modules to import
  2463. # correctly.
  2464. os.environ["LC_ALL"] = "en_US.UTF-8"
  2465. os.environ["LANGUAGE"] = "en"
  2466. # In the case of Android, we have to put the toolchain on the PATH in order to use it.
  2467. if GetTarget() == 'android' and GetHost() != 'android':
  2468. AddToPathEnv("PATH", os.path.join(SDK["ANDROID_TOOLCHAIN"], "bin"))
  2469. if "ANDROID_BUILD_TOOLS" in SDK:
  2470. AddToPathEnv("PATH", SDK["ANDROID_BUILD_TOOLS"])
  2471. if "JDK" in SDK:
  2472. AddToPathEnv("PATH", os.path.join(SDK["JDK"], "bin"))
  2473. os.environ["JAVA_HOME"] = SDK["JDK"]
  2474. if compiler == "MSVC":
  2475. # Add the visual studio tools to PATH et al.
  2476. SetupVisualStudioEnviron()
  2477. if compiler == "GCC":
  2478. # Invoke gcc to determine the system library directories.
  2479. global SYS_LIB_DIRS, SYS_INC_DIRS
  2480. if sys.platform == "darwin":
  2481. # We need to add this one explicitly for some reason.
  2482. SYS_LIB_DIRS.append(SDK["MACOSX"] + "/usr/lib")
  2483. if not SDK.get("MACOSX"):
  2484. # gcc doesn't add this one, but we do want it:
  2485. local_lib = SDK.get("SYSROOT", "") + "/usr/local/lib"
  2486. if os.path.isdir(local_lib):
  2487. SYS_LIB_DIRS.append(local_lib)
  2488. sysroot_flag = ""
  2489. if SDK.get("MACOSX"):
  2490. # The default compiler in Leopard does not respect --sysroot correctly.
  2491. sysroot_flag = " -isysroot " + SDK["MACOSX"]
  2492. #if SDK.get("SYSROOT"):
  2493. # sysroot_flag = ' --sysroot=%s -no-canonical-prefixes' % (SDK["SYSROOT"])
  2494. if GetTarget() == "android":
  2495. sysroot_flag = " -target " + ANDROID_TRIPLE
  2496. # Extract the dirs from the line that starts with 'libraries: ='.
  2497. cmd = GetCXX() + " -print-search-dirs" + sysroot_flag
  2498. handle = os.popen(cmd)
  2499. for line in handle:
  2500. if not line.startswith('libraries: ='):
  2501. continue
  2502. line = line[12:].strip()
  2503. libdirs = line.split(':')
  2504. while libdirs:
  2505. libdir = os.path.normpath(libdirs.pop(0))
  2506. if os.path.isdir(libdir):
  2507. if libdir not in SYS_LIB_DIRS:
  2508. SYS_LIB_DIRS.append(libdir)
  2509. elif len(libdir) == 1:
  2510. # Oops, is this a drive letter? Prepend it to the next.
  2511. libdirs[0] = libdir + ':' + libdirs[0]
  2512. elif GetVerbose():
  2513. print("Ignoring non-existent library directory %s" % (libdir))
  2514. returnval = handle.close()
  2515. if returnval is not None and returnval != 0:
  2516. Warn("%s failed" % (cmd))
  2517. SYS_LIB_DIRS += [SDK.get("SYSROOT", "") + "/usr/lib"]
  2518. # The Android toolchain on Windows doesn't actually add this one.
  2519. if target == 'android' and GetHost() == 'windows':
  2520. libdir = SDK.get("SYSROOT", "") + "/usr/lib"
  2521. if GetTargetArch() == 'x86_64':
  2522. libdir += '64'
  2523. SYS_LIB_DIRS += [libdir]
  2524. # Now extract the preprocessor's include directories.
  2525. cmd = GetCXX() + " -x c++ -v -E " + os.devnull
  2526. cmd += sysroot_flag
  2527. null = open(os.devnull, 'w')
  2528. handle = subprocess.Popen(cmd, stdout=null, stderr=subprocess.PIPE, shell=True)
  2529. scanning = False
  2530. for line in handle.communicate()[1].splitlines():
  2531. line = line.decode('utf-8', 'replace')
  2532. # Start looking at a line that says: #include "..." search starts here
  2533. if not scanning:
  2534. if line.startswith('#include'):
  2535. scanning = True
  2536. continue
  2537. if sys.platform == "win32":
  2538. if not line.startswith(' '):
  2539. continue
  2540. else:
  2541. if not line.startswith(' /'):
  2542. continue
  2543. line = line.strip()
  2544. if line.endswith(" (framework directory)"):
  2545. pass
  2546. elif os.path.isdir(line):
  2547. SYS_INC_DIRS.append(os.path.normpath(line))
  2548. elif GetVerbose():
  2549. print("Ignoring non-existent include directory %s" % (line))
  2550. if handle.returncode != 0 or not SYS_INC_DIRS:
  2551. Warn("%s failed or did not produce the expected result" % (cmd))
  2552. sysroot = SDK.get("SYSROOT", "")
  2553. # Add some sensible directories as a fallback.
  2554. SYS_INC_DIRS = [
  2555. sysroot + "/usr/include",
  2556. sysroot + "/usr/local/include"
  2557. ]
  2558. pcbsd_inc = sysroot + "/usr/PCBSD/local/include"
  2559. if os.path.isdir(pcbsd_inc):
  2560. SYS_INC_DIRS.append(pcbsd_inc)
  2561. null.close()
  2562. # Print out the search paths
  2563. if GetVerbose():
  2564. print("System library search path:")
  2565. for dir in SYS_LIB_DIRS:
  2566. print(" " + dir)
  2567. print("System include search path:")
  2568. for dir in SYS_INC_DIRS:
  2569. print(" " + dir)
  2570. # If we're cross-compiling, no point in putting our output dirs on the path.
  2571. if CrossCompiling():
  2572. return
  2573. # Add our output directories to the environment.
  2574. builtdir = GetOutputDir()
  2575. AddToPathEnv("PYTHONPATH", builtdir)
  2576. AddToPathEnv("PANDA_PRC_DIR", os.path.join(builtdir, "etc"))
  2577. AddToPathEnv("PATH", os.path.join(builtdir, "bin"))
  2578. if GetHost() == 'windows':
  2579. # extension_native_helpers.py currently expects to find libpandaexpress on sys.path.
  2580. AddToPathEnv("PYTHONPATH", os.path.join(builtdir, "bin"))
  2581. AddToPathEnv("PATH", os.path.join(builtdir, "plugins"))
  2582. # Now for the special (DY)LD_LIBRARY_PATH on Unix-esque systems.
  2583. if GetHost() != 'windows':
  2584. # Get the current
  2585. ldpath = os.environ.get("LD_LIBRARY_PATH", "").split(os.pathsep)
  2586. if GetHost() == 'darwin':
  2587. dyldpath = os.environ.get("DYLD_LIBRARY_PATH", "").split(os.pathsep)
  2588. # Remove any potential current Panda installation lib dirs
  2589. for i in ldpath[:]:
  2590. if i.startswith("/usr/lib/panda3d") or \
  2591. i.startswith("/usr/local/panda"):
  2592. ldpath.remove(i)
  2593. if GetHost() == 'darwin':
  2594. for i in dyldpath[:]:
  2595. if i.startswith("/Applications/Panda3D") or \
  2596. i.startswith("/Developer/Panda3D"):
  2597. dyldpath.remove(i)
  2598. # Add built/lib/ to (DY)LD_LIBRARY_PATH
  2599. ldpath.insert(0, os.path.join(builtdir, 'lib'))
  2600. os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(ldpath)
  2601. if GetHost() == 'darwin':
  2602. dyldpath.insert(0, os.path.join(builtdir, 'lib'))
  2603. os.environ["DYLD_LIBRARY_PATH"] = os.pathsep.join(dyldpath)
  2604. # macOS 10.11 removed DYLD_LIBRARY_PATH, but we still need to pass
  2605. # on our lib directory to ppackage, so add it to PATH instead.
  2606. os.environ["PATH"] = os.path.join(builtdir, 'lib') + ':' + os.environ.get("PATH", "")
  2607. # Workaround around compile issue on PCBSD
  2608. if (os.path.exists("/usr/PCBSD")):
  2609. os.environ["LD_LIBRARY_PATH"] += os.pathsep + "/usr/PCBSD/local/lib"
  2610. ########################################################################
  2611. ##
  2612. ## Routines to copy files into the build tree
  2613. ##
  2614. ########################################################################
  2615. def CopyFile(dstfile, srcfile):
  2616. if dstfile[-1] == '/':
  2617. dstfile += os.path.basename(srcfile)
  2618. if NeedsBuild([dstfile], [srcfile]):
  2619. if os.path.islink(srcfile):
  2620. # Preserve symlinks
  2621. if os.path.isfile(dstfile) or os.path.islink(dstfile):
  2622. print("Removing file %s" % (dstfile))
  2623. os.unlink(dstfile)
  2624. elif os.path.isdir(dstfile):
  2625. print("Removing directory %s" % (dstfile))
  2626. shutil.rmtree(dstfile)
  2627. os.symlink(os.readlink(srcfile), dstfile)
  2628. else:
  2629. WriteBinaryFile(dstfile, ReadBinaryFile(srcfile))
  2630. if sys.platform == 'cygwin' and os.path.splitext(dstfile)[1].lower() in ('.dll', '.exe'):
  2631. os.chmod(dstfile, 0o755)
  2632. JustBuilt([dstfile], [srcfile])
  2633. def CopyAllFiles(dstdir, srcdir, suffix=""):
  2634. for x in GetDirectoryContents(srcdir, ["*"+suffix]):
  2635. CopyFile(dstdir + x, srcdir + x)
  2636. def CopyAllHeaders(dir, skip=[]):
  2637. for filename in GetDirectoryContents(dir, ["*.h", "*.I", "*.T"], skip):
  2638. srcfile = dir + "/" + filename
  2639. dstfile = OUTPUTDIR + "/include/" + filename
  2640. if (NeedsBuild([dstfile], [srcfile])):
  2641. WriteBinaryFile(dstfile, ReadBinaryFile(srcfile))
  2642. JustBuilt([dstfile], [srcfile])
  2643. def CopyTree(dstdir, srcdir, omitVCS=True, exclude=()):
  2644. if os.path.isdir(dstdir):
  2645. source_entries = os.listdir(srcdir)
  2646. for entry in source_entries:
  2647. srcpth = os.path.join(srcdir, entry)
  2648. dstpth = os.path.join(dstdir, entry)
  2649. if entry in exclude:
  2650. continue
  2651. if os.path.islink(srcpth) or os.path.isfile(srcpth):
  2652. if not omitVCS or entry not in VCS_FILES:
  2653. CopyFile(dstpth, srcpth)
  2654. else:
  2655. if not omitVCS or entry not in VCS_DIRS:
  2656. CopyTree(dstpth, srcpth)
  2657. # Delete files in dstdir that are not in srcdir.
  2658. for entry in os.listdir(dstdir):
  2659. if entry not in source_entries or entry in exclude:
  2660. path = os.path.join(dstdir, entry)
  2661. if os.path.islink(path) or os.path.isfile(path):
  2662. os.remove(path)
  2663. elif os.path.isdir(path):
  2664. shutil.rmtree(path)
  2665. else:
  2666. if GetHost() == 'windows':
  2667. srcdir = srcdir.replace('/', '\\')
  2668. dstdir = dstdir.replace('/', '\\')
  2669. cmd = 'xcopy /I/Y/E/Q "' + srcdir + '" "' + dstdir + '"'
  2670. oscmd(cmd)
  2671. else:
  2672. if subprocess.call(['cp', '-R', '-f', srcdir, dstdir]) != 0:
  2673. exit("Copy failed.")
  2674. for entry in exclude:
  2675. path = os.path.join(dstdir, entry)
  2676. if os.path.islink(path) or os.path.isfile(path):
  2677. os.remove(path)
  2678. elif os.path.isdir(path):
  2679. shutil.rmtree(path)
  2680. if omitVCS:
  2681. DeleteVCS(dstdir)
  2682. def CopyPythonTree(dstdir, srcdir, threads=0):
  2683. if (not os.path.isdir(dstdir)):
  2684. os.mkdir(dstdir)
  2685. exclude_files = set(VCS_FILES)
  2686. exclude_files.add('panda3d.py')
  2687. for entry in os.listdir(srcdir):
  2688. srcpth = os.path.join(srcdir, entry)
  2689. dstpth = os.path.join(dstdir, entry)
  2690. if os.path.isfile(srcpth):
  2691. base, ext = os.path.splitext(entry)
  2692. if entry not in exclude_files and ext not in SUFFIX_INC + ['.pyc', '.pyo']:
  2693. if (NeedsBuild([dstpth], [srcpth])):
  2694. WriteBinaryFile(dstpth, ReadBinaryFile(srcpth))
  2695. JustBuilt([dstpth], [srcpth])
  2696. elif entry not in VCS_DIRS:
  2697. CopyPythonTree(dstpth, srcpth, threads=threads)
  2698. ########################################################################
  2699. ##
  2700. ## Parse setup.cfg to extract the version number.
  2701. ##
  2702. ########################################################################
  2703. cfg_parser = None
  2704. def GetMetadataValue(key):
  2705. global cfg_parser
  2706. if not cfg_parser:
  2707. # Parse the metadata from the setup.cfg file.
  2708. cfg_parser = configparser.ConfigParser()
  2709. path = os.path.join(os.path.dirname(__file__), '..', 'setup.cfg')
  2710. assert cfg_parser.read(path), "Could not read setup.cfg file."
  2711. value = cfg_parser.get('metadata', key)
  2712. if key == 'classifiers':
  2713. value = value.strip().split('\n')
  2714. return value
  2715. # This function is being phased out.
  2716. def ParsePandaVersion(fn):
  2717. try:
  2718. f = open(fn, "r")
  2719. pattern = re.compile('^[ \t]*[#][ \t]*define[ \t]+PANDA_VERSION[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)')
  2720. for line in f:
  2721. match = pattern.match(line, 0)
  2722. if (match):
  2723. f.close()
  2724. return match.group(1) + "." + match.group(2) + "." + match.group(3)
  2725. f.close()
  2726. except:
  2727. pass
  2728. return "0.0.0"
  2729. ##########################################################################################
  2730. #
  2731. # Utility function to generate a resource file
  2732. #
  2733. ##########################################################################################
  2734. RESOURCE_FILE_TEMPLATE = """VS_VERSION_INFO VERSIONINFO
  2735. FILEVERSION %(commaversion)s
  2736. PRODUCTVERSION %(commaversion)s
  2737. FILEFLAGSMASK 0x3fL
  2738. FILEFLAGS %(debugflag)s
  2739. FILEOS 0x40004L
  2740. FILETYPE 0x2L
  2741. FILESUBTYPE 0x0L
  2742. BEGIN
  2743. BLOCK "StringFileInfo"
  2744. BEGIN
  2745. BLOCK "040904e4"
  2746. BEGIN
  2747. VALUE "FileDescription", "%(description)s\\0"
  2748. VALUE "FileVersion", "%(dotversion)s"
  2749. VALUE "LegalTrademarks", "\\0"
  2750. VALUE "MIMEType", "%(mimetype)s\\0"
  2751. VALUE "FileExtents", "%(extension)s\\0"
  2752. VALUE "FileOpenName", "%(filedesc)s\\0"
  2753. VALUE "OLESelfRegister", "\\0"
  2754. VALUE "OriginalFilename", "%(filename)s\\0"
  2755. VALUE "ProductName", "%(name)s %(version)s\\0"
  2756. VALUE "ProductVersion", "%(dotversion)s"
  2757. END
  2758. END
  2759. BLOCK "VarFileInfo"
  2760. BEGIN
  2761. VALUE "Translation", 0x409, 1252
  2762. END
  2763. END
  2764. """
  2765. def GenerateResourceFile(**kwargs):
  2766. if "debugflag" not in kwargs:
  2767. if GetOptimize() <= 2:
  2768. kwargs["debugflag"] = "0x1L"
  2769. else:
  2770. kwargs["debugflag"] = "0x0L"
  2771. kwargs["dotversion"] = kwargs["version"]
  2772. if len(kwargs["dotversion"].split(".")) == 3:
  2773. kwargs["dotversion"] += ".0"
  2774. if "commaversion" not in kwargs:
  2775. kwargs["commaversion"] = kwargs["dotversion"].replace(".", ",")
  2776. rcdata = ""
  2777. if "noinclude" not in kwargs:
  2778. rcdata += "#define APSTUDIO_READONLY_SYMBOLS\n"
  2779. rcdata += "#include \"winresrc.h\"\n"
  2780. rcdata += "#undef APSTUDIO_READONLY_SYMBOLS\n"
  2781. rcdata += RESOURCE_FILE_TEMPLATE % kwargs
  2782. if "icon" in kwargs:
  2783. rcdata += "\nICON_FILE ICON \"%s\"\n" % kwargs["icon"]
  2784. return rcdata
  2785. def WriteResourceFile(basename, **kwargs):
  2786. if not basename.endswith(".rc"):
  2787. basename += ".rc"
  2788. basename = GetOutputDir() + "/include/" + basename
  2789. ConditionalWriteFile(basename, GenerateResourceFile(**kwargs))
  2790. return basename
  2791. def GenerateEmbeddedStringFile(string_name, data):
  2792. yield 'extern const char %s[] = {\n' % (string_name)
  2793. i = 0
  2794. for byte in data:
  2795. if i == 0:
  2796. yield ' '
  2797. yield ' 0x%02x,' % (byte)
  2798. i += 1
  2799. if i >= 12:
  2800. yield '\n'
  2801. i = 0
  2802. yield '\n};\n'
  2803. def WriteEmbeddedStringFile(basename, inputs, string_name=None):
  2804. if os.path.splitext(basename)[1] not in SUFFIX_INC:
  2805. basename += '.cxx'
  2806. target = GetOutputDir() + "/tmp/" + basename
  2807. if string_name is None:
  2808. string_name = os.path.basename(os.path.splitext(target)[0])
  2809. string_name = string_name.replace('-', '_')
  2810. data = bytearray()
  2811. for input in inputs:
  2812. fp = open(input, 'rb')
  2813. # Insert a #line so that we get meaningful compile/assert errors when
  2814. # the result is inserted by interrogate_module into generated code.
  2815. if os.path.splitext(input)[1] in SUFFIX_INC:
  2816. line = '#line 1 "%s"\n' % (input)
  2817. data += bytearray(line.encode('ascii', 'replace'))
  2818. data += bytearray(fp.read())
  2819. fp.close()
  2820. data.append(0)
  2821. output = ''.join(GenerateEmbeddedStringFile(string_name, data))
  2822. ConditionalWriteFile(target, output)
  2823. return target
  2824. ########################################################################
  2825. ##
  2826. ## FindLocation
  2827. ##
  2828. ########################################################################
  2829. ORIG_EXT = {}
  2830. PYABI_SPECIFIC = set()
  2831. WARNED_FILES = set()
  2832. def GetOrigExt(x):
  2833. return ORIG_EXT[x]
  2834. def SetOrigExt(x, v):
  2835. ORIG_EXT[x] = v
  2836. def GetExtensionSuffix():
  2837. if CrossCompiling():
  2838. return '.{0}.so'.format(GetPythonABI())
  2839. else:
  2840. import _imp
  2841. return _imp.extension_suffixes()[0]
  2842. def GetPythonABI():
  2843. if not CrossCompiling():
  2844. soabi = sysconfig.get_config_var('SOABI')
  2845. if soabi:
  2846. return soabi
  2847. soabi = 'cpython-%d%d' % (sys.version_info[:2])
  2848. if sys.version_info >= (3, 8):
  2849. return soabi
  2850. debug_flag = sysconfig.get_config_var('Py_DEBUG')
  2851. if (debug_flag is None and hasattr(sys, 'gettotalrefcount')) or debug_flag:
  2852. soabi += 'd'
  2853. malloc_flag = sysconfig.get_config_var('WITH_PYMALLOC')
  2854. if malloc_flag is None or malloc_flag:
  2855. soabi += 'm'
  2856. return soabi
  2857. def CalcLocation(fn, ipath):
  2858. if fn.startswith("panda3d/") and fn.endswith(".py"):
  2859. return OUTPUTDIR + "/" + fn
  2860. if (fn.endswith(".class")):return OUTPUTDIR+"/classes/"+fn
  2861. if (fn.count("/")): return fn
  2862. dllext = ""
  2863. target = GetTarget()
  2864. if (GetOptimize() <= 2 and target == 'windows'): dllext = "_d"
  2865. if (fn == "AndroidManifest.xml"): return OUTPUTDIR+"/"+fn
  2866. if (fn == "classes.dex"): return OUTPUTDIR+"/"+fn
  2867. if (fn.endswith(".cxx")): return CxxFindSource(fn, ipath)
  2868. if (fn.endswith(".I")): return CxxFindSource(fn, ipath)
  2869. if (fn.endswith(".h")): return CxxFindSource(fn, ipath)
  2870. if (fn.endswith(".c")): return CxxFindSource(fn, ipath)
  2871. if (fn.endswith(".py")): return CxxFindSource(fn, ipath)
  2872. if (fn.endswith(".yxx")): return CxxFindSource(fn, ipath)
  2873. if (fn.endswith(".lxx")): return CxxFindSource(fn, ipath)
  2874. if (fn.endswith(".xml")): return CxxFindSource(fn, ipath)
  2875. if (fn.endswith(".java")):return CxxFindSource(fn, ipath)
  2876. if (fn.endswith(".egg")): return OUTPUTDIR+"/models/"+fn
  2877. if (fn.endswith(".egg.pz")):return OUTPUTDIR+"/models/"+fn
  2878. if (fn.endswith(".pyd")): return OUTPUTDIR+"/panda3d/"+fn[:-4]+GetExtensionSuffix()
  2879. if (target == 'windows'):
  2880. if (fn.endswith(".def")): return CxxFindSource(fn, ipath)
  2881. if (fn.endswith(".rc")): return CxxFindSource(fn, ipath)
  2882. if (fn.endswith(".idl")): return CxxFindSource(fn, ipath)
  2883. if (fn.endswith(".obj")): return OUTPUTDIR+"/tmp/"+fn
  2884. if (fn.endswith(".res")): return OUTPUTDIR+"/tmp/"+fn
  2885. if (fn.endswith(".tlb")): return OUTPUTDIR+"/tmp/"+fn
  2886. if (fn.endswith(".dll")): return OUTPUTDIR+"/bin/"+fn[:-4]+dllext+".dll"
  2887. if (fn.endswith(".ocx")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".ocx"
  2888. if (fn.endswith(".mll")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".mll"
  2889. if (fn.endswith(".dlo")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".dlo"
  2890. if (fn.endswith(".dli")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".dli"
  2891. if (fn.endswith(".dle")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".dle"
  2892. if (fn.endswith(".plugin")):return OUTPUTDIR+"/plugins/"+fn[:-7]+dllext+".dll"
  2893. if (fn.endswith(".exe")): return OUTPUTDIR+"/bin/"+fn
  2894. if (fn.endswith(".p3d")): return OUTPUTDIR+"/bin/"+fn
  2895. if (fn.endswith(".lib")): return OUTPUTDIR+"/lib/"+fn[:-4]+dllext+".lib"
  2896. if (fn.endswith(".ilb")): return OUTPUTDIR+"/tmp/"+fn[:-4]+dllext+".lib"
  2897. elif (target == 'darwin'):
  2898. if (fn.endswith(".mm")): return CxxFindSource(fn, ipath)
  2899. if (fn.endswith(".r")): return CxxFindSource(fn, ipath)
  2900. if (fn.endswith(".plist")): return CxxFindSource(fn, ipath)
  2901. if (fn.endswith(".obj")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".o"
  2902. if (fn.endswith(".dll")): return OUTPUTDIR+"/lib/"+fn[:-4]+".dylib"
  2903. if (fn.endswith(".mll")): return OUTPUTDIR+"/plugins/"+fn
  2904. if (fn.endswith(".exe")): return OUTPUTDIR+"/bin/"+fn[:-4]
  2905. if (fn.endswith(".p3d")): return OUTPUTDIR+"/bin/"+fn[:-4]
  2906. if (fn.endswith(".lib")): return OUTPUTDIR+"/lib/"+fn[:-4]+".a"
  2907. if (fn.endswith(".ilb")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".a"
  2908. if (fn.endswith(".rsrc")): return OUTPUTDIR+"/tmp/"+fn
  2909. if (fn.endswith(".plugin")):return OUTPUTDIR+"/plugins/"+fn
  2910. if (fn.endswith(".app")): return OUTPUTDIR+"/bin/"+fn
  2911. else:
  2912. if (fn.endswith(".obj")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".o"
  2913. if (fn.endswith(".dll")): return OUTPUTDIR+"/lib/"+fn[:-4]+".so"
  2914. if (fn.endswith(".mll")): return OUTPUTDIR+"/plugins/"+fn
  2915. if (fn.endswith(".plugin")):return OUTPUTDIR+"/plugins/"+fn[:-7]+dllext+".so"
  2916. if (fn.endswith(".exe")): return OUTPUTDIR+"/bin/"+fn[:-4]
  2917. if (fn.endswith(".p3d")): return OUTPUTDIR+"/bin/"+fn[:-4]
  2918. if (fn.endswith(".lib")): return OUTPUTDIR+"/lib/"+fn[:-4]+".a"
  2919. if (fn.endswith(".ilb")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".a"
  2920. if (fn.endswith(".dat")): return OUTPUTDIR+"/tmp/"+fn
  2921. if (fn.endswith(".in")): return OUTPUTDIR+"/pandac/input/"+fn
  2922. return fn
  2923. def FindLocation(fn, ipath, pyabi=None):
  2924. if GetLinkAllStatic():
  2925. if fn.endswith(".dll"):
  2926. fn = fn[:-4] + ".lib"
  2927. elif fn.endswith(".pyd"):
  2928. fn = "libpy.panda3d." \
  2929. + os.path.splitext(fn[:-4] + GetExtensionSuffix())[0] + ".lib"
  2930. loc = CalcLocation(fn, ipath)
  2931. base, ext = os.path.splitext(fn)
  2932. # If this is a target created with PyTargetAdd, we need to make sure it
  2933. # it put in a Python-version-specific directory.
  2934. if loc in PYABI_SPECIFIC:
  2935. if loc.startswith(OUTPUTDIR + "/tmp"):
  2936. if pyabi is not None:
  2937. loc = OUTPUTDIR + "/tmp/" + pyabi + loc[len(OUTPUTDIR) + 4:]
  2938. else:
  2939. raise RuntimeError("%s is a Python-specific target, use PyTargetAdd instead of TargetAdd" % (fn))
  2940. elif ext != ".pyd" and loc not in WARNED_FILES:
  2941. WARNED_FILES.add(loc)
  2942. Warn("file depends on Python but is not in an ABI-specific directory:", loc)
  2943. ORIG_EXT[loc] = ext
  2944. return loc
  2945. ########################################################################
  2946. ##
  2947. ## These files maintain a python_versions.json file in the built/tmp
  2948. ## directory that can be used by the other scripts in this directory.
  2949. ##
  2950. ########################################################################
  2951. def GetCurrentPythonVersionInfo():
  2952. if PkgSkip("PYTHON"):
  2953. return
  2954. from distutils.sysconfig import get_python_lib
  2955. return {
  2956. "version": SDK["PYTHONVERSION"][6:].rstrip('dmu'),
  2957. "soabi": GetPythonABI(),
  2958. "ext_suffix": GetExtensionSuffix(),
  2959. "executable": sys.executable,
  2960. "purelib": get_python_lib(False),
  2961. "platlib": get_python_lib(True),
  2962. }
  2963. def UpdatePythonVersionInfoFile(new_info):
  2964. import json
  2965. json_file = os.path.join(GetOutputDir(), "tmp", "python_versions.json")
  2966. json_data = []
  2967. if os.path.isfile(json_file) and not PkgSkip("PYTHON"):
  2968. try:
  2969. with open(json_file, 'r') as fh:
  2970. json_data = json.load(fh)
  2971. except:
  2972. json_data = []
  2973. # Prune the list by removing the entries that conflict with our build,
  2974. # plus the entries that no longer exist, and the EOL Python versions
  2975. for version_info in json_data[:]:
  2976. core_pyd = os.path.join(GetOutputDir(), "panda3d", "core" + version_info["ext_suffix"])
  2977. if version_info["ext_suffix"] == new_info["ext_suffix"] or \
  2978. version_info["soabi"] == new_info["soabi"] or \
  2979. not os.path.isfile(core_pyd) or \
  2980. version_info["version"].split(".", 1)[0] == "2" or \
  2981. version_info["version"] in ("3.0", "3.1", "3.2", "3.3", "3.4", "3.5"):
  2982. json_data.remove(version_info)
  2983. if not PkgSkip("PYTHON"):
  2984. json_data.append(new_info)
  2985. if VERBOSE:
  2986. print("Writing %s" % (json_file))
  2987. with open(json_file, 'w') as fh:
  2988. json.dump(json_data, fh, indent=4)
  2989. def ReadPythonVersionInfoFile():
  2990. import json
  2991. json_file = os.path.join(GetOutputDir(), "tmp", "python_versions.json")
  2992. if os.path.isfile(json_file):
  2993. try:
  2994. json_data = json.load(open(json_file, 'r'))
  2995. except:
  2996. pass
  2997. # Don't include unsupported versions of Python.
  2998. for version_info in json_data[:]:
  2999. if version_info["version"] in ("2.6", "2.7", "3.0", "3.1", "3.2", "3.3", "3.4"):
  3000. json_data.remove(version_info)
  3001. return json_data
  3002. return []
  3003. ########################################################################
  3004. ##
  3005. ## TargetAdd
  3006. ##
  3007. ## Makepanda maintains a list of make-targets. Each target has
  3008. ## these attributes:
  3009. ##
  3010. ## name - the name of the file being created.
  3011. ## ext - the original file extension, prior to OS-specific translation
  3012. ## inputs - the names of the input files to the compiler
  3013. ## deps - other input files that the target also depends on
  3014. ## opts - compiler options, a catch-all category
  3015. ##
  3016. ## TargetAdd will create the target if it does not exist. Then,
  3017. ## depending on what options you pass, it will push data onto these
  3018. ## various target attributes. This is cumulative: for example, if
  3019. ## you use TargetAdd to add compiler options, then use TargetAdd
  3020. ## again with more compiler options, both sets of options will be
  3021. ## included.
  3022. ##
  3023. ## TargetAdd does some automatic dependency generation on C++ files.
  3024. ## It will scan these files for include-files and automatically push
  3025. ## the include files onto the list of dependencies. In order to do
  3026. ## this, it needs an include-file search path. So if you supply
  3027. ## any C++ input, you also need to supply compiler options containing
  3028. ## include-directories, or alternately, a separate ipath parameter.
  3029. ##
  3030. ## The main body of 'makepanda' is a long list of TargetAdd
  3031. ## directives building up a giant list of make targets. Then,
  3032. ## finally, the targets are run and panda is built.
  3033. ##
  3034. ## Makepanda's dependency system does not understand multiple
  3035. ## outputs from a single build step. When a build step generates
  3036. ## a primary output file and a secondary output file, it is
  3037. ## necessary to trick the dependency system. Insert a dummy
  3038. ## build step that "generates" the secondary output file, using
  3039. ## the primary output file as an input. There is a special
  3040. ## compiler option DEPENDENCYONLY that creates such a dummy
  3041. ## build-step. There are two cases where dummy build steps must
  3042. ## be inserted: bison generates an OBJ and a secondary header
  3043. ## file, interrogate generates an IN and a secondary IGATE.OBJ.
  3044. ##
  3045. ## PyTargetAdd is a special version for targets that depend on Python.
  3046. ## It will create a target for each Python version we are building with,
  3047. ## ensuring that builds with different Python versions won't conflict
  3048. ## when we build for multiple Python ABIs side-by-side.
  3049. ##
  3050. ########################################################################
  3051. class Target:
  3052. pass
  3053. TARGET_LIST = []
  3054. TARGET_TABLE = {}
  3055. def TargetAdd(target, dummy=0, opts=[], input=[], dep=[], ipath=None, winrc=None, pyabi=None):
  3056. if dummy != 0:
  3057. exit("Syntax error in TargetAdd " + target)
  3058. if ipath is None:
  3059. ipath = opts
  3060. if not ipath:
  3061. ipath = []
  3062. if isinstance(input, str):
  3063. input = [input]
  3064. if isinstance(dep, str):
  3065. dep = [dep]
  3066. if target.endswith(".pyd") and not pyabi:
  3067. raise RuntimeError("Use PyTargetAdd to build .pyd targets")
  3068. full = FindLocation(target, [OUTPUTDIR + "/include"], pyabi=pyabi)
  3069. if full not in TARGET_TABLE:
  3070. t = Target()
  3071. t.name = full
  3072. t.inputs = []
  3073. t.deps = {}
  3074. t.opts = []
  3075. TARGET_TABLE[full] = t
  3076. TARGET_LIST.append(t)
  3077. else:
  3078. t = TARGET_TABLE[full]
  3079. for x in opts:
  3080. if x not in t.opts:
  3081. t.opts.append(x)
  3082. ipath = [OUTPUTDIR + "/tmp"] + GetListOption(ipath, "DIR:") + [OUTPUTDIR+"/include"]
  3083. for x in input:
  3084. fullinput = FindLocation(x, ipath, pyabi=pyabi)
  3085. t.inputs.append(fullinput)
  3086. # Don't re-link a library or binary if just its dependency dlls have been altered.
  3087. # This should work out fine in most cases, and often reduces recompilation time.
  3088. if os.path.splitext(x)[-1] not in SUFFIX_DLL:
  3089. t.deps[fullinput] = 1
  3090. (base,suffix) = os.path.splitext(x)
  3091. if SUFFIX_INC.count(suffix):
  3092. for d in CxxCalcDependencies(fullinput, ipath, []):
  3093. t.deps[d] = 1
  3094. elif suffix == '.java':
  3095. for d in JavaCalcDependencies(fullinput, OUTPUTDIR + "/classes"):
  3096. t.deps[d] = 1
  3097. # If we are linking statically, add the source DLL's dynamic dependencies.
  3098. if GetLinkAllStatic() and ORIG_EXT[fullinput] == '.lib' and fullinput in TARGET_TABLE:
  3099. tdep = TARGET_TABLE[fullinput]
  3100. for y in tdep.inputs:
  3101. if ORIG_EXT[y] == '.lib':
  3102. t.inputs.append(y)
  3103. for opt, _ in LIBNAMES + LIBDIRECTORIES + FRAMEWORKDIRECTORIES:
  3104. if opt in tdep.opts and opt not in t.opts:
  3105. t.opts.append(opt)
  3106. if x.endswith(".in"):
  3107. # Mark the _igate.cxx file as a dependency also.
  3108. outbase = os.path.basename(x)[:-3]
  3109. woutc = GetOutputDir()+"/tmp/"+outbase+"_igate.cxx"
  3110. t.deps[woutc] = 1
  3111. if target.endswith(".in"):
  3112. # Add any .N files.
  3113. base, ext = os.path.splitext(fullinput)
  3114. fulln = base + ".N"
  3115. if os.path.isfile(fulln):
  3116. t.deps[fulln] = 1
  3117. for x in dep:
  3118. fulldep = FindLocation(x, ipath, pyabi=pyabi)
  3119. t.deps[fulldep] = 1
  3120. if winrc and GetTarget() == 'windows':
  3121. TargetAdd(target, input=WriteResourceFile(target.split("/")[-1].split(".")[0], **winrc))
  3122. ext = os.path.splitext(target)[1]
  3123. if ext == ".in":
  3124. if not CrossCompiling():
  3125. t.deps[FindLocation("interrogate.exe", [])] = 1
  3126. t.deps[FindLocation("dtool_have_python.dat", [])] = 1
  3127. if ext in (".obj", ".tlb", ".res", ".plugin", ".app") or ext in SUFFIX_DLL or ext in SUFFIX_LIB:
  3128. t.deps[FindLocation("platform.dat", [])] = 1
  3129. if target.endswith(".obj") and any(x.endswith(".in") for x in input):
  3130. if not CrossCompiling():
  3131. t.deps[FindLocation("interrogate_module.exe", [])] = 1
  3132. if target.endswith(".pz") and not CrossCompiling():
  3133. t.deps[FindLocation("pzip.exe", [])] = 1
  3134. if target.endswith(".in"):
  3135. # Also add a target to compile the _igate.cxx file into an _igate.obj.
  3136. outbase = os.path.basename(target)[:-3]
  3137. woutc = OUTPUTDIR + "/tmp/" + outbase + "_igate.cxx"
  3138. CxxDependencyCache[woutc] = []
  3139. PyTargetAdd(outbase + "_igate.obj", opts=opts+['PYTHON','BIGOBJ'], input=woutc, dep=target)
  3140. def PyTargetAdd(target, opts=[], **kwargs):
  3141. if PkgSkip("PYTHON"):
  3142. return
  3143. if 'PYTHON' not in opts:
  3144. opts = opts + ['PYTHON']
  3145. abi = GetPythonABI()
  3146. MakeDirectory(OUTPUTDIR + "/tmp/" + abi)
  3147. # Mark this target as being a Python-specific target.
  3148. orig = CalcLocation(target, [OUTPUTDIR + "/include"])
  3149. PYABI_SPECIFIC.add(orig)
  3150. if orig.startswith(OUTPUTDIR + "/tmp/") and os.path.exists(orig):
  3151. print("Removing file %s" % (orig))
  3152. os.unlink(orig)
  3153. TargetAdd(target, opts=opts, pyabi=abi, **kwargs)