Get Metal driver working

This commit is contained in:
Kovid Goyal 2026-11-04 10:13:36 +05:30
parent 979087e044
commit 5d60395312
No known key found for this signature in database
GPG key ID: 06BC317B515ACE7C
8 changed files with 109 additions and 38 deletions

View file

@ -410,6 +410,7 @@ class Freeze(object):
os.mkdir(pdir)
print('Extracting extension modules from', self.python_stdlib, 'to', pdir)
ext_map = extract_extension_modules(self.python_stdlib, pdir)
self.check_gpu_drivers(pdir, join(kitty_dir, 'shaders'))
shutil.copy(join(os.path.dirname(self_dir), 'site.py'), join(self.python_stdlib, 'site.py'))
for x in bases:
iv['sanitize_source_folder'](join(self.python_stdlib, x))
@ -427,6 +428,20 @@ class Freeze(object):
if f.endswith('.so') or f.endswith('.dylib'):
self.fix_dependencies_in_lib(f)
@flush
def check_gpu_drivers(self, ext_dir: str, shaders_dir: str) -> None:
# Both GPU drivers must be part of the build, along with the built-in
# shaders compiled for their shader targets, otherwise kitty silently
# falls back to whichever driver is present
print('\nChecking GPU drivers...')
for driver, target_prefix in (('opengl', 'glsl-'), ('metal', 'msl-')):
path = join(ext_dir, f'kitty.{driver}.so')
if not os.path.isfile(path):
raise SystemExit(f'The {driver} GPU driver was not built, {path} does not exist')
targets = [x for x in os.listdir(shaders_dir) if x.startswith(target_prefix) and os.path.isfile(join(shaders_dir, x, 'cell.json'))]
if not targets:
raise SystemExit(f'The built-in shaders were not compiled for the {driver} GPU driver in {shaders_dir}')
@flush
def build_frozen_tools(self) -> None:
iv['build_frozen_tools'](join(self.contents_dir, 'MacOS', 'kitty'))

View file

@ -120,8 +120,13 @@ connect_to_display(void *driver, const GPUNativeWindow *display) {
set_error(d, "No Metal capable GPU found");
return false;
}
// MSL 2.4 needs macOS 12, every Mac that can run it supports the Mac2 or Apple7 GPU families
if (![d->device supportsFamily:MTLGPUFamilyMac2] && ![d->device supportsFamily:MTLGPUFamilyApple7]) {
// MSL 2.4 needs macOS 12, every Mac that can run it supports the Mac2 or Apple7 GPU families.
// Mac2 is deprecated from macOS 27, which no longer supports the Intel Macs that need it.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
const bool supported = [d->device supportsFamily:MTLGPUFamilyApple7] || [d->device supportsFamily:MTLGPUFamilyMac2];
#pragma clang diagnostic pop
if (!supported) {
set_error(d, "The GPU %s does not support the Metal features needed by kitty", [[d->device name] UTF8String]);
return false;
}

View file

@ -128,15 +128,20 @@ compile_library(Driver *d, const GPUShaderSource *s) {
}
MTLCompileOptions *opts = [[[MTLCompileOptions alloc] init] autorelease];
[opts setLanguageVersion:MTLLanguageVersion2_4];
// Without fast math, so that rendering matches the other drivers
// OpenGL on Apple GPUs is implemented on top of Metal and uses fast
// math, so that is needed for rendering to match it exactly, for
// example in the pow() of the gamma adjustments of text. Relaxed math
// does the same optimizations but keeps NaN and infinity working, which
// custom shaders might rely on. Before macOS 15, fast math, the default,
// is the only choice.
#if defined(__MAC_15_0) && __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_15_0
if (@available(macOS 15.0, *)) [opts setMathMode:MTLMathModeSafe];
if (@available(macOS 15.0, *)) [opts setMathMode:MTLMathModeRelaxed];
else
#endif
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[opts setFastMathEnabled:NO];
[opts setFastMathEnabled:YES];
#pragma clang diagnostic pop
}
NSError *err = nil;

View file

