@geastack/apple 0.2.19 → 0.2.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @geastack/apple
2
2
 
3
3
  Apple platform support for GeaStack: generated TypeScript bindings for the
4
- Apple SDKs, and the macOS and iOS native build targets that turn a compiled Gea
4
+ Apple SDKs, and the macOS, iOS and tvOS native build targets that turn a compiled Gea
5
5
  app into an `.app`.
6
6
 
7
7
  ```sh
@@ -15,6 +15,7 @@ The `gea` CLI drives the targets:
15
15
  ```sh
16
16
  gea build --target macos
17
17
  gea build --target ios
18
+ gea build --target tvos
18
19
  ```
19
20
 
20
21
  The target build scripts can also be run directly from an app directory that
@@ -24,9 +25,10 @@ has the GeaStack packages installed:
24
25
  node_modules/@geastack/apple/targets/macos/build-macos.sh my-app
25
26
  node_modules/@geastack/apple/targets/ios/build-ios.sh my-app simulator
26
27
  GEA_IOS_DEVELOPMENT_TEAM=ABCDE12345 node_modules/@geastack/apple/targets/ios/build-ios.sh my-app device
28
+ node_modules/@geastack/apple/targets/ios/build-ios.sh my-app simulator tvos
27
29
  ```
28
30
 
29
- Requires Xcode with the macOS and iOS SDKs. Each target directory has its own
31
+ Requires Xcode with the macOS, iOS and tvOS SDKs you target. Each target directory has its own
30
32
  README covering the renderer and project layout.
31
33
 
32
34
  ## Using Apple frameworks from TypeScript
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@geastack/apple",
3
- "version": "0.2.19",
4
- "description": "Generated Apple SDK bindings plus the macOS and iOS native build targets for Gea apps.",
3
+ "version": "0.2.20",
4
+ "description": "Generated Apple SDK bindings plus the macOS, iOS and tvOS native build targets for Gea apps.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
7
7
  "type": "git",
@@ -116,12 +116,12 @@
116
116
  },
117
117
  "dependencies": {
118
118
  "@geastack/compiler": "^1.0.34",
119
- "@geastack/core": "^0.1.51",
119
+ "@geastack/core": "^0.1.52",
120
120
  "@geastack/elements": "^0.1.6",
121
- "@geastack/engine": "^0.1.22",
121
+ "@geastack/engine": "^0.1.23",
122
122
  "@geastack/geaos": "^0.1.3",
123
123
  "@geastack/geatsc-plugin-apple-native": "^0.1.4",
124
- "@geastack/geatsc-plugin-gea": "^0.1.24",
124
+ "@geastack/geatsc-plugin-gea": "^0.1.28",
125
125
  "@geastack/host": "^0.1.23"
126
126
  },
