makepandacore.py 141 KB

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