Skip to content

Writing a backend

A backend runs JOID on a stack that JOID does not ship: another graphics API, the renderer of a game engine, another window library. It creates the bridges for that stack and registers them through a subclass of Backend, without any change to the core. This page builds one, then checks it against the official LWJGL 3 rendering.

Before you start, read Architecture and layers and The bridges.

Your engineWriteModel
Runs on GLFW, OpenAL or OpenGLA Backend subclass that reuses the base modules; on OpenGL, an IGlBinding over the OpenGL functions of your engine.LWJGL 3 backend
Has its own renderer (Vulkan, a modern engine)A RenderBridge subclass with its textures, framebuffers and shaders, plus the bridges you cannot reuse.Vulkan backend
Owns the window and the loop, and lets you draw inside its frameOne of the above, plus the rules of Embedding in a host.LWJGL 2 backend for an input queue that the loop drains

The examples of this page target an imaginary engine: Engine and EngineDevice stand for its API, one method for one call of that API.

Each release publishes joid-backend-template-<version>.zip, a Gradle project that compiles against the JOID jars only.

  1. Put the jars listed in libs/README.md into libs/: the prod, dev and demo jars of the core, the testkit, and the demo jar of the LWJGL 3 backend, which renders the images your backend is compared with.
  2. Rename the package com.example.joid.backend in src/main/java, src/test/java and src/demo/java. In build.gradle, rename group, archivesBaseName, backendPackage and the main class of the runDemo task; in settings.gradle, rename rootProject.name.
  3. Add the libraries of your engine to the compile dependencies. Put the base modules you reuse into the embed configuration, so that they go inside your jars; a binding module needs the agnostic module it binds next to it (joid-base-lwjgl3-openal needs joid-base-openal).

Check: ./gradlew compileJava succeeds. The bridges of the template throw an UnsupportedOperationException that names the method to implement, so the first UI that opens, or the first frame(), fails until you have implemented them.

Backend is the base of every backend: the three official ones are small final classes over it. Your subclass creates its bridges in hooks:

public final class EngineBackend extends Backend {
private final Engine engine;
private EngineBackend(final Engine engine) {
this.engine = engine;
}
public static EngineBackend create(final Engine engine) {
return new EngineBackend(engine);
}
@Override
protected IWindowBridge createWindowBridge() {
return new EngineWindowBridge(this.engine);
}
@Override
protected IRenderBridge createRenderBridge() {
return new EngineRenderBridge(this.engine.getDevice());
}
@Override
protected IAudioBridge createAudioBridge() {
return AlAudioBridge
.create(Lwjgl3AlBinding.inst())
.ownContext(false)
.gain((gain, group) -> gain * this.engine.getVolume(group));
}
@Override
protected IThreadBridge createThreadBridge() {
return new EngineThreadBridge(this.engine);
}
@Override
protected void registerDefaults() {
super.registerDefaults();
ResourceResolver.register(new EngineSpriteResourceResolver(this.engine.getDevice()));
}
@Override
protected void attachInput() {
this.engine.addListener(new EngineInputForwarder(this.engine));
}
}

Full file: EngineBackend.java

Backend.register calls the hooks in this order, between its version check and the loading of JOID (What happens at register() gives the whole sequence from the side of an application):

HookWhat it givesDefault
createAudioBridge()The audio bridge; not called when the application set audio(false).null: no sound.
createWindowBridge()The window bridge.Required.
createRenderBridge()The render bridge.Required.
createThreadBridge()The thread bridge; null keeps the bridge already registered.A FrameThreadBridge on the thread that calls register().
registerDefaults()What goes into the shared registries.A WindowUIBridge through registerDefault, registered only when the application registered no UI bridge before.
attachInput()The connection from the input of the window to JOID.Nothing.

Override registerDefaults() with a call to super.registerDefaults() first, so that the default UI bridge stays. register() runs once: a second call throws an IllegalStateException.

The build of the template writes the version of JOID it compiles against into backend.properties, in the package that backendPackage names: keep that package equal to the package of your Backend subclass. The constructor of Backend reads that file, and register() throws an IllegalStateException when the loaded JOID has another major version; without the file, as when you run from your IDE before any build, it checks nothing.

The application creates the backend, configures it, and calls register() once the engine is ready to draw, then Backend.frame in its loop. The setters of Backend return the type of their target, so an application calls the setters of your subclass first and the common ones after:

final EngineBackend backend = EngineBackend.create(engine).audio(false).register();

The window bridge reports the size, the mouse, the held keys and the clipboard. Its contract and the bridge of this engine are on Window bridge. On GLFW, return a GlfwWindowBridge of base-lwjgl3-glfw.

Extend RenderBridge: it keeps the matrices and the state, and your subclass turns them into the calls of your API.

public final class EngineRenderBridge extends RenderBridge {
private final EngineDevice device;
private ByteBuffer vertices;
public EngineRenderBridge(final EngineDevice device) {
this.device = device;
this.vertices = ByteBuffer.allocateDirect(VertexBuffer.STRIDE * 4096).order(ByteOrder.nativeOrder());
}
public EngineDevice getDevice() {
return this.device;
}
@Override
protected void drawPrimitive(final Primitive primitive, final VertexBuffer buffer, final IShader shader) {
super.requireFrame();
final RenderState state = super.getState();
this.applyTarget(state);
this.device.blend(state.getBlend());
this.device.depth(state.isDepthTest(), state.isDepthWrite());
this.device.cull(state.isCull());
this.device.colorMask(state.isColorWrite());
this.device.stencil(state.getStencil());
final EngineShader program = (EngineShader) shader;
for (final UniformSampler sampler : program.getSamplerMap().values()) {
final SamplerBinding binding = super.resolveSampler(sampler);
final IEngineTexture texture = (IEngineTexture) binding.getTexture();
this.device.texture(sampler.getUnit(), texture.getId(), binding.getSampling());
}
program.upload(state, buffer);
final ByteBuffer vertices = VertexFill.complete(buffer, this.getVertices(buffer));
this.device.draw(primitive == Primitive.LINES, vertices, buffer.getCount(), program.getProgram());
}
@Override
protected void clearColorBuffer(final float red, final float green, final float blue, final float alpha) {
super.requireFrame();
this.applyTarget(super.getState());
this.device.colorMask(true);
this.device.clearColor(red, green, blue, alpha);
}
@Override
protected void clearDepthBuffer() {
super.requireFrame();
this.applyTarget(super.getState());
this.device.depth(false, true);
this.device.clearDepth(1F);
}
@Override
protected void clearStencilBuffer() {
super.requireFrame();
this.applyTarget(super.getState());
this.device.stencilMask(0xFF);
this.device.clearStencil(0);
}
@Override
public ITexture createTexture() {
return new EngineTexture(this.device);
}
@Override
public IFrameBuffer createFrameBuffer(final int width, final int height) {
return new EngineFrameBuffer(this.device, width, height);
}
@Override
public IShader createShader(final ShaderSource vertex, final ShaderSource fragment, final BlendState blend) {
return new EngineShader(this, vertex, fragment, blend);
}
@Override
public void suspend(final Runnable draw) {
draw.run();
}
@Override
public void raster(final IFrameBuffer target, final int width, final int height, final Runnable draw) {
super.requireFrame();
this.device.target(((EngineFrameBuffer) target).getTarget());
this.device.viewport(0, 0, width, height);
draw.run();
}
private void applyTarget(final RenderState state) {
final IFrameBuffer target = state.getFrameBuffer();
this.device.target(target == null ? 0 : ((EngineFrameBuffer) target).getTarget());
final int width = state.getViewportWidth();
final int height = state.getViewportHeight();
this.device.viewport(state.getViewportX(), state.getViewportY(), width, height);
}
private ByteBuffer getVertices(final VertexBuffer buffer) {
final int size = buffer.getCount() * VertexBuffer.STRIDE;
if (this.vertices.capacity() < size) {
this.vertices = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());
}
this.vertices.clear();
return this.vertices;
}
}

Full file: EngineRenderBridge.java

drawPrimitive applies the whole state at each draw, and each clear first allows the writes that it clears: the core changed the state since the previous draw without telling you. For the same reason, suspend runs the drawing of a host as is: the next draw applies the state of JOID again. raster targets the framebuffer at the given size and requires an open frame, like every draw. Render bridge lists every rule a draw respects, and Render pipeline explains what reaches it.

Extend Texture: it keeps the size, the levels and the deletion, and calls four hooks. Pixels arrive as ARGB ints, row by row from the top; forEachStep walks the mip levels, so that every backend fills the same levels (Mipmaps).

public final class EngineTexture extends Texture implements IEngineTexture {
private final int id;
private final EngineDevice device;
public EngineTexture(final EngineDevice device) {
this.device = device;
this.id = device.createTexture();
}
@Override
public int getId() {
return this.id;
}
@Override
protected void allocateStorage(final MipmapChain chain) {
final int maxSize = this.device.getMaxTextureSize();
if (chain.getWidth() > maxSize || chain.getHeight() > maxSize) {
final String size = chain.getWidth() + "x" + chain.getHeight();
throw new IllegalArgumentException(
"A texture of " + size + " exceeds the maximum size " + maxSize + " of the engine, downscale the image"
);
}
this.device.allocateLevels(this.id, chain.getWidth(), chain.getHeight(), 0, chain.getLevels());
}
@Override
protected void uploadPixels(final int[] pixels, final MipmapChain chain) {
this.device.uploadTexture(this.id, chain.getWidth(), chain.getHeight(), pixels);
chain.forEachStep(this::copy);
}
@Override
protected void generateMipmapLevels(final MipmapChain chain, final int allocatedLevels) {
if (allocatedLevels != chain.getLevels()) {
this.device.allocateLevels(this.id, chain.getWidth(), chain.getHeight(), 1, chain.getLevels());
}
chain.forEachStep(this::copy);
}
@Override
protected void deleteStorage() {
this.device.deleteTexture(this.id);
}
private void copy(final int level, final int fromWidth, final int fromHeight, final int width, final int height) {
this.device.copyLevel(this.id, level, fromWidth, fromHeight, width, height);
}
}

Full file: EngineTexture.java

Extend FrameBufferHandle: its constructor takes the color texture, and deleteHandle() releases the rest. A framebuffer has a depth attachment, and no stencil that the core relies on (Framebuffers and depth).

public final class EngineFrameBuffer extends FrameBufferHandle<EngineTexture> {
private final int target;
private final EngineDevice device;
public EngineFrameBuffer(final EngineDevice device, final int width, final int height) {
super(new EngineTexture(device));
super.getTexture().allocate(width, height);
this.device = device;
this.target = device.createTarget(super.getTexture().getId(), width, height);
}
public int getTarget() {
return this.target;
}
@Override
protected void deleteHandle() {
this.device.deleteTarget(this.target);
}
}

Full file: EngineFrameBuffer.java

Extend Shader and give its constructor a GlslShaderTranslator for the GLSL dialect of your API and its uniform layout:

super(bridge, new GlslShaderTranslator(GlslDialect.GLSL_330, UniformLayout.BLOCK), vertex, fragment, blend);

Full file: EngineShader.java

The constructor of Shader builds the uniform block and the samplers and translates both stages. It compiles nothing: compileProgram runs at the first call of isActive(), so the fields of your subclass are ready by then. Implement the three hooks, and send the uniform block at each draw when pack() reports a change:

public void upload(final RenderState state, final VertexBuffer buffer) {
final float[] projection = super.getBridge().getProjection().getRawMatrix();
final UniformBlock block = super.builtins(state, buffer, projection, super.getBridge().getModelView());
if (block.pack()) {
this.device.uniforms(this.program, block.getData());
}
}
@Override
protected void compileProgram(final ShaderTranslation translation) {
this.program = this.device.createProgram(translation.getVertex(), translation.getFragment());
if (this.program == 0) {
JOIDLog.warn("The engine cannot compile a shader program, fix its sources from the log of the engine");
}
}
@Override
protected boolean isProgramActive() {
return this.program != 0;
}
@Override
protected void deleteProgram() {
this.device.deleteProgram(this.program);
this.program = 0;
}

Full file: EngineShader.java

Shader translation explains the dialects, the uniform layouts and what the translator adds.

Both are optional. Without audio, delete the createAudioBridge() override of the template: the default returns null.

registerDefaults() fills the registries that several parties share. The example registers a resource resolver, so that Resource.of accepts the sprites of the engine (Resource resolvers). Register there every registry that your host feeds, as the table of Feed the core, never the interface lists: resource resolvers, asset locators, key resolvers, text converters. Markups and UI bridges belong to the application, which adds them before or after register().

attachInput() connects the events of your window to BridgeHandler.UI. Input forwarding gives the contract and the forwarder of this engine. When the events belong to the loop of the application (a queue drained each frame), leave attachInput() empty and give the application a forwarder to call, as the LWJGL 2 backend does.

With every hook implemented, an application runs your backend like an official one. The DemoWindow of the template, in src/demo/java, registers itself as the UI bridge, then registers ExampleBackend, opens the menu of the demos and calls frame() in an endless loop. Give it the constructor of your backend and the loop of your engine: poll the events, call frame(), present.

Check: ./gradlew runDemo opens the JOID demos on your engine (Demos). On macOS, an engine on GLFW needs jvmArgs '-XstartOnFirstThread' on runDemo and on the test tasks; an engine on AWT or Swing must not have it.

The tests render real frames on a hidden surface, through the ExampleSnapshotBackend of the template in src/test/java. Implement its methods as Testing a backend shows for this engine; RenderBridgeContractTest, BitmapFontContractTest and SnapshotTest of the template already use it.

The testkit compares your rendering with the official one, image by image. Run these steps in order, each one once the previous one is green; Run the tests of your backend says what each task does.

  1. ./gradlew test: the first run fails until the references of your GPU exist.
  2. ./gradlew updateSnapshots.
  3. ./gradlew crossBackendTest.
  4. Open the report.html that a failure prints, fix, and run crossBackendTest again.
  5. ./gradlew build, then ./gradlew testDemoJar testDevJar testProdJar.

When a shot differs, check these first:

SymptomUsual cause
The whole image, or the content of a framebuffer, is upside downThe viewport is not flipped on the screen, or a framebuffer is not stored bottom-up (Orientation).
Shapes vanish behind others, or 3D models look inside outThe depth range is 0 to 1 and the projection was not converted with DepthRange, or the depth is not cleared to 1.
Masks and scroll areas do not clipThe screen has no 8-bit stencil buffer, or clearStencilBuffer clears nothing.
Text and images are blocky when drawn smallerThe mip levels are not filled with forEachStep, or the sampler ignores isMipmapFiltered().
Colors are off by a few levelsThe surface or the texture format is sRGB where JOID reads linear UNORM.

Report a problem with this page