makepackage.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  1. #!/usr/bin/env python
  2. import sys
  3. import os
  4. import shutil
  5. import glob
  6. import re
  7. import subprocess
  8. import sysconfig
  9. from makepandacore import *
  10. from installpanda import *
  11. INSTALLER_DEB_FILE = """
  12. Package: panda3dMAJOR
  13. Version: VERSION
  14. Section: libdevel
  15. Priority: optional
  16. Architecture: ARCH
  17. Essential: no
  18. Depends: DEPENDS
  19. Recommends: RECOMMENDS
  20. Provides: PROVIDES
  21. Conflicts: PROVIDES
  22. Replaces: PROVIDES
  23. Maintainer: rdb <[email protected]>
  24. Installed-Size: INSTSIZE
  25. Description: Panda3D free 3D engine SDK
  26. Panda3D is a game engine which includes graphics, audio, I/O, collision detection, and other abilities relevant to the creation of 3D games. Panda3D is open source and free software under the revised BSD license, and can be used for both free and commercial game development at no financial cost.
  27. Panda3D's intended game-development language is Python. The engine itself is written in C++, and utilizes an automatic wrapper-generator to expose the complete functionality of the engine in a Python interface.
  28. .
  29. This package contains the SDK for development with Panda3D.
  30. """
  31. # We're not putting "python" in the "Requires" field,
  32. # since the rpm-based distros don't have a common
  33. # naming for the Python package.
  34. INSTALLER_SPEC_FILE = """
  35. Summary: The Panda3D free 3D engine SDK
  36. Name: panda3d
  37. Version: VERSION
  38. Release: RPMRELEASE
  39. License: BSD License
  40. Group: Development/Libraries
  41. BuildRoot: PANDASOURCE/targetroot
  42. %description
  43. Panda3D is a game engine which includes graphics, audio, I/O, collision detection, and other abilities relevant to the creation of 3D games. Panda3D is open source and free software under the revised BSD license, and can be used for both free and commercial game development at no financial cost.
  44. Panda3D's intended game-development language is Python. The engine itself is written in C++, and utilizes an automatic wrapper-generator to expose the complete functionality of the engine in a Python interface.
  45. This package contains the SDK for development with Panda3D.
  46. %post
  47. /sbin/ldconfig
  48. %postun
  49. /sbin/ldconfig
  50. %files
  51. %defattr(-,root,root)
  52. /etc/Confauto.prc
  53. /etc/Config.prc
  54. /usr/share/panda3d
  55. /etc/ld.so.conf.d/panda3d.conf
  56. /usr/%_lib/panda3d
  57. /usr/include/panda3d
  58. """
  59. INSTALLER_SPEC_FILE_PVIEW = """\
  60. /usr/share/applications/pview.desktop
  61. /usr/share/mime-info/panda3d.mime
  62. /usr/share/mime-info/panda3d.keys
  63. /usr/share/mime/packages/panda3d.xml
  64. /usr/share/application-registry/panda3d.applications
  65. """
  66. # plist file for Mac OSX
  67. Info_plist = """\
  68. <?xml version="1.0" encoding="UTF-8"?>
  69. <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
  70. <plist version="1.0">
  71. <dict>
  72. <key>CFBundleIdentifier</key>
  73. <string>{package_id}</string>
  74. <key>CFBundleShortVersionString</key>
  75. <string>{version}</string>
  76. <key>IFPkgFlagRelocatable</key>
  77. <false/>
  78. <key>IFPkgFlagAuthorizationAction</key>
  79. <string>RootAuthorization</string>
  80. <key>IFPkgFlagAllowBackRev</key>
  81. <true/>
  82. </dict>
  83. </plist>
  84. """
  85. # FreeBSD pkg-descr
  86. INSTALLER_PKG_DESCR_FILE = """
  87. Panda3D is a game engine which includes graphics, audio, I/O, collision detection, and other abilities relevant to the creation of 3D games. Panda3D is open source and free software under the revised BSD license, and can be used for both free and commercial game development at no financial cost.
  88. Panda3D's intended game-development language is Python. The engine itself is written in C++, and utilizes an automatic wrapper-generator to expose the complete functionality of the engine in a Python interface.
  89. This package contains the SDK for development with Panda3D.
  90. WWW: https://www.panda3d.org/
  91. """
  92. # FreeBSD PKG Manifest template file
  93. INSTALLER_PKG_MANIFEST_FILE = """
  94. name: NAME
  95. version: VERSION
  96. arch: ARCH
  97. origin: ORIGIN
  98. comment: "Panda3D free 3D engine SDK"
  99. www: https://www.panda3d.org
  100. maintainer: rdb <[email protected]>
  101. prefix: /usr/local
  102. flatsize: INSTSIZEMB
  103. deps: {DEPENDS}
  104. """
  105. # Since we're adding a bunch of install scripts to the macOS intaller, we'll
  106. # put the platform-checking code in some variables to reduce repetition.
  107. MACOS_SCRIPT_PREFIX = """\
  108. #!/bin/bash
  109. IFS=.
  110. read -a version_info <<< "`sw_vers -productVersion`"
  111. if (( ${version_info[0]} == 10 && ${version_info[1]} < 15 )); then
  112. """
  113. MACOS_SCRIPT_POSTFIX = """\
  114. fi
  115. """
  116. def MakeInstallerNSIS(version, file, title, installdir, compressor="lzma", **kwargs):
  117. outputdir = GetOutputDir()
  118. if os.path.isfile(file):
  119. os.remove(file)
  120. elif os.path.isdir(file):
  121. shutil.rmtree(file)
  122. if GetTargetArch() == 'x64':
  123. regview = '64'
  124. else:
  125. regview = '32'
  126. print("Building " + title + " installer at %s" % (file))
  127. if compressor != "lzma":
  128. print("Note: you are using zlib, which is faster, but lzma gives better compression.")
  129. if os.path.exists("nsis-output.exe"):
  130. os.remove("nsis-output.exe")
  131. WriteFile(outputdir + "/tmp/__init__.py", "")
  132. nsis_defs = {
  133. 'COMPRESSOR': compressor,
  134. 'TITLE': title,
  135. 'INSTALLDIR': installdir,
  136. 'OUTFILE': '..\\' + file,
  137. 'BUILT': '..\\' + outputdir,
  138. 'SOURCE': '..',
  139. 'REGVIEW': regview,
  140. 'MAJOR_VER': '.'.join(version.split('.')[:2]),
  141. }
  142. # Are we shipping a version of Python?
  143. if os.path.isfile(os.path.join(outputdir, "python", "python.exe")):
  144. py_dlls = (
  145. glob.glob(os.path.join(outputdir, "python", "python[0-9][0-9].dll"))
  146. + glob.glob(os.path.join(outputdir, "python", "python[0-9][0-9]_d.dll"))
  147. + glob.glob(os.path.join(outputdir, "python", "python[0-9][0-9][0-9].dll"))
  148. + glob.glob(os.path.join(outputdir, "python", "python[0-9][0-9][0-9]_d.dll"))
  149. )
  150. assert py_dlls
  151. py_dll = os.path.basename(py_dlls[0])
  152. py_dllver = py_dll.strip(".DHLNOPTY_dhlnopty")
  153. pyver = py_dllver[0] + '.' + py_dllver[1:]
  154. if GetTargetArch() != 'x64':
  155. pyver += '-32'
  156. nsis_defs['INCLUDE_PYVER'] = pyver
  157. if GetHost() == 'windows':
  158. cmd = os.path.join(GetThirdpartyBase(), 'win-nsis', 'makensis') + ' /V2'
  159. for item in nsis_defs.items():
  160. cmd += ' /D%s="%s"' % item
  161. else:
  162. cmd = 'makensis -V2'
  163. for item in nsis_defs.items():
  164. cmd += ' -D%s="%s"' % item
  165. cmd += ' "makepanda\\installer.nsi"'
  166. oscmd(cmd)
  167. def MakeDebugSymbolArchive(zipname, dirname):
  168. outputdir = GetOutputDir()
  169. import zipfile
  170. zip = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)
  171. for fn in glob.glob(os.path.join(outputdir, 'bin', '*.pdb')):
  172. zip.write(fn, dirname + '/bin/' + os.path.basename(fn))
  173. for fn in glob.glob(os.path.join(outputdir, 'panda3d', '*.pdb')):
  174. zip.write(fn, dirname + '/panda3d/' + os.path.basename(fn))
  175. for fn in glob.glob(os.path.join(outputdir, 'plugins', '*.pdb')):
  176. zip.write(fn, dirname + '/plugins/' + os.path.basename(fn))
  177. for fn in glob.glob(os.path.join(outputdir, 'python', '*.pdb')):
  178. zip.write(fn, dirname + '/python/' + os.path.basename(fn))
  179. for fn in glob.glob(os.path.join(outputdir, 'python', 'DLLs', '*.pdb')):
  180. zip.write(fn, dirname + '/python/DLLs/' + os.path.basename(fn))
  181. zip.close()
  182. def MakeInstallerLinux(version, debversion=None, rpmversion=None, rpmrelease=1,
  183. python_versions=[], **kwargs):
  184. outputdir = GetOutputDir()
  185. # We pack the default Python 3 version that ships with Ubuntu.
  186. python3_ver = None
  187. install_python_versions = []
  188. # What's the system version of Python 3?
  189. oscmd('python3 -V > "%s/tmp/python3_version.txt"' % (outputdir))
  190. sys_python3_ver = '.'.join(ReadFile(outputdir + "/tmp/python3_version.txt").strip().split(' ')[1].split('.')[:2])
  191. # Check that we built with support for it.
  192. for version_info in python_versions:
  193. if version_info["version"] == sys_python3_ver:
  194. python3_ver = sys_python3_ver
  195. install_python_versions.append(version_info)
  196. major_version = '.'.join(version.split('.')[:2])
  197. if not debversion:
  198. debversion = version
  199. if not rpmversion:
  200. rpmversion = version
  201. # Clean and set up a directory to install Panda3D into
  202. oscmd("rm -rf targetroot data.tar.gz control.tar.gz panda3d.spec")
  203. oscmd("mkdir -m 0755 targetroot")
  204. dpkg_present = False
  205. if os.path.exists("/usr/bin/dpkg-architecture") and os.path.exists("/usr/bin/dpkg-deb"):
  206. dpkg_present = True
  207. rpmbuild_present = False
  208. if os.path.exists("/usr/bin/rpmbuild"):
  209. rpmbuild_present = True
  210. if dpkg_present and rpmbuild_present:
  211. Warn("both dpkg and rpmbuild present.")
  212. if dpkg_present:
  213. # Invoke installpanda.py to install it into a temporary dir
  214. lib_dir = GetDebLibDir()
  215. InstallPanda(
  216. destdir="targetroot",
  217. prefix="/usr",
  218. outputdir=outputdir,
  219. libdir=lib_dir,
  220. python_versions=install_python_versions,
  221. )
  222. oscmd("chmod -R 755 targetroot/usr/share/panda3d")
  223. oscmd("mkdir -m 0755 -p targetroot/usr/share/man/man1")
  224. oscmd("install -m 0644 doc/man/*.1 targetroot/usr/share/man/man1/")
  225. oscmd("dpkg --print-architecture > " + outputdir + "/tmp/architecture.txt")
  226. pkg_arch = ReadFile(outputdir + "/tmp/architecture.txt").strip()
  227. txt = INSTALLER_DEB_FILE[1:]
  228. txt = (
  229. txt.replace("VERSION", debversion)
  230. .replace("ARCH", pkg_arch)
  231. .replace("MAJOR", major_version)
  232. )
  233. txt = txt.replace("INSTSIZE", str(GetDirectorySize("targetroot") // 1024))
  234. oscmd("mkdir -m 0755 -p targetroot/DEBIAN")
  235. oscmd("cd targetroot && (find usr -type f -exec md5sum {} ;) > DEBIAN/md5sums")
  236. oscmd("cd targetroot && (find etc -type f -exec md5sum {} ;) >> DEBIAN/md5sums")
  237. WriteFile("targetroot/DEBIAN/conffiles", "/etc/Config.prc\n")
  238. WriteFile("targetroot/DEBIAN/postinst", "#!/bin/sh\necho running ldconfig\nldconfig\n")
  239. oscmd("cp targetroot/DEBIAN/postinst targetroot/DEBIAN/postrm")
  240. # Determine the package name and the locations that
  241. # dpkg-shlibdeps should look in for executables.
  242. pkg_version = debversion
  243. pkg_name = "panda3d" + major_version
  244. lib_pattern = "debian/%s/usr/%s/panda3d/*.so*" % (pkg_name, lib_dir)
  245. bin_pattern = "debian/%s/usr/bin/*" % (pkg_name)
  246. # dpkg-shlibdeps looks in the debian/{pkg_name}/DEBIAN/shlibs directory
  247. # and also expects a debian/control file, so we create this dummy set-up.
  248. oscmd("mkdir targetroot/debian")
  249. oscmd("ln -s .. targetroot/debian/" + pkg_name)
  250. WriteFile("targetroot/debian/control", "")
  251. dpkg_shlibdeps = "dpkg-shlibdeps"
  252. if GetVerbose():
  253. dpkg_shlibdeps += " -v"
  254. pkg_name = "panda3d" + major_version
  255. pkg_dir = "debian/panda3d" + major_version
  256. # Generate a symbols file so that other packages can know which symbols we export.
  257. oscmd(f"cd targetroot && dpkg-gensymbols -q -ODEBIAN/symbols -v{pkg_version} -p{pkg_name} -e{lib_pattern}")
  258. # Library dependencies are required, binary dependencies are recommended.
  259. # We explicitly exclude libphysx-extras since we don't want to depend on PhysX.
  260. oscmd(f"cd targetroot && LD_LIBRARY_PATH=usr/{lib_dir}/panda3d {dpkg_shlibdeps} -Tdebian/substvars_dep --ignore-missing-info -x{pkg_name} -xlibphysx-extras {lib_pattern}")
  261. oscmd(f"cd targetroot && LD_LIBRARY_PATH=usr/{lib_dir}/panda3d {dpkg_shlibdeps} -Tdebian/substvars_rec --ignore-missing-info -x{pkg_name} {bin_pattern}")
  262. # Parse the substvars files generated by dpkg-shlibdeps.
  263. depends = ReadFile("targetroot/debian/substvars_dep").replace("shlibs:Depends=", "").strip()
  264. recommends = ReadFile("targetroot/debian/substvars_rec").replace("shlibs:Depends=", "").strip()
  265. provides = "panda3d"
  266. if python3_ver:
  267. depends += ", python%s" % (python3_ver)
  268. recommends += ", python-pmw, python3-tk (>= %s)" % (python3_ver)
  269. provides += ", python3-panda3d"
  270. # Write back the dependencies, and delete the dummy set-up.
  271. txt = txt.replace("DEPENDS", depends.strip(', '))
  272. txt = txt.replace("RECOMMENDS", recommends.strip(', '))
  273. txt = txt.replace("PROVIDES", provides.strip(', '))
  274. WriteFile("targetroot/DEBIAN/control", txt)
  275. oscmd("rm -rf targetroot/debian")
  276. # Package it all up into a .deb file.
  277. oscmd("chmod -R 755 targetroot/DEBIAN")
  278. oscmd("chmod 644 targetroot/DEBIAN/control targetroot/DEBIAN/md5sums")
  279. oscmd("chmod 644 targetroot/DEBIAN/conffiles targetroot/DEBIAN/symbols")
  280. oscmd("fakeroot dpkg-deb -b targetroot %s_%s_%s.deb" % (pkg_name, pkg_version, pkg_arch))
  281. elif rpmbuild_present:
  282. # Invoke installpanda.py to install it into a temporary dir
  283. InstallPanda(
  284. destdir="targetroot",
  285. prefix="/usr",
  286. outputdir=outputdir,
  287. libdir=GetRPMLibDir(),
  288. python_versions=install_python_versions,
  289. )
  290. oscmd("chmod -R 755 targetroot/usr/share/panda3d")
  291. oscmd("rpm -E '%_target_cpu' > " + outputdir + "/tmp/architecture.txt")
  292. arch = ReadFile(outputdir + "/tmp/architecture.txt").strip()
  293. pandasource = os.path.abspath(os.getcwd())
  294. txt = INSTALLER_SPEC_FILE[1:]
  295. # Add the MIME associations if we have pview
  296. if not PkgSkip("PVIEW"):
  297. txt += INSTALLER_SPEC_FILE_PVIEW
  298. # Add the platform-specific Python directories.
  299. dirs = set()
  300. for version_info in install_python_versions:
  301. dirs.add(version_info["platlib"])
  302. dirs.add(version_info["purelib"])
  303. for dir in dirs:
  304. txt += dir + "\n"
  305. # Add the binaries in /usr/bin explicitly to the spec file
  306. for base in os.listdir(outputdir + "/bin"):
  307. if not base.startswith("deploy-stub"):
  308. txt += "/usr/bin/%s\n" % (base)
  309. # Write out the spec file.
  310. txt = txt.replace("VERSION", rpmversion)
  311. txt = txt.replace("RPMRELEASE", str(rpmrelease))
  312. txt = txt.replace("PANDASOURCE", pandasource)
  313. WriteFile("panda3d.spec", txt)
  314. oscmd("fakeroot rpmbuild --define '_rpmdir "+pandasource+"' --buildroot '"+os.path.abspath("targetroot")+"' -bb panda3d.spec")
  315. oscmd("mv "+arch+"/panda3d-"+rpmversion+"-"+rpmrelease+"."+arch+".rpm .")
  316. oscmd("rm -rf "+arch, True)
  317. else:
  318. exit("To build an installer, either rpmbuild or dpkg-deb must be present on your system!")
  319. def MakeInstallerOSX(version, python_versions=[], installdir=None, **kwargs):
  320. outputdir = GetOutputDir()
  321. if installdir is None:
  322. installdir = "/Library/Developer/Panda3D"
  323. dmg_name = "Panda3D-" + version
  324. if len(python_versions) == 1 and not python_versions[0]["version"].startswith("2."):
  325. dmg_name += "-py" + python_versions[0]["version"]
  326. dmg_name += ".dmg"
  327. if os.path.isfile(dmg_name):
  328. oscmd("rm -f %s" % dmg_name)
  329. if os.path.exists("dstroot"):
  330. oscmd("rm -rf dstroot")
  331. if os.path.exists("Panda3D-rw.dmg"):
  332. oscmd('rm -f Panda3D-rw.dmg')
  333. oscmd("mkdir -p dstroot/base/%s/lib" % installdir)
  334. oscmd("mkdir -p dstroot/base/%s/etc" % installdir)
  335. oscmd("cp %s/etc/Config.prc dstroot/base/%s/etc/Config.prc" % (outputdir, installdir))
  336. oscmd("cp %s/etc/Confauto.prc dstroot/base/%s/etc/Confauto.prc" % (outputdir, installdir))
  337. oscmd("cp -R %s/models dstroot/base/%s/models" % (outputdir, installdir))
  338. oscmd("cp -R doc/LICENSE dstroot/base/%s/LICENSE" % installdir)
  339. oscmd("cp -R doc/ReleaseNotes dstroot/base/%s/ReleaseNotes" % installdir)
  340. if os.path.isdir(outputdir + "/Frameworks") and os.listdir(outputdir + "/Frameworks"):
  341. oscmd("cp -R %s/Frameworks dstroot/base/%s/Frameworks" % (outputdir, installdir))
  342. if os.path.isdir(outputdir + "/plugins"):
  343. oscmd("cp -R %s/plugins dstroot/base/%s/plugins" % (outputdir, installdir))
  344. # Libraries that shouldn't be in base, but are instead in other modules.
  345. no_base_libs = ['libp3ffmpeg', 'libp3fmod_audio', 'libfmodex', 'libfmodexL']
  346. for base in os.listdir(outputdir + "/lib"):
  347. if not base.endswith(".a") and base.split('.')[0] not in no_base_libs:
  348. libname = ("dstroot/base/%s/lib/" % installdir) + base
  349. # We really need to specify -R in order not to follow symlinks
  350. # On OSX, just specifying -P is not enough to do that.
  351. oscmd("cp -R -P " + outputdir + "/lib/" + base + " " + libname)
  352. oscmd("mkdir -p dstroot/tools/%s/bin" % installdir)
  353. oscmd("mkdir -p dstroot/tools/etc/paths.d")
  354. # Trailing newline is important, works around a bug in OSX
  355. WriteFile("dstroot/tools/etc/paths.d/Panda3D", "/%s/bin\n" % installdir)
  356. oscmd("mkdir -m 0755 -p dstroot/tools/usr/local/share/man/man1")
  357. oscmd("install -m 0644 doc/man/*.1 dstroot/tools/usr/local/share/man/man1/")
  358. for base in os.listdir(outputdir + "/bin"):
  359. if not base.startswith("deploy-stub"):
  360. binname = ("dstroot/tools/%s/bin/" % installdir) + base
  361. # OSX needs the -R argument to copy symbolic links correctly, it doesn't have -d. How weird.
  362. oscmd("cp -R " + outputdir + "/bin/" + base + " " + binname)
  363. if python_versions:
  364. # Let's only write a ppython link if there is only one Python version.
  365. if len(python_versions) == 1:
  366. oscmd("mkdir -p dstroot/pythoncode/usr/local/bin")
  367. oscmd("ln -s %s dstroot/pythoncode/usr/local/bin/ppython" % (python_versions[0]["executable"]))
  368. oscmd("mkdir -p dstroot/pythoncode/%s/panda3d" % installdir)
  369. oscmd("cp -R %s/pandac dstroot/pythoncode/%s/pandac" % (outputdir, installdir))
  370. oscmd("cp -R %s/direct dstroot/pythoncode/%s/direct" % (outputdir, installdir))
  371. oscmd("cp -R %s/*.so dstroot/pythoncode/%s/" % (outputdir, installdir), True)
  372. oscmd("cp -R %s/*.py dstroot/pythoncode/%s/" % (outputdir, installdir), True)
  373. if os.path.isdir(outputdir+"/Pmw"):
  374. oscmd("cp -R %s/Pmw dstroot/pythoncode/%s/Pmw" % (outputdir, installdir))
  375. # Copy over panda3d.dist-info directory.
  376. if os.path.isdir(outputdir + "/panda3d.dist-info"):
  377. oscmd("cp -R %s/panda3d.dist-info dstroot/pythoncode/%s/panda3d.dist-info" % (outputdir, installdir))
  378. for base in os.listdir(outputdir + "/panda3d"):
  379. if base.endswith('.py'):
  380. libname = ("dstroot/pythoncode/%s/panda3d/" % installdir) + base
  381. oscmd("cp -R " + outputdir + "/panda3d/" + base + " " + libname)
  382. for version_info in python_versions:
  383. pyver = version_info["version"]
  384. oscmd("mkdir -p dstroot/pybindings%s/Library/Python/%s/site-packages" % (pyver, pyver))
  385. oscmd("mkdir -p dstroot/pybindings%s/%s/panda3d" % (pyver, installdir))
  386. # Copy over extension modules.
  387. suffix = version_info["ext_suffix"]
  388. for base in os.listdir(outputdir+"/panda3d"):
  389. if base.endswith(suffix) and '.' not in base[:-len(suffix)]:
  390. libname = "dstroot/pybindings%s/%s/panda3d/%s" % (pyver, installdir, base)
  391. # We really need to specify -R in order not to follow symlinks
  392. # On OSX, just specifying -P is not enough to do that.
  393. oscmd("cp -R -P " + outputdir + "/panda3d/" + base + " " + libname)
  394. # Write a .pth file.
  395. oscmd("mkdir -p dstroot/pybindings%s/Library/Python/%s/site-packages" % (pyver, pyver))
  396. WriteFile("dstroot/pybindings%s/Library/Python/%s/site-packages/Panda3D.pth" % (pyver, pyver), installdir)
  397. # Somewhere in Python 2.7.13 and 3.7, the above path was removed from
  398. # sys.path of the python.org distribution. See bpo-28440 and GH #502.
  399. if pyver not in ("3.0", "3.1", "3.2", "3.3", "3.4", "3.5", "3.6"):
  400. dir = "dstroot/pybindings%s/Library/Frameworks/Python.framework/Versions/%s/lib/python%s/site-packages" % (pyver, pyver, pyver)
  401. oscmd("mkdir -p %s" % (dir))
  402. WriteFile("%s/Panda3D.pth" % (dir), installdir)
  403. # Also place it somewhere the Homebrew version of Python can find it.
  404. dir = "dstroot/pybindings%s/usr/local/lib/python%s/site-packages" % (pyver, pyver)
  405. oscmd("mkdir -p %s" % (dir))
  406. WriteFile("%s/Panda3D.pth" % (dir), installdir)
  407. if not PkgSkip("FFMPEG"):
  408. oscmd("mkdir -p dstroot/ffmpeg/%s/lib" % installdir)
  409. oscmd("cp -R %s/lib/libp3ffmpeg.* dstroot/ffmpeg/%s/lib/" % (outputdir, installdir))
  410. #if not PkgSkip("OPENAL"):
  411. # oscmd("mkdir -p dstroot/openal/Developer/Panda3D/lib")
  412. # oscmd("cp -R %s/lib/libp3openal_audio.* dstroot/openal/Developer/Panda3D/lib/" % outputdir)
  413. if not PkgSkip("FMODEX"):
  414. oscmd("mkdir -p dstroot/fmodex/%s/lib" % installdir)
  415. oscmd("cp -R %s/lib/libp3fmod_audio.* dstroot/fmodex/%s/lib/" % (outputdir, installdir))
  416. oscmd("cp -R %s/lib/libfmodex* dstroot/fmodex/%s/lib/" % (outputdir, installdir))
  417. oscmd("mkdir -p dstroot/headers/%s/lib" % installdir)
  418. oscmd("cp -R %s/include dstroot/headers/%s/include" % (outputdir, installdir))
  419. if os.path.isdir("samples"):
  420. oscmd("mkdir -p dstroot/samples/%s/samples" % installdir)
  421. oscmd("cp -R samples/* dstroot/samples/%s/samples" % installdir)
  422. DeleteVCS("dstroot")
  423. DeleteBuildFiles("dstroot")
  424. # Compile Python files. Do this *after* the DeleteVCS step, above, which
  425. # deletes __pycache__ directories.
  426. for version_info in python_versions:
  427. if os.path.isdir("dstroot/pythoncode/%s/Pmw" % installdir):
  428. oscmd("%s -m compileall -q -f -d %s/Pmw dstroot/pythoncode/%s/Pmw" % (version_info["executable"], installdir, installdir), True)
  429. oscmd("%s -m compileall -q -f -d %s/direct dstroot/pythoncode/%s/direct" % (version_info["executable"], installdir, installdir))
  430. oscmd("%s -m compileall -q -f -d %s/pandac dstroot/pythoncode/%s/pandac" % (version_info["executable"], installdir, installdir))
  431. oscmd("%s -m compileall -q -f -d %s/panda3d dstroot/pythoncode/%s/panda3d" % (version_info["executable"], installdir, installdir))
  432. oscmd("chmod -R 0775 dstroot/*")
  433. # We need to be root to perform a chown. Bleh.
  434. # Fortunately PackageMaker does it for us, on 10.5 and above.
  435. #oscmd("chown -R root:admin dstroot/*", True)
  436. oscmd("mkdir -p dstroot/Panda3D/Panda3D.mpkg/Contents/Packages/")
  437. oscmd("mkdir -p dstroot/Panda3D/Panda3D.mpkg/Contents/Resources/en.lproj/")
  438. pkgs = ["base", "tools", "headers"]
  439. # Starting with 1.10.5, Panda3D is installed by default in
  440. # /Library/Developer/Panda3D instead of /Developer/Panda3D. To keep
  441. # compatibility for those who rely on the old location, we add a symlink
  442. # if they're running macOS 10.14 or less. We also remove the old
  443. # installation.
  444. script_components = set()
  445. def write_script(component, phase, contents):
  446. if installdir == "/Developer/Panda3D":
  447. return
  448. script_components.add(component)
  449. oscmd("mkdir -p dstroot/scripts/%s" % component)
  450. ln_script = open("dstroot/scripts/%s/%s" % (component, phase), "w")
  451. ln_script.write(MACOS_SCRIPT_PREFIX)
  452. ln_script.write(contents)
  453. ln_script.write(MACOS_SCRIPT_POSTFIX)
  454. ln_script.close()
  455. oscmd("chmod +x dstroot/scripts/%s/%s" % (component, phase))
  456. write_script('base', 'postinstall', """
  457. pkgutil --pkg-info org.panda3d.panda3d.base.pkg
  458. if [ $? = 0 ]; then
  459. rm -rf /Developer/Panda3D
  460. fi
  461. mkdir -p /Developer
  462. ln -s %s /Developer/Panda3D
  463. """ % installdir)
  464. # We don't specify rm -r since /Developer/Panda3D/Tools is a symlink
  465. write_script('tools', 'postinstall', """
  466. pkgutil --pkg-info org.panda3d.panda3d.tools.pkg
  467. if [ $? = 0 ]; then
  468. rm -f /Developer/Tools/Panda3D
  469. fi
  470. mkdir -p /Developer/Tools
  471. ln -s %s/bin /Developer/Tools/Panda3D
  472. """ % installdir)
  473. if os.path.isdir("samples"):
  474. pkgs.append("samples")
  475. write_script('samples', 'postinstall', """
  476. pkgutil --pkg-info org.panda3d.panda3d.samples.pkg
  477. if [ $? = 0 ]; then
  478. rm -f /Developer/Examples/Panda3D
  479. fi
  480. mkdir -p /Developer/Examples
  481. ln -s %s/samples /Developer/Examples/Panda3D
  482. """ % installdir)
  483. if python_versions:
  484. pkgs.append("pythoncode")
  485. for version_info in python_versions:
  486. pkgs.append("pybindings" + version_info["version"])
  487. if not PkgSkip("FFMPEG"):
  488. pkgs.append("ffmpeg")
  489. #if not PkgSkip("OPENAL"):
  490. # pkgs.append("openal")
  491. if not PkgSkip("FMODEX"):
  492. pkgs.append("fmodex")
  493. for pkg in pkgs:
  494. identifier = "org.panda3d.panda3d.%s.pkg" % pkg
  495. scripts_path = "dstroot/scripts/%s" % pkg
  496. plist = open("/tmp/Info_plist", "w")
  497. plist.write(Info_plist.format(package_id=identifier, version=version))
  498. plist.close()
  499. if not os.path.isdir("dstroot/" + pkg):
  500. os.makedirs("dstroot/" + pkg)
  501. if pkg in script_components:
  502. pkg_scripts = ' --scripts ' + scripts_path
  503. else:
  504. pkg_scripts = ''
  505. if os.path.exists("/usr/bin/pkgbuild"):
  506. cmd = f'/usr/bin/pkgbuild --identifier {identifier} --version {version} --root dstroot/{pkg}/ dstroot/Panda3D/Panda3D.mpkg/Contents/Packages/{pkg}.pkg {pkg_scripts}'
  507. else:
  508. exit("pkgbuild could not be found!")
  509. oscmd(cmd)
  510. if os.path.isfile("/tmp/Info_plist"):
  511. oscmd("rm -f /tmp/Info_plist")
  512. # Now that we've built all of the individual packages, build the metapackage.
  513. dist = open("dstroot/Panda3D/Panda3D.mpkg/Contents/distribution.dist", "w")
  514. dist.write('<?xml version="1.0" encoding="utf-8"?>\n')
  515. dist.write('<installer-script minSpecVersion="1.000000" authoringTool="com.apple.PackageMaker" authoringToolVersion="3.0.3" authoringToolBuild="174">\n')
  516. dist.write(' <title>Panda3D SDK %s</title>\n' % (version))
  517. dist.write(' <allowed-os-versions>\n')
  518. dist.write(' <os-version min="10.9"/>\n')
  519. dist.write(' </allowed-os-versions>\n')
  520. dist.write(' <options customize="always" allow-external-scripts="no" rootVolumeOnly="false" hostArchitectures="x86_64"/>\n')
  521. dist.write(' <license language="en" mime-type="text/plain">%s</license>\n' % ReadFile("doc/LICENSE"))
  522. dist.write(' <readme language="en" mime-type="text/plain">')
  523. dist.write('WARNING: From Panda3D version 1.10.5 onwards, the default installation has been changed from /Developer/Panda3D to /Library/Developer/Panda3D\n')
  524. dist.write('This installation script will remove any existing installation in /Developer and if possible create a symbolic link towards /Library/Developer/Panda3D\n')
  525. dist.write(' </readme>')
  526. dist.write(' <script>\n')
  527. dist.write(' function isPythonVersionInstalled(version) {\n')
  528. dist.write(' return system.files.fileExistsAtPath("/usr/bin/python" + version)\n')
  529. dist.write(' || system.files.fileExistsAtPath("/usr/local/bin/python" + version)\n')
  530. dist.write(' || system.files.fileExistsAtPath("/opt/local/bin/python" + version)\n')
  531. dist.write(' || system.files.fileExistsAtPath("/sw/bin/python" + version)\n')
  532. dist.write(' || system.files.fileExistsAtPath("/System/Library/Frameworks/Python.framework/Versions/" + version + "/bin/python")\n')
  533. dist.write(' || system.files.fileExistsAtPath("/Library/Frameworks/Python.framework/Versions/" + version + "/bin/python");\n')
  534. dist.write(' }\n')
  535. dist.write(' </script>\n')
  536. dist.write(' <choices-outline>\n')
  537. dist.write(' <line choice="base"/>\n')
  538. if python_versions:
  539. dist.write(' <line choice="pythoncode">\n')
  540. for version_info in sorted(python_versions, key=lambda info: info["version"], reverse=True):
  541. dist.write(' <line choice="pybindings%s"/>\n' % (version_info["version"]))
  542. dist.write(' </line>\n')
  543. dist.write(' <line choice="tools"/>\n')
  544. if os.path.isdir("samples"):
  545. dist.write(' <line choice="samples"/>\n')
  546. if not PkgSkip("FFMPEG"):
  547. dist.write(' <line choice="ffmpeg"/>\n')
  548. if not PkgSkip("FMODEX"):
  549. dist.write(' <line choice="fmodex"/>\n')
  550. dist.write(' <line choice="headers"/>\n')
  551. dist.write(' </choices-outline>\n')
  552. dist.write(' <choice id="base" title="Panda3D Base Installation" description="This package contains the Panda3D libraries, configuration files and models/textures that are needed to use Panda3D.&#10;&#10;Location: %s/" start_enabled="false">\n' % installdir)
  553. dist.write(' <pkg-ref id="org.panda3d.panda3d.base.pkg"/>\n')
  554. dist.write(' </choice>\n')
  555. dist.write(' <choice id="tools" title="Tools" tooltip="Useful tools and model converters to help with Panda3D development" description="This package contains the various utilities that ship with Panda3D, including packaging tools, model converters, and many more.&#10;&#10;Location: %s/bin/">\n' % installdir)
  556. dist.write(' <pkg-ref id="org.panda3d.panda3d.tools.pkg"/>\n')
  557. dist.write(' </choice>\n')
  558. if python_versions:
  559. dist.write(' <choice id="pythoncode" title="Python Support" tooltip="Python bindings for the Panda3D libraries" description="This package contains the \'direct\', \'pandac\' and \'panda3d\' python packages that are needed to do Python development with Panda3D.&#10;&#10;Location: %s/">\n' % installdir)
  560. dist.write(' <pkg-ref id="org.panda3d.panda3d.pythoncode.pkg"/>\n')
  561. dist.write(' </choice>\n')
  562. for version_info in python_versions:
  563. pyver = version_info["version"]
  564. cond = "isPythonVersionInstalled('%s')" % (pyver)
  565. dist.write(' <choice id="pybindings%s" start_selected="%s" title="Python %s Bindings" tooltip="Python bindings for the Panda3D libraries" description="Support for Python %s.">\n' % (pyver, cond, pyver, pyver))
  566. dist.write(' <pkg-ref id="org.panda3d.panda3d.pybindings%s.pkg"/>\n' % (pyver))
  567. dist.write(' </choice>\n')
  568. if not PkgSkip("FFMPEG"):
  569. dist.write(' <choice id="ffmpeg" title="FFMpeg Plug-In" tooltip="FFMpeg video and audio decoding plug-in" description="This package contains the FFMpeg plug-in, which is used for decoding video and audio files with OpenAL.')
  570. if PkgSkip("VORBIS") and PkgSkip("OPUS"):
  571. dist.write(' It is not required for loading .wav files, which Panda3D can read out of the box.">\n')
  572. elif PkgSkip("VORBIS"):
  573. dist.write(' It is not required for loading .wav or .opus files, which Panda3D can read out of the box.">\n')
  574. elif PkgSkip("OPUS"):
  575. dist.write(' It is not required for loading .wav or .ogg files, which Panda3D can read out of the box.">\n')
  576. else:
  577. dist.write(' It is not required for loading .wav, .ogg or .opus files, which Panda3D can read out of the box.">\n')
  578. dist.write(' <pkg-ref id="org.panda3d.panda3d.ffmpeg.pkg"/>\n')
  579. dist.write(' </choice>\n')
  580. #if not PkgSkip("OPENAL"):
  581. # dist.write(' <choice id="openal" title="OpenAL Audio Plug-In" tooltip="OpenAL audio output plug-in" description="This package contains the OpenAL audio plug-in, which is an open-source library for playing sounds.">\n')
  582. # dist.write(' <pkg-ref id="org.panda3d.panda3d.openal.pkg"/>\n')
  583. # dist.write(' </choice>\n')
  584. if not PkgSkip("FMODEX"):
  585. dist.write(' <choice id="fmodex" title="FMOD Ex Plug-In" tooltip="FMOD Ex audio output plug-in" description="This package contains the FMOD Ex audio plug-in, which is a commercial library for playing sounds. It is an optional component as Panda3D can use the open-source alternative OpenAL instead.">\n')
  586. dist.write(' <pkg-ref id="org.panda3d.panda3d.fmodex.pkg"/>\n')
  587. dist.write(' </choice>\n')
  588. if os.path.isdir("samples"):
  589. dist.write(' <choice id="samples" title="Sample Programs" tooltip="Python sample programs that use Panda3D" description="This package contains the Python sample programs that can help you with learning how to use Panda3D.&#10;&#10;Location: %s/samples">\n' % installdir)
  590. dist.write(' <pkg-ref id="org.panda3d.panda3d.samples.pkg"/>\n')
  591. dist.write(' </choice>\n')
  592. dist.write(' <choice id="headers" title="C++ Header Files" tooltip="Header files for C++ development with Panda3D" description="This package contains the C++ header files that are needed in order to do C++ development with Panda3D. You don\'t need this if you want to develop in Python.&#10;&#10;Location: %s/include/" start_selected="false">\n' % installdir)
  593. dist.write(' <pkg-ref id="org.panda3d.panda3d.headers.pkg"/>\n')
  594. dist.write(' </choice>\n')
  595. for pkg in pkgs:
  596. size = GetDirectorySize("dstroot/" + pkg) // 1024
  597. dist.write(' <pkg-ref id="org.panda3d.panda3d.%s.pkg" installKBytes="%d" version="1" auth="Root">file:./Contents/Packages/%s.pkg</pkg-ref>\n' % (pkg, size, pkg))
  598. dist.write('</installer-script>\n')
  599. dist.close()
  600. oscmd('hdiutil create Panda3D-rw.dmg -volname "Panda3D SDK %s" -srcfolder dstroot/Panda3D' % (version))
  601. oscmd('hdiutil convert Panda3D-rw.dmg -format UDBZ -o %s' % (dmg_name))
  602. oscmd('rm -f Panda3D-rw.dmg')
  603. def MakeInstallerFreeBSD(version, python_versions=[], **kwargs):
  604. outputdir = GetOutputDir()
  605. oscmd("rm -rf targetroot +DESC pkg-plist +MANIFEST")
  606. oscmd("mkdir targetroot")
  607. # Invoke installpanda.py to install it into a temporary dir
  608. InstallPanda(
  609. destdir="targetroot",
  610. prefix="/usr/local",
  611. outputdir=outputdir,
  612. python_versions=python_versions,
  613. )
  614. if not os.path.exists("/usr/sbin/pkg"):
  615. exit("Cannot create an installer without pkg")
  616. plist_txt = ''
  617. for root, dirs, files in os.walk("targetroot/usr/local/", True):
  618. for f in files:
  619. plist_txt += os.path.join(root, f)[21:] + "\n"
  620. plist_txt += "@postexec /sbin/ldconfig -m /usr/local/lib/panda3d\n"
  621. plist_txt += "@postunexec /sbin/ldconfig -R\n"
  622. for remdir in ("lib/panda3d", "share/panda3d", "include/panda3d"):
  623. for root, dirs, files in os.walk("targetroot/usr/local/" + remdir, False):
  624. for d in dirs:
  625. plist_txt += "@dir %s\n" % os.path.join(root, d)[21:]
  626. plist_txt += "@dir %s\n" % remdir
  627. oscmd("echo \"`pkg config abi | tr '[:upper:]' '[:lower:]' | cut -d: -f1,2`:*\" > " + outputdir + "/tmp/architecture.txt")
  628. pkg_arch = ReadFile(outputdir+"/tmp/architecture.txt").strip()
  629. dependencies = ''
  630. if not PkgSkip("PYTHON"):
  631. # If this version of Python was installed from a package or ports, let's mark it as dependency.
  632. oscmd("rm -f %s/tmp/python_dep" % outputdir)
  633. if "PYTHONVERSION" in SDK:
  634. pyver_nodot = SDK["PYTHONVERSION"][6:].rstrip('dmu').replace('.', '')
  635. else:
  636. pyver_nodot = "%d%d" % (sys.version_info[:2])
  637. oscmd("pkg query \"\n\t%%n : {\n\t\torigin : %%o,\n\t\tversion : %%v\n\t},\n\" python%s > %s/tmp/python_dep" % (pyver_nodot, outputdir), True)
  638. if os.path.isfile(outputdir + "/tmp/python_dep"):
  639. python_pkg = ReadFile(outputdir + "/tmp/python_dep")
  640. if python_pkg:
  641. dependencies += python_pkg
  642. manifest_txt = INSTALLER_PKG_MANIFEST_FILE[1:].replace("NAME", 'panda3d')
  643. manifest_txt = manifest_txt.replace("VERSION", version)
  644. manifest_txt = manifest_txt.replace("ARCH", pkg_arch)
  645. manifest_txt = manifest_txt.replace("ORIGIN", 'devel/panda3d')
  646. manifest_txt = manifest_txt.replace("DEPENDS", dependencies)
  647. manifest_txt = manifest_txt.replace("INSTSIZE", str(GetDirectorySize("targetroot") // 1024 // 1024))
  648. WriteFile("pkg-plist", plist_txt)
  649. WriteFile("+DESC", INSTALLER_PKG_DESCR_FILE[1:])
  650. WriteFile("+MANIFEST", manifest_txt)
  651. oscmd("pkg create -p pkg-plist -r %s -m . -o . %s" % (os.path.abspath("targetroot"), "--verbose" if GetVerbose() else "--quiet"))
  652. def MakeInstallerAndroid(version, **kwargs):
  653. outputdir = GetOutputDir()
  654. oscmd("rm -rf apkroot")
  655. oscmd("mkdir apkroot")
  656. # Also remove the temporary apks.
  657. apk_unaligned = os.path.join(outputdir, "tmp", "panda3d-unaligned.apk")
  658. apk_unsigned = os.path.join(outputdir, "tmp", "panda3d-unsigned.apk")
  659. if os.path.exists(apk_unaligned):
  660. os.unlink(apk_unaligned)
  661. if os.path.exists(apk_unsigned):
  662. os.unlink(apk_unsigned)
  663. # Copy the compiled Java classes.
  664. oscmd("cp %s apkroot/classes.dex" % (os.path.join(outputdir, "classes.dex")))
  665. # Copy the libraries one by one. In case of library dependencies, strip
  666. # off any suffix (eg. libfile.so.1.0), as Android does not support them.
  667. source_dir = os.path.join(outputdir, "lib")
  668. target_dir = os.path.join("apkroot", "lib", SDK["ANDROID_ABI"])
  669. if not os.path.exists(target_dir):
  670. os.makedirs(target_dir, mode=0o755)
  671. # Determine the library directories we should look in.
  672. libpath = [source_dir]
  673. for dir in os.environ.get("LD_LIBRARY_PATH", "").split(':'):
  674. dir = os.path.expandvars(dir)
  675. dir = os.path.expanduser(dir)
  676. if os.path.isdir(dir):
  677. dir = os.path.realpath(dir)
  678. if not dir.startswith("/system") and not dir.startswith("/vendor"):
  679. libpath.append(dir)
  680. def copy_library(source, base):
  681. # Copy file to destination, stripping version suffix.
  682. target = os.path.join(target_dir, base)
  683. if not target.endswith('.so'):
  684. target = target.rpartition('.so.')[0] + '.so'
  685. if os.path.isfile(target):
  686. # Already processed.
  687. return
  688. shutil.copy(source, target)
  689. # Walk through the library dependencies.
  690. handle = subprocess.Popen(['readelf', '--dynamic', target], stdout=subprocess.PIPE)
  691. for line in handle.communicate()[0].splitlines():
  692. # The line will look something like:
  693. # 0x0000000000000001 (NEEDED) Shared library: [libpanda.so]
  694. line = line.decode('utf-8', 'replace').strip()
  695. if not line or '(NEEDED)' not in line or '[' not in line or ']' not in line:
  696. continue
  697. # Extract the part between square brackets.
  698. idx = line.index('[')
  699. dep = line[idx + 1 : line.index(']', idx)]
  700. # Change .so.1.2 suffix to .so, as needed for loading in .apk
  701. if '.so.' in dep:
  702. orig_dep = dep
  703. dep = dep.rpartition('.so.')[0] + '.so'
  704. oscmd("patchelf --replace-needed %s %s %s" % (orig_dep, dep, target), True)
  705. # Find it on the LD_LIBRARY_PATH.
  706. for dir in libpath:
  707. fulldep = os.path.join(dir, dep)
  708. if os.path.isfile(fulldep):
  709. copy_library(os.path.realpath(fulldep), dep)
  710. break
  711. # Now copy every lib in the lib dir, and its dependencies.
  712. for base in os.listdir(source_dir):
  713. if not base.startswith('lib'):
  714. continue
  715. if not base.endswith('.so') and '.so.' not in base:
  716. continue
  717. source = os.path.join(source_dir, base)
  718. if os.path.islink(source):
  719. continue
  720. copy_library(source, base)
  721. # Same for Python extension modules. However, Android is strict about
  722. # library naming, so we have a special naming scheme for these, in
  723. # conjunction with a custom import hook to find these modules.
  724. if not PkgSkip("PYTHON"):
  725. suffix = GetExtensionSuffix()
  726. source_dir = os.path.join(outputdir, "panda3d")
  727. for base in os.listdir(source_dir):
  728. if not base.endswith(suffix):
  729. continue
  730. modname = base[:-len(suffix)]
  731. if '.' not in modname:
  732. source = os.path.join(source_dir, base)
  733. copy_library(source, "libpy.panda3d.{}.so".format(modname))
  734. # Same for standard Python modules.
  735. if CrossCompiling():
  736. source_dir = os.path.join(GetThirdpartyDir(), "python", "lib", SDK["PYTHONVERSION"], "lib-dynload")
  737. else:
  738. import _ctypes
  739. source_dir = os.path.dirname(_ctypes.__file__)
  740. for base in os.listdir(source_dir):
  741. if not base.endswith('.so'):
  742. continue
  743. modname = base.partition('.')[0]
  744. source = os.path.join(source_dir, base)
  745. copy_library(source, "libpy.{}.so".format(modname))
  746. def copy_python_tree(source_root, target_root):
  747. for source_dir, dirs, files in os.walk(source_root):
  748. if 'site-packages' in dirs:
  749. dirs.remove('site-packages')
  750. if not any(base.endswith('.py') for base in files):
  751. continue
  752. target_dir = os.path.join(target_root, os.path.relpath(source_dir, source_root))
  753. target_dir = os.path.normpath(target_dir)
  754. os.makedirs(target_dir, 0o755)
  755. for base in files:
  756. if base.endswith('.py'):
  757. target = os.path.join(target_dir, base)
  758. shutil.copy(os.path.join(source_dir, base), target)
  759. # Copy the Python standard library to the .apk as well.
  760. stdlib_source = sysconfig.get_path("stdlib")
  761. stdlib_target = os.path.join("apkroot", "lib", "python{0}.{1}".format(*sys.version_info))
  762. copy_python_tree(stdlib_source, stdlib_target)
  763. # But also copy over our custom site.py.
  764. shutil.copy("panda/src/android/site.py", os.path.join(stdlib_target, "site.py"))
  765. # And now make a site-packages directory containing our direct/panda3d/pandac modules.
  766. for tree in "panda3d", "direct", "pandac":
  767. copy_python_tree(
  768. os.path.join(outputdir, tree),
  769. os.path.join(stdlib_target, "site-packages", tree),
  770. )
  771. # Copy the models and config files to the virtual assets filesystem.
  772. oscmd("mkdir apkroot/assets")
  773. oscmd("cp -R %s apkroot/assets/models" % (os.path.join(outputdir, "models")))
  774. oscmd("cp -R %s apkroot/assets/etc" % (os.path.join(outputdir, "etc")))
  775. # Make an empty res folder. It's needed for the apk to be installable, apparently.
  776. oscmd("mkdir apkroot/res")
  777. # Now package up the application
  778. oscmd("cp panda/src/android/pview_manifest.xml apkroot/AndroidManifest.xml")
  779. aapt_cmd = "aapt package"
  780. aapt_cmd += " -F %s" % (apk_unaligned)
  781. aapt_cmd += " -M apkroot/AndroidManifest.xml"
  782. aapt_cmd += " -A apkroot/assets -S apkroot/res"
  783. aapt_cmd += " -I %s" % (SDK["ANDROID_JAR"])
  784. oscmd(aapt_cmd)
  785. # And add all the libraries to it.
  786. oscmd("aapt add %s classes.dex" % (os.path.join('..', apk_unaligned)), cwd="apkroot")
  787. for path, dirs, files in os.walk('apkroot/lib'):
  788. if files:
  789. rel = os.path.relpath(path, 'apkroot')
  790. rel_files = [os.path.join(rel, file).replace('\\', '/') for file in files]
  791. oscmd("aapt add %s %s" % (os.path.join('..', apk_unaligned), ' '.join(rel_files)), cwd="apkroot")
  792. # Now align the .apk, which is necessary for Android to load it.
  793. oscmd("zipalign -v -p 4 %s %s" % (apk_unaligned, apk_unsigned))
  794. # Finally, sign it using a debug key. This is generated if it doesn't exist.
  795. if GetHost() == 'android':
  796. # Termux version of apksigner automatically generates a debug key.
  797. oscmd("apksigner debug.ks %s panda3d.apk" % (apk_unsigned))
  798. else:
  799. if not os.path.isfile('debug.ks'):
  800. oscmd("keytool -genkey -noprompt -dname CN=Panda3D,O=Panda3D,C=US -keystore debug.ks -storepass android -alias androiddebugkey -keypass android -keyalg RSA -keysize 2048 -validity 1000")
  801. oscmd("apksigner sign --ks debug.ks --ks-pass pass:android --min-sdk-version %s --out panda3d.apk %s" % (SDK["ANDROID_API"], apk_unsigned))
  802. # Clean up.
  803. oscmd("rm -rf apkroot")
  804. os.unlink(apk_unaligned)
  805. os.unlink(apk_unsigned)
  806. def MakeInstaller(version, **kwargs):
  807. target = GetTarget()
  808. if target == 'windows':
  809. dir = kwargs.pop('installdir', None)
  810. if dir is None:
  811. dir = "C:\\Panda3D-" + version
  812. if GetTargetArch() == 'x64':
  813. dir += '-x64'
  814. fn = "Panda3D-"
  815. title = "Panda3D SDK " + version
  816. fn += version
  817. python_versions = kwargs.get('python_versions', [])
  818. if len(python_versions) == 1:
  819. fn += '-py' + python_versions[0]["version"]
  820. if GetOptimize() <= 2:
  821. fn += "-dbg"
  822. if GetTargetArch() == 'x64':
  823. fn += '-x64'
  824. MakeInstallerNSIS(version, fn + '.exe', title, dir, **kwargs)
  825. MakeDebugSymbolArchive(fn + '-pdb.zip', dir)
  826. elif target == 'linux':
  827. MakeInstallerLinux(version, **kwargs)
  828. elif target == 'darwin':
  829. MakeInstallerOSX(version, **kwargs)
  830. elif target == 'freebsd':
  831. MakeInstallerFreeBSD(version, **kwargs)
  832. elif target == 'android':
  833. MakeInstallerAndroid(version, **kwargs)
  834. else:
  835. exit("Do not know how to make an installer for this platform")
  836. if __name__ == "__main__":
  837. version = GetMetadataValue('version')
  838. parser = OptionParser()
  839. parser.add_option(
  840. '',
  841. '--version',
  842. dest='version',
  843. help='Panda3D version number (default: %s)' % (version),
  844. default=version,
  845. )
  846. parser.add_option(
  847. '',
  848. '--debversion',
  849. dest='debversion',
  850. help='Version number for .deb file',
  851. default=None,
  852. )
  853. parser.add_option(
  854. '',
  855. '--rpmversion',
  856. dest='rpmversion',
  857. help='Version number for .rpm file',
  858. default=None,
  859. )
  860. parser.add_option(
  861. '',
  862. '--rpmrelease',
  863. dest='rpmrelease',
  864. help='Release number for .rpm file',
  865. default='1',
  866. )
  867. parser.add_option(
  868. '',
  869. '--outputdir',
  870. dest='outputdir',
  871. help='Makepanda\'s output directory (default: built)',
  872. default='built',
  873. )
  874. parser.add_option(
  875. '',
  876. '--verbose',
  877. dest='verbose',
  878. help='Enable verbose output',
  879. action='store_true',
  880. default=False,
  881. )
  882. parser.add_option(
  883. '',
  884. '--lzma',
  885. dest='compressor',
  886. help='Use LZMA compression',
  887. action='store_const',
  888. const='lzma',
  889. default='zlib',
  890. )
  891. parser.add_option(
  892. '',
  893. '--installdir',
  894. dest='installdir',
  895. help='Where on the system the installer should put the SDK (Windows, macOS)',
  896. )
  897. (options, args) = parser.parse_args()
  898. SetVerbose(options.verbose)
  899. SetOutputDir(options.outputdir)
  900. # Read out the optimize option.
  901. opt = ReadFile(os.path.join(options.outputdir, "tmp", "optimize.dat"))
  902. SetOptimize(int(opt.strip()))
  903. # Read out whether we should set PkgSkip("PYTHON") and some others.
  904. # Temporary hack; needs better solution.
  905. pkg_list = "PYTHON", "FFMPEG", "OPENAL", "FMODEX", "PVIEW", "VORBIS", "OPUS"
  906. PkgListSet(pkg_list)
  907. for pkg in pkg_list:
  908. dat_path = "dtool_have_%s.dat" % (pkg.lower())
  909. content = ReadFile(os.path.join(options.outputdir, "tmp", dat_path))
  910. if int(content.strip()):
  911. PkgEnable(pkg)
  912. else:
  913. PkgDisable(pkg)
  914. # Parse the version.
  915. match = re.match(r'^\d+\.\d+(\.\d+)+', options.version)
  916. if not match:
  917. exit("version requires three digits")
  918. MakeInstaller(
  919. version=match.group(),
  920. outputdir=options.outputdir,
  921. optimize=GetOptimize(),
  922. compressor=options.compressor,
  923. debversion=options.debversion,
  924. rpmversion=options.rpmversion,
  925. rpmrelease=options.rpmrelease,
  926. python_versions=ReadPythonVersionInfoFile(),
  927. installdir=options.installdir,
  928. )