makepandacore.py 136 KB

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