127
127
  "scripts": {
@@ -80,3 +80,17 @@ GEA_IOS_DEVELOPMENT_TEAM=ABCDE12345 gea run --target tvos --mode device --app bo
80
80
  Use `gea build` with the same options to generate the Xcode project and build
81
81
  without launching. Outputs are under the app's `dist/tvos`. The UIKit build
82
82
  script shares its signing, device selection, and simulator overrides with iOS.
83
+
84
+ An app can pin the resolution it renders at, for example 4K on Apple TV, with
85
+ `gea.targets.tvos.build.display` (`gea.targets.ios.build.display` on iOS):
86
+
87
+ ```json
88
+ "tvos": { "build": { "display": { "width": 3840, "height": 2160 } } }
89
+ ```
90
+
91
+ Set both or neither. Per-target native code goes under `gea.targets.<ios|tvos>`:
92
+ `nativeSources`, `nativeLibraries` (static archives), `frameworks` (system
93
+ frameworks), `nativeIncludeDirectories`, `nativeResources` (directories copied
94
+ into the bundle) and `tsconfig` (the TypeScript project the compiler reads).
95
+ Native code can own part of the window as a host extension, a rendering
96
+ surface for example, by registering itself through `main/gea_uikit_host.h`.
@@ -186,7 +186,31 @@ generate_app() {
186
186
  while IFS= read -r plugin_path; do
187
187
  [[ -z "$plugin_path" ]] || args+=(--extra-geatsc-plugin "$plugin_path")
188
188
  done <<< "$plugin_paths"
189
+ # gea.targets.<ios|tvos>.tsconfig: the TypeScript project the compiler reads
190
+ # the program under, as build-windows.mjs passes it. Without it the compiler
191
+ # takes the project nearest the staged entry, and an app that maps modules
192
+ # through `paths` (a three.js app's barrel) is read with those modules untyped.
193
+ local project
194
+ project="$(node "$GEA_CLI" apps inspect "$app_id" --json | node -e '
195
+ const app = JSON.parse(require("node:fs").readFileSync(0, "utf8"));
196
+ const tsconfig = app.targetConfig?.[process.argv[1]]?.tsconfig;
197
+ if (tsconfig) console.log(require("node:path").resolve(app.root, tsconfig));
198
+ ' "$GEA_APPLE_UIKIT_PLATFORM")" || return 1
199
+ [[ -z "$project" ]] || args+=(--project "$project")
200
+ # The compiler plugins this app's packages ship, resolved by `gea build`
201
+ # (src/macos/adapter.mjs) exactly as for macOS -- a three.js app's WebGL
202
+ # lowering arrives this way.
203
+ if [[ -n "${GEA_EXTRA_GEATSC_PLUGINS:-}" ]]; then
204
+ while IFS= read -r plugin_path; do
205
+ [[ -z "$plugin_path" ]] || args+=(--extra-geatsc-plugin "$plugin_path")
206
+ done <<< "${GEA_EXTRA_GEATSC_PLUGINS//:/$'\n'}"
207
+ fi
208
+ # <app>/<ios|tvos>/geatsc-native-plugin.mjs, or the app's own root when the
209
+ # app already is that folder (an app kept under a tvos/ directory).
189
210
  local native_plugin="$root/$GEA_APPLE_UIKIT_PLATFORM/geatsc-native-plugin.mjs"
211
+ if [[ ! -f "$native_plugin" && "$(basename "$root")" == "$GEA_APPLE_UIKIT_PLATFORM" ]]; then
212
+ native_plugin="$root/geatsc-native-plugin.mjs"
213
+ fi
190
214
  if [[ -f "$native_plugin" ]]; then
191
215
  args+=(--extra-geatsc-plugin "$native_plugin")
192
216
  fi
@@ -165,15 +165,22 @@ const rendererSources = [
165
165
  'renderer/native_scroll_container.mm',
166
166
  'renderer/view_reconciler.mm',
167
167
  ].map((file) => source(path.join(iosDir, 'main', file), 'sourcecode.cpp.objcpp'))
168
+ // gea.targets.<ios|tvos>: per-target native sources, static archives, system
169
+ // frameworks and include directories (validated by the CLI's nativeLink), and
170
+ // resource directories staged into the app bundle (nativeResources).
171
+ const uikitTarget = tvos ? 'tvos' : 'ios'
172
+ const appNativeLink = appMeta.nativeLink?.[uikitTarget] || {}
168
173
  const appNativeSources = [...new Map([
169
174
  ...findAppNativeSources(),
170
175
  ...(appMeta.nativeSourcePaths || []).map((file) => source(file, nativeSourceKind(file))),
176
+ ...(appMeta.targetNativeSourcePaths?.[uikitTarget] || []).map((file) => source(file, nativeSourceKind(file))),
171
177
  ].map((entry) => [entry.file, entry])).values()]
172
178
  const sources = [
173
179
  source(path.join(iosDir, 'main/ios_main.mm'), 'sourcecode.cpp.objcpp'),
174
180
  source(path.join(iosDir, 'main/ios_root_background.cpp')),
175
181
  ...rendererSources,
176
182
  source(path.join(iosDir, 'main/canvas_view.mm'), 'sourcecode.cpp.objcpp'),
183
+ source(path.join(iosDir, 'main/uikit_host.mm'), 'sourcecode.cpp.objcpp'),
177
184
  source(path.join(iosDir, 'main/color_convert.mm'), 'sourcecode.cpp.objcpp'),
178
185
  source(path.join(iosDir, 'main/image_bridge.mm'), 'sourcecode.cpp.objcpp'),
179
186
  source(path.join(iosDir, 'main/font_registry.mm'), 'sourcecode.cpp.objcpp'),
@@ -208,6 +215,12 @@ if (existing(assetsGenerated)) sources.push(assetsGenerated)
208
215
  const hasGeneratedFonts = sources.some((entry) => path.basename(entry.file) === 'gea_embedded_font_generated.cpp')
209
216
 
210
217
  const fontResources = findFontResources().map((file) => resource(file))
218
+ // Each nativeResources destination becomes a folder of the same name in the
219
+ // bundle: stage them under the generated directory, then reference the folders.
220
+ const nativeResourceDir = path.join(generatedDir, 'native-resources')
221
+ const nativeResourceNames = Object.keys(appMeta.nativeResources?.[uikitTarget] || {})
222
+ if (nativeResourceNames.length) gea(['apps', 'sync-native-resources', appId, '--target', uikitTarget, '--output', nativeResourceDir])
223
+ const folderResources = nativeResourceNames.map((name) => resource(path.join(nativeResourceDir, name), 'folder'))
211
224
  const appIconAssets = resource(appIconAssetsDir, 'folder.assetcatalog')
212
225
  const appIconResources = skipAppIcon ? [] : [appIconAssets]
213
226
  const uiTestSource = source(path.join(iosDir, 'test/GeaIosRubberBandUITests.swift'), 'sourcecode.swift')
@@ -223,6 +236,7 @@ const frameworks = [
223
236
  'CoreLocation.framework',
224
237
  'CoreMedia.framework',
225
238
  'CoreVideo.framework',
239
+ 'IOSurface.framework',
226
240
  'ImageIO.framework',
227
241
  'MapKit.framework',
228
242
  'AVFoundation.framework',
@@ -234,6 +248,9 @@ const frameworks = [
234
248
  'MetalKit.framework',
235
249
  'Foundation.framework',
236
250
  ]
251
+ for (const name of appNativeLink.frameworks || []) {
252
+ if (!frameworks.includes(`${name}.framework`)) frameworks.push(`${name}.framework`)
253
+ }
237
254
 
238
255
  const productId = id('product')
239
256
  const targetId = id('target')
@@ -277,6 +294,12 @@ for (const r of fontResources) {
277
294
  buildFiles.push(`${id(`build:${label}`)} /* ${path.basename(r.file)} in Resources */ = {isa = PBXBuildFile; fileRef = ${id(`file:${label}`)} /* ${path.basename(r.file)} */; };`)
278
295
  }
279
296
 
297
+ for (const r of folderResources) {
298
+ const label = rel(r.file)
299
+ fileRefs.push(`${id(`file:${label}`)} /* ${path.basename(r.file)} */ = {isa = PBXFileReference; lastKnownFileType = folder; path = ${q(r.file)}; sourceTree = "<absolute>"; };`)
300
+ buildFiles.push(`${id(`build:${label}`)} /* ${path.basename(r.file)} in Resources */ = {isa = PBXBuildFile; fileRef = ${id(`file:${label}`)} /* ${path.basename(r.file)} */; };`)
301
+ }
302
+
280
303
  for (const a of appIconResources) {
281
304
  const label = rel(a.file)
282
305
  fileRefs.push(`${id(`file:${label}`)} /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = ${a.kind}; path = ${q(a.file)}; sourceTree = "<absolute>"; };`)
@@ -307,6 +330,7 @@ const includePaths = [
307
330
  generatedDir,
308
331
  path.join(appRoot, tvos ? 'tvos' : 'ios'),
309
332
  ...new Set(appNativeSources.map(({ file }) => path.dirname(file))),
333
+ ...(appNativeLink.nativeIncludeDirectories || []),
310
334
  // Framework include roots (core/host/engine includes + vendor/stb + AnimatedGIF)
311
335
  // from the shared manifest gea_sources.sh, passed by build-ios.sh via env.
312
336
  ...(process.env.GEA_FW_INCLUDE_DIRS || '').split('\n').filter(Boolean),
@@ -334,6 +358,8 @@ function buildSettings(configuration) {
334
358
  // native pixel with no runtime format branch and no colour conversion.
335
359
  'GEA_EMBEDDED_PIXEL_FORMAT=1',
336
360
  ...(hasGeneratedFonts ? ['GEA_EMBEDDED_HAS_GENERATED_FONTS=1'] : []),
361
+ // gea.defines and the resolved build settings' macros.
362
+ ...(buildConfig.defines || []),
337
363
  ]
338
364
  return `{
339
365
  ALWAYS_SEARCH_USER_PATHS = NO;${skipAppIcon ? '' : `
@@ -352,7 +378,7 @@ function buildSettings(configuration) {
352
378
  ${tvos ? 'TVOS_DEPLOYMENT_TARGET = 17.0;' : 'IPHONEOS_DEPLOYMENT_TARGET = 16.0;'}
353
379
  LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
354
380
  ONLY_ACTIVE_ARCH = ${configuration === 'Debug' ? 'YES' : 'NO'};
355
- OTHER_LDFLAGS = ("$(inherited)", "-Wl,-no_deduplicate");
381
+ OTHER_LDFLAGS = (${['$(inherited)', '-Wl,-no_deduplicate', ...(appNativeLink.nativeLibraries || [])].map(q).join(', ')});
356
382
  PRODUCT_BUNDLE_IDENTIFIER = ${q(bundleId)};
357
383
  PRODUCT_NAME = ${q(appName)};
358
384
  SDKROOT = ${tvos ? 'appletvos' : 'iphoneos'};
@@ -387,6 +413,7 @@ const sourceChildren = sources.map((s) => `${id(`file:${rel(s.file)}`)} /* ${pat
387
413
  const uiTestSourceChildren = uiTestSources.map((s) => `${id(`file:${rel(s.file)}`)} /* ${path.basename(s.file)} */`)
388
414
  const resourceChildren = [
389
415
  ...fontResources.map((r) => `${id(`file:${rel(r.file)}`)} /* ${path.basename(r.file)} */`),
416
+ ...folderResources.map((r) => `${id(`file:${rel(r.file)}`)} /* ${path.basename(r.file)} */`),
390
417
  ...appIconResources.map((a) => `${id(`file:${rel(a.file)}`)} /* Assets.xcassets */`),
391
418
  ]
392
419
  const frameworkChildren = frameworks.map((fw) => `${id(`file:${fw}`)} /* ${fw} */`)
@@ -402,6 +429,7 @@ const sourceBuildRefs = sources.map((s) => `${id(`build:${rel(s.file)}`)} /* ${p
402
429
  const uiTestSourceBuildRefs = uiTestSources.map((s) => `${id(`build:${rel(s.file)}`)} /* ${path.basename(s.file)} in Sources */`)
403
430
  const resourceBuildRefs = [
404
431
  ...fontResources.map((r) => `${id(`build:${rel(r.file)}`)} /* ${path.basename(r.file)} in Resources */`),
432
+ ...folderResources.map((r) => `${id(`build:${rel(r.file)}`)} /* ${path.basename(r.file)} in Resources */`),
405
433
  ...appIconResources.map((a) => `${id(`build:${rel(a.file)}`)} /* Assets.xcassets in Resources */`),
406
434
  ]
407
435
  const frameworkBuildRefs = frameworks.map((fw) => `${id(`build:${fw}`)} /* ${fw} in Frameworks */`)
@@ -4,4 +4,6 @@
4
4
 
5
5
  @interface GeaCanvasView : UIView
6
6
  @property(nonatomic, assign) int nodeId;
7
+ // Shows the canvas node's current pixels.
8
+ - (void)present;
7
9
  @end
@@ -4,15 +4,145 @@
4
4
  #include "pixel.h"
5
5
  #include "ui/tree_internal.h"
6
6
 
7
+ #include <dispatch/dispatch.h>
8
+ #import <IOSurface/IOSurfaceRef.h>
9
+ #import <Metal/Metal.h>
10
+ #import <QuartzCore/CAMetalLayer.h>
11
+ #include <TargetConditionals.h>
12
+ #include <unistd.h>
13
+
14
+ #include <algorithm>
15
+ #include <mutex>
16
+ #include <vector>
17
+
7
18
  namespace {
8
19
 
9
- void releaseFrame(void *, const void *data, std::size_t)
20
+ // A frame's pixels are handed to Core Animation inside a CGImage, which may
21
+ // still be reading one after the next frame starts: each frame takes a buffer
22
+ // from this pool and the image's release returns it. A fresh allocation per
23
+ // frame instead page-faults the whole buffer in again every time.
24
+ struct FrameBuffer {
25
+ std::uint8_t *bytes;
26
+ std::size_t size;
27
+ };
28
+ std::mutex gFramePoolLock;
29
+ std::vector<FrameBuffer> gFramePool;
30
+
31
+ void releaseFrame(void *, const void *data, std::size_t size)
32
+ {
33
+ std::lock_guard<std::mutex> lock(gFramePoolLock);
34
+ gFramePool.push_back({static_cast<std::uint8_t *>(const_cast<void *>(data)), size});
35
+ }
36
+
37
+ std::uint8_t *takeFrame(std::size_t size)
38
+ {
39
+ {
40
+ std::lock_guard<std::mutex> lock(gFramePoolLock);
41
+ while (!gFramePool.empty()) {
42
+ const FrameBuffer buffer = gFramePool.back();
43
+ gFramePool.pop_back();
44
+ if (buffer.size == size) return buffer.bytes;
45
+ std::free(buffer.bytes); // the canvas was resized
46
+ }
47
+ }
48
+ return static_cast<std::uint8_t *>(std::malloc(size));
49
+ }
50
+
51
+ #if GEA_EMBEDDED_PIXEL_FORMAT == GEA_PIXEL_RGBA8888
52
+ // Draws the canvas texture over the whole drawable, opaque.
53
+ NSString *const kPresentShader = @R"(
54
+ #include <metal_stdlib>
55
+ using namespace metal;
56
+ struct Corner { float4 position [[position]]; float2 uv; };
57
+ vertex Corner canvasVertex(uint id [[vertex_id]]) {
58
+ const float2 uv = float2((id << 1) & 2, id & 2);
59
+ Corner corner;
60
+ corner.position = float4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0);
61
+ corner.uv = uv;
62
+ return corner;
63
+ }
64
+ fragment half4 canvasFragment(Corner in [[stage_in]], texture2d<half> canvas [[texture(0)]]) {
65
+ constexpr sampler nearest(filter::nearest);
66
+ return half4(canvas.sample(nearest, in.uv).rgb, 1.0h);
67
+ }
68
+ )";
69
+
70
+ struct GpuPresenter {
71
+ id<MTLDevice> device;
72
+ id<MTLCommandQueue> queue;
73
+ id<MTLRenderPipelineState> pipeline;
74
+ };
75
+
76
+ // The shared Metal state, or nullptr where there is no usable GPU.
77
+ GpuPresenter *gpuPresenter()
78
+ {
79
+ static GpuPresenter *presenter = []() -> GpuPresenter * {
80
+ id<MTLDevice> device = MTLCreateSystemDefaultDevice();
81
+ if (!device) return nullptr;
82
+ NSError *error = nil;
83
+ id<MTLLibrary> library = [device newLibraryWithSource:kPresentShader options:nil error:&error];
84
+ if (!library) return nullptr;
85
+ MTLRenderPipelineDescriptor *descriptor = [MTLRenderPipelineDescriptor new];
86
+ descriptor.vertexFunction = [library newFunctionWithName:@"canvasVertex"];
87
+ descriptor.fragmentFunction = [library newFunctionWithName:@"canvasFragment"];
88
+ descriptor.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm;
89
+ id<MTLRenderPipelineState> pipeline = [device newRenderPipelineStateWithDescriptor:descriptor error:&error];
90
+ id<MTLCommandQueue> queue = [device newCommandQueue];
91
+ if (!pipeline || !queue) return nullptr;
92
+ return new GpuPresenter{device, queue, pipeline};
93
+ }();
94
+ return presenter;
95
+ }
96
+
97
+ IOSurfaceRef createSurface(int w, int h)
98
+ {
99
+ NSDictionary *properties = @{
100
+ (id)kIOSurfaceWidth: @(w),
101
+ (id)kIOSurfaceHeight: @(h),
102
+ (id)kIOSurfaceBytesPerElement: @4,
103
+ (id)kIOSurfacePixelFormat: @(static_cast<std::uint32_t>('BGRA')),
104
+ };
105
+ return IOSurfaceCreate((__bridge CFDictionaryRef)properties);
106
+ }
107
+
108
+ // RGBA8888 rows into an opaque BGRA surface, sliced across every core.
109
+ void copyToSurface(const std::uint32_t *src, int w, int h, IOSurfaceRef surface)
10
110
  {
11
- std::free(const_cast<void *>(data));
111
+ auto *base = static_cast<std::uint8_t *>(IOSurfaceGetBaseAddress(surface));
112
+ const std::size_t stride = IOSurfaceGetBytesPerRow(surface);
113
+ constexpr int kRowsPerSlice = 64;
114
+ const int slices = (h + kRowsPerSlice - 1) / kRowsPerSlice;
115
+ dispatch_apply(static_cast<size_t>(slices), dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^(size_t slice) {
116
+ const int y0 = static_cast<int>(slice) * kRowsPerSlice;
117
+ const int y1 = std::min(h, y0 + kRowsPerSlice);
118
+ for (int y = y0; y < y1; ++y) {
119
+ const std::uint32_t *in = src + static_cast<std::size_t>(y) * w;
120
+ auto *out = reinterpret_cast<std::uint32_t *>(base + static_cast<std::size_t>(y) * stride);
121
+ for (int x = 0; x < w; ++x) {
122
+ const std::uint32_t p = in[x]; // bytes R,G,B,A -> B,G,R,A (little-endian words)
123
+ out[x] = (p & 0x0000FF00u) | ((p & 0xFFu) << 16) | ((p >> 16) & 0xFFu) | 0xFF000000u;
124
+ }
125
+ }
126
+ });
12
127
  }
128
+ #endif
13
129
 
14
130
  } // namespace
15
131
 
132
+ @interface GeaCanvasView ()
133
+ #if GEA_EMBEDDED_PIXEL_FORMAT == GEA_PIXEL_RGBA8888
134
+ // Surfaces handed to Core Animation, reused once the render server is done
135
+ // with them. The render server reads an IOSurface in place, in the GPU's own
136
+ // BGRA format; a CGImage is converted and uploaded anew every frame.
137
+ @property(nonatomic, strong) NSMutableArray *surfaces;
138
+ // The GPU path: the canvas buffer wrapped as a texture (no copy) and drawn
139
+ // into a Metal layer's drawable.
140
+ @property(nonatomic, strong) CAMetalLayer *metalLayer;
141
+ @property(nonatomic, strong) id<MTLTexture> canvasTexture;
142
+ @property(nonatomic, assign) const void *texturePixels;
143
+ #endif
144
+ @end
145
+
16
146
  @implementation GeaCanvasView
17
147
 
18
148
  - (instancetype)initWithFrame:(CGRect)frame
@@ -27,9 +157,12 @@ void releaseFrame(void *, const void *data, std::size_t)
27
157
  return self;
28
158
  }
29
159
 
30
- - (void)drawRect:(CGRect)dirtyRect
160
+ // Sets the canvas pixels as the layer's contents, so the GPU scales and
161
+ // composites them. Drawing them in drawRect instead pushes every pixel through
162
+ // CoreGraphics on the CPU, which for a 4K canvas takes longer than the app's
163
+ // whole frame.
164
+ - (void)present
31
165
  {
32
- (void)dirtyRect;
33
166
  if (self.nodeId < 0) return;
34
167
  auto &tree = gea::embedded::ui::Tree::instance();
35
168
  if (self.nodeId >= tree.nodeCount()) return;
@@ -40,13 +173,57 @@ void releaseFrame(void *, const void *data, std::size_t)
40
173
  const int h = canvas->height();
41
174
  if (!src || w <= 0 || h <= 0) return;
42
175
 
176
+ #if GEA_EMBEDDED_PIXEL_FORMAT == GEA_PIXEL_RGBA8888
177
+ if ([self presentOnGpu:src width:w height:h]) return;
178
+ {
179
+ if (!self.surfaces) self.surfaces = [NSMutableArray array];
180
+ IOSurfaceRef surface = nullptr;
181
+ const id shown = self.layer.contents;
182
+ for (id candidate in self.surfaces) {
183
+ IOSurfaceRef s = (__bridge IOSurfaceRef)candidate;
184
+ if (static_cast<int>(IOSurfaceGetWidth(s)) != w || static_cast<int>(IOSurfaceGetHeight(s)) != h) continue;
185
+ if (candidate == shown || IOSurfaceIsInUse(s)) continue;
186
+ surface = s;
187
+ break;
188
+ }
189
+ if (!surface && self.surfaces.count < 4) {
190
+ IOSurfaceRef created = createSurface(w, h);
191
+ if (created) {
192
+ [self.surfaces addObject:(__bridge_transfer id)created];
193
+ surface = created;
194
+ }
195
+ }
196
+ if (surface && IOSurfaceLock(surface, 0, nullptr) == 0) {
197
+ copyToSurface(reinterpret_cast<const std::uint32_t *>(src), w, h, surface);
198
+ IOSurfaceUnlock(surface, 0, nullptr);
199
+ // No implicit animation: a contents change would otherwise cross-fade.
200
+ [CATransaction begin];
201
+ [CATransaction setDisableActions:YES];
202
+ self.layer.contentsGravity = kCAGravityResize;
203
+ self.layer.contents = (__bridge id)surface;
204
+ [CATransaction commit];
205
+ return;
206
+ }
207
+ }
208
+ #endif
43
209
  const std::size_t bytes = static_cast<std::size_t>(w) * h * 4;
44
- auto *dst = static_cast<std::uint8_t *>(std::malloc(bytes));
210
+ auto *dst = takeFrame(bytes);
45
211
  if (!dst) return;
46
212
  #if GEA_EMBEDDED_PIXEL_FORMAT == GEA_PIXEL_RGBA8888
47
213
  // native_t is already RGBA8888 (R,G,B,A bytes per pixel) — exactly the
48
- // CGImage's RGBX layout — so present it straight through.
49
- std::memcpy(dst, src, bytes);
214
+ // CGImage's RGBX layout — so present it straight through. One core cannot
215
+ // saturate memory bandwidth: a large canvas copies in slices on every core.
216
+ constexpr std::size_t kSlice = 4u << 20;
217
+ if (bytes >= 2 * kSlice) {
218
+ const std::size_t slices = (bytes + kSlice - 1) / kSlice;
219
+ const auto *from = reinterpret_cast<const std::uint8_t *>(src);
220
+ dispatch_apply(slices, dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^(size_t i) {
221
+ const std::size_t offset = i * kSlice;
222
+ std::memcpy(dst + offset, from + offset, std::min(kSlice, bytes - offset));
223
+ });
224
+ } else {
225
+ std::memcpy(dst, src, bytes);
226
+ }
50
227
  #else
51
228
  for (int i = 0; i < w * h; i++) {
52
229
  int r, g, b;
@@ -74,12 +251,95 @@ void releaseFrame(void *, const void *data, std::size_t)
74
251
  false,
75
252
  kCGRenderingIntentDefault);
76
253
  if (image) {
77
- UIImage *uiImage = [UIImage imageWithCGImage:image scale:1.0 orientation:UIImageOrientationUp];
78
- [uiImage drawInRect:self.bounds];
254
+ // No implicit animation: a contents change would otherwise cross-fade.
255
+ [CATransaction begin];
256
+ [CATransaction setDisableActions:YES];
257
+ self.layer.contentsGravity = kCAGravityResize;
258
+ self.layer.contents = (__bridge id)image;
259
+ [CATransaction commit];
79
260
  CGImageRelease(image);
80
261
  }
81
262
  CGDataProviderRelease(provider);
82
263
  CGColorSpaceRelease(cs);
83
264
  }
84
265
 
266
+ #if GEA_EMBEDDED_PIXEL_FORMAT == GEA_PIXEL_RGBA8888
267
+ // The GPU reads the canvas buffer where it lies (the canvas store allocates it
268
+ // in whole pages on Apple hosts) and writes the drawable: the CPU copies
269
+ // nothing. Returns NO where the buffer cannot be wrapped, for the copy paths.
270
+ - (BOOL)presentOnGpu:(const void *)src width:(int)w height:(int)h
271
+ {
272
+ #if TARGET_OS_SIMULATOR
273
+ // The simulator's Metal driver cannot wrap app memory (it traps): copy.
274
+ (void)src;
275
+ (void)w;
276
+ (void)h;
277
+ return NO;
278
+ #else
279
+ GpuPresenter *gpu = gpuPresenter();
280
+ if (!gpu) return NO;
281
+ const std::size_t page = static_cast<std::size_t>(getpagesize());
282
+ const std::size_t rowBytes = static_cast<std::size_t>(w) * 4;
283
+ if (reinterpret_cast<std::uintptr_t>(src) % page != 0) return NO;
284
+ if (rowBytes % [gpu->device minimumLinearTextureAlignmentForPixelFormat:MTLPixelFormatRGBA8Unorm] != 0) return NO;
285
+
286
+ if (src != self.texturePixels || !self.canvasTexture || static_cast<int>(self.canvasTexture.width) != w ||
287
+ static_cast<int>(self.canvasTexture.height) != h) {
288
+ self.canvasTexture = nil;
289
+ self.texturePixels = nullptr;
290
+ const std::size_t bytes = (rowBytes * h + page - 1) & ~(page - 1);
291
+ id<MTLBuffer> buffer = [gpu->device newBufferWithBytesNoCopy:const_cast<void *>(src)
292
+ length:bytes
293
+ options:MTLResourceStorageModeShared
294
+ deallocator:nil];
295
+ if (!buffer) return NO;
296
+ MTLTextureDescriptor *descriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
297
+ width:w
298
+ height:h
299
+ mipmapped:NO];
300
+ descriptor.storageMode = MTLStorageModeShared;
301
+ descriptor.usage = MTLTextureUsageShaderRead;
302
+ self.canvasTexture = [buffer newTextureWithDescriptor:descriptor offset:0 bytesPerRow:rowBytes];
303
+ if (!self.canvasTexture) return NO;
304
+ self.texturePixels = src;
305
+ }
306
+
307
+ [CATransaction begin];
308
+ [CATransaction setDisableActions:YES];
309
+ if (!self.metalLayer) {
310
+ CAMetalLayer *layer = [CAMetalLayer layer];
311
+ layer.device = gpu->device;
312
+ layer.pixelFormat = MTLPixelFormatBGRA8Unorm;
313
+ layer.framebufferOnly = YES;
314
+ layer.opaque = YES;
315
+ [self.layer addSublayer:layer];
316
+ self.metalLayer = layer;
317
+ self.layer.contents = nil;
318
+ }
319
+ if (!CGRectEqualToRect(self.metalLayer.frame, self.bounds)) self.metalLayer.frame = self.bounds;
320
+ const CGSize size = CGSizeMake(w, h);
321
+ if (!CGSizeEqualToSize(self.metalLayer.drawableSize, size)) self.metalLayer.drawableSize = size;
322
+ [CATransaction commit];
323
+
324
+ id<CAMetalDrawable> drawable = [self.metalLayer nextDrawable];
325
+ if (!drawable) return YES; // none free this frame: skip it
326
+ MTLRenderPassDescriptor *pass = [MTLRenderPassDescriptor renderPassDescriptor];
327
+ pass.colorAttachments[0].texture = drawable.texture;
328
+ pass.colorAttachments[0].loadAction = MTLLoadActionDontCare;
329
+ pass.colorAttachments[0].storeAction = MTLStoreActionStore;
330
+ id<MTLCommandBuffer> commands = [gpu->queue commandBuffer];
331
+ id<MTLRenderCommandEncoder> encoder = [commands renderCommandEncoderWithDescriptor:pass];
332
+ [encoder setRenderPipelineState:gpu->pipeline];
333
+ [encoder setFragmentTexture:self.canvasTexture atIndex:0];
334
+ [encoder drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];
335
+ [encoder endEncoding];
336
+ [commands presentDrawable:drawable];
337
+ [commands commit];
338
+ // The app draws into this same buffer next frame: wait out the GPU's read.
339
+ [commands waitUntilCompleted];
340
+ return YES;
341
+ #endif
342
+ }
343
+ #endif
344
+
85
345
  @end
@@ -12,6 +12,10 @@ namespace gea::ios {
12
12
  // resolved back to the CSS family name, then matched against fonts registered
13
13
  // from the app bundle. Unknown ids fall back to the system font.
14
14
  UIFont *fontForId(int fontId, CGFloat sizePt);
15
+ // Whether UIKit resolves `family` to a face of that family (not a fallback).
16
+ bool fontResolvesFamily(NSString *family, CGFloat size);
15
17
  #endif
18
+ // Registers the app bundle's .ttf/.otf files with CoreText (once).
19
+ void ensureFontsRegistered();
16
20
 
17
21
  } // namespace gea::ios
@@ -79,6 +79,18 @@ UIFont *fontForFamily(NSString *family, CGFloat size)
79
79
 
80
80
  } // namespace
81
81
 
82
+ void ensureFontsRegistered() { ensureBundledFontsRegistered(); }
83
+
84
+ // Whether UIKit has a face of `family` itself, not the system fallback CoreText
85
+ // substitutes for a family it does not know.
86
+ bool fontResolvesFamily(NSString *family, CGFloat size)
87
+ {
88
+ UIFont *font = fontForFamily(family, size > 0 ? size : 16);
89
+ if (!font) return false;
90
+ return [font.familyName caseInsensitiveCompare:family] == NSOrderedSame ||
91
+ [font.fontName caseInsensitiveCompare:family] == NSOrderedSame;
92
+ }
93
+
82
94
  UIFont *fontForId(int fontId, CGFloat sizePt)
83
95
  {
84
96
  #if TARGET_OS_TV
@@ -111,6 +123,20 @@ extern "C" bool gea_host_measure_text(const char *text,
111
123
  }
112
124
 
113
125
  @autoreleasepool {
126
+ const char *familyName = gea::framework::graphics::FontRegistry::familyName(fontId);
127
+ NSString *family = familyName && familyName[0] ? [NSString stringWithUTF8String:familyName] : nil;
128
+ #ifdef GEA_EMBEDDED_HAS_GENERATED_FONTS
129
+ // A family UIKit cannot resolve (a CSS alias such as "Outfit M", baked
130
+ // into the binary with no font file in the bundle) would be measured in
131
+ // the system fallback face, while the engine draws it with its baked
132
+ // glyphs: the box comes out narrower than the text and clips it. Leave
133
+ // those to the engine, which measures the face it draws.
134
+ gea::ios::ensureFontsRegistered();
135
+ if (family && !gea::ios::fontResolvesFamily(family, fontSize) &&
136
+ gea::framework::graphics::FontRegistry::rasterizedFamily(fontId, fontSize).valid()) {
137
+ return false;
138
+ }
139
+ #endif
114
140
  UIFont *font = gea::ios::fontForId(fontId, fontSize);
115
141
  if (!font) return false;
116
142
 
@@ -0,0 +1,55 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Host extensions: native code a package (or an app) compiles into an iOS or
3
+ // tvOS build to own part of the window -- typically a rendering surface such as
4
+ // a CAMetalLayer that a GL or GPU layer presents into, which the generated
5
+ // program draws through. The UIKit counterpart of gea_win32_host.h.
6
+ //
7
+ // The target calls every registered extension at fixed points of its life
8
+ // cycle; an extension registers itself from a static initializer:
9
+ //
10
+ // static const gea_uikit_host_extension kSurface = {
11
+ // GEA_UIKIT_HOST_EXTENSION_VERSION, "my-surface", attach, layout, begin, end, detach };
12
+ // static const bool kRegistered = (gea_uikit_register_host_extension(&kSurface), true);
13
+ //
14
+ // Every callback may be null. Sizes are in points (layout pixels); `scale` is
15
+ // device pixels per point.
16
+ #pragma once
17
+
18
+ #ifdef __cplusplus
19
+ extern "C" {
20
+ #endif
21
+
22
+ #define GEA_UIKIT_HOST_EXTENSION_VERSION 1u
23
+
24
+ typedef struct gea_uikit_host_extension {
25
+ unsigned version; // GEA_UIKIT_HOST_EXTENSION_VERSION
26
+ const char *name; // for diagnostics
27
+ // Once, after the window's root view exists and before the app's top level
28
+ // runs. `rootView` is the root UIView (a bridged UIView *): an extension adds
29
+ // its own subviews to it. Returning zero logs an error naming the extension.
30
+ int (*attach)(void *rootView, double width, double height, double scale);
31
+ // The root view's size or scale changed.
32
+ void (*layout)(double width, double height, double scale);
33
+ // Around the app's initialization and around every frame. A zero return
34
+ // from begin_frame skips that frame; end_frame runs whenever begin_frame ran.
35
+ int (*begin_frame)(void);
36
+ void (*end_frame)(void);
37
+ // Never called today (an iOS app is not shut down); for symmetry with Windows.
38
+ void (*detach)(void);
39
+ } gea_uikit_host_extension;
40
+
41
+ void gea_uikit_register_host_extension(const gea_uikit_host_extension *extension);
42
+
43
+ // Called by the target (ios_main.mm).
44
+ void gea_uikit_host_attach(void *rootView, double width, double height, double scale);
45
+ void gea_uikit_host_layout(double width, double height, double scale);
46
+ // Returns zero when an extension skipped the frame; gea_uikit_host_end_frame
47
+ // must follow a nonzero return.
48
+ int gea_uikit_host_begin_frame(void);
49
+ void gea_uikit_host_end_frame(void);
50
+ // Whether any extension is registered (the host then leaves the window to it).
51
+ int gea_uikit_host_has_extensions(void);
52
+
53
+ #ifdef __cplusplus
54
+ }
55
+ #endif
@@ -17,6 +17,7 @@
17
17
  #include "event.h"
18
18
  #include "events.h"
19
19
  #include "font_registry.h"
20
+ #include "gea_uikit_host.h"
20
21
  #include "image.h"
21
22
  #include "ios_renderer.h"
22
23
  #include "ios_root_background.h"
@@ -678,6 +679,9 @@ static void dispatchRemoteKey(int keyCode)
678
679
  @property(nonatomic, strong) GeaDisplayView *displayView;
679
680
  @property(nonatomic, strong) UIView *nativeRootView;
680
681
  @property(nonatomic, strong) CADisplayLink *displayLink;
682
+ // The root view's size (height times scale, so a scale change shows) last
683
+ // reported to the host extensions.
684
+ @property(nonatomic, assign) CGSize extensionLayout;
681
685
  - (void)installNativeRootView:(UIView *)view;
682
686
  @end
683
687
 
@@ -820,7 +824,15 @@ static void dispatchRemoteKey(int keyCode)
820
824
  // On iOS the build sets GEA_EMBEDDED_PIXEL_FORMAT=GEA_PIXEL_RGBA8888, so the
821
825
  // ImageStore decodes straight to full-colour RGBA8888 native pixels (no 565
822
826
  // quantization, no separate retained buffer) for native UIImageView.
827
+ // Host extensions (a package's GL or GPU surface) take their part of the
828
+ // window before the program's top level runs: the program creates its
829
+ // context while it initializes, inside the extensions' frame bracket.
830
+ const CGSize rootSize = self.rootView.bounds.size;
831
+ self.extensionLayout = CGSizeMake(rootSize.width, rootSize.height * viewportScale);
832
+ gea_uikit_host_attach((__bridge void *)self.rootView, rootSize.width, rootSize.height, viewportScale);
833
+ const bool extensionsBegun = gea_uikit_host_begin_frame() != 0;
823
834
  gea::framework::app::Application::init(viewportWidth, viewportHeight, devicePixelRatio);
835
+ if (extensionsBegun) gea_uikit_host_end_frame();
824
836
  [self syncAppBackgroundColor];
825
837
  [self tick:nil];
826
838
 
@@ -879,7 +891,25 @@ static void dispatchRemoteKey(int keyCode)
879
891
  }
880
892
  gea::embedded::ui::StyleSheet::instance().startCssAnimations(static_cast<std::uint32_t>(nowMs));
881
893
  gea::css::AnimationEngine::instance().tick(static_cast<std::uint32_t>(nowMs));
882
- gea::framework::app::Application::frame(nowMs);
894
+ // Native views present the tree, so the software framebuffer is never
895
+ // shown: skip rasterizing it (a 4K canvas costs two full-frame copies).
896
+ gea::embedded::ui::Tree::instance().setSoftwareRasterSuppressed(
897
+ !self.nativeRootView && gea::ios::IosRenderer::instance().hasNativeTree() &&
898
+ !gea::framework::display::Underlay::active());
899
+ if (gea_uikit_host_has_extensions()) {
900
+ const CGSize rootSize = self.rootView.bounds.size;
901
+ const CGFloat scale = [self viewportScale];
902
+ const CGSize layout = CGSizeMake(rootSize.width, rootSize.height * scale);
903
+ if (!CGSizeEqualToSize(layout, self.extensionLayout)) {
904
+ self.extensionLayout = layout;
905
+ gea_uikit_host_layout(rootSize.width, rootSize.height, scale);
906
+ }
907
+ if (!gea_uikit_host_begin_frame()) return;
908
+ gea::framework::app::Application::frame(nowMs);
909
+ gea_uikit_host_end_frame();
910
+ } else {
911
+ gea::framework::app::Application::frame(nowMs);
912
+ }
883
913
  [self syncAppBackgroundColor];
884
914
  auto &tree = gea::embedded::ui::Tree::instance();
885
915
  const int root = tree.mountedRoot();
@@ -167,7 +167,7 @@ void applyImageProps(UIImageView *imageView, const gea::embedded::ui::Node &node
167
167
  void applyCanvasProps(GeaCanvasView *canvasView, int nodeId)
168
168
  {
169
169
  canvasView.nodeId = nodeId;
170
- [canvasView setNeedsDisplay];
170
+ [canvasView present];
171
171
  }
172
172
 
173
173
  void applyTypeSpecificProps(UIView *view, const gea::embedded::ui::Node &node, int nodeId, CGFloat scale)
@@ -0,0 +1,71 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // The registry and life-cycle calls of iOS/tvOS host extensions (gea_uikit_host.h).
3
+ #include "gea_uikit_host.h"
4
+
5
+ #include <cstdio>
6
+
7
+ namespace {
8
+
9
+ constexpr int kMaxExtensions = 8;
10
+ const gea_uikit_host_extension *gExtensions[kMaxExtensions];
11
+ int gExtensionCount = 0;
12
+ // Extensions whose begin_frame ran this frame, so only they get end_frame.
13
+ bool gBegun[kMaxExtensions];
14
+
15
+ } // namespace
16
+
17
+ extern "C" void gea_uikit_register_host_extension(const gea_uikit_host_extension *extension)
18
+ {
19
+ if (!extension || extension->version != GEA_UIKIT_HOST_EXTENSION_VERSION) {
20
+ std::fprintf(stderr, "[gea] host extension %s has an unsupported version\n", extension && extension->name ? extension->name : "?");
21
+ return;
22
+ }
23
+ if (gExtensionCount >= kMaxExtensions) {
24
+ std::fprintf(stderr, "[gea] too many host extensions; %s ignored\n", extension->name ? extension->name : "?");
25
+ return;
26
+ }
27
+ gExtensions[gExtensionCount++] = extension;
28
+ }
29
+
30
+ extern "C" int gea_uikit_host_has_extensions(void) { return gExtensionCount > 0; }
31
+
32
+ extern "C" void gea_uikit_host_attach(void *rootView, double width, double height, double scale)
33
+ {
34
+ for (int i = 0; i < gExtensionCount; ++i) {
35
+ const auto *extension = gExtensions[i];
36
+ if (extension->attach && !extension->attach(rootView, width, height, scale)) {
37
+ std::fprintf(stderr, "[gea] host extension %s failed to attach\n", extension->name ? extension->name : "?");
38
+ }
39
+ }
40
+ }
41
+
42
+ extern "C" void gea_uikit_host_layout(double width, double height, double scale)
43
+ {
44
+ for (int i = 0; i < gExtensionCount; ++i) {
45
+ if (gExtensions[i]->layout) gExtensions[i]->layout(width, height, scale);
46
+ }
47
+ }
48
+
49
+ extern "C" int gea_uikit_host_begin_frame(void)
50
+ {
51
+ bool run = true;
52
+ for (int i = 0; i < gExtensionCount; ++i) {
53
+ gBegun[i] = false;
54
+ if (!run) continue;
55
+ if (gExtensions[i]->begin_frame && !gExtensions[i]->begin_frame()) {
56
+ run = false;
57
+ continue;
58
+ }
59
+ gBegun[i] = true;
60
+ }
61
+ if (!run) gea_uikit_host_end_frame();
62
+ return run ? 1 : 0;
63
+ }
64
+
65
+ extern "C" void gea_uikit_host_end_frame(void)
66
+ {
67
+ for (int i = gExtensionCount - 1; i >= 0; --i) {
68
+ if (gBegun[i] && gExtensions[i]->end_frame) gExtensions[i]->end_frame();
69
+ gBegun[i] = false;
70
+ }
71
+ }