makepandacore.py 135 KB

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