makepandacore.py 140 KB

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