Your own C++ host
The host's side of the contract with the engine. Platform interfaces, SDK settings, the frame loop, threads, DevTools and shutdown.
A host is the program that owns the window, the GPU device and the input loop. The engine owns none of them. This page is the reference for what the host provides and in what order. For a first working page, follow Your first view. For the compile and link settings, see Requirements.
The package contains the engine and its headers, but no host and no renderer backend. You write the host, and either write a render context or use the Unreal plugin or the O3DE gem. See Rendering backends.
The order that works
Four things must happen in this order:
- Settings that the SDK reads while it initializes.
- The platform interfaces.
ApertureSDK::Initialize, with your license settings.- The platform and the JavaScript engine.
#include <APHTML/APEngine.h>
#include <APHTML/Interfaces/APCFileSystem.h>
#include <APHTML/Interfaces/APCLoggingSystem.h>
#include <APHTML/Interfaces/APCMemoryAllocator.h>
#include <APHTML/Interfaces/APCPlatform.h>
#include <memory>
#include <string>
struct ApertureHost
{
std::string root; // IAPCFileSystem keeps this pointer, not a copy
std::unique_ptr<aperture::core::IAPCFileSystem> fileSystem;
std::unique_ptr<aperture::core::DefaultLoggingSystem> logging;
std::unique_ptr<aperture::core::IAPCMemoryAllocator> memory;
};
// executableDirectory is the folder that holds your .exe, ending in a path separator.
bool StartAperture(ApertureHost& host, const std::string& executableDirectory)
{
// 1. Settings the SDK reads while it initializes.
aperture::ApertureSDK::SetScriptThreadCount(2);
aperture::ApertureSDK::SetPlatformName("MyEngine");
aperture::ApertureSDK::SetPlatformVersion("1.0");
// 2. The platform interfaces.
host.root = executableDirectory;
host.fileSystem = std::make_unique<aperture::core::IAPCFileSystem>(host.root.c_str());
host.logging = std::make_unique<aperture::core::DefaultLoggingSystem>();
host.memory = std::make_unique<aperture::core::IAPCMemoryAllocator>();
auto platform = aperture::core::IAPCPlatform::GetEnginePlatform();
platform->SetFileSystem(host.fileSystem.get());
platform->SetLoggingSystem(host.logging.get());
platform->SetMemoryAllocator(host.memory.get());
// 3. The license check runs inside Initialize and uses the interfaces above.
aperture::LicenseConfig license;
license.key = "APUI-XXXX-XXXX-XXXX-XXXX"; // development builds only
license.projectId = "your-project-id";
aperture::ApertureSDK::Initialize(license);
if (!aperture::ApertureSDK::IsSDKActive())
return false; // the reason is in the log; do not create a view
// 4. The platform, then V8. Nothing starts V8 for you.
if (!platform->InitializePlatform())
return false;
platform->StartPlatform();
return platform->InitializeJavaScriptEngine().IsSuccess();
}ApertureSDK::ConfigureJavaScriptEngineand the thread counts must come beforeInitialize. The engine refuses a changed thread count once the SDK is active, and the log says so. Set a script cache provider before you create the first view.InitializePlatform()returnsfalsewhen no logging system is installed.InitializeJavaScriptEngine()needs an active SDK. Without the call, a page that contains a script tag runs no script, and the log says to call it.- Create a
UIViewonly whileIsSDKActive()istrue. A view created on an inactive SDK is undefined behavior, andUIViewdoes not guard against it.
Where the license settings go
aperture::LicenseConfig has three fields. A host fills them in before Initialize:
| Field | Meaning |
|---|---|
key | The APUI- key from your project page. Development SDKs verify it locally against the signed certificate. Shipping and console builds do not need it. |
projectId | The Project ID (a UUID) from your project page. |
certificatePath | The path of aperture.license, UTF-8. Empty means aperture.license next to the executable, or in the application directory on a console. |
Do not commit the key. Read it from the environment, a per-user file or your build machine's secret
store. A development SDK checks the key and signed aperture.license locally. Shipping and
console SDKs validate the certificate without a development key. There is no activation request,
machine binding or cached lease. The SDK's own configuration determines those checks; linking it
into a different host configuration does not change them. See Licensing in practice.
The Unreal plugin and the O3DE gem expose the same three
fields in their own settings. See Unreal Engine and
O3DE.
Platform interfaces
The engine reaches the outside world through interfaces that you install on
aperture::core::IAPCPlatform::GetEnginePlatform(). It keeps a raw pointer to each one, so the
object must outlive the platform.
| Interface | Install with | Needed? |
|---|---|---|
IAPCLoggingSystem | SetLoggingSystem | Yes. InitializePlatform() fails without it, and a license failure is reported through it. DefaultLoggingSystem is the stock implementation. |
IAPCFileSystem | SetFileSystem | Yes, for any page that loads a file and for text: the search for the bundled fonts uses it. See File system. |
IAPCMemoryAllocator | SetMemoryAllocator | Yes. See below. |
IAPCNetworkProvider | SetNetworkProvider | For fetch(), XMLHttpRequest, WebSocket and loadHtmlFromUrl(). Also the activation channel of a development build on a PC platform other than Windows. |
IAPCTimerProvider | SetTimerProvider | No. It supplies the clock behind setTimeout, setInterval and performance.now(). Without one the engine uses its own. |
IAPCAudioOutput, IAPCVideoDecoder | SetAudioOutput, SetVideoDecoder | Only for <video>. See Video and audio. |
IScriptCacheProvider | ApertureSDK::SetScriptCacheProvider | No. It stores V8's compiled bytecode between runs. |
Logging. DefaultLoggingSystem keeps the messages and can forward them. Install a forwarding
callback to send engine and page output to your own log:
host.logging->SetInternalEngineLogging(true);
host.logging->SetLogForwardCallback(
[](aperture::core::IAPCLoggingSystem::LogLevel level, const std::string& message)
{
MyEngine::Log("Aperture", static_cast<int>(level), message.c_str());
});A page's console calls reach the same system through DOMConsoleHook, with the call's level and
message. To take over everything, derive from IAPCLoggingSystem and implement its eight pure
virtual functions.
Memory. IAPCMemoryAllocator is not a hook for every allocation. The engine calls it for
V8's ArrayBuffer memory and for a few URI strings, and it does not redirect the engine's own
heap. Install one anyway: the ArrayBuffer allocator calls through it without checking for null. V8
calls Alloc with an alignment of 0, so an allocator that forwards the alignment must treat 0
as "default".
class GameAllocator final : public aperture::core::IAPCMemoryAllocator
{
public:
void* Alloc(size_t size, size_t align) override
{
return MyEngine::Alloc(size, align != 0 ? align : 16);
}
void Free(void* memory) override { MyEngine::Free(memory); }
void* Realloc(void* memory, size_t oldSize, size_t newSize, size_t align) override
{
return MyEngine::Realloc(memory, oldSize, newSize, align != 0 ? align : 16);
}
};Network. aperture::networking::DefaultNetworkProvider (in apertureuinetwork.dll) provides
HTTP, HTTPS and WebSocket. Register it, or implement IAPCNetworkProvider over your own stack:
FetchAsync is the one function you must write, and OpenWebSocket is optional. The completion
callback may run on any thread. For a WebSocket, the engine moves your event handlers to the script
thread itself. See
Requirements for the files it needs.
#include <NetworkEngine/HTTPS/DefaultNetworkProvider.h>
aperture::networking::DefaultNetworkProvider network;
aperture::core::IAPCPlatform::GetEnginePlatform()->SetNetworkProvider(&network);SDK settings
These are static functions on aperture::ApertureSDK.
| Setting | What it does |
|---|---|
SetScriptThreadCount(n) | Sizes V8's worker pool. It is the only thread count the engine reads. Set it before Initialize. |
SetRenderThreadCount(n), SetCompositionThreadCount(n) | The SDK stores the values and the engine reads neither of them in this version. They change nothing. |
SetPlatformName, SetPlatformVersion | The SDK stores the strings and returns them from GetPlatformName and GetPlatformVersion. The engine does not read them. |
ConfigureJavaScriptEngine(JSEngineConfig) | Where V8's icuDataPath and snapshotBlobPath are, the EV8EngineFlags to pass (ExposeGC by default, Jitless for platforms without executable memory), tierUpBudget and validateResourcesOnInit. The config holds bare const char* paths. Keep the strings alive until InitializeJavaScriptEngine() has run. Call it before Initialize. The config also declares lazyInitialization (default true, documented as "V8 starts on first script execution"), but the engine never reads it: V8 starts in InitializeJavaScriptEngine() either way. |
SetParallelStyleEnabled(bool) | The multi-threaded style pass. On by default, and you can switch it at runtime. |
SetIncrementalLayoutEnabled(bool) | Skips clean subtrees when laying out. On by default. |
SetGeometryUploadCacheEnabled(bool) | Skips re-uploading geometry that is already on the GPU. Off by default. |
SetSlugPrimitivesEnabled(bool) | Draws rounded backgrounds and borders through the GPU vector glyph path. Off by default. These draws are VectorGlyphText commands, so the backend needs the glyph buffers (see Text), and the setting does nothing while vector glyph rendering is off. |
SetScriptCacheProvider(provider) | Bytecode cache. Set it before you create a view. WriteCache is called only when ApertureSDK::IsCachingAllowed() is true. |
Text has its own switch, FontEngineBridge::SetVectorGlyphRenderingEnabled(bool) from
APHTML/Font/FontEngineBridge.h (the header needs LINAVG_DISABLE_TEXT_SUPPORT, see
Requirements). Vector glyphs are on by default,
and the backend must handle the route in use: see
Rendering backends.
The frame
You own the frame loop. A view advances only when you tick it.
void Frame(aperture::UIView& view, float deltaSeconds,
aperture::harrlow::renderpath::APHIRenderContext& renderContext)
{
// 1. Forward this frame's input to the view (see Input).
// 2. Advance time, run timers, scripts and animations.
view.tick(deltaSeconds);
// 3. Paint into a command list.
const auto& commands = view.buildCommandList();
// 4. Your render context draws it. Your backend begins and presents the frame.
renderContext.SubmitHarrlowCommands(commands);
}tick() advances CSS animations and transitions, runs timers and requestAnimationFrame
callbacks, and updates style and layout. buildCommandList() paints. Ticking without building
advances state and draws nothing.
- Call
setRenderPathContext(context)once after you create a view. Pass the same context that later draws its list. Without it, opacity groups, blend isolation, filters and masks fall back to per-vertex alpha, which blends overlapping children twice. - Give the view's size with
setViewportSize(width, height).setMediaEnvironmentsets the device pixel ratio, dark mode and reduced motion for@mediaandmatchMedia, andsetEnvVariablesetsenv(safe-area-inset-*)values. - The command list is a
HarrlowCommandList. See Rendering backends. UIView::renderToTexture()and the functions around it are stubs. To draw a view into a texture, make your render context bind a render target of your own before it draws the list.
Several views
Each UIView has its own DOM, window, V8 isolate, input state and command list. The engine keeps
no global list of views, so you tick and draw each one. Tick every view once per frame: the
animation clock advances once per frame, from the first view ticked in it, and not once per view.
for (auto& view : views)
view->tick(deltaSeconds);
for (auto& view : views)
Draw(view->buildCommandList()); // your renderer, in the order you want them compositedCommon uses are a HUD and a menu with different focus rules, one view per player in split screen, and a world-space screen drawn into a render target.
Threads
- Treat a view as single-threaded. Style, layout, script and paint run on the thread that
calls
tick()andbuildCommandList(), and nothing locks a view against a second thread. Keep input, DOM calls,executeJavaScriptand canvas work on that thread. - The engine uses worker threads for resource loading, V8's background work, and the style pass
(
SetParallelStyleEnabled). Font work is serialized behind one global mutex. - A network provider may complete a request on any thread, and the header does not promise which.
- A native function that script calls through the binder runs on whichever thread is running the
page's script: the one that calls
tick(), the input functions orexecuteJavaScript. If that is your game thread, there is nothing to marshal. If the view lives on a separate UI thread, hand the call over to your game thread before you touch state that is not thread-safe. See Scripting.
If your engine replaces the global operator new and operator delete (Unreal does), do not pass
an owning std::vector or std::string across the DLL boundary. The header names the pointer
overloads for that case: executeJavaScriptRaw, getDocumentTitleRaw, getDocumentUrlRaw and
getFocusedElementIdRaw.
DevTools
Chrome DevTools attach to a view through a server that your host starts. It opens a debugging port,
so start it only in builds that stay inside your team. The package holds
apertureuideveloperengine.dll in every configuration. aperture::developer::DevToolsHost is the
facade for embedders. It needs only its own header and publishes one inspected view at a time.
#include <DeveloperEngine/DevToolsHost.h>
aperture::developer::DevToolsHost* devTools = aperture::developer::DevToolsHost::Create();
if (devTools) // null while another instance is alive: one per process
{
aperture::developer::DevToolsHostConfig config; // 127.0.0.1:9222 by default
config.m_authToken = "pick-a-token"; // empty disables the token check
if (devTools->Start(config))
devTools->SetInspectedView(&view);
}
// Every frame, on the main thread. Without it, most commands time out.
if (devTools)
devTools->Tick();Browser-origin protection is always on. Cross-origin WebSocket and HTTP requests are rejected, and
so are non-loopback Host headers on a loopback bind. The 26.08.0.1 Windows SDK includes the
network-enabled server. A custom PartialCore source build can still select its stub network;
see The PartialCore build. APPlayer, which
is in the source tree, starts DevTools on 127.0.0.1:9222 at launch.
Video and audio
<video> decoding is compiled in only where APUI_HAS_VIDEO is defined, which a full engine build
does and the PartialCore packages do not. In a build with video, the engine installs its own Windows
decoder when you register none. IAPCVideoDecoder replaces it, and IAPCAudioOutput receives the
audio of <video> elements.
Shutdown
Release things in the reverse order that you created them:
void StopAperture(ApertureHost& host, aperture::UIView* view)
{
delete view; // views first: they borrow the interfaces
// shut down your render context and release its GPU resources here
if (auto platform = aperture::core::IAPCPlatform::GetEnginePlatform())
platform->KillPlatform(); // also shuts V8 down
host.memory.reset();
host.logging.reset();
host.fileSystem.reset();
aperture::ApertureSDK::Shutdown();
}- Stop DevTools (
DevToolsHost::Destroy). - Destroy every
UIView. - Shut down your render context and release its GPU resources.
- Call
KillPlatform(). - Destroy the interfaces you installed.
- Call
ApertureSDK::Shutdown().
ApertureSDK::Shutdown() marks the SDK inactive, so a "restart the UI engine" command can call
Initialize again in the same process. It does not tear down the task system, the V8 platform or
the log writers, which live until the process exits. KillPlatform() releases the platform object:
the next GetEnginePlatform() returns a new one with nothing installed, so a restart installs the
interfaces again before it calls Initialize.
Integration
How Aperture UI plugs into a game. Your own C++ host, the Unreal Engine plugin or the O3DE gem, and the pages for rendering, input, scripting and files.
Unreal Engine
The Aperture UI plugin for Unreal Engine. Install, license settings, a UMG widget, view assets, screen layers, world-space screens and the Blueprint API.