Skip to content

Instantly share code, notes, and snippets.

@RedstoneWizard08
Created August 24, 2024 04:10
Show Gist options
  • Save RedstoneWizard08/0e0cbe5bd7bc2c1cedc582ec1658ee24 to your computer and use it in GitHub Desktop.
Save RedstoneWizard08/0e0cbe5bd7bc2c1cedc582ec1658ee24 to your computer and use it in GitHub Desktop.
Skia Emscripten Build Script (Python)
"""
Automated WASM build tool for Skia (which works better than the one in CanvasKit).
Built with love and Python by RedstoneWizard08. (MIT licensed)
Use with: https://github.com/google/skia
Tools required:
- Python 3 (3.11 was used when making this)
- Ninja
Usage:
1. Place in the root directory of the cloned repo.
2. Make sure you update submodules!
3. Run `tools/git-sync-deps`
4. Run this script with `python3`.
5. Check the help menu for arguments and other info!
"""
"""
MIT License
Copyright (c) 2024 RedstoneWizard08
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import os
import sys
import hashlib
import subprocess
from argparse import ArgumentParser
DEBUG_LOG = False
def log(s: str):
if DEBUG_LOG:
print(f"\x1b[1;32m[CONFIG]\x1b[0m {s}")
def print_status(desc: str, data: bool) -> bool:
if data:
log(f"Enabling {desc}.")
else:
log(f"Disabling {desc}.")
return data
def print_status_i(desc: str, data: bool) -> bool:
if data:
log(f"Including {desc}.")
else:
log(f"Omitting {desc}.")
return data
def lower(s: str) -> str:
return s.lower()
def print_config(name: str, value):
print(f"\x1b[1;35m{name}: \x1b[0m\x1b[34m{value}\x1b[0m")
def fix_value(v):
if type(v) is bool:
return str(v).lower()
elif type(v) is str:
return f"\"{v}\""
else:
raise Exception(f"Unsupported argument type: {type(v)}")
cmd = ArgumentParser("gen_wasm.py")
is_official_build = True
is_debug = False
profile_build = False
enable_ganesh = True
enable_graphite = False
enable_webgl = False
enable_webgpu = False
use_expat = False
include_viewer = False
gn_font = "skia_enable_fontmgr_custom_directory=false "
woff2_font = "skia_use_freetype_woff2=true"
enable_font = True
enable_embedded_font = True
gn_shaper = "skia_use_icu=true skia_use_client_icu=false skia_use_libgrapheme=false skia_use_icu4x=false skia_use_system_icu=false skia_use_harfbuzz=true skia_use_system_harfbuzz=false "
do_decode = True
encode_jpeg = None
encode_png = None
encode_webp = None
superquiet = False
# Arguments
cmd.add_argument("-q", "--quiet", help="Suppress config summary output", default=False, action="store_true")
cmd.add_argument("-qq", "--superquiet", help="Suppress all output", default=False, action="store_true")
cmd.add_argument("-b", "--backend", choices=["CPU", "WebGL", "WebGPU", "cpu", "webgl", "webgpu"], default="WebGL")
cmd.add_argument("--emsdk", type=str, help="Emscripten SDK folder", default=os.environ["EMSDK"])
cmd.add_argument("-t", "--force-tracing", help="Force tracing", default=False, action="store_true")
cmd.add_argument("-d", "--debug", help="Enable debug build", default=False, action="store_true")
cmd.add_argument("-p", "--profiling", help="Enable profiling", default=False, action="store_true")
cmd.add_argument("-s", "--skp-serialize", help="Enable SKP serialization", default=True, action="store_true")
cmd.add_argument("-x", "--effects-deserialize", help="Enable effects deserialization", default=True, action="store_true")
cmd.add_argument("-k", "--skottie", help="Include Skottie", default=True, action="store_true")
cmd.add_argument("-v", "--viewer", help="Include viewer", default=False, action="store_true")
cmd.add_argument("-a", "--pathops", help="Include PathOps", default=True, action="store_true")
cmd.add_argument("-m", "--matrix", help="Include matrix helper code", default=True, action="store_true")
cmd.add_argument("-c", "--canvas", help="Include HTML Canvas API bindings", default=True, action="store_true")
cmd.add_argument("-K", "--canvaskit", help="Build as CanvasKit.", default=False, action="store_true")
cmd.add_argument("-F", "--alias-font", help="Enable alias font", default=True, action="store_true")
cmd.add_argument("-l", "--legacy-draw-vertices", help="Enable legacy vertex drawing", default=False, action="store_true")
cmd.add_argument("-D", "--debugger", help="Enable the debugger", default=False, action="store_true")
cmd.add_argument("-S", "--primitive-shaper", help="Enable the primitive shaper", default=False, action="store_true")
cmd.add_argument("-u", "--client-unicode", help="Use client-provided skunicode data and harfbuzz instead of the icu-provided data", default=False, action="store_true")
cmd.add_argument("-g", "--paragraph", help="Enable paragraph", default=True, action="store_true")
cmd.add_argument("-f", "--no-font", help="Omit built-in fonts, font manager and all code dealing with fonts", default=False, action="store_true")
cmd.add_argument("-e", "--no-embedded-font", help="Omit built-in fonts", default=False, action="store_true")
cmd.add_argument("-C", "--no-codecs", help="Omit codecs", default=False, action="store_true")
cmd.add_argument("-P", "--no-encode-png", help="Disable PNG encoding", default=False, action="store_true")
cmd.add_argument("-J", "--no-encode-jpeg", help="Disable JPEG encoding", default=False, action="store_true")
cmd.add_argument("-W", "--no-encode-webp", help="Disable WEBP encoding", default=False, action="store_true")
cmd.add_argument("build_dir", metavar="dir", type=str, help="The folder to configure/build in")
args = cmd.parse_args()
quiet = args.quiet
emsdk = args.emsdk
canvaskit = print_status("CanvasKit mode", args.canvaskit)
if args.superquiet:
quiet = True
superquiet = True
if not emsdk or emsdk == "":
print("\x1b[1;31mError:\x1b[0m Missing argument: \x1b[36m--emsdk\x1b[0m. This can also be set with the \x1b[36mEMSDK\x1b[0m environment variable.")
exit(1)
if args.backend.lower() == "cpu":
log("Using CPU backend.")
enable_ganesh = False
elif args.backend.lower() == "webgpu":
log("Using GPU backend.")
enable_webgpu = True
enable_graphite = True
enable_ganesh = False
else:
log("Using WebGL backend.")
enable_webgl = True
force_tracing = print_status("tracing", args.force_tracing)
if args.debug:
is_debug = True
is_official_build = False
elif args.profiling:
profile_build = True
serialize_skp = print_status("SKP serialization", args.skp_serialize)
deserialize_effects = print_status("effects deserialization", args.effects_deserialize)
enable_skottie = print_status_i("Skottie", args.skottie)
if args.viewer:
log("Including viewer.")
include_viewer = True
use_expat = True
is_official_build = False
enable_pathops = print_status_i("PathOps", args.pathops)
enable_matrix = print_status_i("matrix helper code", args.matrix)
enable_canvas = print_status_i("HTML Canvas API bindings", args.canvas)
if args.no_font:
log("Omitting built-in fonts, font manager, and all code dealing with fonts.")
enable_font = False
enable_embedded_font = False
gn_font += "skia_enable_fontmgr_custom_embedded=false skia_enable_fontmgr_custom_empty=false "
else:
if args.no_embedded_font:
log("Omitting built-in fonts")
enable_embedded_font = False
gn_font += "skia_enable_fontmgr_custom_embedded=true skia_enable_fontmgr_custom_empty=true "
enable_alias_font = print_status("the alias font", args.alias_font)
legacy_draw_vertices = print_status("legacy vertex drawing", args.legacy_draw_vertices)
debugger_enabled = print_status("the debugger", args.debugger)
if args.primitive_shaper:
log("Using the primitive shaper instead of the Harfbuzz/ICU one.")
gn_shaper = "skia_use_icu=false skia_use_harfbuzz=false "
if args.client_unicode:
log("Using client-provided skunicode data and harfbuzz instead of the icu-provided data.")
gn_shaper = "skia_use_icu=false skia_use_client_icu=true skia_use_libgrapheme=false skia_use_icu4x=false skia_use_harfbuzz=true skia_use_system_harfbuzz=false "
enable_paragraph = print_status_i("paragraph", args.paragraph)
if args.no_codecs:
log("Omitting codecs.")
do_decode = False
encode_jpeg = print_status("JPEG encoding", False)
encode_png = print_status("PNG encoding", False)
encode_webp = print_status("WEBP encoding", False)
else:
encode_jpeg = print_status("JPEG encoding", not args.no_encode_jpeg)
encode_png = print_status("PNG encoding", not args.no_encode_png)
encode_webp = print_status("WEBP encoding", not args.no_encode_webp)
build_dir = os.path.abspath(args.build_dir)
mode = "Debug" if is_debug else "Release"
final_config = {
"Is Official Build": is_official_build,
"Use Ganesh": enable_ganesh,
"Use Graphite": enable_graphite,
"Use WebGL": enable_webgl,
"Use WebGPU": enable_webgpu,
"Use Expat": use_expat,
"Include Viewer": include_viewer,
}
feature_configs = {
"Tracing": force_tracing,
"Profiling": profile_build,
"Fonts": enable_font,
"Embedded Fonts": enable_embedded_font,
"Decoding": do_decode,
"JPEG Support": encode_jpeg,
"PNG Support": encode_png,
"WEBP Support": encode_webp,
"SKP Serialization": serialize_skp,
"Effects Deserialization": deserialize_effects,
"Skottie": enable_skottie,
"PathOps": enable_pathops,
"Matrix Helpers": enable_matrix,
"HTML Canvas API Bindings": enable_canvas,
"Alias Font": enable_alias_font,
"Legacy Vertex Drawing": legacy_draw_vertices,
"Debugger": debugger_enabled,
"Paragraph": enable_paragraph,
}
if not quiet:
print("\x1b[1mCONFIG SUMMARY\x1b[0m")
print()
print_config("Mode", mode)
print_config("Build Folder", build_dir)
print()
print("\x1b[1mFlags\x1b[0m")
print()
for key, val in final_config.items():
print_config(key, val)
print()
print("\x1b[1mFeatures\x1b[0m")
print()
for key, val in feature_configs.items():
print_config(key, val)
base_args = {
"cc": "emcc",
"cxx": "em++",
"ar": "emar",
"is_debug": is_debug,
"is_official_build": is_official_build,
"is_component_build": False,
"is_trivial_abi": True,
"werror": True,
"target_cpu": "wasm",
}
# Prefixed with "skia_use_"
libs = {
"angle": False,
"dng_sdk": False,
"dawn": enable_webgpu,
"webgl": enable_webgl,
"webgpu": enable_webgpu,
"expat": use_expat,
"fontconfig": False,
"freetype": True,
"libheif": False,
"libjpeg_turbo_decode": do_decode,
"libjpeg_turbo_encode": encode_jpeg,
"no_jpeg_encode": not encode_jpeg,
"libpng_decode": do_decode,
"libpng_encode": encode_png,
"no_png_encode": not encode_png,
"libwebp_decode": do_decode,
"libwebp_encode": encode_webp,
"no_webp_encode": not encode_webp,
"lua": False,
"piex": False,
"system_freetype2": False,
"system_libjpeg_turbo": False,
"system_libpng": False,
"system_libwebp": False,
"system_zlib": False,
"vulkan": False,
"wuffs": True,
"zlib": True,
}
# Prefixed with "skia_enable_"
toggles = {
"ganesh": enable_ganesh,
"graphite": enable_graphite,
"skottie": enable_skottie,
"skshaper": True,
"skparagraph": True,
"pdf": False,
}
# Prefixed with "skia_"
extras = {
"build_for_debugger": debugger_enabled,
"emsdk_dir": emsdk,
}
# Prefixed with "skia_canvaskit_"
canvaskit_args = {
"enable_rt_shader": True,
"force_tracing": force_tracing,
"profile_build": profile_build,
"enable_skp_serialization": serialize_skp,
"enable_effects_deserialization": deserialize_effects,
"include_viewer": include_viewer,
"enable_pathops": enable_pathops,
"enable_matrix_helper": enable_matrix,
"enable_canvas_bindings": enable_canvas,
"enable_font": enable_font,
"enable_embedded_font": enable_embedded_font,
"enable_alias_font": enable_alias_font,
"legacy_draw_vertices_blend_mode": legacy_draw_vertices,
"enable_debugger": debugger_enabled,
"enable_paragraph": enable_paragraph,
"enable_webgl": enable_webgl,
"enable_webgpu": enable_webgpu,
}
extra = " " + gn_shaper + gn_font + woff2_font
all_args = []
_libs = [("skia_use_" + key, val) for key, val in libs.items()]
_toggles = [("skia_enable_" + key, val) for key, val in toggles.items()]
_extras = [("skia_" + key, val) for key, val in extras.items()]
_canvaskit = [("skia_canvaskit_" + key, val) for key, val in canvaskit_args.items()] if canvaskit else []
_all = list(base_args.items()) + _libs + _toggles + _extras + _canvaskit
for key, val in _all:
all_args.append(f"{key}={fix_value(val)}")
final_args = " ".join(all_args) + extra
log("Configuring with:")
log(final_args)
stdout = subprocess.DEVNULL if superquiet else sys.stdout
stderr = subprocess.DEVNULL if superquiet else sys.stderr
configured = False
args_file = os.path.join(build_dir, ".config_args")
hasher = hashlib.sha1()
hasher.update(final_args.encode("utf-8"))
final_hash = hasher.hexdigest()
if os.path.exists(args_file):
with open(args_file, "r") as f:
existing_hash = f.read()
configured = final_hash == existing_hash
if not quiet:
print()
print("\x1b[1;36mConfiguring...\x1b[0m")
if configured:
print("\x1b[1;33mAlready configured! Skipping...\x1b[0m")
else:
print(f"\x1b[90mbin/gn gen {build_dir} '--args={final_args}'\x1b[0m")
if not configured:
subprocess.run(["bin/gn", "gen", build_dir, f"--args={final_args}"], stdout=stdout, stderr=stderr)
with open(args_file, "w") as f:
f.write(final_hash)
if not quiet:
if not configured:
print("\x1b[1;36mConfigured!\x1b[0m")
print("\x1b[1;36mBuilding...\x1b[0m")
print(f"\x1b[90mninja -C {build_dir}\x1b[0m")
subprocess.run(["ninja", "-C", build_dir], stdout=stdout, stderr=stderr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment