makepandacore.py 136 KB

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