@ -93,12 +93,10 @@ to_underline_exclusion_pos(uint2 sprite_idx) {
uint
read_sprite_decorations_idx(uint2 sprite_idx) {
int idx = int(sprite_idx[0] & SPRITE_INDEX_MASK);
int width, height;
sprite_decorations_map.GetDimensions(width, height);
int2 sz = int2(width, height);
int2 sz = texture_size(sprite_decorations_map);
int y = idx / sz[0];
int x = idx - y * sz[0];
return sprite_decorations_map[int2(x, y)];
return texel_fetch(sprite_decorations_map, int2(x, y));
}
uint2
@ -291,13 +289,11 @@ calculate_premul_foreground_from_sprites(
float4 cursor_color_premult,
float effective_text_alpha, ) {
// Return premul foreground color from decorations (cursor, underline, strikethrough)
int width, height, layer;
sprites.GetDimensions(width, height, layer);
float3 sz = float3(float(width), float(height), float(layer));
float3 sz = float3(texture_size(sprites));
float underline_alpha = sprites.SampleLevel(underline_pos, 0).w;
int3 fetch_coord = int3(int(sprite_pos.x * sz.x), int(underline_exclusion_pos), int(sprite_pos.z));
float underline_exclusion = sprites[fetch_coord].w;
float underline_exclusion = texel_fetch(sprites, fetch_coord).w;
underline_alpha *= 1.0 - underline_exclusion;
float strike_alpha = sprites.SampleLevel(strike_pos, 0).w;

View file

@ -9,6 +9,7 @@
import blit_common;
import background;
import utils;
// False for the variant used when the image is drawn at its natural size,
// which needs only a single pixel read per fragment.
@ -44,7 +45,7 @@ uniform Sampler2D<uint2> image; // a two channel RG8UI texture // binding slots:
float4
premult_color_at(int2 pos, uint has_alpha) {
uint2 px = image[pos];
uint2 px = texel_fetch(image, pos);
float alpha = has_alpha != 0 ? float(px.g) / 255.0 : 1.0;
return float4(indexed_image_color(px.r) * alpha, alpha);
}
@ -55,9 +56,9 @@ fragment_main(float2 texcoord: TEXCOORD)
: SV_Target {
// Integer textures cannot be filtered and anyway the palette lookup must
// happen before interpolation, so do bilinear filtering here.
int width, height;
image.GetDimensions(width, height);
const int2 limit = int2(width - 1, height - 1);
const int2 size = texture_size(image);
const int width = size.x, height = size.y;
const int2 limit = size - 1;
// When the image is drawn at its natural size every fragment is at the
// center of a pixel, so just read that pixel. is_scaled is a compile time
// constant so this is not a branch in the shader.

View file

@ -1199,10 +1199,12 @@ def fixup_metal_code(msl: str, entry_points: dict[str, str], shader_name: str) -
@lru_cache(maxsize=2)
def metal_compiler_available() -> bool:
# The Metal compiler is part of Xcode, it is not available on other platforms
# The Metal compiler is part of Xcode, it is not available on other
# platforms. Recent versions of Xcode ship it as a separate component,
# without which xcrun finds a stub that fails, so actually run it.
if sys.platform != 'darwin' or not shutil.which('xcrun'):
return False
return subprocess.run(['xcrun', '-sdk', 'macosx', '-f', 'metal'], capture_output=True).returncode == 0
return subprocess.run(['xcrun', '-sdk', 'macosx', 'metal', '--version'], capture_output=True).returncode == 0
def msl_validation_command(target: ShaderTarget, path: str) -> list[str]:
@ -1798,19 +1800,33 @@ def compile_builtin_shaders(build_dir: str, dest_dir: str, parallel_run: Paralle
target_commands.append(commands_to_compile_to_glsl(source_tree, build_dir, dest_dir, target, built_files[target]))
# Now run all commands
parallel_run(chain(*target_commands))
# Write the metadata of every target before validating any of them, as
# outputs are only rebuilt when out of date, so metadata not written
# because validation of another target failed would never be written.
for target, built in built_files.items():
if target.is_single_module:
write_module_metadata(built, target, build_dir)
if target.is_spirv and shutil.which('spirv-val'):
parallel_run((True, f'Validating |{os.path.basename(x)}| ...', spirv_validation_command(target, x)) for x in built)
if target.is_msl and metal_compiler_available():
parallel_run((True, f'Validating |{os.path.basename(x)}| ...', msl_validation_command(target, x)) for x in built)
continue
fixup_opengl_files(built, target, build_dir)
if shutil.which('glslangValidator'):
else:
fixup_opengl_files(built, target, build_dir)
for target, built in built_files.items():
cmds: list[tuple[bool, str, list[str]]] = []
if target.is_spirv and shutil.which('spirv-val'):
cmds = [(True, f'Validating |{os.path.basename(x)}| ...', spirv_validation_command(target, x)) for x in built]
elif target.is_msl and metal_compiler_available():
cmds = [(True, f'Validating |{os.path.basename(x)}| ...', msl_validation_command(target, x)) for x in built]
elif not target.is_single_module and shutil.which('glslangValidator'):
from kitty.shaders.validate_shaders import validation_command_for_file
parallel_run((True, f'Validating |{os.path.basename(x)}| ...', validation_command_for_file(x)) for x in built)
cmds = [(True, f'Validating |{os.path.basename(x)}| ...', validation_command_for_file(x)) for x in built]
try:
parallel_run(cmds)
except BaseException:
# Remove the outputs that failed validation, so that they are
# built, and validated, again by the next build
for x in built:
with suppress(FileNotFoundError):
os.remove(x)
raise
def main() -> None:

View file

@ -33,3 +33,46 @@ public float4
vec4_premul(float4 rgba) {
return float4(rgba.rgb * rgba.a, rgba.a);
}
// Reading texels and texture sizes of combined texture samplers. slangc
// (2026.14) generates broken MSL for Load(), operator[] and GetDimensions()
// of combined texture samplers: it passes the sampler in place of the
// arguments. Metal splits them into a texture and a sampler, which are $0
// and $1 in the MSL intrinsics below, the arguments follow them.
public __generic<T : ITexelElement> T
texel_fetch(Sampler2D<T> s, int2 pos) {
__target_switch {
case metal: __intrinsic_asm "$0.read(uint2($2))$z";
default: return s[pos];
}
}
public __generic<T : ITexelElement> T
texel_fetch(Sampler2DArray<T> s, int3 pos) {
__target_switch {
case metal: __intrinsic_asm "$0.read(uint2(($2).xy), uint(($2).z))$z";
default: return s[pos];
}
}
public __generic<T : ITexelElement> int2
texture_size(Sampler2D<T> s) {
__target_switch {
case metal: __intrinsic_asm "int2($0.get_width(), $0.get_height())";
default:
int w, h;
s.GetDimensions(w, h);
return int2(w, h);
}
}
public __generic<T : ITexelElement> int3
texture_size(Sampler2DArray<T> s) {
__target_switch {
case metal: __intrinsic_asm "int3($0.get_width(), $0.get_height(), $0.get_array_size())";
default:
int w, h, l;
s.GetDimensions(w, h, l);
return int3(w, h, l);
}
}

View file

@ -1337,19 +1337,9 @@ def gpu_drivers_to_build() -> List[str]:
return ans
# TODO: Remove once the Metal GPU driver is complete. The shaders for the
# Metal driver are needed only on macOS, they are also built on other
# platforms, where the slangc output can be checked but not run, while the
# Metal driver is being developed.
BUILD_METAL_SHADERS_ON_ALL_PLATFORMS = True
def gpu_shader_targets_to_build() -> List[str]:
# The shader targets the built-in shaders are compiled for, those of the GPU drivers being built
drivers = gpu_drivers_to_build()
if BUILD_METAL_SHADERS_ON_ALL_PLATFORMS and 'metal' not in drivers:
drivers.append('metal')
return [t for driver in drivers for t in gpu_driver_shader_targets(driver)]
return [t for driver in gpu_drivers_to_build() for t in gpu_driver_shader_targets(driver)]
def gpu_driver_init_env(env: Env, driver: str = 'opengl') -> Env: