From f948b991a05b8a0a52069553a61fba3c520470c7 Mon Sep 17 00:00:00 2001 From: Svjatoslav Agejenko Date: Thu, 26 Nov 2026 22:43:53 +0200 Subject: [PATCH] feat(engine): import the seven-module engine and the demo app The engine written in the aukio-v3 repository moves here, where the project's name and history live: Modules/{world,renderer,swing, scheduler,gi,hid,navigation} as JPMS modules plus Applications/demos with MinimalExample. Packages and module names carry no version segment any more (eu.svjatoslav.aukio.world, .render, .sched, .gi, .hid, .navigation, .swing), so the jars are named aukio-. The build is Gradle 9.6.0 through the committed wrapper, compiling and testing on a Java 21 toolchain whatever JDK launched the daemon, with toolchain auto-download disabled so the build stays offline; the gate is ./gradlew --offline build -Ptla. The v3 module map becomes Documentation/index.org and the previous workspace vision page is kept beside it as Documentation/vision.org. pom.xml and verify.sh go: this repository no longer builds with Maven, and the old gate pointed at the removed workspace-v2 module and its scenario tables. .gitignore keeps the old rules and gains the Gradle, .openidea and TLC scratch ones. The source arrived from aukio-v3 by copy, so the file history lives in that repository; this commit is the entry point in aukio. --- .gitignore | 11 + AGENTS.org | 103 +++++ Applications/demos/build.gradle | 10 + .../demos/launcher/ApplicationListPanel.java | 64 +++ .../svjatoslav/aukio/demos/launcher/Main.java | 37 ++ .../aukio/demos/minimal/MinimalExample.java | 113 ++++++ Documentation/index.org | 328 ++++++++-------- Documentation/vision.org | 203 ++++++++++ Modules/gi/Documentation/index.org | 82 ++++ Modules/gi/build.gradle | 11 + .../eu/svjatoslav/aukio/gi/package-info.java | 27 ++ Modules/gi/src/main/java/module-info.java | 16 + .../svjatoslav/aukio/gi/ModuleShapeTest.java | 178 +++++++++ Modules/hid/Documentation/index.org | 116 ++++++ Modules/hid/build.gradle | 7 + .../java/eu/svjatoslav/aukio/hid/Motion.java | 26 ++ .../svjatoslav/aukio/hid/SpaceNavigator.java | 217 ++++++++++ Modules/hid/src/main/java/module-info.java | 15 + .../svjatoslav/aukio/hid/ModuleShapeTest.java | 162 ++++++++ .../aukio/hid/SpaceNavigatorTest.java | 99 +++++ Modules/navigation/Documentation/index.org | 108 +++++ Modules/navigation/build.gradle | 8 + .../aukio/navigation/CameraDriver.java | 26 ++ .../aukio/navigation/FlyCamera.java | 199 ++++++++++ .../aukio/navigation/InputRecorder.java | 109 ++++++ .../aukio/navigation/ViewInput.java | 128 ++++++ .../navigation/src/main/java/module-info.java | 22 ++ .../aukio/navigation/FlyCameraTest.java | 177 +++++++++ .../aukio/navigation/InputRecorderTest.java | 79 ++++ .../aukio/navigation/ModuleShapeTest.java | 177 +++++++++ Modules/renderer/Documentation/index.org | 120 ++++++ Modules/renderer/build.gradle | 9 + .../java/eu/svjatoslav/aukio/render/Cull.java | 43 ++ .../svjatoslav/aukio/render/FrameBuffer.java | 90 +++++ .../svjatoslav/aukio/render/Projection.java | 96 +++++ .../eu/svjatoslav/aukio/render/Raster.java | 89 +++++ .../eu/svjatoslav/aukio/render/Renderer.java | 95 +++++ .../svjatoslav/aukio/render/package-info.java | 26 ++ .../renderer/src/main/java/module-info.java | 15 + .../aukio/render/ModuleShapeTest.java | 176 +++++++++ .../svjatoslav/aukio/render/RendererTest.java | 198 ++++++++++ Modules/scheduler/Documentation/index.org | 78 ++++ Modules/scheduler/Model/FrameGate.tla | 105 +++++ .../Model/FrameGate_buggy_bgfirst.cfg | 16 + .../Model/FrameGate_buggy_countbg.cfg | 17 + Modules/scheduler/Model/FrameGate_gate.cfg | 15 + Modules/scheduler/Model/check-models.sh | 43 ++ Modules/scheduler/build.gradle | 17 + .../eu/svjatoslav/aukio/sched/Scheduler.java | 53 +++ .../svjatoslav/aukio/sched/package-info.java | 5 + .../scheduler/src/main/java/module-info.java | 10 + .../svjatoslav/aukio/sched/SchedulerTest.java | 43 ++ Modules/swing/Documentation/index.org | 104 +++++ Modules/swing/build.gradle | 14 + .../eu/svjatoslav/aukio/swing/AukioView.java | 370 ++++++++++++++++++ .../svjatoslav/aukio/swing/package-info.java | 24 ++ Modules/swing/src/main/java/module-info.java | 17 + .../aukio/swing/ModuleShapeTest.java | 185 +++++++++ Modules/world/Documentation/index.org | 110 ++++++ Modules/world/build.gradle | 7 + .../java/eu/svjatoslav/aukio/world/Boxes.java | 37 ++ .../eu/svjatoslav/aukio/world/Camera.java | 46 +++ .../java/eu/svjatoslav/aukio/world/Mesh.java | 84 ++++ .../java/eu/svjatoslav/aukio/world/Node.java | 52 +++ .../java/eu/svjatoslav/aukio/world/Scene.java | 63 +++ .../eu/svjatoslav/aukio/world/Transform.java | 97 +++++ .../java/eu/svjatoslav/aukio/world/Vec3.java | 27 ++ .../svjatoslav/aukio/world/package-info.java | 31 ++ Modules/world/src/main/java/module-info.java | 13 + .../eu/svjatoslav/aukio/world/BoxesTest.java | 68 ++++ .../aukio/world/ModuleShapeTest.java | 161 ++++++++ .../svjatoslav/aukio/world/TransformTest.java | 56 +++ README.org | 41 ++ build.gradle | 47 +++ gradle.properties | 4 + gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 43453 bytes gradle/wrapper/gradle-wrapper.properties | 7 + gradlew | 249 ++++++++++++ gradlew.bat | 92 +++++ pom.xml | 55 --- settings.gradle | 14 + verify.sh | 130 ------ 82 files changed, 6067 insertions(+), 355 deletions(-) create mode 100644 AGENTS.org create mode 100644 Applications/demos/build.gradle create mode 100644 Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/launcher/ApplicationListPanel.java create mode 100644 Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/launcher/Main.java create mode 100644 Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/minimal/MinimalExample.java create mode 100644 Documentation/vision.org create mode 100644 Modules/gi/Documentation/index.org create mode 100644 Modules/gi/build.gradle create mode 100644 Modules/gi/src/main/java/eu/svjatoslav/aukio/gi/package-info.java create mode 100644 Modules/gi/src/main/java/module-info.java create mode 100644 Modules/gi/src/test/java/eu/svjatoslav/aukio/gi/ModuleShapeTest.java create mode 100644 Modules/hid/Documentation/index.org create mode 100644 Modules/hid/build.gradle create mode 100644 Modules/hid/src/main/java/eu/svjatoslav/aukio/hid/Motion.java create mode 100644 Modules/hid/src/main/java/eu/svjatoslav/aukio/hid/SpaceNavigator.java create mode 100644 Modules/hid/src/main/java/module-info.java create mode 100644 Modules/hid/src/test/java/eu/svjatoslav/aukio/hid/ModuleShapeTest.java create mode 100644 Modules/hid/src/test/java/eu/svjatoslav/aukio/hid/SpaceNavigatorTest.java create mode 100644 Modules/navigation/Documentation/index.org create mode 100644 Modules/navigation/build.gradle create mode 100644 Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/CameraDriver.java create mode 100644 Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/FlyCamera.java create mode 100644 Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/InputRecorder.java create mode 100644 Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/ViewInput.java create mode 100644 Modules/navigation/src/main/java/module-info.java create mode 100644 Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/FlyCameraTest.java create mode 100644 Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/InputRecorderTest.java create mode 100644 Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/ModuleShapeTest.java create mode 100644 Modules/renderer/Documentation/index.org create mode 100644 Modules/renderer/build.gradle create mode 100644 Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Cull.java create mode 100644 Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/FrameBuffer.java create mode 100644 Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Projection.java create mode 100644 Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Raster.java create mode 100644 Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Renderer.java create mode 100644 Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/package-info.java create mode 100644 Modules/renderer/src/main/java/module-info.java create mode 100644 Modules/renderer/src/test/java/eu/svjatoslav/aukio/render/ModuleShapeTest.java create mode 100644 Modules/renderer/src/test/java/eu/svjatoslav/aukio/render/RendererTest.java create mode 100644 Modules/scheduler/Documentation/index.org create mode 100644 Modules/scheduler/Model/FrameGate.tla create mode 100644 Modules/scheduler/Model/FrameGate_buggy_bgfirst.cfg create mode 100644 Modules/scheduler/Model/FrameGate_buggy_countbg.cfg create mode 100644 Modules/scheduler/Model/FrameGate_gate.cfg create mode 100755 Modules/scheduler/Model/check-models.sh create mode 100644 Modules/scheduler/build.gradle create mode 100644 Modules/scheduler/src/main/java/eu/svjatoslav/aukio/sched/Scheduler.java create mode 100644 Modules/scheduler/src/main/java/eu/svjatoslav/aukio/sched/package-info.java create mode 100644 Modules/scheduler/src/main/java/module-info.java create mode 100644 Modules/scheduler/src/test/java/eu/svjatoslav/aukio/sched/SchedulerTest.java create mode 100644 Modules/swing/Documentation/index.org create mode 100644 Modules/swing/build.gradle create mode 100644 Modules/swing/src/main/java/eu/svjatoslav/aukio/swing/AukioView.java create mode 100644 Modules/swing/src/main/java/eu/svjatoslav/aukio/swing/package-info.java create mode 100644 Modules/swing/src/main/java/module-info.java create mode 100644 Modules/swing/src/test/java/eu/svjatoslav/aukio/swing/ModuleShapeTest.java create mode 100644 Modules/world/Documentation/index.org create mode 100644 Modules/world/build.gradle create mode 100644 Modules/world/src/main/java/eu/svjatoslav/aukio/world/Boxes.java create mode 100644 Modules/world/src/main/java/eu/svjatoslav/aukio/world/Camera.java create mode 100644 Modules/world/src/main/java/eu/svjatoslav/aukio/world/Mesh.java create mode 100644 Modules/world/src/main/java/eu/svjatoslav/aukio/world/Node.java create mode 100644 Modules/world/src/main/java/eu/svjatoslav/aukio/world/Scene.java create mode 100644 Modules/world/src/main/java/eu/svjatoslav/aukio/world/Transform.java create mode 100644 Modules/world/src/main/java/eu/svjatoslav/aukio/world/Vec3.java create mode 100644 Modules/world/src/main/java/eu/svjatoslav/aukio/world/package-info.java create mode 100644 Modules/world/src/main/java/module-info.java create mode 100644 Modules/world/src/test/java/eu/svjatoslav/aukio/world/BoxesTest.java create mode 100644 Modules/world/src/test/java/eu/svjatoslav/aukio/world/ModuleShapeTest.java create mode 100644 Modules/world/src/test/java/eu/svjatoslav/aukio/world/TransformTest.java create mode 100644 README.org create mode 100644 build.gradle create mode 100644 gradle.properties create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100755 gradlew create mode 100644 gradlew.bat delete mode 100644 pom.xml create mode 100644 settings.gradle delete mode 100755 verify.sh diff --git a/.gitignore b/.gitignore index 31e209b..0aae896 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,14 @@ target/ *.html # jcstress result dumps (parallel agent) jcstress-results-*.bin.gz + +# Gradle +.gradle/ +build/ +*.class +.vscode/ +.openidea/ + +# TLC scratch +Modules/scheduler/Model/states/ +Modules/scheduler/Model/*_TTrace_* diff --git a/AGENTS.org b/AGENTS.org new file mode 100644 index 0000000..a3fbf4b --- /dev/null +++ b/AGENTS.org @@ -0,0 +1,103 @@ +#+TITLE: AGENTS - aukio + +* What this is + +Read =Documentation/index.org= first; it is the map, this file is the +recipe. + +* Hard rules + +- The user owns judgment. Propose, wait for an explicit go, land ONE readable + change, stop. Never batch several pieces into one turn. +- NEVER git commit and NEVER push. The user commits himself. +- A module's tests must run with the other modules absent from the + classpath. That is the proof of isolation, not a diagram. +- One public package per module; everything else is package-private or under + =.internal.=. +- Every module declares =module-info.java= in =src/main/java/=, named after its + package, exporting that one package and requiring only what its build file + depends on. A =requires= on another engine module that is not a dependency is + a compile error, which is the whole point. +- Java 21 =--release=; the build is Gradle 9.6.0 through =./gradlew=, run + offline (every dependency is already in =~/.m2=, reached through + =mavenLocal()=). Compiling and testing happen on a Java 21 toolchain even + when a newer JDK launched Gradle, and a missing toolchain fails the build + instead of being downloaded. +- Every heading under =Documentation/= carries a =CUSTOM_ID=; + sub-pages open with a back-link to their anchor in the map. + +* Working rules for the agent + +- Report the command and what it printed. "It works" is the user's + word, not yours; never claim a behaviour without the check that + demonstrates it. +- A behaviour is accepted only when a check fails before and passes + after, and that check stays in the build. +- Anything with interleaving or ordering goes spec-first: a model in + the module's =Model/= directory, a gate config wired into + =./gradlew -Ptla check=, and a buggy config that must violate the + invariant the gate asserts. +- A comment states what the code relies on. No benchmark folklore, no + dates, no "we tried this once" — provenance belongs in the docs, not + in a constant's Javadoc. +- Documentation describes the current state. Do not record the edit + history in it. + +* Layout + +- =Modules/scheduler/= :: CPU budget, work queues, frame gate. =Model/= holds + its TLA+ model and =check-models.sh=. +- =Modules/world/= :: the scene as data - geometry, object tree, mesh, + primitives, camera pose. Its descriptor requires no other engine module, and + =ModuleShapeTest= fails the build if that changes or if a file passes 800 + lines. +- =Modules/gi/= :: direct and indirect light, lightmaps, and the bake order. It + requires the world and the scheduler and may require nothing else: a + =requires= on the renderer, or on =java.desktop=, is a build failure. +- =Modules/renderer/= :: projection, culling and rasterisation. It requires the + world and nothing else; =ModuleShapeTest= holds that requirement list, the one + package, and the 800-line limit. +- =Modules/navigation/= :: one frame of input as a record, and the camera policy + that answers it (=FlyCamera=). Requires the world and nothing else - the input + record is data, so a policy is testable without a window. +- =Modules/swing/= :: the embeddable view component and its render loop. The + only engine module that requires =java.desktop=; it depends on the renderer + and the renderer never depends on it. +- =Modules/hid/= :: 3D input devices read off =/dev/hidraw= - the toolkit cannot + deliver them, so they are not the swing adapter's business. Requires nothing; + its reader thread is blocked I/O and deliberately outside the scheduler's CPU + budget. +- =Documentation/= :: the map. Each module keeps its own page in its own + =Documentation/= directory, next to the code it describes. +- =README.org= :: layout and build, one screen. + +* Build and checks + +#+begin_src sh +export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64 +./gradlew --offline build # compile and unit tests +./gradlew --offline -Ptla :scheduler:check # TLA+ gate (green configs only) +Modules/scheduler/Model/check-models.sh # gate must pass, every probe must fail +#+end_src + +The buggy model configs are excluded from the Gradle gate on +purpose: they fail by design, and a probe that passes proves the +invariant is vacuous. + +* Known traps + +- Never trust an exit code that travelled through a pipe. Gradle prints + =BUILD SUCCESSFUL= only when every task passed, and the counts live in + each module's =build/test-results/test/*.xml=; read one of the two + before reporting a build or a test run as green. +- TLC writes =states/= and =*_TTrace_*= into the invocation directory. Run it from + the module's =Model/= directory (both are gitignored) or the repo root gains + scratch. +- The thread budget is a policy default (75% of logical cores), not an + enforcement: nothing yet bounds the process with it, so a module + that sizes its own pool is a defect to report rather than a + convenience. +- A bare =Xvfb= has no window manager, so no window is ever activated and + keyboard events never reach the application, however the window is focused. + Run a WM (=xfwm4=) on the display, or drive the component's listeners + directly in a probe, before concluding that input handling is broken. diff --git a/Applications/demos/build.gradle b/Applications/demos/build.gradle new file mode 100644 index 0000000..5723b18 --- /dev/null +++ b/Applications/demos/build.gradle @@ -0,0 +1,10 @@ +// The demo applications. They embed the engine's view component in ordinary Swing +// windows, so they depend on the adapter and on nothing else from the engine. + +dependencies { + implementation project(':swing') + implementation project(':hid') + // The demo picks the engine's camera policy; an application that wants its + // own implements CameraDriver instead and does not need this. + implementation project(':navigation') +} diff --git a/Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/launcher/ApplicationListPanel.java b/Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/launcher/ApplicationListPanel.java new file mode 100644 index 0000000..5e292df --- /dev/null +++ b/Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/launcher/ApplicationListPanel.java @@ -0,0 +1,64 @@ +package eu.svjatoslav.aukio.demos.launcher; + +import eu.svjatoslav.aukio.demos.minimal.MinimalExample; + +import javax.swing.JButton; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.border.EmptyBorder; +import java.awt.Dimension; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; + +/** + * The list of demos this application can open. + * + *

One entry per demo, added in reading order. A demo is an independent + * program with its own {@code main}, so an entry does nothing more than start + * that program; the launcher never learns what a demo draws.

+ */ +final class ApplicationListPanel extends JPanel { + + private static final long serialVersionUID = 1L; + + ApplicationListPanel() { + super(new GridBagLayout()); + setBorder(new EmptyBorder(32, 48, 32, 48)); + setPreferredSize(new Dimension(480, 320)); + add(entry("Minimal example", MinimalExample::main), row(0)); + } + + private static JButton entry(final String name, final DemoEntry demo) { + final JButton button = new JButton(name); + button.addActionListener(event -> launch(name, demo)); + return button; + } + + /** A demo that cannot start is reported here rather than swallowed by the event thread. */ + private static void launch(final String name, final DemoEntry demo) { + try { + demo.run(new String[0]); + } catch (final Exception failure) { + failure.printStackTrace(); + JOptionPane.showMessageDialog(null, name + " could not start: " + failure, + Main.WINDOW_TITLE, JOptionPane.ERROR_MESSAGE); + } + } + + private static GridBagConstraints row(final int row) { + final GridBagConstraints constraints = new GridBagConstraints(); + constraints.gridx = 0; + constraints.gridy = row; + constraints.weightx = 1; + constraints.fill = GridBagConstraints.HORIZONTAL; + constraints.insets = new Insets(4, 4, 4, 4); + return constraints; + } + + /** A demo's entry point, as the launcher sees it. */ + @FunctionalInterface + private interface DemoEntry { + void run(String[] args) throws Exception; + } +} diff --git a/Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/launcher/Main.java b/Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/launcher/Main.java new file mode 100644 index 0000000..0ba479b --- /dev/null +++ b/Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/launcher/Main.java @@ -0,0 +1,37 @@ +package eu.svjatoslav.aukio.demos.launcher; + +import javax.swing.JFrame; +import javax.swing.SwingUtilities; +import java.awt.BorderLayout; + +import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE; + +/** + * Entry point for the Aukio V3 demos launcher. + * + *

The window lists the demos that can be opened. There are none yet, so it + * says so; adding a demo is a change inside {@link ApplicationListPanel}, not + * here. + */ +public final class Main { + + static final String WINDOW_TITLE = "Aukio V3 demos"; + + private Main() { + } + + public static void main(final String[] args) { + SwingUtilities.invokeLater(Main::buildAndShowGuiWindow); + } + + private static void buildAndShowGuiWindow() { + final JFrame frame = new JFrame(WINDOW_TITLE); + frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); + frame.getContentPane().setLayout(new BorderLayout()); + frame.getContentPane().add(new ApplicationListPanel(), BorderLayout.CENTER); + frame.pack(); + frame.setMinimumSize(frame.getSize()); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } +} diff --git a/Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/minimal/MinimalExample.java b/Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/minimal/MinimalExample.java new file mode 100644 index 0000000..c4dcb06 --- /dev/null +++ b/Applications/demos/src/main/java/eu/svjatoslav/aukio/demos/minimal/MinimalExample.java @@ -0,0 +1,113 @@ +package eu.svjatoslav.aukio.demos.minimal; + +import eu.svjatoslav.aukio.hid.SpaceNavigator; +import eu.svjatoslav.aukio.navigation.FlyCamera; +import eu.svjatoslav.aukio.render.FrameBuffer; +import eu.svjatoslav.aukio.render.Renderer; +import eu.svjatoslav.aukio.swing.AukioView; +import eu.svjatoslav.aukio.world.Boxes; +import eu.svjatoslav.aukio.world.Camera; +import eu.svjatoslav.aukio.world.Node; +import eu.svjatoslav.aukio.world.Scene; +import eu.svjatoslav.aukio.world.Vec3; + +import javax.imageio.ImageIO; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; +import java.awt.BorderLayout; +import java.awt.image.BufferedImage; +import java.io.File; + +import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE; + +/** + * One red box, a camera pulled back, and a view you can fly around it - the + * scene every Aukio engine ships as its first demo. + * + *

The scene is carried over unchanged from the first engine, so a render here + * can be put side by side with that engine's golden image: a 100-unit box + * centred on the origin, and a level camera a hundred units above it and three + * hundred back, which is why the box sits below the middle of the picture and + * its top face is just visible.

+ * + *

The window mode wires three things a demo needs and the engine must not + * decide: a camera policy, the input the view records, and the 3D mouse. Moving + * the pointer with a button held looks around, the keyboard flies, and a + * SpaceNavigator or SpaceMouse pushes the camera exactly as far as the cap is + * pushed. If no 3D mouse is attached the other two still work and the demo says + * nothing about it.

+ * + *

Run with no arguments for the window; run with {@code shot} for one + * headless frame written to {@code target/minimal-example.png}, which is what a + * pixel comparison against another engine needs.

+ */ +public final class MinimalExample { + + static final int SHOT_WIDTH = 1920; + static final int SHOT_HEIGHT = 1080; + static final int BACKGROUND = 0xFF000000; + static final int RED = 0xFFFF0000; + + private static final double HALF_EDGE = 50; + private static final double CAMERA_HEIGHT = 100; + private static final double CAMERA_DISTANCE = 300; + + private MinimalExample() { + } + + /** The demo scene: one box, centred, no lights and no animation. */ + public static Scene buildScene() { + final Vec3 corner = new Vec3(-HALF_EDGE, -HALF_EDGE, -HALF_EDGE); + final Vec3 opposite = new Vec3(HALF_EDGE, HALF_EDGE, HALF_EDGE); + return new Scene(Node.mesh(Boxes.box(corner, opposite, RED))); + } + + /** Level camera, no yaw and no pitch, above the box and back along -Z. */ + public static Camera buildCamera() { + return Camera.of(new Vec3(0, CAMERA_HEIGHT, -CAMERA_DISTANCE), 0, 0); + } + + public static void main(final String[] args) throws Exception { + if (args.length > 0 && "shot".equals(args[0])) { + writeShot(); + return; + } + openWindow(); + } + + private static void writeShot() throws Exception { + final FrameBuffer frame = new FrameBuffer(SHOT_WIDTH, SHOT_HEIGHT); + frame.clear(BACKGROUND); + Renderer.render(buildScene(), buildCamera(), frame); + final BufferedImage image = + new BufferedImage(SHOT_WIDTH, SHOT_HEIGHT, BufferedImage.TYPE_INT_RGB); + image.setRGB(0, 0, SHOT_WIDTH, SHOT_HEIGHT, frame.pixels(), 0, SHOT_WIDTH); + final File out = shotFile(); + out.getParentFile().mkdirs(); + ImageIO.write(image, "png", out); + System.out.println("wrote " + out.getAbsolutePath()); + } + + static File shotFile() { + return new File("target/minimal-example.png"); + } + + private static void openWindow() { + SwingUtilities.invokeLater(() -> { + final FlyCamera fly = new FlyCamera(buildCamera()); + final JFrame window = new JFrame("Minimal example (Aukio V3) - WASD and drag, or 3D mouse"); + window.setDefaultCloseOperation(DISPOSE_ON_CLOSE); + window.getContentPane().setLayout(new BorderLayout()); + final AukioView view = new AukioView(buildScene(), fly.camera()); + view.setDriver(fly); + window.getContentPane().add(view, BorderLayout.CENTER); + window.setSize(960, 600); + window.setLocationRelativeTo(null); + window.setVisible(true); + view.requestFocusInWindow(); + view.start(); + new SpaceNavigator(motion -> view.setDeviceMotion(motion.x(), motion.y(), motion.z(), + motion.yaw(), motion.pitch(), motion.roll())).start(); + }); + } +} diff --git a/Documentation/index.org b/Documentation/index.org index 89b0a3c..bc79af1 100644 --- a/Documentation/index.org +++ b/Documentation/index.org @@ -1,203 +1,191 @@ #+SETUPFILE: ~/.emacs.d/org-styles/html/darksun.theme -#+TITLE: Aukio — System for Data Storage, Computation, Exploration and Interaction +#+TITLE: Aukio V3 - documentation #+LANGUAGE: en -#+LATEX_HEADER: \usepackage[margin=1.0in]{geometry} -#+LATEX_HEADER: \usepackage{parskip} -#+LATEX_HEADER: \usepackage[none]{hyphenat} - -#+OPTIONS: H:20 num:20 -#+OPTIONS: author:nil - -* Vision - :PROPERTIES: - :CUSTOM_ID: vision - :ID: 1f4e1c17-d25f-4d92-aa9b-5785f1d86f4f - :END: - -: A tool to amplify human ability - -The goal is a /bicycle for the mind/ — a powerful, extensible, hackable, -general-purpose computing environment for working with knowledge. - -The system is built around the following priorities: - -+ *Knowledge-first.* Data and insights should be easy to discover, - understand, manipulate, transform and visualize. - -+ *Intuitive, visual, real-time, 3D-first interface.* - - #+BEGIN_QUOTE - "Virtual reality holds the key to the evolution of the human mind." - — Dr. Lawrence Angelo, /The Lawnmower Man/ (1992) - #+END_QUOTE - - - -** Extensible, Programmable Computing Environment — An Example - :PROPERTIES: - :CUSTOM_ID: extensible-programmable-computing-environment - :ID: c19c5a3b-dfb0-4f7f-961c-a387b925669f - :END: - -[[https://www.johndcook.com/blog/2008/04/27/one-program-to-rule-them-all/][GNU Emacs]] is perhaps the best existing example of this philosophy. At -its core, Emacs is a text editor built on top of a Lisp runtime. Data -storage and computation can be expressed in [[https://www.defmacro.org/ramblings/lisp.html][Lisp]], which is itself a -programmable programming language — new paradigms and domain-specific -languages can be added dynamically. Text buffers serve as building -blocks for arbitrary user interfaces. The result is an environment -that can be adapted and extended to fit virtually any problem domain. - -** Architecture and Components - :PROPERTIES: - :CUSTOM_ID: architecture-and-components - :ID: 52dbbf4c-2ef4-42a6-8331-ad006b6a52ae - :END: - -+ [[https://www3.svjatoslav.eu/projects/aukio/][Aukio]] — Parent project and the product: a spatial computing - environment (3D virtual workspace). - + [[https://www3.svjatoslav.eu/projects/aukio-data/][Aukio Data]] — Data storage and computation engine. (Very early - stage, nothing to see yet) - + [[https://www3.svjatoslav.eu/projects/aukio-3d/][Aukio 3D]] — Real-time 3D engine for user interface and data - visualization. The workspace runs on its 2.0 rewrite - (~aukio-3d-2~); Aukio 3D v1 is no longer used by Aukio. (Working - and usable, fast evolving) - + [[https://www3.svjatoslav.eu/projects/aukio-3d-demos/][Aukio 3D Demos]] — Demonstration scenes showcasing the - capabilities of the Aukio 3D engine. (Many demos, in good shape) - -The system is far from complete — the scope is large and available -time is limited. - -** Roles and boundaries - -+ *Aukio 3D* is a reusable library. Anyone can take it to build games - or visualizations. It keeps only generic mechanisms: the renderer, - the pass kernel and substrate, the camera, input stores, and the - widget layer (text grids with an SDF atlas, 3D-anchored labels) that - games can also use (in-game consoles, interactive screens). -+ *Aukio* is the concrete product built on that library: the virtual - workspace you actually work in (~workspace-v2~). Application- - integration bridges (PTY/terminal, window capture of X11 apps over - Xvfb, future VNC client) live here. - Exception to the "no native code in the engine" rule: XR glasses - head tracking (RayNeo IMU over hidraw, ~eu.svjatoslav.aukio.e3d.gui.headtrack~) - lives in the ENGINE, so every app and demo gets look-around head - tracking automatically when glasses are plugged in — including - hot-plug at runtime. -+ *Aukio 3D Demos* remains the capability gallery and regression - harness. Workspace features are prototyped as demos, but the real - thing lives in Aukio. - -** Virtual workspace - -Aukio is a spatial computing environment: a persistent 3D world where -every program you use — text editor, terminal, browser, virtual -machine, data view — is a virtual object you place, walk to, and work -at. It replaces window-switching with spatial memory: related tools -live near each other, and your body remembers where things are. - -Roadmap for external applications, from cheapest to most general: - -+ *Virtual machines* — talk VNC/SPICE to the guest display instead of - scraping a window; the protocol provides both framebuffer updates - and input injection. -+ *Arbitrary Linux applications* (browser, etc.) — run the app on a - dedicated ~Xvfb~ display, capture pixels via ~XShmGetImage~, inject - input via XTEST; the app lives only inside the 3D world. - -* Ideas + +:PROPERTIES: +:CUSTOM_ID: aukio +:END: + +#+OPTIONS: H:20 num:nil author:nil + +* What this documentation is +:PROPERTIES: +:CUSTOM_ID: what-this-documentation-is +:END: + +The map of the engine. One page per module; each page states what that module +owns, what it guarantees, and what it deliberately does not do yet. + +The repository README is the one-screen entry point (layout and build), and +=AGENTS.org= at the root is the operating recipe for an AI agent working in the +tree. This directory is what a human reads. + +* Modules +:PROPERTIES: +:CUSTOM_ID: modules +:END: + +- Scheduler :: decides how many threads exist and which work runs on them. +- World :: the scene as data: geometry, transforms, object tree, primitives. +- Global illumination :: the light a surface receives, and the baking of it. +- Renderer :: the algorithms that turn a world into pixels. +- Navigation :: one frame of input, and the camera policy that answers it. +- Swing adapter :: the component a host application embeds, and its render loop. +- HID devices :: 3D mice, read off a character device that no toolkit delivers. +- Demos :: the demonstration applications, and the launcher that lists them. + +** Scheduler :PROPERTIES: -:CUSTOM_ID: ideas +:CUSTOM_ID: scheduler :END: -** Molecular dynamics integration +The single owner of the CPU budget. It is the one place that knows how +many worker threads the process may use, and the only place that +decides whether a render task or a background task runs next. + +Today it holds the budget and nothing else; the queues, the priority +rule and the frame gate are named on its page as planned work, not as +behaviour. + +See [[file:../Modules/scheduler/Documentation/index.org][the scheduler page]]. + +** World :PROPERTIES: -:CUSTOM_ID: molecular-dynamics-integration +:CUSTOM_ID: world :END: -Integrate with [[https://www.gromacs.org/][GROMACS]] or a similar molecular dynamics simulator. +The scene as data: geometry, transforms, the object tree, triangle storage in +object space, the primitives, and the camera pose. It carries the object model +deliberately - a node owns a transform and children inherit it, so a chain of +parts is posed by writing transforms rather than by rewriting vertices. -Users could place atoms in molecular dynamics models and manipulate -them directly with hand gestures (in VR) or mouse drag-and-drop -(desktop), seeing immediate force-based reactions. in 3D, the -simulation becomes a tangible object you "hold" and adjust. +It is the bottom of the engine and requires nothing: not the renderer, not the +toolkit, not the scheduler, which the build enforces rather than promises. -Teams in VR could jointly manipulate a protein model while viewing -real-time simulation data, with each member's avatar contributing to -the workspace. +See [[file:../Modules/world/Documentation/index.org][the world page]]. -** Emacs client integration +** Global illumination :PROPERTIES: -:CUSTOM_ID: emacs-client-integration +:CUSTOM_ID: gi :END: -Allow Aukio to act as an Emacs client, connecting to a running Emacs -instance. Text editors could then be spawned as objects in 3D space, -each backed by the live Emacs process. This would make all existing -Emacs plugins and functionality available inside the Aukio environment. +The light a surface actually receives: direct light with visibility, indirect +light, lightmaps, and the policy for what to bake next. -** Document represented as geometry +It writes light into world storage and the renderer samples it, so the two never +meet: the raster carries no bake logic, and the baker carries no pixels. It +requires the world and the scheduler, and it cannot require the renderer or the +toolkit - the build refuses both. -Text editors would be replaced by floating 3D "cubes" where code -structure is visualized spatially - functions as connected nodes, -dependencies as glowing wires. Moving a function node would -automatically rewire related components, making refactoring a spatial -act. In 2D, this requires mental mapping; in 3D, the structure is -visible and manipulable. +Three rules, each of which cost a bug in the previous engine: light is published +complete or not at all, displayed quality never drops, and light positions and +normals are always in world space. -Ideas in Obsidian-like systems could be arranged in 3D mind maps where -proximity indicates relevance - clicking a node pulls connected -documents into view, creating a navigable "knowledge landscape". +See [[file:../Modules/gi/Documentation/index.org][the global illumination page]]. -** Electronics circuit simulation integration +** Renderer :PROPERTIES: -:CUSTOM_ID: electronics-circuit-simulation-integration +:CUSTOM_ID: renderer :END: -Integrate with [[https://ngspice.sourceforge.io/][ngspice]], [[http://www.bwsst.com/][SPICE]], or a similar electronics circuit -simulator, enabling interactive circuit design and simulation in 3D. +The algorithms that turn a world into pixels: the frame buffer, the projection +from a camera pose and a viewport to screen coordinates, culling and +rasterisation. + +A pose is world data, a projection is not. The camera's position and rotation +belong to the world; the =scale = width / 3= that turns them into screen +coordinates belongs here, because only the renderer knows how wide the picture +is. + +See [[file:../Modules/renderer/Documentation/index.org][the renderer page]]. + +** Navigation +:PROPERTIES: +:CUSTOM_ID: navigation +:END + +One frame of user intent as a record, and the camera that answers it. Keys, +pointer movement, wheel notches and the six axes of a 3D device go in; the pose +the next frame is drawn from comes out. -A circuit designer using ngspice could place resistors/capacitors in -3D space, connect them with virtual wires, and simultaneously -visualize current flow as animated particles while overlaying -Pandas-generated performance metrics. This eliminates -context-switching between tools - data, simulation, and visualization -coexist in one spatial workflow. +The record lives here rather than in the toolkit adapter because a policy that +cannot be tested without a window stops being tested: =FlyCameraTest= flies with +no toolkit on its classpath at all. Keys and device deflection are levels and +survive into every frame; pointer deltas and wheel notches are spent by exactly +one frame. The module requires the world - a pose is world data - and nothing +else. -This would provide contextual continuity. Related tools (e.g., a -simulation and its data analysis) can be spatially adjacent in space, -avoiding the "window-switching" friction of 2D desktops. +See [[file:../Modules/navigation/Documentation/index.org][the navigation page]]. -** 3D visualization of statistical data +** Swing adapter +:PROPERTIES: +:CUSTOM_ID: swing +:END: -Dataframes from Pandas would render as 3D grids where rows/columns -occupy spatial axes. Dragging a region of the grid would instantly -filter related data. Unlike 2D tables where multidimensional -relationships are flattened, 3D preserves natural spatial -relationships- e.g., high-value data points "tower" above low-value -ones, creating intuitive topographical insights. +The component a host application embeds, plus the render loop that feeds it. A +host with its own frame, tab or split pane takes only this; nothing here owns a +window, and nothing here knows what the scene contains. -A 3D scatter plot shows all variables simultaneously; rotating it -reveals patterns invisible in 2D projections. +It is the only engine module that may require =java.desktop=, and it depends on +the renderer rather than the other way round, so the engine itself stays +headless. -Students could "walk through" a dataset experiencing trends as spatial -terrain rather than abstract graphs. +See [[file:../Modules/swing/Documentation/index.org][the swing adapter page]]. -* Source code +** HID devices :PROPERTIES: -:CUSTOM_ID: source-code +:CUSTOM_ID: hid :END: -*This program is free software: released under Creative Commons Zero -(CC0) license* +Input devices no toolkit can hand over: a 3Dconnexion cap arrives as bytes on +=/dev/hidraw=, so a host with no window still has it. The module reads the +device and reports six normalised axes; what those axes mean is the host's +decision. + +It requires nothing at all, which is what lets a test, a server or a terminal +read the same device as a windowed application. The reader thread is a blocked +I/O thread - not CPU budget, so the scheduler has no business with it - and it +never waits for a frame: a cap that lags the picture it steers is useless. -*Program author:* -- Svjatoslav Agejenko -- Homepage: https://svjatoslav.eu -- Email: mailto://svjatoslav@svjatoslav.eu -- See also: [[https://www.svjatoslav.eu/projects/][Other software projects hosted at svjatoslav.eu]] +See [[file:../Modules/hid/Documentation/index.org][the HID page]]. + +** Demos +:PROPERTIES: +:CUSTOM_ID: demos +:END: -*Getting the source code:* -- [[https://www2.svjatoslav.eu/gitweb/?p=aukio.git;a=snapshot;h=HEAD;sf=tgz][Download latest snapshot in TAR GZ format]] -- [[https://www2.svjatoslav.eu/gitweb/?p=aukio.git;a=summary][Browse Git repository online]] -- Clone Git repository using command: - : git clone https://www2.svjatoslav.eu/git/aukio.git +The applications a person runs. Each is a small program of its own that embeds +the view component in an ordinary window, and the launcher is a list of them +rather than a framework that knows what they draw. + +The first one is =MinimalExample=: one red box, a camera pulled back - the scene +every Aukio engine has shipped as its first demo, carried over unchanged so a +render here can be put beside the previous engine's golden image. It writes one +1920x1080 frame to =target/minimal-example.png= when started with =shot=, which +is what a pixel comparison needs. + +In the window it is flown, by three means at once: + +| Input | Effect | +|------------------------+-----------------------------------------------------------| +| drag with a button | look around; the pointer delta is pixels, the rate is 0.02 rad per pixel | +| =W A S D=, arrows, =Q R= | fly and strafe level, rise and sink; Dvorak =, O E ' .= follow the physical WASD keys | +| wheel | height only: turning it away from you descends, towards you rises; one notch is a hundred units per second of thrust | +| 3D mouse cap | proportional drive: push to fly along the view, twist to turn, tilt to look, press for down | + +The rates are the previous engine's, not new ones - they were tuned against this +device and this hand - except that the cap's sensitivity is a single constant at +the top of =FlyCamera=, and the previous engine's value was tuned for a +kilometre-scale world rather than a hundred-unit box. + +The 3D mouse is read straight from =/dev/hidraw= in plain Java, so there is no +native library and no device daemon to install; the udev rule that makes the node +readable lives with the older engines in their repositories. A device that is +unplugged and plugged back in is found again within two seconds. + +#+begin_src sh +export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64 +./gradlew --offline :demos:build +CP=$(ls -d Applications/demos/build/classes/java/main Modules/*/build/classes/java/main | paste -sd:) +java -cp "$CP" eu.svjatoslav.aukio.demos.minimal.MinimalExample shot +#+end_src diff --git a/Documentation/vision.org b/Documentation/vision.org new file mode 100644 index 0000000..89b0a3c --- /dev/null +++ b/Documentation/vision.org @@ -0,0 +1,203 @@ +#+SETUPFILE: ~/.emacs.d/org-styles/html/darksun.theme +#+TITLE: Aukio — System for Data Storage, Computation, Exploration and Interaction +#+LANGUAGE: en +#+LATEX_HEADER: \usepackage[margin=1.0in]{geometry} +#+LATEX_HEADER: \usepackage{parskip} +#+LATEX_HEADER: \usepackage[none]{hyphenat} + +#+OPTIONS: H:20 num:20 +#+OPTIONS: author:nil + +* Vision + :PROPERTIES: + :CUSTOM_ID: vision + :ID: 1f4e1c17-d25f-4d92-aa9b-5785f1d86f4f + :END: + +: A tool to amplify human ability + +The goal is a /bicycle for the mind/ — a powerful, extensible, hackable, +general-purpose computing environment for working with knowledge. + +The system is built around the following priorities: + ++ *Knowledge-first.* Data and insights should be easy to discover, + understand, manipulate, transform and visualize. + ++ *Intuitive, visual, real-time, 3D-first interface.* + + #+BEGIN_QUOTE + "Virtual reality holds the key to the evolution of the human mind." + — Dr. Lawrence Angelo, /The Lawnmower Man/ (1992) + #+END_QUOTE + + + +** Extensible, Programmable Computing Environment — An Example + :PROPERTIES: + :CUSTOM_ID: extensible-programmable-computing-environment + :ID: c19c5a3b-dfb0-4f7f-961c-a387b925669f + :END: + +[[https://www.johndcook.com/blog/2008/04/27/one-program-to-rule-them-all/][GNU Emacs]] is perhaps the best existing example of this philosophy. At +its core, Emacs is a text editor built on top of a Lisp runtime. Data +storage and computation can be expressed in [[https://www.defmacro.org/ramblings/lisp.html][Lisp]], which is itself a +programmable programming language — new paradigms and domain-specific +languages can be added dynamically. Text buffers serve as building +blocks for arbitrary user interfaces. The result is an environment +that can be adapted and extended to fit virtually any problem domain. + +** Architecture and Components + :PROPERTIES: + :CUSTOM_ID: architecture-and-components + :ID: 52dbbf4c-2ef4-42a6-8331-ad006b6a52ae + :END: + ++ [[https://www3.svjatoslav.eu/projects/aukio/][Aukio]] — Parent project and the product: a spatial computing + environment (3D virtual workspace). + + [[https://www3.svjatoslav.eu/projects/aukio-data/][Aukio Data]] — Data storage and computation engine. (Very early + stage, nothing to see yet) + + [[https://www3.svjatoslav.eu/projects/aukio-3d/][Aukio 3D]] — Real-time 3D engine for user interface and data + visualization. The workspace runs on its 2.0 rewrite + (~aukio-3d-2~); Aukio 3D v1 is no longer used by Aukio. (Working + and usable, fast evolving) + + [[https://www3.svjatoslav.eu/projects/aukio-3d-demos/][Aukio 3D Demos]] — Demonstration scenes showcasing the + capabilities of the Aukio 3D engine. (Many demos, in good shape) + +The system is far from complete — the scope is large and available +time is limited. + +** Roles and boundaries + ++ *Aukio 3D* is a reusable library. Anyone can take it to build games + or visualizations. It keeps only generic mechanisms: the renderer, + the pass kernel and substrate, the camera, input stores, and the + widget layer (text grids with an SDF atlas, 3D-anchored labels) that + games can also use (in-game consoles, interactive screens). ++ *Aukio* is the concrete product built on that library: the virtual + workspace you actually work in (~workspace-v2~). Application- + integration bridges (PTY/terminal, window capture of X11 apps over + Xvfb, future VNC client) live here. + Exception to the "no native code in the engine" rule: XR glasses + head tracking (RayNeo IMU over hidraw, ~eu.svjatoslav.aukio.e3d.gui.headtrack~) + lives in the ENGINE, so every app and demo gets look-around head + tracking automatically when glasses are plugged in — including + hot-plug at runtime. ++ *Aukio 3D Demos* remains the capability gallery and regression + harness. Workspace features are prototyped as demos, but the real + thing lives in Aukio. + +** Virtual workspace + +Aukio is a spatial computing environment: a persistent 3D world where +every program you use — text editor, terminal, browser, virtual +machine, data view — is a virtual object you place, walk to, and work +at. It replaces window-switching with spatial memory: related tools +live near each other, and your body remembers where things are. + +Roadmap for external applications, from cheapest to most general: + ++ *Virtual machines* — talk VNC/SPICE to the guest display instead of + scraping a window; the protocol provides both framebuffer updates + and input injection. ++ *Arbitrary Linux applications* (browser, etc.) — run the app on a + dedicated ~Xvfb~ display, capture pixels via ~XShmGetImage~, inject + input via XTEST; the app lives only inside the 3D world. + +* Ideas +:PROPERTIES: +:CUSTOM_ID: ideas +:END: + +** Molecular dynamics integration +:PROPERTIES: +:CUSTOM_ID: molecular-dynamics-integration +:END: + +Integrate with [[https://www.gromacs.org/][GROMACS]] or a similar molecular dynamics simulator. + +Users could place atoms in molecular dynamics models and manipulate +them directly with hand gestures (in VR) or mouse drag-and-drop +(desktop), seeing immediate force-based reactions. in 3D, the +simulation becomes a tangible object you "hold" and adjust. + +Teams in VR could jointly manipulate a protein model while viewing +real-time simulation data, with each member's avatar contributing to +the workspace. + +** Emacs client integration +:PROPERTIES: +:CUSTOM_ID: emacs-client-integration +:END: + +Allow Aukio to act as an Emacs client, connecting to a running Emacs +instance. Text editors could then be spawned as objects in 3D space, +each backed by the live Emacs process. This would make all existing +Emacs plugins and functionality available inside the Aukio environment. + +** Document represented as geometry + +Text editors would be replaced by floating 3D "cubes" where code +structure is visualized spatially - functions as connected nodes, +dependencies as glowing wires. Moving a function node would +automatically rewire related components, making refactoring a spatial +act. In 2D, this requires mental mapping; in 3D, the structure is +visible and manipulable. + +Ideas in Obsidian-like systems could be arranged in 3D mind maps where +proximity indicates relevance - clicking a node pulls connected +documents into view, creating a navigable "knowledge landscape". + +** Electronics circuit simulation integration +:PROPERTIES: +:CUSTOM_ID: electronics-circuit-simulation-integration +:END: + +Integrate with [[https://ngspice.sourceforge.io/][ngspice]], [[http://www.bwsst.com/][SPICE]], or a similar electronics circuit +simulator, enabling interactive circuit design and simulation in 3D. + +A circuit designer using ngspice could place resistors/capacitors in +3D space, connect them with virtual wires, and simultaneously +visualize current flow as animated particles while overlaying +Pandas-generated performance metrics. This eliminates +context-switching between tools - data, simulation, and visualization +coexist in one spatial workflow. + +This would provide contextual continuity. Related tools (e.g., a +simulation and its data analysis) can be spatially adjacent in space, +avoiding the "window-switching" friction of 2D desktops. + +** 3D visualization of statistical data + +Dataframes from Pandas would render as 3D grids where rows/columns +occupy spatial axes. Dragging a region of the grid would instantly +filter related data. Unlike 2D tables where multidimensional +relationships are flattened, 3D preserves natural spatial +relationships- e.g., high-value data points "tower" above low-value +ones, creating intuitive topographical insights. + +A 3D scatter plot shows all variables simultaneously; rotating it +reveals patterns invisible in 2D projections. + +Students could "walk through" a dataset experiencing trends as spatial +terrain rather than abstract graphs. + +* Source code +:PROPERTIES: +:CUSTOM_ID: source-code +:END: + +*This program is free software: released under Creative Commons Zero +(CC0) license* + +*Program author:* +- Svjatoslav Agejenko +- Homepage: https://svjatoslav.eu +- Email: mailto://svjatoslav@svjatoslav.eu +- See also: [[https://www.svjatoslav.eu/projects/][Other software projects hosted at svjatoslav.eu]] + +*Getting the source code:* +- [[https://www2.svjatoslav.eu/gitweb/?p=aukio.git;a=snapshot;h=HEAD;sf=tgz][Download latest snapshot in TAR GZ format]] +- [[https://www2.svjatoslav.eu/gitweb/?p=aukio.git;a=summary][Browse Git repository online]] +- Clone Git repository using command: + : git clone https://www2.svjatoslav.eu/git/aukio.git diff --git a/Modules/gi/Documentation/index.org b/Modules/gi/Documentation/index.org new file mode 100644 index 0000000..5877aef --- /dev/null +++ b/Modules/gi/Documentation/index.org @@ -0,0 +1,82 @@ +#+SETUPFILE: ~/.emacs.d/org-styles/html/darksun.theme +#+TITLE: Global illumination +#+LANGUAGE: en + +:PROPERTIES: +:CUSTOM_ID: gi-page +:END: + +#+OPTIONS: H:20 num:nil author:nil + +[[file:../../../Documentation/index.html#outline-container-gi][<- Back to index]] + +* What it owns +:PROPERTIES: +:CUSTOM_ID: gi-owns +:END: + +The light a surface actually receives: direct light with visibility, indirect +light, the lightmaps that hold per-texel results, and the policy that decides +what to bake next and in which order. + +It is the Java module =eu.svjatoslav.aukio.gi=. It requires the world and the +scheduler, and it cannot require the renderer or =java.desktop= - both are +build failures, because a baker that draws has stopped being a baker. + +* Where the light goes +:PROPERTIES: +:CUSTOM_ID: gi-where +:END: + +This module writes light into world storage; the renderer samples it. Neither +knows the other exists. That is what keeps the raster free of bake logic and the +baker free of pixels: swap the raster and the bakes still hold; turn GI off and +the raster draws with whatever direct light the app supplies. + +* The three rules it exists to keep +:PROPERTIES: +:CUSTOM_ID: gi-rules +:END: + +1. Light is published complete or not at all. A store that is allocated but not + yet baked reads as zeros, and zeros times albedo is a black frame. Until a + bake completes, the previous light stays on screen. +2. Displayed quality never drops. A re-pin, a streamed append or leaving a ring + may add unbaked surfaces, but it must never replace fine light with coarse + light or with none. +3. Coordinates are world coordinates. A light position and a normal in different + spaces produce light that appears displaced - the previous engine's phantom + lights were exactly that. + +* What it does not own +:PROPERTIES: +:CUSTOM_ID: gi-not-owns +:END: + +- No pixels and no frame buffer. That is the renderer's. +- No threads. The scheduler owns the process budget; this module submits work + and never sizes a pool of its own. +- No scene. Geometry, poses and lights belong to the world. + +* What the build checks +:PROPERTIES: +:CUSTOM_ID: gi-checks +:END: + +=ModuleShapeTest= holds the requirement list itself - world and scheduler, no +renderer, no toolkit - plus one package, files under 800 lines, and imports that +stay inside those two modules. + +#+begin_src sh +export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64 +./gradlew --offline :gi:test # the baker alone, other modules absent +#+end_src + +* Implemented today +:PROPERTIES: +:CUSTOM_ID: gi-implemented +:END: + +The module, its descriptor and its shape check. Nothing is baked yet; the first +piece will be direct light with visibility, because everything else is measured +against it. diff --git a/Modules/gi/build.gradle b/Modules/gi/build.gradle new file mode 100644 index 0000000..8dc11af --- /dev/null +++ b/Modules/gi/build.gradle @@ -0,0 +1,11 @@ +// Global illumination: the producer of light. It reads the world, spends the +// scheduler's budget, and writes light where the renderer can find it - it +// never draws and never owns a thread. + +dependencies { + // api: this module's own surface is expressed in world types (meshes, poses). + api project(':world') + // implementation: the scheduler is how the work gets run, not part of the + // API. The app that assembles modules decides which budget it gets. + implementation project(':scheduler') +} diff --git a/Modules/gi/src/main/java/eu/svjatoslav/aukio/gi/package-info.java b/Modules/gi/src/main/java/eu/svjatoslav/aukio/gi/package-info.java new file mode 100644 index 0000000..abb349b --- /dev/null +++ b/Modules/gi/src/main/java/eu/svjatoslav/aukio/gi/package-info.java @@ -0,0 +1,27 @@ +/** + * Global illumination: turning geometry and lights into the light each surface + * actually receives. + * + *

What belongs here: direct light with visibility, indirect light, the + * lightmaps that hold per-texel results, and the policy that decides what gets + * baked next and in which order. What does not, and never will: pixels, the + * window, the scene itself, or a thread of its own - the scheduler owns the + * budget, and this module asks it for work.

+ * + *

Three rules carry over from the previous engine, each of which cost a bug + * that took days to find:

+ * + * + */ +package eu.svjatoslav.aukio.gi; diff --git a/Modules/gi/src/main/java/module-info.java b/Modules/gi/src/main/java/module-info.java new file mode 100644 index 0000000..e550a00 --- /dev/null +++ b/Modules/gi/src/main/java/module-info.java @@ -0,0 +1,16 @@ +/** + * The global illumination module: the producer of light. + * + *

It reads the world, spends the scheduler's thread budget, and writes the + * light it computes where the renderer can sample it. It never writes a pixel + * and never owns a thread - that is why its descriptor requires the world and + * the scheduler and cannot require the renderer.

+ * + *

The export arrives with the first type. A package that holds only + * =package-info= cannot be exported, so the descriptor declares the module and + * its requirements now.

+ */ +module eu.svjatoslav.aukio.gi { + requires transitive eu.svjatoslav.aukio.world; + requires eu.svjatoslav.aukio.sched; +} diff --git a/Modules/gi/src/test/java/eu/svjatoslav/aukio/gi/ModuleShapeTest.java b/Modules/gi/src/test/java/eu/svjatoslav/aukio/gi/ModuleShapeTest.java new file mode 100644 index 0000000..c535fff --- /dev/null +++ b/Modules/gi/src/test/java/eu/svjatoslav/aukio/gi/ModuleShapeTest.java @@ -0,0 +1,178 @@ +package eu.svjatoslav.aukio.gi; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * The module's shape, checked rather than promised. + * + *

The requirement list is the load-bearing check here: global illumination + * produces light, so it may see the world and the scheduler and nothing else. + * A =requires= on the renderer would mean the baker has started drawing; a + * =requires= on =java.desktop= would mean it has started owning a window.

+ */ +class ModuleShapeTest { + + private static final int MAX_FILE_LINES = 800; + + private static final Path SOURCE_ROOT = Path.of("src", "main", "java"); + + private static final String MODULE_PACKAGE = "eu.svjatoslav.aukio.gi"; + + private static final String WORLD_PACKAGE = "eu.svjatoslav.aukio.world"; + + private static final String SCHED_PACKAGE = "eu.svjatoslav.aukio.sched"; + + private static final Set ALLOWED_ENGINE_MODULES = Set.of(WORLD_PACKAGE, SCHED_PACKAGE); + + private static final Pattern PACKAGE = Pattern.compile("^\\s*package\\s+([\\w.]+)\\s*;", Pattern.MULTILINE); + + private static final Pattern IMPORT = Pattern.compile("^\\s*import\\s+(?:static\\s+)?([\\w.*]+)\\s*;", Pattern.MULTILINE); + + private static final Pattern DECLARED_MODULE = Pattern.compile("^\\s*module\\s+([\\w.]+)\\s*\\{", Pattern.MULTILINE); + + private static final Pattern EXPORT = Pattern.compile("^\\s*exports\\s+([\\w.]+)\\s*;", Pattern.MULTILINE); + + private static final Pattern REQUIRES = Pattern.compile("^\\s*requires\\s+(?:transitive\\s+)?([\\w.]+)\\s*;", Pattern.MULTILINE); + + @Test + void sourcesLiveInExactlyOnePackage() throws IOException { + final List problems = new ArrayList<>(); + for (final Path file : sources()) { + final String declared = declaredPackage(file); + if (!MODULE_PACKAGE.equals(declared)) { + problems.add(relativize(file) + " declares package " + declared); + } + } + assertTrue(problems.isEmpty(), "one public package per module, found: " + problems); + } + + @Test + void theDescriptorAsksForTheWorldAndTheSchedulerOnly() throws IOException { + final String descriptor = descriptor(); + assertEquals(MODULE_PACKAGE, firstMatch(DECLARED_MODULE, descriptor), + "the module name is derived from its package"); + final List required = allMatches(REQUIRES, descriptor); + assertTrue(required.contains(WORLD_PACKAGE), "the baker reads the world: " + required); + assertTrue(required.contains(SCHED_PACKAGE), "the baker spends the scheduler's budget: " + required); + for (final String module : required) { + final boolean ours = module.startsWith("eu.svjatoslav.aukio."); + if (ours && !ALLOWED_ENGINE_MODULES.contains(module)) { + fail("global illumination is not allowed to require " + module); + } + } + final List exports = allMatches(EXPORT, descriptor); + assertTrue(exports.size() <= 1, "one public package at most, found: " + exports); + for (final String exported : exports) { + assertEquals(MODULE_PACKAGE, exported, "only the module's own package may be exported"); + } + } + + @Test + void noFileExceedsTheLineLimit() throws IOException { + final List tooLong = new ArrayList<>(); + for (final Path file : sources()) { + final int lines = Files.readAllLines(file, StandardCharsets.UTF_8).size(); + if (lines > MAX_FILE_LINES) { + tooLong.add(relativize(file) + " " + lines + " lines"); + } + } + assertTrue(tooLong.isEmpty(), "over " + MAX_FILE_LINES + " lines: " + tooLong); + } + + @Test + void importsStayInsideTheAllowedModules() throws IOException { + final List foreign = new ArrayList<>(); + for (final Path file : sources()) { + for (final String imported : imports(file)) { + if (!imported.startsWith("eu.svjatoslav.aukio.")) { + continue; + } + final boolean allowed = imported.startsWith(MODULE_PACKAGE) + || imported.startsWith(WORLD_PACKAGE) + || imported.startsWith(SCHED_PACKAGE); + if (!allowed) { + foreign.add(relativize(file) + " imports " + imported); + } + } + } + assertTrue(foreign.isEmpty(), "the baker sees the world and the scheduler, nothing else: " + foreign); + } + + @Test + void theModuleItselfHasSources() throws IOException { + assertFalse(sources().isEmpty(), "no sources under " + SOURCE_ROOT + " - the checks above would be vacuous"); + } + + private static List sources() throws IOException { + if (!Files.isDirectory(SOURCE_ROOT)) { + fail("run from the module directory: " + SOURCE_ROOT.toAbsolutePath() + " does not exist"); + } + try (Stream walk = Files.walk(SOURCE_ROOT)) { + return walk.filter(Files::isRegularFile) + .filter(path -> path.toString().endsWith(".java")) + .filter(path -> !path.getFileName().toString().equals("module-info.java")) + .sorted() + .toList(); + } + } + + private static String descriptor() throws IOException { + final Path file = SOURCE_ROOT.resolve("module-info.java"); + if (!Files.isRegularFile(file)) { + fail("the module declares no descriptor: " + relativize(file) + " is missing"); + } + return Files.readString(file, StandardCharsets.UTF_8); + } + + private static String declaredPackage(final Path file) throws IOException { + final String text = Files.readString(file, StandardCharsets.UTF_8); + final Matcher matcher = PACKAGE.matcher(text); + if (!matcher.find()) { + return ""; + } + assertEquals(1, countMatches(PACKAGE, text), "more than one package declaration in " + relativize(file)); + return matcher.group(1); + } + + private static List imports(final Path file) throws IOException { + return allMatches(IMPORT, Files.readString(file, StandardCharsets.UTF_8)); + } + + private static String firstMatch(final Pattern pattern, final String text) { + final List found = allMatches(pattern, text); + return found.isEmpty() ? "" : found.get(0); + } + + private static List allMatches(final Pattern pattern, final String text) { + final List found = new ArrayList<>(); + final Matcher matcher = pattern.matcher(text); + while (matcher.find()) { + found.add(matcher.group(1)); + } + return found; + } + + private static int countMatches(final Pattern pattern, final String text) { + return allMatches(pattern, text).size(); + } + + private static String relativize(final Path path) { + return Path.of("").toAbsolutePath().relativize(path.toAbsolutePath()).toString(); + } +} diff --git a/Modules/hid/Documentation/index.org b/Modules/hid/Documentation/index.org new file mode 100644 index 0000000..44c2aa1 --- /dev/null +++ b/Modules/hid/Documentation/index.org @@ -0,0 +1,116 @@ +#+SETUPFILE: ~/.emacs.d/org-styles/html/darksun.theme +#+TITLE: HID devices +#+LANGUAGE: en + +:PROPERTIES: +:CUSTOM_ID: hid-page +:END: + +#+OPTIONS: H:20 num:nil author:nil + +[[file:../../../Documentation/index.html#outline-container-hid][<- Back to index]] + +* What it owns +:PROPERTIES: +:CUSTOM_ID: hid-owns +:END + +Input devices the toolkit cannot deliver, read directly from =/dev/hidraw=: a +3Dconnexion 6DOF mouse today, whatever else arrives as bytes from a character +device later. + +It is the Java module =eu.svjatoslav.aukio.hid= and it requires nothing at +all - not the world, not the renderer, not the toolkit. A device is a level in +six axes and a listener call; nothing else is needed to report one, and a host +with no window can read a cap exactly like a windowed one. + +* Why it is its own module +:PROPERTIES: +:CUSTOM_ID: hid-why +:END + +A key press arrives through a toolkit, so =Modules/swing= records it. A cap +deflection does not: it is a report on a character device, and a host that has no +window - a test, a server, a terminal - still has a USB port. Putting the reader +inside the Swing adapter would tie the engine's device support to +=java.desktop=; putting it in the world would give the data model a file +descriptor and a thread, which that module's page forbids. + +=Modules/hid= is therefore the sixth kind of thing in the engine, and the only one +that owns a file descriptor. + +* The thread, and why the scheduler does not own it +:PROPERTIES: +:CUSTOM_ID: hid-thread +:END + +The reader runs one daemon thread per device, and that lifetime is spent blocked +in =read()= waiting for a hand to move. It is cheap and it is not CPU budget: the +scheduler decides how much compute this process may use, and a blocked I/O +thread uses none of it. Scheduling it would also mean a navigation source could +be starved by a frame - the cap would lag the picture it steers, which is the one +thing a 3D mouse must never do. + +* What it does not own +:PROPERTIES: +:CUSTOM_ID: hid-not-owns +:END + +- No camera policy. A deflection is reported as =Motion=, six axes in -1..1; how + that becomes a pose - or an object position, or a light - is the host's + decision, and the demo's =FlyCamera= is one such decision. +- No toolkit, no window, no scene. +- No discovery UI. A device that is not attached is not an error; the reader + looks again every two seconds, so a replug needs no restart. + +* The protocol +:PROPERTIES: +:CUSTOM_ID: hid-protocol +:END + +Two models are recognised, and both speak the same signs and the same +full-deflection range: + +- SpaceNavigator over USB: 7-byte reports, sent only while the cap is deflected + or a button changes, so silence is normal rather than a fault. Report 1 carries + translation, report 2 rotation, report 3 buttons, each axis a little-endian + signed 16-bit pair. +- SpaceMouse Wireless over Bluetooth: one 13-byte report carries all six axes. + +Raw signs, measured on the hardware: x to the right, y towards the user, z +pressed down, yaw twisted clockwise seen from above, pitch tilted away from the +user, roll tilted right. Axes are shaped before they leave the module - a +deadband of one count, then a quadratic response - so a small push gives fine +control and the rim gives full speed. + +The udev rule that makes the node readable lives in the older engines' +repositories (=aukio-3d/udev/99-spacenavigator.rules=); nothing here depends on +it existing at build time. + +* What the build checks +:PROPERTIES: +:CUSTOM_ID: hid-checks +:END + +=ModuleShapeTest= holds the shape: one package, a descriptor that requires no +other engine module, files under 800 lines, and imports that never leave the +module. + +=SpaceNavigatorTest= pins the protocol rather than a device: the endianness, the +report ids and the axis-to-role mapping are exactly what fails silently on real +hardware, where a wrong offset reads as a tiny movement instead of an error. + +#+begin_src sh +export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64 +./gradlew --offline :hid:test # the module alone, other modules absent +#+end_src + +* Implemented today +:PROPERTIES: +:CUSTOM_ID: hid-implemented +:END + +=SpaceNavigator= for the USB SpaceNavigator and the Bluetooth SpaceMouse +Wireless, and =Motion= as the six-axis reading. The button reports are recognised +and ignored: the cap button is a brake in the older engines, and a brake is a +navigation decision that belongs to whichever policy wants it. diff --git a/Modules/hid/build.gradle b/Modules/hid/build.gradle new file mode 100644 index 0000000..8ee30a1 --- /dev/null +++ b/Modules/hid/build.gradle @@ -0,0 +1,7 @@ +// Input devices no toolkit delivers: 3D mice first, and whatever else arrives as +// bytes from a character device later. It requires nothing at all, so a host +// with no window can use it exactly like a windowed one. + +dependencies { + // none +} diff --git a/Modules/hid/src/main/java/eu/svjatoslav/aukio/hid/Motion.java b/Modules/hid/src/main/java/eu/svjatoslav/aukio/hid/Motion.java new file mode 100644 index 0000000..5f434a9 --- /dev/null +++ b/Modules/hid/src/main/java/eu/svjatoslav/aukio/hid/Motion.java @@ -0,0 +1,26 @@ +package eu.svjatoslav.aukio.hid; + +/** + * What a 3D device is being asked to do right now, as six normalised axes. + * + *

Every value is -1..1: the transport applies a deadband and a quadratic + * response before this record exists, so a small push gives fine control and the + * rim gives full speed. The axes are levels, not deltas - a cap that is held + * keeps reporting until it is released - because that is what the hardware + * sends.

+ * + *

Signs are the hardware's, not the camera's: x to the right, y towards the + * user, z pressed down, yaw twisted to the right, pitch tilted away from the + * user, roll tilted right. A navigation policy flips them into whatever its own + * conventions are; this module only reports what the device did.

+ */ +public record Motion(double x, double y, double z, double yaw, double pitch, double roll) { + + /** Nothing touched: a hand off the cap. */ + public static final Motion REST = new Motion(0, 0, 0, 0, 0, 0); + + /** Whether any axis is currently deflected. */ + public boolean moving() { + return x != 0 || y != 0 || z != 0 || yaw != 0 || pitch != 0 || roll != 0; + } +} diff --git a/Modules/hid/src/main/java/eu/svjatoslav/aukio/hid/SpaceNavigator.java b/Modules/hid/src/main/java/eu/svjatoslav/aukio/hid/SpaceNavigator.java new file mode 100644 index 0000000..df30a8f --- /dev/null +++ b/Modules/hid/src/main/java/eu/svjatoslav/aukio/hid/SpaceNavigator.java @@ -0,0 +1,217 @@ +package eu.svjatoslav.aukio.hid; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; + +/** + * A 3Dconnexion 6DOF mouse, read from /dev/hidraw in plain Java. + * + *

No native library and no device daemon: the kernel already presents the + * device as a character device, a udev rule makes it readable by the user, and + * the reports are a dozen bytes. Two models are recognised - the USB + * SpaceNavigator and the Bluetooth SpaceMouse Wireless - because both speak the + * same axis signs and the same full-deflection range.

+ * + *

Protocol, SpaceNavigator over USB: 7-byte reports, sent only while the cap + * is deflected or a button changes, so silence is normal rather than a fault.

+ * + *
+ *   report[0] = 1   translation, int16 little endian at 1, 3, 5
+ *   report[0] = 2   rotation,    int16 little endian at 1, 3, 5
+ *   report[0] = 3   buttons,     report[1] bit 0 = left, bit 1 = right
+ * 
+ * + *

Protocol, SpaceMouse Wireless: one 13-byte report carries all six axes, + * translation then rotation, with the same little-endian int16 pairs.

+ * + *

Raw signs, measured on the hardware: x to the right, y towards the user, + * z pressed down, yaw twisted clockwise seen from above, pitch tilted away from + * the user, roll tilted right. Axes are shaped before they leave this class - a + * deadband of one count, then a quadratic response - so the driver receives + * -1..1 with fine control near the centre and full speed at the rim.

+ * + *

The hidraw node number changes on every replug, so the device is found by + * scanning /sys/class/hidraw for a known HID id and is re-scanned after a read + * failure: unplugging and plugging back in needs no restart.

+ */ +public final class SpaceNavigator { + + /** Where each decoded report goes. Called on the reader thread. */ + @FunctionalInterface + public interface MotionListener { + void motion(Motion motion); + } + + private static final String[] HID_IDS = { + "0003:0000046D:0000C626", // SpaceNavigator, USB + "0005:0000256F:0000C63A" // SpaceMouse Wireless, Bluetooth + }; + + /** How long to wait before looking for the device again. */ + private static final long RESCAN_MILLIS = 2000; + + /** Raw counts below this are a hand resting on the cap, not a push. */ + private static final int DEADBAND = 1; + + /** Full deflection, per the HID descriptor. */ + private static final double FULL_DEFLECTION = 350.0; + + private final MotionListener listener; + private final Thread thread; + + private volatile boolean running = true; + private volatile FileChannel open; + + public SpaceNavigator(final MotionListener listener) { + this.listener = listener; + this.thread = new Thread(this::loop, "space-navigator"); + this.thread.setDaemon(true); + } + + public void start() { + thread.start(); + } + + public void stop() { + running = false; + final FileChannel channel = open; + if (channel != null) { + try { + channel.close(); + } catch (final IOException ignored) { + // stopping is not a failure + } + } + thread.interrupt(); + } + + private void loop() { + final double[] axes = new double[6]; + while (running) { + final Path node = findDevice(); + if (node == null) { + if (!pause()) { + return; + } + continue; + } + System.out.println("space navigator: " + node); + try (FileChannel channel = FileChannel.open(node, StandardOpenOption.READ)) { + open = channel; + final ByteBuffer report = ByteBuffer.allocate(32); + while (running) { + report.clear(); + final int length = channel.read(report); + if (length > 0 && decode(report.array(), length, axes)) { + listener.motion(new Motion(axes[0], axes[1], axes[2], + axes[3], axes[4], axes[5])); + } + } + } catch (final IOException failure) { + if (running) { + System.out.println("space navigator: " + node + " stopped reading (" + + failure.getMessage() + "), looking for it again"); + } + } finally { + open = null; + } + if (!pause()) { + return; + } + } + } + + /** @return false when the thread was interrupted and must stop */ + private boolean pause() { + try { + Thread.sleep(RESCAN_MILLIS); + return true; + } catch (final InterruptedException interrupted) { + Thread.currentThread().interrupt(); + return false; + } + } + + /** @return the hidraw node of a supported device, or null when none is attached */ + static Path findDevice() { + final Path hidraw = Path.of("/sys/class/hidraw"); + if (!Files.isDirectory(hidraw)) { + return null; + } + try (DirectoryStream nodes = Files.newDirectoryStream(hidraw, "hidraw*")) { + for (final Path node : nodes) { + final Path uevent = node.resolve("device").resolve("uevent"); + if (!Files.isRegularFile(uevent)) { + continue; + } + final String content = Files.readString(uevent, StandardCharsets.UTF_8); + for (final String hidId : HID_IDS) { + if (content.contains(hidId)) { + return Path.of("/dev", node.getFileName().toString()); + } + } + } + } catch (final IOException unreadable) { + return null; + } + return null; + } + + /** + * Decodes one report into the six axes. + * + * @param report the bytes read + * @param length how many of them are valid + * @param axes receives x, y, z, yaw, pitch, roll; untouched when this is not a motion report + * @return whether the report carried motion + */ + static boolean decode(final byte[] report, final int length, final double[] axes) { + if (length < 4) { + return false; + } + final int id = report[0] & 0xFF; + if (id == 1 && length >= 13) { + axes[0] = shaped(axis(report, 1)); + axes[1] = shaped(axis(report, 3)); + axes[2] = shaped(axis(report, 5)); + axes[4] = shaped(axis(report, 7)); // RX, pitch + axes[5] = shaped(axis(report, 9)); // RY, roll + axes[3] = shaped(axis(report, 11)); // RZ, yaw + return true; + } + if (id == 1 && length >= 7) { + axes[0] = shaped(axis(report, 1)); + axes[1] = shaped(axis(report, 3)); + axes[2] = shaped(axis(report, 5)); + return true; + } + if (id == 2 && length >= 7) { + axes[4] = shaped(axis(report, 1)); // pitch, tilt away from the user + axes[5] = shaped(axis(report, 3)); // roll, tilt to the right + axes[3] = shaped(axis(report, 5)); // yaw, twist to the right + return true; + } + return false; + } + + /** Little-endian signed 16-bit at an offset. */ + private static int axis(final byte[] report, final int offset) { + return (short) ((report[offset] & 0xFF) | (report[offset + 1] << 8)); + } + + /** Deadband, then a quadratic response: fine control near the centre, full speed at the rim. */ + static double shaped(final int raw) { + final int magnitude = Math.abs(raw); + if (magnitude <= DEADBAND) { + return 0; + } + final double normalised = (magnitude - DEADBAND) / (FULL_DEFLECTION - DEADBAND); + return Math.copySign(normalised * normalised, raw); + } +} diff --git a/Modules/hid/src/main/java/module-info.java b/Modules/hid/src/main/java/module-info.java new file mode 100644 index 0000000..dc47abd --- /dev/null +++ b/Modules/hid/src/main/java/module-info.java @@ -0,0 +1,15 @@ +/** + * The HID module: 3D input devices the toolkit knows nothing about. + * + *

A 6DOF mouse arrives as bytes from a character device, not as an event from + * a window, so no toolkit can deliver it and no window has to exist for it to + * work. This module reads such devices and reports their deflection as data - + * six normalised axes - and the host decides what that means.

+ * + *

It requires nothing: not the world, not the renderer, not the toolkit. A + * device is a level in six axes and a listener call, and no other module is + * needed to say that.

+ */ +module eu.svjatoslav.aukio.hid { + exports eu.svjatoslav.aukio.hid; +} diff --git a/Modules/hid/src/test/java/eu/svjatoslav/aukio/hid/ModuleShapeTest.java b/Modules/hid/src/test/java/eu/svjatoslav/aukio/hid/ModuleShapeTest.java new file mode 100644 index 0000000..de655cb --- /dev/null +++ b/Modules/hid/src/test/java/eu/svjatoslav/aukio/hid/ModuleShapeTest.java @@ -0,0 +1,162 @@ +package eu.svjatoslav.aukio.hid; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * The module's shape, checked rather than promised: one public package, one + * descriptor, no requirement on any other engine module, and no file longer + * than the agreed limit. + * + *

The requirement list is the important one here. A device reader needs a + * byte stream and nothing else; if it ever requires the world or the renderer, + * then flying a camera has leaked into the module that should only be reporting + * what the hardware said.

+ */ +class ModuleShapeTest { + + private static final int MAX_FILE_LINES = 800; + + private static final Path SOURCE_ROOT = Path.of("src", "main", "java"); + + private static final String MODULE_PACKAGE = "eu.svjatoslav.aukio.hid"; + + private static final Pattern PACKAGE = Pattern.compile("^\\s*package\\s+([\\w.]+)\\s*;", Pattern.MULTILINE); + + private static final Pattern IMPORT = Pattern.compile("^\\s*import\\s+(?:static\\s+)?([\\w.*]+)\\s*;", Pattern.MULTILINE); + + private static final Pattern DECLARED_MODULE = Pattern.compile("^\\s*module\\s+([\\w.]+)\\s*\\{", Pattern.MULTILINE); + + private static final Pattern EXPORT = Pattern.compile("^\\s*exports\\s+([\\w.]+)\\s*;", Pattern.MULTILINE); + + private static final Pattern REQUIRES = Pattern.compile("^\\s*requires\\s+(?:transitive\\s+)?([\\w.]+)\\s*;", Pattern.MULTILINE); + + @Test + void sourcesLiveInExactlyOnePackage() throws IOException { + final List problems = new ArrayList<>(); + for (final Path file : sources()) { + final String declared = declaredPackage(file); + if (!MODULE_PACKAGE.equals(declared)) { + problems.add(relativize(file) + " declares package " + declared); + } + } + assertTrue(problems.isEmpty(), "one public package per module, found: " + problems); + } + + @Test + void theDescriptorRequiresNoEngineModule() throws IOException { + final String descriptor = descriptor(); + assertEquals(MODULE_PACKAGE, firstMatch(DECLARED_MODULE, descriptor), + "the module name is derived from its package"); + for (final String required : allMatches(REQUIRES, descriptor)) { + assertFalse(required.startsWith("eu.svjatoslav.aukio."), + "a device reader requires no engine module, found: " + required); + } + final List exports = allMatches(EXPORT, descriptor); + assertTrue(exports.size() <= 1, "one public package at most, found: " + exports); + for (final String exported : exports) { + assertEquals(MODULE_PACKAGE, exported, "only the module's own package may be exported"); + } + } + + @Test + void noFileExceedsTheLineLimit() throws IOException { + final List tooLong = new ArrayList<>(); + for (final Path file : sources()) { + final int lines = Files.readAllLines(file, StandardCharsets.UTF_8).size(); + if (lines > MAX_FILE_LINES) { + tooLong.add(relativize(file) + " " + lines + " lines"); + } + } + assertTrue(tooLong.isEmpty(), "over " + MAX_FILE_LINES + " lines: " + tooLong); + } + + @Test + void importsStayInsideThisModule() throws IOException { + final List foreign = new ArrayList<>(); + for (final Path file : sources()) { + for (final String imported : imports(file)) { + if (imported.startsWith("eu.svjatoslav.aukio.") && !imported.startsWith(MODULE_PACKAGE)) { + foreign.add(relativize(file) + " imports " + imported); + } + } + } + assertTrue(foreign.isEmpty(), "this module imports no other engine module: " + foreign); + } + + @Test + void theModuleItselfHasSources() throws IOException { + assertFalse(sources().isEmpty(), "no sources under " + SOURCE_ROOT + " - the checks above would be vacuous"); + } + + private static List sources() throws IOException { + if (!Files.isDirectory(SOURCE_ROOT)) { + fail("run from the module directory: " + SOURCE_ROOT.toAbsolutePath() + " does not exist"); + } + try (Stream walk = Files.walk(SOURCE_ROOT)) { + return walk.filter(Files::isRegularFile) + .filter(path -> path.toString().endsWith(".java")) + .filter(path -> !path.getFileName().toString().equals("module-info.java")) + .sorted() + .toList(); + } + } + + private static String descriptor() throws IOException { + final Path file = SOURCE_ROOT.resolve("module-info.java"); + if (!Files.isRegularFile(file)) { + fail("the module declares no descriptor: " + relativize(file) + " is missing"); + } + return Files.readString(file, StandardCharsets.UTF_8); + } + + private static String declaredPackage(final Path file) throws IOException { + final String text = Files.readString(file, StandardCharsets.UTF_8); + final Matcher matcher = PACKAGE.matcher(text); + if (!matcher.find()) { + return ""; + } + assertEquals(1, countMatches(PACKAGE, text), "more than one package declaration in " + relativize(file)); + return matcher.group(1); + } + + private static List imports(final Path file) throws IOException { + return allMatches(IMPORT, Files.readString(file, StandardCharsets.UTF_8)); + } + + private static String firstMatch(final Pattern pattern, final String text) { + final List found = allMatches(pattern, text); + return found.isEmpty() ? "" : found.get(0); + } + + private static List allMatches(final Pattern pattern, final String text) { + final List found = new ArrayList<>(); + final Matcher matcher = pattern.matcher(text); + while (matcher.find()) { + found.add(matcher.group(1)); + } + return found; + } + + private static int countMatches(final Pattern pattern, final String text) { + return allMatches(pattern, text).size(); + } + + private static String relativize(final Path path) { + return Path.of("").toAbsolutePath().relativize(path.toAbsolutePath()).toString(); + } +} diff --git a/Modules/hid/src/test/java/eu/svjatoslav/aukio/hid/SpaceNavigatorTest.java b/Modules/hid/src/test/java/eu/svjatoslav/aukio/hid/SpaceNavigatorTest.java new file mode 100644 index 0000000..b62b7e6 --- /dev/null +++ b/Modules/hid/src/test/java/eu/svjatoslav/aukio/hid/SpaceNavigatorTest.java @@ -0,0 +1,99 @@ +package eu.svjatoslav.aukio.hid; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The HID protocol and the response curve, checked against recorded report + * shapes rather than against a device. + * + *

The endianness, the report ids and the sign mapping are exactly the things + * that fail silently on real hardware - a wrong offset reads as a tiny movement + * rather than as an error - so they are pinned here, and the live check only has + * to confirm that the pipe opens.

+ */ +class SpaceNavigatorTest { + + private static final double EXACT = 1e-12; + + @Test + void aTranslationReportFillsTheFirstThreeAxes() { + final double[] axes = new double[6]; + assertTrue(SpaceNavigator.decode(report(1, 350, -350, 0), 7, axes)); + assertEquals(1.0, axes[0], EXACT, "push right is full x"); + assertEquals(-1.0, axes[1], EXACT, "pull towards the user is full -y"); + assertEquals(0, axes[2], EXACT); + assertEquals(0, axes[3], EXACT); + } + + @Test + void aRotationReportFillsYawPitchAndRoll() { + final double[] axes = new double[6]; + assertTrue(SpaceNavigator.decode(report(2, 350, 350, 350), 7, axes)); + assertEquals(1.0, axes[4], EXACT, "the first rotation axis is pitch, tilt away"); + assertEquals(1.0, axes[5], EXACT, "the second is roll, tilt right"); + assertEquals(1.0, axes[3], EXACT, "the third is yaw, twist right"); + } + + @Test + void aCombinedReportCarriesAllSixAxes() { + final byte[] report = new byte[13]; + report[0] = 1; + put(report, 1, 350); + put(report, 3, 175); + put(report, 5, -350); + put(report, 7, 350); // RX, pitch + put(report, 9, -350); // RY, roll + put(report, 11, 175); // RZ, yaw + final double[] axes = new double[6]; + assertTrue(SpaceNavigator.decode(report, 13, axes)); + assertEquals(1.0, axes[0], EXACT); + assertEquals(0.2486, axes[1], 1e-4, "half deflection is a quarter of the speed, by the curve"); + assertEquals(-1.0, axes[2], EXACT); + assertEquals(1.0, axes[4], EXACT, "pitch comes from the RX axis at offset 7"); + assertEquals(-1.0, axes[5], EXACT, "roll from RY at offset 9"); + assertEquals(0.2486, axes[3], 1e-4, "yaw from RZ at offset 11"); + } + + @Test + void aButtonReportIsNotMotion() { + final byte[] report = new byte[7]; + report[0] = 3; + report[1] = 1; + final double[] axes = new double[]{0.5, 0.5, 0.5, 0.5, 0.5, 0.5}; + assertFalse(SpaceNavigator.decode(report, 7, axes)); + assertEquals(0.5, axes[0], EXACT, "a button report must not disturb the axes"); + } + + @Test + void theDeadbandIsSilent() { + assertEquals(0, SpaceNavigator.shaped(0), EXACT); + assertEquals(0, SpaceNavigator.shaped(1), EXACT); + assertEquals(0, SpaceNavigator.shaped(-1), EXACT); + } + + @Test + void theCurveIsQuadraticAndReachesOneAtTheRim() { + assertEquals(-1.0, SpaceNavigator.shaped(-350), EXACT); + final double quarter = SpaceNavigator.shaped(88); + assertTrue(quarter > 0.05 && quarter < 0.07, "a quarter push is a fraction of the speed: " + quarter); + } + + /** A 7-byte report: id, then three little-endian 16-bit axes. */ + private static byte[] report(final int id, final int first, final int second, final int third) { + final byte[] report = new byte[7]; + report[0] = (byte) id; + put(report, 1, first); + put(report, 3, second); + put(report, 5, third); + return report; + } + + private static void put(final byte[] report, final int offset, final int value) { + report[offset] = (byte) (value & 0xFF); + report[offset + 1] = (byte) ((value >> 8) & 0xFF); + } +} diff --git a/Modules/navigation/Documentation/index.org b/Modules/navigation/Documentation/index.org new file mode 100644 index 0000000..4f009fb --- /dev/null +++ b/Modules/navigation/Documentation/index.org @@ -0,0 +1,108 @@ +#+SETUPFILE: ~/.emacs.d/org-styles/html/darksun.theme +#+TITLE: Navigation +#+LANGUAGE: en + +:PROPERTIES: +:CUSTOM_ID: navigation-page +:END: + +#+OPTIONS: H:20 num:nil author:nil + +[[file:../../../Documentation/index.html#outline-container-navigation][<- Back to index]] + +* What it owns +:PROPERTIES: +:CUSTOM_ID: navigation-owns +:END + +What the user asked for during one frame, and the camera policy that answers it. + +It is the Java module =eu.svjatoslav.aukio.navigation=: it requires the world, +because a pose is world data, and it deliberately requires nothing else - in +particular not the toolkit. Whoever fills the input record - a Swing component, a +test, a device with no window at all - the same policy flies the same way. + +* The seam: a record in, a pose out +:PROPERTIES: +:CUSTOM_ID: navigation-seam +:END + +| Type | Role | +|-----------------+---------------------------------------------------------------| +| =ViewInput= | one frame's worth of user intent, immutable | +| =InputRecorder= | where a host writes events; one snapshot is drained per frame | +| =CameraDriver= | the contract: record and elapsed seconds in, a pose out | +| =FlyCamera= | the engine's driver, with the rates every Aukio engine used | + +Two kinds of value live in a record, and the difference is the rule the previous +engine learned the hard way. Keys and 3D-device deflection are *levels*: true +until something changes them, copied into every frame. Pointer movement and wheel +notches are *accumulations*: drained by exactly one frame, so a drag is applied +once and never replayed. A value that is read and consumed in the same place is a +value applied twice, and that is why the recorder and the driver are separate +objects rather than one method. + +Keys travel as AWT key codes. The toolkit is where keys come from, so its +numbering is the dialect a record speaks; that keeps every policy from growing a +table of its own. + +* FlyCamera +:PROPERTIES: +:CUSTOM_ID: navigation-fly +:END + +The engine's camera: the pointer looks, the keyboard moves, the wheel changes +height, a 3D mouse does all three proportionally. The rates are the previous +engine's - a fiftieth of a radian per pixel, 2000 units per second squared of +acceleration growing with speed and damped at 5 per second up to 600 units per +second, a cap that drives five times the keyboard top speed, a wheel notch worth +a hundred units per second of thrust. + +Two behaviours are easy to get wrong and are deliberate. Keyboard movement is +level: forward and strafe come from yaw only, so pitching up to look at a roof +does not fly you into it. The cap, by contrast, flies along the view direction +with pitch included, because pushing it away means "go where I am looking". + +* What it does not own +:PROPERTIES: +:CUSTOM_ID: navigation-not-owns +:END + +- The scene, the frame, and everything the renderer does with them. +- Reading devices: a 3D mouse arrives through =Modules/hid= as =Motion=, and a host + hands it to the record it is filling. +- Toolkits. A host with no window drives the same record, and a host that wants + to orbit, walk or follow a path implements =CameraDriver= instead of using + =FlyCamera=. + +* What the build checks +:PROPERTIES: +:CUSTOM_ID: navigation-checks +:END + +=ModuleShapeTest= holds the shape: one package, a descriptor that requires the +world and no other engine module, files under 800 lines, and imports that stay +inside the module and the world. Proving the descriptor is not vacuous is one +line: adding =requires eu.svjatoslav.aukio.render= to it fails to compile with +"module not found". + +=FlyCameraTest= and =InputRecorderTest= drive the policy headlessly - keys, drags, +wheel notches and cap deflection in, poses out - which is the reason the input +record does not live in the toolkit module: a policy that needs a window to be +tested is a policy that stops being tested. + +#+begin_src sh +export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64 +./gradlew --offline :navigation:test # the module alone, other modules absent +#+end_src + +* Implemented today +:PROPERTIES: +:CUSTOM_ID: navigation-implemented +:END + +=ViewInput= with keys, pointer delta, wheel notches and six device axes; +=InputRecorder= as the host's write seam; =CameraDriver=; =FlyCamera= with the +previous engine's rates. Not here yet: orbiting and walking policies, a key map +for a host that is not a toolkit, and anything that moves the scene rather than +the camera. diff --git a/Modules/navigation/build.gradle b/Modules/navigation/build.gradle new file mode 100644 index 0000000..1851bff --- /dev/null +++ b/Modules/navigation/build.gradle @@ -0,0 +1,8 @@ +// What a frame of input is, and the camera policy that answers it. It knows the +// world (a pose is world data) and deliberately not the toolkit, so the same +// flying works in a test, a server, or a host with no window. + +dependencies { + // api: a driver hands back world types, so callers of this module name them. + api project(':world') +} diff --git a/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/CameraDriver.java b/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/CameraDriver.java new file mode 100644 index 0000000..bbf5da1 --- /dev/null +++ b/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/CameraDriver.java @@ -0,0 +1,26 @@ +package eu.svjatoslav.aukio.navigation; + +import eu.svjatoslav.aukio.world.Camera; + +/** + * The host's answer to one frame of input: the pose the next frame is drawn + * from. + * + *

A view knows nothing about flying, walking or orbiting, and this is where + * that stays true: each frame the host hands over what the user did and how long + * the frame took, and takes back a pose. {@link FlyCamera} is the engine's + * answer, and an application that wants another one implements this instead.

+ * + *

Called on the render thread, once per rendered frame, never on an event + * dispatch thread.

+ */ +@FunctionalInterface +public interface CameraDriver { + + /** + * @param input what the user did during this frame + * @param seconds time since the previous rendered frame, 0 on the first + * @return the pose for this frame, or null to keep the current one + */ + Camera frame(ViewInput input, double seconds); +} diff --git a/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/FlyCamera.java b/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/FlyCamera.java new file mode 100644 index 0000000..0cc0b25 --- /dev/null +++ b/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/FlyCamera.java @@ -0,0 +1,199 @@ +package eu.svjatoslav.aukio.navigation; + +import eu.svjatoslav.aukio.world.Camera; +import eu.svjatoslav.aukio.world.Vec3; + +/** + * Flying, the way every Aukio engine has flown: the pointer looks, the keyboard + * moves, the 3D mouse does both proportionally. + * + *

The rates are the previous engine's, not new numbers: pointer at a fiftieth + * of a radian per pixel, keyboard acceleration of 2000 units per second squared + * growing with speed and damped at 5 per second up to 600 units per second, and + * a 3D cap that drives five times the keyboard top speed at full deflection and + * twists twice as fast as it tilts. They were tuned against the real device and + * the same hand, so keeping them is what makes this feel like the engine that + * came before rather than a new one.

+ * + *

Two behaviours are easy to get wrong and are copied deliberately. Keyboard + * movement is level - forward and strafe come from yaw only, pitch only steers + * the view - while the cap flies along the view direction with pitch included, + * because pushing the cap away means "go where I am looking". And the cap is a + * level, not an impulse: it moves the camera for as long as it is deflected and + * stops the same frame it is released.

+ */ +public final class FlyCamera implements CameraDriver { + + /** + * Key codes in the input record's dialect, which is AWT's: the toolkit is + * where keys come from, so its numbering is what travels. The Dvorak cluster + * mirrors the physical WASD positions, so the same fingers fly in both + * layouts. + */ + static final int KEY_W = 87; + static final int KEY_A = 65; + static final int KEY_S = 83; + static final int KEY_D = 68; + static final int KEY_Q = 81; + static final int KEY_R = 82; + static final int KEY_E = 69; + static final int KEY_O = 79; + static final int KEY_COMMA = 44; + static final int KEY_PERIOD = 46; + static final int KEY_QUOTE = 222; + static final int KEY_UP = 38; + static final int KEY_DOWN = 40; + static final int KEY_LEFT = 37; + static final int KEY_RIGHT = 39; + + static final double MOUSE_SENSITIVITY = 0.02; + static final double PITCH_LIMIT = 1.5; + /** One wheel notch, in units per second of thrust: the legacy camera gave a + * notch fifty times its acceleration factor, which is this number here. */ + static final double WHEEL_THRUST = 100.0; + static final double ACCELERATION = 2000.0; + static final double ACCELERATION_SPEED_REFERENCE = 200.0; + static final double DAMPING = 5.0; + static final double MAX_SPEED = 600.0; + static final double CAP_SPEED_FACTOR = 5.0; + static final double CAP_SENSITIVITY = 5.0; + static final double CAP_YAW_RATE = Math.toRadians(180); + static final double CAP_PITCH_RATE = Math.toRadians(90); + static final double MAX_FRAME_SECONDS = 0.25; + + private double x; + private double y; + private double z; + private double yaw; + private double pitch; + private double velocityX; + private double velocityY; + private double velocityZ; + + public FlyCamera(final Camera start) { + this.x = start.position().x(); + this.y = start.position().y(); + this.z = start.position().z(); + this.yaw = start.yaw(); + this.pitch = start.pitch(); + } + + /** The pose as it stands, for a view that has not asked for a frame yet. */ + public Camera camera() { + return Camera.of(new Vec3(x, y, z), yaw, pitch); + } + + @Override + public Camera frame(final ViewInput input, final double seconds) { + final double dt = Math.min(Math.max(seconds, 0), MAX_FRAME_SECONDS); + if (dt > 0) { + look(input, dt); + fly(input, dt); + drive(input, dt); + } + return camera(); + } + + /** Pointer drag and cap tilt/twist: once per frame, because both are angles, not distances. */ + private void look(final ViewInput input, final double dt) { + yaw += input.dragX() * MOUSE_SENSITIVITY; + pitch = clamp(pitch - input.dragY() * MOUSE_SENSITIVITY); + yaw += input.deviceYaw() * CAP_YAW_RATE * CAP_SENSITIVITY * dt; + pitch = clamp(pitch + input.devicePitch() * CAP_PITCH_RATE * CAP_SENSITIVITY * dt); + } + + /** Keyboard and wheel: accelerate along the level view basis, damp, cap, move. */ + private void fly(final ViewInput input, final double dt) { + final double sinYaw = Math.sin(yaw); + final double cosYaw = Math.cos(yaw); + double dirX = 0; + double dirY = 0; + double dirZ = 0; + if (down(input, KEY_W, KEY_UP, KEY_COMMA)) { + dirX += sinYaw; + dirZ += cosYaw; + } + if (down(input, KEY_S, KEY_DOWN, KEY_O)) { + dirX -= sinYaw; + dirZ -= cosYaw; + } + if (down(input, KEY_D, KEY_RIGHT, KEY_E)) { + dirX += cosYaw; + dirZ -= sinYaw; + } + if (down(input, KEY_A, KEY_LEFT)) { + dirX -= cosYaw; + dirZ += sinYaw; + } + if (down(input, KEY_R, KEY_PERIOD)) { + dirY += 1; + } + if (down(input, KEY_Q, KEY_QUOTE)) { + dirY -= 1; + } + final double length = Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); + if (length > 0) { + final double speed = Math.sqrt(velocityX * velocityX + velocityY * velocityY + + velocityZ * velocityZ); + final double acceleration = ACCELERATION * (1 + speed / ACCELERATION_SPEED_REFERENCE); + velocityX += dirX / length * acceleration * dt; + velocityY += dirY / length * acceleration * dt; + velocityZ += dirZ / length * acceleration * dt; + } + // The wheel pushes vertically and nothing else, which is what both + // earlier engines did and what makes it a height control rather than a + // zoom: turning the wheel away from the user descends, towards the user + // rises. A notch is a push, so it is spent by the frame that reads it. + if (input.wheel() != 0) { + final double speed = Math.sqrt(velocityX * velocityX + velocityY * velocityY + + velocityZ * velocityZ); + velocityY -= input.wheel() * WHEEL_THRUST * (1 + speed / ACCELERATION_SPEED_REFERENCE); + } + final double damp = Math.exp(-DAMPING * dt); + velocityX *= damp; + velocityY *= damp; + velocityZ *= damp; + final double speed = Math.sqrt(velocityX * velocityX + velocityY * velocityY + + velocityZ * velocityZ); + if (speed > MAX_SPEED) { + final double limit = MAX_SPEED / speed; + velocityX *= limit; + velocityY *= limit; + velocityZ *= limit; + } + x += velocityX * dt; + y += velocityY * dt; + z += velocityZ * dt; + } + + /** 3D mouse: deflection is velocity along the view basis, released means stopped. */ + private void drive(final ViewInput input, final double dt) { + final double strafe = input.deviceX(); + final double forward = -input.deviceY(); + final double vertical = -input.deviceZ(); + if (strafe == 0 && forward == 0 && vertical == 0) { + return; + } + final double sinYaw = Math.sin(yaw); + final double cosYaw = Math.cos(yaw); + final double sinPitch = Math.sin(pitch); + final double cosPitch = Math.cos(pitch); + final double step = CAP_SPEED_FACTOR * MAX_SPEED * CAP_SENSITIVITY * dt; + x += (sinYaw * cosPitch * forward + cosYaw * strafe) * step; + y += (sinPitch * forward + vertical) * step; + z += (cosYaw * cosPitch * forward - sinYaw * strafe) * step; + } + + private static boolean down(final ViewInput input, final int... keyCodes) { + for (final int keyCode : keyCodes) { + if (input.isDown(keyCode)) { + return true; + } + } + return false; + } + + private static double clamp(final double value) { + return value < -PITCH_LIMIT ? -PITCH_LIMIT : Math.min(value, PITCH_LIMIT); + } +} diff --git a/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/InputRecorder.java b/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/InputRecorder.java new file mode 100644 index 0000000..c8ed0b1 --- /dev/null +++ b/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/InputRecorder.java @@ -0,0 +1,109 @@ +package eu.svjatoslav.aukio.navigation; + +import java.util.TreeSet; + +/** + * Where the component writes what its listeners saw, and where the render thread + * takes it from. + * + *

Two kinds of value live here, and the difference is the whole point. Keys + * and device deflection are levels: they are true until something changes them, + * so they are copied into every frame's snapshot. Pointer movement and wheel + * notches are accumulations: they are drained exactly once per frame, so a drag + * is applied once and never replayed.

+ * + *

The writers are whatever collects events - the toolkit listeners, a device + * thread, a test - and the single reader is the frame that renders next. That is + * why this type is public: it is the seam a host uses to feed the engine, and a + * host that is not Swing uses exactly the same one.

+ */ +public final class InputRecorder { + + private final Object lock = new Object(); + + private final TreeSet keys = new TreeSet<>(); + + private double dragX; + private double dragY; + private int wheel; + + private final double[] device = new double[6]; + + public void keyDown(final int keyCode) { + synchronized (lock) { + keys.add(keyCode); + } + } + + public void keyUp(final int keyCode) { + synchronized (lock) { + keys.remove(keyCode); + } + } + + /** A window that loses focus never sees the key releases, so they are dropped here. */ + public void clearKeys() { + synchronized (lock) { + keys.clear(); + } + } + + public void addPointerDelta(final double dx, final double dy) { + synchronized (lock) { + dragX += dx; + dragY += dy; + } + } + + /** Wheel notches accumulate like the pointer: they are spent by one frame. */ + public void addWheel(final int rotation) { + synchronized (lock) { + wheel += rotation; + } + } + + /** Device deflection is a level, written by the device thread and read every frame. */ + public void setDeviceMotion(final double x, final double y, final double z, + final double yaw, final double pitch, final double roll) { + synchronized (lock) { + device[0] = x; + device[1] = y; + device[2] = z; + device[3] = yaw; + device[4] = pitch; + device[5] = roll; + } + } + + /** One snapshot per frame; the pointer delta is consumed here and nowhere else. */ + public ViewInput drain() { + synchronized (lock) { + final int[] held = new int[keys.size()]; + int slot = 0; + for (final int key : keys) { + held[slot++] = key; + } + final ViewInput input = ViewInput.of(held, dragX, dragY, wheel, + device[0], device[1], device[2], device[3], device[4], device[5]); + dragX = 0; + dragY = 0; + wheel = 0; + return input; + } + } + + /** Whether a frame is worth rendering at all. */ + public boolean isActive() { + synchronized (lock) { + if (!keys.isEmpty() || dragX != 0 || dragY != 0 || wheel != 0) { + return true; + } + for (final double axis : device) { + if (axis != 0) { + return true; + } + } + return false; + } + } +} diff --git a/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/ViewInput.java b/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/ViewInput.java new file mode 100644 index 0000000..5bbf360 --- /dev/null +++ b/Modules/navigation/src/main/java/eu/svjatoslav/aukio/navigation/ViewInput.java @@ -0,0 +1,128 @@ +package eu.svjatoslav.aukio.navigation; + +import java.util.Arrays; + +/** + * What the user asked for during one frame: the keys still held, the pointer + * movement since the previous frame, and the current deflection of a 3D device. + * + *

This is a record, not a channel. A host adapter - the toolkit component, or + * anything else that collects events - builds one per frame and hands it to a + * {@link CameraDriver}; nothing else may read those pointer deltas, or they + * would be applied twice. Key state and device deflection are levels, so reading + * them twice is harmless - the pointer delta and the wheel notches are the + * values that are spent.

+ * + *

Keys arrive as AWT key codes because that is the dialect the toolkit speaks + * and the one the toolkits before this engine used; a different host would have + * to translate its own codes into them, which is cheaper than every policy + * growing a table.

+ * + *

Device axes are normalised to -1..1 through a deadband and a quadratic + * response, so a small push gives fine control and the rim gives full speed. + * Signs are the hardware's: x to the right, y towards the user, z pressed down, + * yaw twisted to the right, pitch tilted away from the user, roll tilted right. + * The driver flips them into the camera's own conventions; keeping the raw sense + * here is what lets one snapshot serve any controller.

+ */ +public final class ViewInput { + + /** Nothing held, nothing moved: an idle frame. */ + public static final ViewInput NOTHING = new ViewInput(new int[0], 0, 0, 0, + new double[]{0, 0, 0, 0, 0, 0}); + + private final int[] keys; + + private final double dragX; + private final double dragY; + private final int wheel; + private final double[] device; + + private ViewInput(final int[] keys, final double dragX, final double dragY, final int wheel, + final double[] device) { + this.keys = keys; + this.dragX = dragX; + this.dragY = dragY; + this.wheel = wheel; + this.device = device; + } + + /** + * @param keys key codes held at the start of the frame, in any order + * @param dragX pointer movement to the right since the previous frame, in pixels + * @param dragY pointer movement downwards since the previous frame, in pixels + * @param wheel wheel notches since the previous frame, positive scrolling away from the user + */ + public static ViewInput of(final int[] keys, final double dragX, final double dragY, final int wheel, + final double deviceX, final double deviceY, final double deviceZ, + final double deviceYaw, final double devicePitch, final double deviceRoll) { + final int[] sorted = keys.clone(); + Arrays.sort(sorted); + return new ViewInput(sorted, dragX, dragY, wheel, + new double[]{deviceX, deviceY, deviceZ, deviceYaw, devicePitch, deviceRoll}); + } + + /** @param keyCode an AWT key code, the toolkit's own dialect */ + public boolean isDown(final int keyCode) { + return Arrays.binarySearch(keys, keyCode) >= 0; + } + + /** The key codes held, ascending. */ + public int[] keys() { + return keys.clone(); + } + + public double dragX() { + return dragX; + } + + public double dragY() { + return dragY; + } + + /** + * Wheel notches since the previous frame, positive when the wheel was turned + * away from the user. A notch is an accumulation like the pointer delta: the + * frame that reads it spends it. + */ + public int wheel() { + return wheel; + } + + public double deviceX() { + return device[0]; + } + + public double deviceY() { + return device[1]; + } + + public double deviceZ() { + return device[2]; + } + + public double deviceYaw() { + return device[3]; + } + + public double devicePitch() { + return device[4]; + } + + public double deviceRoll() { + return device[5]; + } + + /** Whether anything is still being asked for, which decides if another frame is needed. */ + public boolean anyActivity() { + if (keys.length > 0 || dragX != 0 || dragY != 0 || wheel != 0) { + return true; + } + for (final double axis : device) { + if (axis != 0) { + return true; + } + } + return false; + } +} diff --git a/Modules/navigation/src/main/java/module-info.java b/Modules/navigation/src/main/java/module-info.java new file mode 100644 index 0000000..badb0aa --- /dev/null +++ b/Modules/navigation/src/main/java/module-info.java @@ -0,0 +1,22 @@ +/** + * The navigation module: the input a frame receives, and the camera policy that + * answers it. + * + *

A frame's worth of input is a record - keys held, pointer movement, wheel + * notches, the six axes of a 3D device - and a driver turns it into the pose the + * next frame is drawn from. The engine ships one driver, {@code FlyCamera}, with + * the rates every Aukio engine has used; a host that wants to orbit, walk or be + * driven by a path writes its own and the modules below never learn about it.

+ * + *

It requires the world, because a pose is world data and a driver produces + * one. It deliberately does not require the toolkit: input arrives here as a + * record, whoever filled it, so the same policy flies a windowed application, a + * test, or a device with no window at all.

+ */ +module eu.svjatoslav.aukio.navigation { + // transitive: this module's own API is expressed in world types (a pose in, + // a pose out), so anything that requires navigation needs the world to name + // them. + requires transitive eu.svjatoslav.aukio.world; + exports eu.svjatoslav.aukio.navigation; +} diff --git a/Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/FlyCameraTest.java b/Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/FlyCameraTest.java new file mode 100644 index 0000000..07c2835 --- /dev/null +++ b/Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/FlyCameraTest.java @@ -0,0 +1,177 @@ +package eu.svjatoslav.aukio.navigation; + +import eu.svjatoslav.aukio.world.Camera; +import eu.svjatoslav.aukio.world.Vec3; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The camera controls, driven without a window: keys fly, a drag looks, the cap + * pushes proportionally. + * + *

Each test feeds input frames to the driver and reads the pose back, which is + * the whole point of the driver seam - the behaviour that a person feels can be + * asserted headlessly, and the arithmetic cannot rot unnoticed behind a panel.

+ */ +class FlyCameraTest { + + private static final double HALF_A_SECOND = 0.05; + private static final int TEN_FRAMES = 10; + private static final int TWENTY_FRAMES = 20; + + private static final ViewInput NOTHING = ViewInput.NOTHING; + + @Test + void noInputLeavesThePoseAlone() { + final FlyCamera fly = new FlyCamera(Camera.of(new Vec3(1, 2, 3), 0.4, -0.2)); + fly.frame(NOTHING, HALF_A_SECOND); + assertEquals(1, fly.camera().position().x(), 1e-12); + assertEquals(2, fly.camera().position().y(), 1e-12); + assertEquals(3, fly.camera().position().z(), 1e-12); + assertEquals(0.4, fly.camera().yaw(), 1e-12); + assertEquals(-0.2, fly.camera().pitch(), 1e-12); + } + + @Test + void wFliesForwardAlongTheViewDirection() { + final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 0, 0))); + hold(fly, new int[]{FlyCamera.KEY_W}, TWENTY_FRAMES); + assertEquals(0, fly.camera().position().x(), 1e-9, "level flight has no sideways drift"); + assertEquals(0, fly.camera().position().y(), 1e-9, "level flight has no vertical drift"); + assertTrue(fly.camera().position().z() > 200, + "a second at full speed covers hundreds of units, not " + fly.camera().position().z()); + } + + @Test + void dStrafesRight() { + final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 0, 0))); + hold(fly, new int[]{FlyCamera.KEY_D}, TWENTY_FRAMES); + assertTrue(fly.camera().position().x() > 200, "strafe right goes to +X, got " + + fly.camera().position().x()); + assertEquals(0, fly.camera().position().z(), 1e-9); + } + + @Test + void rRisesAndQSinks() { + final FlyCamera up = new FlyCamera(Camera.at(new Vec3(0, 0, 0))); + hold(up, new int[]{FlyCamera.KEY_R}, TEN_FRAMES); + assertTrue(up.camera().position().y() > 0, "R rises, got " + up.camera().position().y()); + + final FlyCamera down = new FlyCamera(Camera.at(new Vec3(0, 0, 0))); + hold(down, new int[]{FlyCamera.KEY_Q}, TEN_FRAMES); + assertTrue(down.camera().position().y() < 0, "Q sinks, got " + down.camera().position().y()); + } + + @Test + void theWheelChangesHeightAndNothingElse() { + final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 100, 0))); + // a notch away from the user is the legacy gesture for going down + fly.frame(wheel(1), HALF_A_SECOND); + hold(fly, new int[0], TEN_FRAMES); + final double descent = 100 - fly.camera().position().y(); + // a notch is a hundred units per second of thrust, damped at five per + // second, so one notch carries the camera about twenty units + assertTrue(descent > 15 && descent < 30, + "one notch descends about twenty units, got " + descent); + assertEquals(0, fly.camera().position().x(), 1e-9, "the wheel is a height control, not a strafe"); + assertEquals(0, fly.camera().position().z(), 1e-9, "the wheel is a height control, not a thrust"); + } + + @Test + void theWheelTowardsTheUserRises() { + final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 100, 0))); + fly.frame(wheel(-1), HALF_A_SECOND); + hold(fly, new int[0], TEN_FRAMES); + assertTrue(fly.camera().position().y() > 100, "wheel towards the user rises, got " + + fly.camera().position().y()); + } + + @Test + void aNotchIsSpentByTheFrameThatReadsIt() { + final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 100, 0))); + fly.frame(wheel(1), HALF_A_SECOND); + // the push is a thrust: the camera keeps its velocity, but a frame that + // carries no notch must not add another one + final double afterFirst = fly.camera().position().y(); + final double firstStepDrop = 100 - afterFirst; + fly.frame(NOTHING, HALF_A_SECOND); + final double nextStepDrop = afterFirst - fly.camera().position().y(); + assertTrue(nextStepDrop < firstStepDrop, "a spent notch must not push again: " + nextStepDrop + + " in the next frame against " + firstStepDrop + " in the notch frame"); + } + + @Test + void draggingRightTurnsRight() { + final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 0, 0))); + fly.frame(input(new int[0], 100, 0), HALF_A_SECOND); + assertEquals(2.0, fly.camera().yaw(), 1e-9, "a hundred pixels at 0.02 radians each"); + } + + @Test + void draggingUpLooksUpAndStopsAtTheLimit() { + final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 0, 0))); + fly.frame(input(new int[0], 0, -10000), HALF_A_SECOND); + assertEquals(FlyCamera.PITCH_LIMIT, fly.camera().pitch(), 1e-9, "pitch is clamped upright"); + } + + @Test + void theCapFliesForward() { + final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 0, 0))); + for (int frame = 0; frame < TEN_FRAMES; frame++) { + // pushing the cap away from the user reads negative on the y axis + fly.frame(input(new int[0], 0, 0, 0, -1, 0, 0, 0, 0), HALF_A_SECOND); + } + assertTrue(fly.camera().position().z() > 100, "the cap flies along the view, got " + + fly.camera().position().z()); + assertEquals(0, fly.camera().position().x(), 1e-9); + } + + @Test + void theCapStopsTheFrameItIsReleased() { + final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 0, 0))); + fly.frame(input(new int[0], 0, 0, 0, -1, 0, 0, 0, 0), HALF_A_SECOND); + final double moved = fly.camera().position().z(); + fly.frame(NOTHING, HALF_A_SECOND); + assertEquals(moved, fly.camera().position().z(), 1e-12, "a released cap does not coast"); + } + + @Test + void theCapTwistsTheCamera() { + final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 0, 0))); + fly.frame(input(new int[0], 0, 0, 0, 0, 0, 1, 0, 0), HALF_A_SECOND); + assertTrue(fly.camera().yaw() > 0, "twisting clockwise turns right, got " + fly.camera().yaw()); + } + + @Test + void aFrameOfZeroSecondsChangesNothing() { + final FlyCamera fly = new FlyCamera(Camera.at(new Vec3(0, 0, 0))); + fly.frame(input(new int[]{FlyCamera.KEY_W}, 50, 50, 1, 1, 1, 1, 1, 1), 0); + assertEquals(0, fly.camera().position().z(), 1e-12); + assertEquals(0, fly.camera().yaw(), 1e-12); + } + + private static void hold(final FlyCamera fly, final int[] keys, final int frames) { + for (int frame = 0; frame < frames; frame++) { + fly.frame(input(keys, 0, 0), HALF_A_SECOND); + } + } + + private static ViewInput input(final int[] keys, final double dragX, final double dragY) { + return ViewInput.of(keys, dragX, dragY, 0, 0, 0, 0, 0, 0, 0); + } + + /** @param wheel notches, positive away from the user */ + private static ViewInput wheel(final int notches) { + return ViewInput.of(new int[0], 0, 0, notches, 0, 0, 0, 0, 0, 0); + } + + private static ViewInput input(final int[] keys, final double dragX, final double dragY, + final double deviceX, final double deviceY, final double deviceZ, + final double deviceYaw, final double devicePitch, + final double deviceRoll) { + return ViewInput.of(keys, dragX, dragY, 0, deviceX, deviceY, deviceZ, + deviceYaw, devicePitch, deviceRoll); + } +} diff --git a/Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/InputRecorderTest.java b/Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/InputRecorderTest.java new file mode 100644 index 0000000..7054745 --- /dev/null +++ b/Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/InputRecorderTest.java @@ -0,0 +1,79 @@ +package eu.svjatoslav.aukio.navigation; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * What survives a frame and what does not: keys and device deflection are + * levels, the pointer delta is spent by the frame that reads it. + * + *

This is the rule the previous engine broke with a signature built from + * live mouse deltas, so it is asserted rather than trusted.

+ */ +class InputRecorderTest { + + @Test + void keysAreStillHeldOnTheNextFrame() { + final InputRecorder recorder = new InputRecorder(); + recorder.keyDown(87); + assertTrue(recorder.drain().isDown(87)); + assertTrue(recorder.drain().isDown(87), "a key is a level until it is released"); + recorder.keyUp(87); + assertFalse(recorder.drain().isDown(87)); + } + + @Test + void pointerMovementIsSpentByTheFrameThatReadsIt() { + final InputRecorder recorder = new InputRecorder(); + recorder.addPointerDelta(10, -4); + final ViewInput first = recorder.drain(); + assertTrue(first.dragX() == 10 && first.dragY() == -4); + final ViewInput second = recorder.drain(); + assertTrue(second.dragX() == 0 && second.dragY() == 0, "a drag must not be applied twice"); + } + + @Test + void pointerMovementAccumulatesUntilTheFrameReadsIt() { + final InputRecorder recorder = new InputRecorder(); + recorder.addPointerDelta(3, 0); + recorder.addPointerDelta(4, 0); + assertTrue(recorder.drain().dragX() == 7); + } + + @Test + void deviceDeflectionPersistsUntilItChanges() { + final InputRecorder recorder = new InputRecorder(); + recorder.setDeviceMotion(0.5, 0, 0, 0, 0, 0); + assertTrue(recorder.drain().deviceX() == 0.5); + assertTrue(recorder.drain().deviceX() == 0.5, "a held cap keeps reporting, frame after frame"); + recorder.setDeviceMotion(0, 0, 0, 0, 0, 0); + assertFalse(recorder.drain().anyActivity()); + } + + @Test + void wheelNotchesAreSpentByTheFrameThatReadsThem() { + final InputRecorder recorder = new InputRecorder(); + recorder.addWheel(1); + recorder.addWheel(1); + assertTrue(recorder.drain().wheel() == 2, "two notches in one frame are one push of two"); + assertTrue(recorder.drain().wheel() == 0, "a notch must not be applied twice"); + } + + @Test + void losingFocusDropsHeldKeys() { + final InputRecorder recorder = new InputRecorder(); + recorder.keyDown(65); + recorder.clearKeys(); + assertFalse(recorder.drain().isDown(65), "a key released while unfocused would otherwise stick"); + } + + @Test + void anIdleRecorderAsksForNoFrames() { + final InputRecorder recorder = new InputRecorder(); + assertFalse(recorder.isActive()); + recorder.keyDown(87); + assertTrue(recorder.isActive()); + } +} diff --git a/Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/ModuleShapeTest.java b/Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/ModuleShapeTest.java new file mode 100644 index 0000000..9c462cb --- /dev/null +++ b/Modules/navigation/src/test/java/eu/svjatoslav/aukio/navigation/ModuleShapeTest.java @@ -0,0 +1,177 @@ +package eu.svjatoslav.aukio.navigation; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * The module's shape, checked rather than promised: one public package, one + * export, no file longer than the agreed limit, and no import of another module + * in this tree but the world. + * + *

The rule that matters here is the one that is absent: no requirement on the + * toolkit. A policy that could not fly without a window would be a policy that + * cannot be tested, and the whole point of keeping input as a record is that it + * can be driven by a test as easily as by a mouse.

+ */ +class ModuleShapeTest { + + private static final int MAX_FILE_LINES = 800; + + private static final Path SOURCE_ROOT = Path.of("src", "main", "java"); + + private static final String MODULE_PACKAGE = "eu.svjatoslav.aukio.navigation"; + + private static final String WORLD_PACKAGE = "eu.svjatoslav.aukio.world"; + + private static final Pattern PACKAGE = Pattern.compile("^\\s*package\\s+([\\w.]+)\\s*;", Pattern.MULTILINE); + + private static final Pattern IMPORT = Pattern.compile("^\\s*import\\s+(?:static\\s+)?([\\w.*]+)\\s*;", Pattern.MULTILINE); + + private static final Pattern DECLARED_MODULE = Pattern.compile("^\\s*module\\s+([\\w.]+)\\s*\\{", Pattern.MULTILINE); + + private static final Pattern EXPORT = Pattern.compile("^\\s*exports\\s+([\\w.]+)\\s*;", Pattern.MULTILINE); + + private static final Pattern REQUIRES = Pattern.compile("^\\s*requires\\s+(?:transitive\\s+)?([\\w.]+)\\s*;", Pattern.MULTILINE); + + @Test + void sourcesLiveInExactlyOnePackage() throws IOException { + final List problems = new ArrayList<>(); + for (final Path file : sources()) { + final String declared = declaredPackage(file); + if (!MODULE_PACKAGE.equals(declared)) { + problems.add(relativize(file) + " declares package " + declared); + continue; + } + final Path directory = file.getParent(); + if (!directory.endsWith(Path.of("", MODULE_PACKAGE.split("\\.")))) { + problems.add(relativize(file) + " sits in " + relativize(directory) + + " but declares " + MODULE_PACKAGE); + } + } + assertTrue(problems.isEmpty(), "one public package per module, found: " + problems); + } + + @Test + void theDescriptorExportsThatOnePackageAndRequiresTheWorldOnly() throws IOException { + final String descriptor = descriptor(); + assertEquals(MODULE_PACKAGE, firstMatch(DECLARED_MODULE, descriptor), + "the module name is derived from its package, so a requires clause reads naturally"); + final List exports = allMatches(EXPORT, descriptor); + assertTrue(exports.size() <= 1, "the module exports at most its one public package, found: " + exports); + for (final String exported : exports) { + assertEquals(MODULE_PACKAGE, exported, "only the module's own package may be exported"); + } + final List required = allMatches(REQUIRES, descriptor); + assertTrue(required.contains(WORLD_PACKAGE), + "a driver produces a world pose, so its descriptor says so: " + required); + for (final String module : required) { + final boolean ours = module.startsWith("eu.svjatoslav.aukio."); + if (ours && !module.equals(WORLD_PACKAGE)) { + fail("navigation requires no engine module but the world, found: " + module); + } + } + } + + @Test + void noFileExceedsTheLineLimit() throws IOException { + final List tooLong = new ArrayList<>(); + for (final Path file : sources()) { + final int lines = Files.readAllLines(file, StandardCharsets.UTF_8).size(); + if (lines > MAX_FILE_LINES) { + tooLong.add(relativize(file) + " " + lines + " lines"); + } + } + assertTrue(tooLong.isEmpty(), "over " + MAX_FILE_LINES + " lines: " + tooLong); + } + + @Test + void importsReachIntoTheWorldAndNoFurther() throws IOException { + final List foreign = new ArrayList<>(); + for (final Path file : sources()) { + for (final String imported : imports(file)) { + if (imported.startsWith("eu.svjatoslav.aukio.") + && !imported.startsWith(MODULE_PACKAGE) + && !imported.startsWith(WORLD_PACKAGE)) { + foreign.add(relativize(file) + " imports " + imported); + } + } + } + assertTrue(foreign.isEmpty(), "navigation may see the world and nothing else: " + foreign); + } + + @Test + void theModuleItselfHasSources() throws IOException { + assertFalse(sources().isEmpty(), "no sources under " + SOURCE_ROOT + " - the checks above would be vacuous"); + } + + private static List sources() throws IOException { + if (!Files.isDirectory(SOURCE_ROOT)) { + fail("run from the module directory: " + SOURCE_ROOT.toAbsolutePath() + " does not exist"); + } + try (Stream walk = Files.walk(SOURCE_ROOT)) { + return walk.filter(Files::isRegularFile) + .filter(path -> path.toString().endsWith(".java")) + .filter(path -> !path.getFileName().toString().equals("module-info.java")) + .sorted() + .toList(); + } + } + + private static String descriptor() throws IOException { + final Path file = SOURCE_ROOT.resolve("module-info.java"); + if (!Files.isRegularFile(file)) { + fail("the module declares no descriptor: " + relativize(file) + " is missing"); + } + return Files.readString(file, StandardCharsets.UTF_8); + } + + private static String declaredPackage(final Path file) throws IOException { + final String text = Files.readString(file, StandardCharsets.UTF_8); + final Matcher matcher = PACKAGE.matcher(text); + if (!matcher.find()) { + return ""; + } + assertEquals(1, countMatches(PACKAGE, text), "more than one package declaration in " + relativize(file)); + return matcher.group(1); + } + + private static List imports(final Path file) throws IOException { + return allMatches(IMPORT, Files.readString(file, StandardCharsets.UTF_8)); + } + + private static String firstMatch(final Pattern pattern, final String text) { + final List found = allMatches(pattern, text); + return found.isEmpty() ? "" : found.get(0); + } + + private static List allMatches(final Pattern pattern, final String text) { + final List found = new ArrayList<>(); + final Matcher matcher = pattern.matcher(text); + while (matcher.find()) { + found.add(matcher.group(1)); + } + return found; + } + + private static int countMatches(final Pattern pattern, final String text) { + return allMatches(pattern, text).size(); + } + + private static String relativize(final Path path) { + return Path.of("").toAbsolutePath().relativize(path.toAbsolutePath()).toString(); + } +} diff --git a/Modules/renderer/Documentation/index.org b/Modules/renderer/Documentation/index.org new file mode 100644 index 0000000..6921b7f --- /dev/null +++ b/Modules/renderer/Documentation/index.org @@ -0,0 +1,120 @@ +#+SETUPFILE: ~/.emacs.d/org-styles/html/darksun.theme +#+TITLE: Renderer +#+LANGUAGE: en + +:PROPERTIES: +:CUSTOM_ID: renderer-page +:END: + +#+OPTIONS: H:20 num:nil author:nil + +[[file:../../../Documentation/index.html#outline-container-renderer][<- Back to index]] + +* What it owns +:PROPERTIES: +:CUSTOM_ID: renderer-owns +:END: + +The algorithms that turn a world into pixels: the frame buffer, the projection +from a camera pose and a viewport to screen coordinates, culling, and +rasterisation. + +It owns no scene data. Geometry, the object tree, triangle storage, the +primitives and the camera pose all live in =Modules/world=; the renderer reads +them and produces an image. + +| Seam | Owns | +|---------------+----------------------------------------------------------| +| frame buffer | the pixels and the depth buffer being written | +| transform | camera pose + viewport in, screen coordinates out | +| cull | backface verdict, viewport rejection, per-node bounds | +| raster | tile fill, depth test, flat colour | + +* A pose is data, a projection is not +:PROPERTIES: +:CUSTOM_ID: renderer-pose +:END: + +The camera's position and rotation are world data. The =scale = width / 3= +convention that turns them into screen coordinates is here, because only the +renderer knows how wide the picture is. If that constant moved into the world, +the world would need a viewport and the two modules would collapse into one. + +* Invariants +:PROPERTIES: +:CUSTOM_ID: renderer-invariants +:END: + +- Local coordinates arrive already composed. By the time a triangle reaches the + transform stage it is in world space; anything else is a bug in the world, not + a convention to accommodate here. +- A frame is produced whole. Nothing half-written is visible to another thread, + so a reader either sees the previous frame or the next one. +- The same world and the same pose produce the same pixels. A rendering feature + that is not deterministic cannot be verified. + +* What the build checks +:PROPERTIES: +:CUSTOM_ID: renderer-checks +:END: + +The descriptor is =module eu.svjatoslav.aukio.render= with exactly one +requirement, =eu.svjatoslav.aukio.world=; naming any other engine module is a +compile error. + +=ModuleShapeTest= adds what the compiler cannot: one package, files under 800 +lines, imports that reach into the world and no further, an export that is the +module's own package, and the requirement list itself. + +=RendererTest= pins the picture rather than the code: it renders the first +engine's minimal scene - one 100-unit red box, a level camera a hundred units up +and three hundred back - at 1920x1080 and asserts the silhouette the first +engine actually drew, the covered area to within two percent, one flat colour, +and byte-identical pixels across two runs. It also checks that a nearer surface +wins, and that a triangle crossing the near plane keeps the part in front of it. +A projection convention, a field of view or a depth-test change moves the box and +fails the test. + +#+begin_src sh +export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64 +./gradlew --offline :renderer:test # module alone, other modules absent +#+end_src + +* Implemented today +:PROPERTIES: +:CUSTOM_ID: renderer-implemented +:END: + +The frame buffer and the three stages, enough to draw a flat-shaded scene: + +| Type | What it does | +|---------------+---------------------------------------------------------------| +| =FrameBuffer= | pixels plus reciprocal depth; zero depth means uncovered | +| =Projection= | camera pose and picture size in, screen coordinates out | +| =Cull= | drops a projected polygon whose bounds miss the picture | +| =Raster= | flat-colour fill with a depth test, triangle or clipped quad | +| =Renderer= | one frame: clip to the near plane, project, cull, rasterise | + +The near plane is inside =Renderer= rather than in =Cull= because a clip +produces new vertices and a cull produces a verdict. Clipping is +Sutherland-Hodgman in camera space: a triangle crossing the plane becomes a quad +rather than a hole. + +There is no backface verdict yet, and that is deliberate. The first engine did +not cull backfaces either - it let the depth buffer resolve a closed solid - and +no mesh in the world module carries a winding contract that a verdict could be +judged against. The condition on adding one is the contract, not the algorithm. + +The renderer is single threaded. A frame that is a few hundred triangles wide +buys more from reproducible ordering than from a pool, and a renderer that owns +a pool would be a second place deciding how much CPU this process may use - the +scheduler's job. + +* Deliberately not here +:PROPERTIES: +:CUSTOM_ID: renderer-not-here +:END: + +Global illumination, CSG, OBJ loading, SDF text, the octree raytracer, stereo and +the developer tools. Each is a separate module built on top of the world and the +renderer, so both keep compiling and testing with them absent. diff --git a/Modules/renderer/build.gradle b/Modules/renderer/build.gradle new file mode 100644 index 0000000..7ef62ea --- /dev/null +++ b/Modules/renderer/build.gradle @@ -0,0 +1,9 @@ +// The algorithms that turn a world into pixels: projection, culling and +// rasterisation. It knows the world, the world does not know it. + +dependencies { + // api, not implementation: a caller of the renderer passes world types + // (scene, camera pose) straight through, so those types are part of this + // module's own surface. + api project(':world') +} diff --git a/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Cull.java b/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Cull.java new file mode 100644 index 0000000..47fa765 --- /dev/null +++ b/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Cull.java @@ -0,0 +1,43 @@ +package eu.svjatoslav.aukio.render; + +/** + * What must not reach the raster stage. + * + *

Today that is one verdict: a projected polygon whose bounding box misses + * the picture entirely. The near plane is handled earlier, by the clip in + * {@link Renderer}, because a clip produces new vertices and a cull does + * not.

+ * + *

There is deliberately no backface verdict here yet. The first engine never + * culled backfaces either - it let the depth buffer resolve a closed solid - and + * no mesh in the world module carries a winding contract to judge against. + * Adding one without that contract would be a rule the data cannot keep.

+ */ +public final class Cull { + + private Cull() { + } + + /** + * @param xs screen-space x of the polygon's vertices + * @param ys screen-space y of the polygon's vertices + * @param count how many vertices the polygon has, 3 or 4 + * @return whether any part of it can land on a pixel + */ + public static boolean onScreen(final double[] xs, final double[] ys, final int count, + final int width, final int height) { + double minX = xs[0]; + double maxX = xs[0]; + double minY = ys[0]; + double maxY = ys[0]; + for (int i = 1; i < count; i++) { + minX = Math.min(minX, xs[i]); + maxX = Math.max(maxX, xs[i]); + minY = Math.min(minY, ys[i]); + maxY = Math.max(maxY, ys[i]); + } + // pixel centres live at x + 0.5, so the boxes overlap the picture when + // the vertex range crosses it by more than one pixel on either side + return maxX > 0 && minX < width && maxY > 0 && minY < height; + } +} diff --git a/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/FrameBuffer.java b/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/FrameBuffer.java new file mode 100644 index 0000000..0e6c59d --- /dev/null +++ b/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/FrameBuffer.java @@ -0,0 +1,90 @@ +package eu.svjatoslav.aukio.render; + +import java.util.Arrays; + +/** + * The pixels and the depth buffer one frame is painted into. + * + *

Depth is stored as a reciprocal, one over the camera-space z: it grows + * towards the viewer, so a nearer fragment has the larger value and the test is + * a plain "greater than". Zero means nothing has been written, which is why + * clearing a buffer is a fill and a zeroing rather than a pass over the depth + * array with a far-plane value.

+ * + *

A buffer is not thread safe by design: one renderer owns one buffer for + * the duration of a frame, and only the finished pixels are ever handed on.

+ * + *

The pixel array may be supplied by the caller, which is what lets a host + * render straight into the raster of an image it will blit: no copy per frame + * and no allocation per frame. The depth array is always the buffer's own, + * because nothing outside wants to see it.

+ */ +public final class FrameBuffer { + + private final int width; + private final int height; + private final int[] pixels; + private final double[] reciprocalDepth; + + public FrameBuffer(final int width, final int height) { + this(width, height, new int[requireSaneSize(width, height)]); + } + + /** + * @param pixels the array the renderer writes into; a host that renders into + * an image's own raster passes it here and then blits it with + * no copy at all + */ + public FrameBuffer(final int width, final int height, final int[] pixels) { + requireSaneSize(width, height); + if (pixels.length != width * height) { + throw new IllegalArgumentException( + "the pixel array must hold exactly " + (width * height) + " pixels: " + pixels.length); + } + this.width = width; + this.height = height; + this.pixels = pixels; + this.reciprocalDepth = new double[width * height]; + } + + private static int requireSaneSize(final int width, final int height) { + if (width <= 0 || height <= 0) { + throw new IllegalArgumentException("an empty buffer cannot be rendered into: " + width + "x" + height); + } + return width * height; + } + + public int width() { + return width; + } + + public int height() { + return height; + } + + /** The pixels, row-major, in ARGB. Writing to this array is the caller's risk. */ + public int[] pixels() { + return pixels; + } + + public int pixelAt(final int x, final int y) { + return pixels[y * width + x]; + } + + /** Reciprocal depth at a pixel; 0 means the pixel was never covered. */ + public double depthAt(final int x, final int y) { + return reciprocalDepth[y * width + x]; + } + + public void clear(final int argb) { + Arrays.fill(pixels, argb); + Arrays.fill(reciprocalDepth, 0); + } + + /** Writes a fragment without a depth test; the raster decides what to keep. */ + void write(final int x, final int y, final int argb, final double depth) { + final int index = y * width + x; + pixels[index] = argb; + reciprocalDepth[index] = depth; + } +} diff --git a/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Projection.java b/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Projection.java new file mode 100644 index 0000000..65386f8 --- /dev/null +++ b/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Projection.java @@ -0,0 +1,96 @@ +package eu.svjatoslav.aukio.render; + +import eu.svjatoslav.aukio.world.Camera; + +/** + * Camera pose plus picture size in, screen coordinates out. + * + *

The pose arrives from the world; the width arrives from the frame, and so + * does the one constant this module owns: the camera's scale is a third of the + * picture width. If that constant lived in the world, the world would need a + * viewport and the two modules would be one.

+ * + *

The transform is the one the previous engines used, kept because renders + * across engines are compared to the pixel: subtract the eye, turn the world by + * the inverse yaw about +Y, then by the pitch about +X so that the camera's + * forward direction ends up on +Z. Screen y grows downwards, hence the + * subtraction in {@code sy}.

+ */ +public final class Projection { + + private static final double SCALE_PER_WIDTH = 1.0 / 3.0; + + private final double eyeX; + private final double eyeY; + private final double eyeZ; + private final double cosYaw; + private final double sinYaw; + private final double cosPitch; + private final double sinPitch; + private final double scale; + private final double centerX; + private final double centerY; + private final int width; + private final int height; + + public Projection(final Camera camera, final int width, final int height) { + if (width <= 0 || height <= 0) { + throw new IllegalArgumentException("a projection needs a picture: " + width + "x" + height); + } + this.width = width; + this.height = height; + this.eyeX = camera.position().x(); + this.eyeY = camera.position().y(); + this.eyeZ = camera.position().z(); + this.cosYaw = Math.cos(camera.yaw()); + this.sinYaw = Math.sin(camera.yaw()); + this.cosPitch = Math.cos(camera.pitch()); + this.sinPitch = Math.sin(camera.pitch()); + this.scale = width * SCALE_PER_WIDTH; + this.centerX = width / 2.0; + this.centerY = height / 2.0; + } + + /** Stored as written, because it is the engine's field of view, not a tuning knob. */ + public double scale() { + return scale; + } + + public int width() { + return width; + } + + public int height() { + return height; + } + + /** + * World space to camera space: x right, y up, z forward. + * + * @param out receives x, y, z + */ + public void toCameraSpace(final double worldX, final double worldY, final double worldZ, + final double[] out) { + final double dx = worldX - eyeX; + final double dy = worldY - eyeY; + final double dz = worldZ - eyeZ; + final double x = dx * cosYaw - dz * sinYaw; + final double z = dx * sinYaw + dz * cosYaw; + out[0] = x; + out[1] = dy * cosPitch - z * sinPitch; + out[2] = dy * sinPitch + z * cosPitch; + } + + /** + * Camera space to screen space. + * + * @param camera a vertex in front of the camera; z must be positive + * @param out receives screen x, screen y and reciprocal depth + */ + public void toScreenSpace(final double[] camera, final double[] out) { + final double reciprocal = 1.0 / camera[2]; + out[0] = centerX + camera[0] * reciprocal * scale; + out[1] = centerY - camera[1] * reciprocal * scale; + out[2] = reciprocal; + } +} diff --git a/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Raster.java b/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Raster.java new file mode 100644 index 0000000..64d3c5d --- /dev/null +++ b/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Raster.java @@ -0,0 +1,89 @@ +package eu.svjatoslav.aukio.render; + +/** + * Flat-coloured triangle and quad fill with a depth test. + * + *

A polygon is filled by testing every pixel centre inside its bounding box + * against the polygon's edges, interpolating reciprocal depth from the same + * barycentric weights, and writing the pixel when it is nearer than whatever is + * already there. Pixels whose centre lies exactly on an edge count as inside + * for all polygons that share that edge; the depth test makes the second write + * harmless, and the alternative - dropping them - leaves one-pixel seams + * through a closed solid.

+ */ +public final class Raster { + + private Raster() { + } + + /** + * @param xs screen-space x per vertex + * @param ys screen-space y per vertex + * @param depth reciprocal depth per vertex + * @param count 3 for a triangle, 4 for a clipped quad + * @param argb flat colour + */ + public static void fill(final FrameBuffer frame, final double[] xs, final double[] ys, + final double[] depth, final int count, final int argb) { + if (count < 3) { + return; + } + final double area = area(xs, ys, count); + if (area == 0) { + return; + } + final boolean positive = area > 0; + double minX = xs[0]; + double maxX = xs[0]; + double minY = ys[0]; + double maxY = ys[0]; + for (int i = 1; i < count; i++) { + minX = Math.min(minX, xs[i]); + maxX = Math.max(maxX, xs[i]); + minY = Math.min(minY, ys[i]); + maxY = Math.max(maxY, ys[i]); + } + final int firstX = (int) Math.max(0, Math.ceil(minX - 0.5)); + final int lastX = (int) Math.min(frame.width() - 1, Math.floor(maxX - 0.5)); + final int firstY = (int) Math.max(0, Math.ceil(minY - 0.5)); + final int lastY = (int) Math.min(frame.height() - 1, Math.floor(maxY - 0.5)); + final double[] edges = new double[4]; + for (int y = firstY; y <= lastY; y++) { + final double pixelY = y + 0.5; + for (int x = firstX; x <= lastX; x++) { + final double pixelX = x + 0.5; + boolean inside = true; + for (int i = 0; i < count; i++) { + final int j = (i + 1) % count; + final double edge = (xs[j] - xs[i]) * (pixelY - ys[i]) + - (ys[j] - ys[i]) * (pixelX - xs[i]); + if (positive ? edge < 0 : edge > 0) { + inside = false; + break; + } + edges[i] = edge; + } + if (!inside) { + continue; + } + double interpolated = 0; + for (int i = 0; i < count; i++) { + interpolated += (edges[i] / area) * depth[i]; + } + if (interpolated > frame.depthAt(x, y)) { + frame.write(x, y, argb, interpolated); + } + } + } + } + + /** Twice the signed area; only its sign and the weights built from it are used. */ + private static double area(final double[] xs, final double[] ys, final int count) { + double total = 0; + for (int i = 0; i < count; i++) { + final int j = (i + 1) % count; + total += xs[i] * ys[j] - xs[j] * ys[i]; + } + return total; + } +} diff --git a/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Renderer.java b/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Renderer.java new file mode 100644 index 0000000..9d62628 --- /dev/null +++ b/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/Renderer.java @@ -0,0 +1,95 @@ +package eu.svjatoslav.aukio.render; + +import eu.svjatoslav.aukio.world.Camera; +import eu.svjatoslav.aukio.world.Scene; + +/** + * One frame, start to finish: compose the scene, project it, drop what cannot + * be seen, rasterise what is left. + * + *

Single threaded on purpose. A frame is small enough that the ordering + * guarantees are worth more than the threads, and the scheduler module is where + * a parallel dispatch will be argued for; a renderer that owns a pool would be + * a second place deciding how much CPU this process may use.

+ * + *

The same scene and the same camera produce the same pixels: the walk order + * comes from the scene, the geometry is read, never mutated, and nothing here + * consults a clock or a random source.

+ */ +public final class Renderer { + + /** Everything nearer than this is clipped away; a vertex behind the eye cannot be projected. */ + private static final double NEAR = 0.1; + + private Renderer() { + } + + public static void render(final Scene scene, final Camera camera, final FrameBuffer frame) { + final Projection projection = new Projection(camera, frame.width(), frame.height()); + final double[][] cameraSpace = new double[3][3]; + final double[][] clipped = new double[4][3]; + final double[] screenX = new double[4]; + final double[] screenY = new double[4]; + final double[] screenDepth = new double[4]; + final double[] vertex = new double[3]; + + scene.forEachTriangle((x0, y0, z0, x1, y1, z1, x2, y2, z2, argb) -> { + projection.toCameraSpace(x0, y0, z0, cameraSpace[0]); + projection.toCameraSpace(x1, y1, z1, cameraSpace[1]); + projection.toCameraSpace(x2, y2, z2, cameraSpace[2]); + final int count = clipToNearPlane(cameraSpace, clipped); + if (count < 3) { + return; + } + for (int i = 0; i < count; i++) { + projection.toScreenSpace(clipped[i], vertex); + screenX[i] = vertex[0]; + screenY[i] = vertex[1]; + screenDepth[i] = vertex[2]; + } + if (!Cull.onScreen(screenX, screenY, count, frame.width(), frame.height())) { + return; + } + Raster.fill(frame, screenX, screenY, screenDepth, count, argb); + }); + } + + /** + * Sutherland-Hodgman against the near plane, in camera space. + * + *

A triangle crossing the plane becomes a quad - three vertices and one + * intersection - and that quad is what the raster then fills. Dropping a + * straddling triangle instead would leave the hole the previous engine had + * to fix by hand.

+ * + * @param triangle the three camera-space vertices + * @param out receives at most four clipped vertices + * @return the number of vertices written, 0 to 4 + */ + private static int clipToNearPlane(final double[][] triangle, final double[][] out) { + int count = 0; + for (int i = 0; i < 3; i++) { + final double[] current = triangle[i]; + final double[] next = triangle[(i + 1) % 3]; + final boolean currentInside = current[2] >= NEAR; + final boolean nextInside = next[2] >= NEAR; + if (currentInside) { + copy(current, out[count++]); + } + if (currentInside != nextInside) { + final double t = (NEAR - current[2]) / (next[2] - current[2]); + out[count][0] = current[0] + t * (next[0] - current[0]); + out[count][1] = current[1] + t * (next[1] - current[1]); + out[count][2] = NEAR; + count++; + } + } + return count; + } + + private static void copy(final double[] from, final double[] to) { + to[0] = from[0]; + to[1] = from[1]; + to[2] = from[2]; + } +} diff --git a/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/package-info.java b/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/package-info.java new file mode 100644 index 0000000..9b9f288 --- /dev/null +++ b/Modules/renderer/src/main/java/eu/svjatoslav/aukio/render/package-info.java @@ -0,0 +1,26 @@ +/** + * The renderer: algorithms that turn a world into pixels. + * + *

Nothing here is scene data. Geometry, transforms, the object tree, the + * primitives and the camera pose all belong to {@code + * eu.svjatoslav.aukio.world}; this module reads them and produces an image. + * The distinction that keeps it honest: a pose is world data, a projection is + * not - turning a pose into screen coordinates needs the viewport, and the + * viewport is a property of the image being painted.

+ * + *
    + *
  • frame buffer - the pixels and the depth buffer being written.
  • + *
  • transform - camera pose and viewport in, screen coordinates and depth + * out. The camera's {@code scale = width / 3} convention lives here, + * because only this module knows how wide the picture is.
  • + *
  • cull - backface verdict, viewport rejection, and the per-node bounding + * test that uses the world's boxes.
  • + *
  • raster - tile fill, depth test, flat colour.
  • + *
+ * + *

Two rules carry over from the shell and belong here instead: a frame is + * produced whole, never half-written to something another thread can see, and + * the same world and pose must produce the same pixels - a rendering feature is + * verifiable only if its output is deterministic.

+ */ +package eu.svjatoslav.aukio.render; diff --git a/Modules/renderer/src/main/java/module-info.java b/Modules/renderer/src/main/java/module-info.java new file mode 100644 index 0000000..da204f9 --- /dev/null +++ b/Modules/renderer/src/main/java/module-info.java @@ -0,0 +1,15 @@ +/** + * The renderer module: the algorithms that turn a world into pixels. + * + *

Projection, culling, rasterisation and the frame buffer it paints into. + * The scene itself - geometry, transforms, the object tree, the primitives - + * lives in {@code eu.svjatoslav.aukio.world}, so this module reads the world + * and produces pixels, and the world has never heard of it.

+ */ +module eu.svjatoslav.aukio.render { + // transitive: the renderer's own API takes world types (a scene and a pose + // in, pixels out), so anything that requires the renderer needs the world + // to name those types. + requires transitive eu.svjatoslav.aukio.world; + exports eu.svjatoslav.aukio.render; +} diff --git a/Modules/renderer/src/test/java/eu/svjatoslav/aukio/render/ModuleShapeTest.java b/Modules/renderer/src/test/java/eu/svjatoslav/aukio/render/ModuleShapeTest.java new file mode 100644 index 0000000..fbed070 --- /dev/null +++ b/Modules/renderer/src/test/java/eu/svjatoslav/aukio/render/ModuleShapeTest.java @@ -0,0 +1,176 @@ +package eu.svjatoslav.aukio.render; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * The module's shape, checked rather than promised: one public package, one + * export, no file longer than the agreed limit, and no import of another module + * in this tree. + * + *

These are the rules that keep the renderer from turning into the whole + * engine again. Rules that live only in prose are the ones that get broken + * first, so they live here as a build failure.

+ */ +class ModuleShapeTest { + + private static final int MAX_FILE_LINES = 800; + + private static final Path SOURCE_ROOT = Path.of("src", "main", "java"); + + private static final String MODULE_PACKAGE = "eu.svjatoslav.aukio.render"; + + private static final String WORLD_PACKAGE = "eu.svjatoslav.aukio.world"; + + private static final Pattern PACKAGE = Pattern.compile("^\\s*package\\s+([\\w.]+)\\s*;", Pattern.MULTILINE); + + private static final Pattern IMPORT = Pattern.compile("^\\s*import\\s+(?:static\\s+)?([\\w.*]+)\\s*;", Pattern.MULTILINE); + + private static final Pattern DECLARED_MODULE = Pattern.compile("^\\s*module\\s+([\\w.]+)\\s*\\{", Pattern.MULTILINE); + + private static final Pattern EXPORT = Pattern.compile("^\\s*exports\\s+([\\w.]+)\\s*;", Pattern.MULTILINE); + + private static final Pattern REQUIRES = Pattern.compile("^\\s*requires\\s+(?:transitive\\s+)?([\\w.]+)\\s*;", Pattern.MULTILINE); + + @Test + void sourcesLiveInExactlyOnePackage() throws IOException { + final List problems = new ArrayList<>(); + for (final Path file : sources()) { + final String declared = declaredPackage(file); + if (!MODULE_PACKAGE.equals(declared)) { + problems.add(relativize(file) + " declares package " + declared); + continue; + } + final Path directory = file.getParent(); + if (!directory.endsWith(Path.of("", MODULE_PACKAGE.split("\\.")))) { + problems.add(relativize(file) + " sits in " + relativize(directory) + + " but declares " + MODULE_PACKAGE); + } + } + assertTrue(problems.isEmpty(), "one public package per module, found: " + problems); + } + + @Test + void theDescriptorExportsThatOnePackageAndRequiresTheWorldOnly() throws IOException { + final String descriptor = descriptor(); + assertEquals(MODULE_PACKAGE, firstMatch(DECLARED_MODULE, descriptor), + "the module name is derived from its package, so a requires clause reads naturally"); + final List exports = allMatches(EXPORT, descriptor); + assertTrue(exports.size() <= 1, "the module exports at most its one public package, found: " + exports); + for (final String exported : exports) { + assertEquals(MODULE_PACKAGE, exported, "only the module's own package may be exported"); + } + final List required = allMatches(REQUIRES, descriptor); + assertTrue(required.contains(WORLD_PACKAGE), + "the renderer draws the world, so its descriptor says so: " + required); + for (final String module : required) { + final boolean ours = module.startsWith("eu.svjatoslav.aukio."); + if (ours && !module.equals(WORLD_PACKAGE)) { + fail("the renderer requires no engine module but the world, found: " + module); + } + } + } + + @Test + void noFileExceedsTheLineLimit() throws IOException { + final List tooLong = new ArrayList<>(); + for (final Path file : sources()) { + final int lines = Files.readAllLines(file, StandardCharsets.UTF_8).size(); + if (lines > MAX_FILE_LINES) { + tooLong.add(relativize(file) + " " + lines + " lines"); + } + } + assertTrue(tooLong.isEmpty(), "over " + MAX_FILE_LINES + " lines: " + tooLong); + } + + @Test + void importsReachIntoTheWorldAndNoFurther() throws IOException { + final List foreign = new ArrayList<>(); + for (final Path file : sources()) { + for (final String imported : imports(file)) { + if (imported.startsWith("eu.svjatoslav.aukio.") + && !imported.startsWith(MODULE_PACKAGE) + && !imported.startsWith(WORLD_PACKAGE)) { + foreign.add(relativize(file) + " imports " + imported); + } + } + } + assertTrue(foreign.isEmpty(), "the renderer may see the world and nothing else: " + foreign); + } + + @Test + void theModuleItselfHasSources() throws IOException { + assertFalse(sources().isEmpty(), "no sources under " + SOURCE_ROOT + " - the checks above would be vacuous"); + } + + private static List sources() throws IOException { + if (!Files.isDirectory(SOURCE_ROOT)) { + fail("run from the module directory: " + SOURCE_ROOT.toAbsolutePath() + " does not exist"); + } + try (Stream walk = Files.walk(SOURCE_ROOT)) { + return walk.filter(Files::isRegularFile) + .filter(path -> path.toString().endsWith(".java")) + .filter(path -> !path.getFileName().toString().equals("module-info.java")) + .sorted() + .toList(); + } + } + + private static String descriptor() throws IOException { + final Path file = SOURCE_ROOT.resolve("module-info.java"); + if (!Files.isRegularFile(file)) { + fail("the module declares no descriptor: " + relativize(file) + " is missing"); + } + return Files.readString(file, StandardCharsets.UTF_8); + } + + private static String declaredPackage(final Path file) throws IOException { + final String text = Files.readString(file, StandardCharsets.UTF_8); + final Matcher matcher = PACKAGE.matcher(text); + if (!matcher.find()) { + return ""; + } + assertEquals(1, countMatches(PACKAGE, text), "more than one package declaration in " + relativize(file)); + return matcher.group(1); + } + + private static List imports(final Path file) throws IOException { + return allMatches(IMPORT, Files.readString(file, StandardCharsets.UTF_8)); + } + + private static String firstMatch(final Pattern pattern, final String text) { + final List found = allMatches(pattern, text); + return found.isEmpty() ? "" : found.get(0); + } + + private static List allMatches(final Pattern pattern, final String text) { + final List found = new ArrayList<>(); + final Matcher matcher = pattern.matcher(text); + while (matcher.find()) { + found.add(matcher.group(1)); + } + return found; + } + + private static int countMatches(final Pattern pattern, final String text) { + return allMatches(pattern, text).size(); + } + + private static String relativize(final Path path) { + return Path.of("").toAbsolutePath().relativize(path.toAbsolutePath()).toString(); + } +} diff --git a/Modules/renderer/src/test/java/eu/svjatoslav/aukio/render/RendererTest.java b/Modules/renderer/src/test/java/eu/svjatoslav/aukio/render/RendererTest.java new file mode 100644 index 0000000..d479fe7 --- /dev/null +++ b/Modules/renderer/src/test/java/eu/svjatoslav/aukio/render/RendererTest.java @@ -0,0 +1,198 @@ +package eu.svjatoslav.aukio.render; + +import eu.svjatoslav.aukio.world.Boxes; +import eu.svjatoslav.aukio.world.Camera; +import eu.svjatoslav.aukio.world.Mesh; +import eu.svjatoslav.aukio.world.Node; +import eu.svjatoslav.aukio.world.Scene; +import eu.svjatoslav.aukio.world.Vec3; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * One frame of the first scene, checked against the picture the first engine + * actually drew. + * + *

The silhouette numbers are measurements of that engine's golden image at + * the same size and pose, so this test is a cross-engine comparison and not a + * self-portrait: if the projection convention, the depth test or the field of + * view drifts, the box lands somewhere else.

+ */ +class RendererTest { + + private static final int WIDTH = 1920; + private static final int HEIGHT = 1080; + private static final int BACKGROUND = 0xFF000000; + private static final int RED = 0xFFFF0000; + + /** Measured on the first engine's 1920x1080 minimal-scene golden. */ + private static final int GOLDEN_MIN_X = 832; + private static final int GOLDEN_MAX_X = 1087; + private static final int GOLDEN_MIN_Y = 632; + private static final int GOLDEN_MAX_Y = 924; + private static final int GOLDEN_PIXELS = 73548; + + @Test + void theBoxLandsWhereTheFirstEngineDrewIt() { + final FrameBuffer frame = renderBox(); + assertEquals(GOLDEN_MIN_X, leftmostRed(frame), 1, "left edge"); + assertEquals(GOLDEN_MAX_X, rightmostRed(frame), 1, "right edge"); + assertEquals(GOLDEN_MIN_Y, topmostRed(frame), 1, "top edge"); + assertEquals(GOLDEN_MAX_Y, bottommostRed(frame), 1, "bottom edge"); + } + + @Test + void theBoxCoversTheSameAreaWithinTwoPercent() { + final FrameBuffer frame = renderBox(); + final int covered = redPixels(frame); + final double drift = Math.abs(covered - GOLDEN_PIXELS) / (double) GOLDEN_PIXELS; + assertTrue(drift < 0.02, "covered " + covered + " pixels against " + GOLDEN_PIXELS + + " in the golden image, a drift of " + String.format("%.3f%%", drift * 100)); + } + + @Test + void theBoxIsOneFlatColour() { + final FrameBuffer frame = renderBox(); + for (int y = 0; y < HEIGHT; y++) { + for (int x = 0; x < WIDTH; x++) { + final int pixel = frame.pixelAt(x, y); + if (pixel != BACKGROUND) { + assertEquals(RED, pixel, "shaded pixel at " + x + "," + y); + } + } + } + } + + @Test + void aFrameBufferRendersIntoTheArrayItWasGiven() { + // a host that renders into an image's own raster passes that array here + final int[] pixels = new int[640 * 480]; + final FrameBuffer frame = new FrameBuffer(640, 480, pixels); + frame.clear(BACKGROUND); + assertEquals(BACKGROUND, pixels[0], "clearing writes the caller's array"); + Renderer.render(new Scene(Node.mesh( + Boxes.box(new Vec3(-50, -50, -50), new Vec3(50, 50, 50), RED))), + Camera.of(new Vec3(0, 100, -300), 0, 0), frame); + int red = 0; + for (final int pixel : pixels) { + if (pixel == RED) { + red++; + } + } + assertTrue(red > 0, "the render landed in the caller's array, not a copy of it"); + assertEquals(pixels, frame.pixels(), "the buffer exposes the array it was given"); + } + + @Test + void theSameSceneAndPoseProduceTheSamePixels() { + final FrameBuffer first = renderBox(); + final FrameBuffer second = renderBox(); + assertArrayEquals(first.pixels(), second.pixels(), "rendering is deterministic"); + } + + @Test + void theNearerSurfaceWins() { + // a small red box in front of a large blue plane: the box hides the + // plane where they overlap, the plane shows everywhere else + final Mesh bluePlane = Mesh.builder() + .quad(new Vec3(-5000, -5000, 500), new Vec3(5000, -5000, 500), + new Vec3(5000, 5000, 500), new Vec3(-5000, 5000, 500), 0xFF0000FF) + .build(); + final Scene scene = new Scene(Node.group(eu.svjatoslav.aukio.world.Transform.IDENTITY, + Node.of(eu.svjatoslav.aukio.world.Transform.of(new Vec3(0, 0, 500 - 50), 0, 0), + Boxes.box(new Vec3(-50, -50, -50), new Vec3(50, 50, 50), RED)), + Node.mesh(bluePlane))); + final FrameBuffer frame = new FrameBuffer(WIDTH, HEIGHT); + frame.clear(BACKGROUND); + Renderer.render(scene, Camera.at(Vec3.ORIGIN), frame); + assertEquals(RED, frame.pixelAt(WIDTH / 2, HEIGHT / 2), "the box is in front of the plane"); + assertEquals(0xFF0000FF, frame.pixelAt(WIDTH / 2, HEIGHT - 2), "the plane fills the rest"); + } + + @Test + void aTriangleCrossingTheNearPlaneKeepsItsVisiblePart() { + final Mesh triangle = Mesh.builder() + .triangle(new Vec3(-100, -100, 100), new Vec3(100, -100, 100), + new Vec3(0, 100, -310), 0xFF00FF00) + .build(); + final FrameBuffer frame = new FrameBuffer(640, 480); + frame.clear(BACKGROUND); + Renderer.render(new Scene(Node.mesh(triangle)), Camera.at(Vec3.ORIGIN), frame); + int green = 0; + for (int y = 0; y < frame.height(); y++) { + for (int x = 0; x < frame.width(); x++) { + if (frame.pixelAt(x, y) == 0xFF00FF00) { + green++; + } + } + } + assertTrue(green > 0, "the part in front of the camera must still be drawn"); + } + + private static FrameBuffer renderBox() { + final Scene scene = new Scene(Node.mesh( + Boxes.box(new Vec3(-50, -50, -50), new Vec3(50, 50, 50), RED))); + final Camera camera = Camera.of(new Vec3(0, 100, -300), 0, 0); + final FrameBuffer frame = new FrameBuffer(WIDTH, HEIGHT); + frame.clear(BACKGROUND); + Renderer.render(scene, camera, frame); + return frame; + } + + private static int redPixels(final FrameBuffer frame) { + int count = 0; + for (int y = 0; y < HEIGHT; y++) { + for (int x = 0; x < WIDTH; x++) { + if (frame.pixelAt(x, y) == RED) { + count++; + } + } + } + return count; + } + + private static int leftmostRed(final FrameBuffer frame) { + return bound(frame, true); + } + + private static int rightmostRed(final FrameBuffer frame) { + return bound(frame, false); + } + + private static int topmostRed(final FrameBuffer frame) { + for (int y = 0; y < HEIGHT; y++) { + for (int x = 0; x < WIDTH; x++) { + if (frame.pixelAt(x, y) == RED) { + return y; + } + } + } + return -1; + } + + private static int bottommostRed(final FrameBuffer frame) { + for (int y = HEIGHT - 1; y >= 0; y--) { + for (int x = 0; x < WIDTH; x++) { + if (frame.pixelAt(x, y) == RED) { + return y; + } + } + } + return -1; + } + + private static int bound(final FrameBuffer frame, final boolean left) { + for (int step = 0; step < WIDTH; step++) { + final int x = left ? step : WIDTH - 1 - step; + for (int y = 0; y < HEIGHT; y++) { + if (frame.pixelAt(x, y) == RED) { + return x; + } + } + } + return -1; + } +} diff --git a/Modules/scheduler/Documentation/index.org b/Modules/scheduler/Documentation/index.org new file mode 100644 index 0000000..d222045 --- /dev/null +++ b/Modules/scheduler/Documentation/index.org @@ -0,0 +1,78 @@ +#+SETUPFILE: ~/.emacs.d/org-styles/html/darksun.theme +#+TITLE: Scheduler +#+LANGUAGE: en + +:PROPERTIES: +:CUSTOM_ID: scheduler-page +:END: + +#+OPTIONS: H:20 num:nil author:nil + +[[file:../../../Documentation/index.html#outline-container-scheduler][<- Back to index]] + +* What it owns +:PROPERTIES: +:CUSTOM_ID: what-it-owns +:END: + +The scheduler is the only component that knows how many worker threads +the process may use, and the only one that decides which queued work +runs next. + +It is the Java module =eu.svjatoslav.aukio.sched=, declared in +=src/main/java/module-info.java=, and it exports exactly one package. Any other +module that wants it must name it in its own descriptor, so the dependency is +visible in the language, not only in the build file. + +* The budget +:PROPERTIES: +:CUSTOM_ID: the-budget +:END: + +- The default is 75% of available CPU cores, rounded down and never + below 1. +- The remainder is not waste: JVM threads (GC, JIT, compiler, + finalizers) and the OS need to run, and a pool that claims every + core starves itself exactly when it matters. +- It is a policy default, not a property of any machine. Any caller + can override it per scheduler with =setThreadCount(int)=. + +* Implemented today +:PROPERTIES: +:CUSTOM_ID: implemented-today +:END: + +=-= Scheduler holds the budget only. + +| Member | Meaning | +|--------------------+------------------------------------------------| +| =Scheduler()= | Detects the cores, takes 75% of them. | +| =threadCount()= | The current budget, in worker threads. | +| =setThreadCount()= | Replaces the budget; refuses anything below 1. | + +* The model +:PROPERTIES: +:CUSTOM_ID: the-model +:END: + +=Model/FrameGate.tla= models the scheduler's two ordering rules as a state +machine, before either exists in code: a background item is taken only when no +frame item is queued, and the frame gate fires once, only after every frame +item has finished. + +| Config | What it shows | +|-------------------------------+--------------------------------------------------| +| =FrameGate_gate.cfg= | the intended design: completes with no error | +| =FrameGate_buggy_bgfirst.cfg= | violates =NoBadTake=: background taken too early | +| =FrameGate_buggy_countbg.cfg= | violates =GateNotEarly=: background advances it | + +The buggy configurations are why the gate configuration means anything: an +invariant that also holds when the scheduler does the wrong thing proves +nothing. + +#+begin_src sh +Modules/scheduler/Model/check-models.sh # gate passes, both probes fail as named +./gradlew -Ptla :scheduler:check # the gate alone, wired into the build +#+end_src + + diff --git a/Modules/scheduler/Model/FrameGate.tla b/Modules/scheduler/Model/FrameGate.tla new file mode 100644 index 0000000..7b3ad22 --- /dev/null +++ b/Modules/scheduler/Model/FrameGate.tla @@ -0,0 +1,105 @@ +------------------------------ MODULE FrameGate ------------------------------ +(* + The scheduler's two ordering rules, modelled before they are implemented. + + F1 a background item is taken only when no frame item is queued + F2 the frame gate fires once, and only after every frame item has finished + F3 no pre-emption: an item leaves `running` only through Complete + + Bug = "none" both rules hold + Bug = "bgFirst" a worker may take a background item while frame work waits + Bug = "countBg" a background completion also advances the gate + + A buggy run is not a demonstration, it is the non-vacuity probe: each buggy + config must violate the invariant that names its rule. +*) +EXTENDS Naturals, FiniteSets, TLC + +CONSTANTS Workers, FrameItems, BgItems, Bug + +Items == FrameItems \cup BgItems + +ASSUME FrameItems # {} +ASSUME BgItems # {} +ASSUME FrameItems \cap BgItems = {} +ASSUME Bug \in {"none", "bgFirst", "countBg"} + +\* A worker may ignore the frame queue only on purpose. +AllowBgFirst == Bug \in {"bgFirst", "countBg"} + +VARIABLES queue, running, done, remaining, fired, fires, badTake + +vars == <> + +TypeOK == + /\ queue \subseteq Items + /\ done \subseteq Items + /\ remaining \in 0..Cardinality(FrameItems) + /\ fired \in BOOLEAN + /\ fires \in 0..1 + /\ badTake \in BOOLEAN + /\ \A w \in Workers : running[w] \in Items \cup {0} + +Init == + /\ queue = {} + /\ running = [w \in Workers |-> 0] + /\ done = {} + /\ remaining = Cardinality(FrameItems) + /\ fired = FALSE + /\ fires = 0 + /\ badTake = FALSE + +Submit(i) == + /\ i \in Items + /\ i \notin queue + /\ i \notin done + /\ \A w \in Workers : running[w] # i + /\ queue' = queue \cup {i} + /\ UNCHANGED <> + +\* Which queued item may this worker start: frame work first, unless the bug +\* says otherwise. +Pool == + IF AllowBgFirst THEN queue + ELSE IF queue \cap FrameItems # {} THEN queue \cap FrameItems + ELSE queue + +Take(w) == + /\ running[w] = 0 + /\ queue # {} + /\ \E i \in Pool : + /\ queue' = queue \ {i} + /\ running' = [running EXCEPT ![w] = i] + /\ badTake' = (badTake \/ (i \in BgItems /\ queue \cap FrameItems # {})) + /\ UNCHANGED <> + +Complete(w) == + /\ running[w] # 0 + /\ LET i == running[w] IN + /\ done' = done \cup {i} + /\ running' = [running EXCEPT ![w] = 0] + /\ remaining' = + IF i \in FrameItems THEN remaining - 1 + ELSE IF Bug = "countBg" THEN remaining - 1 + ELSE remaining + /\ fired' = (fired \/ remaining' = 0) + /\ fires' = IF ~fired /\ remaining' = 0 THEN fires + 1 ELSE fires + /\ UNCHANGED <> + +Next == + \/ \E i \in Items : Submit(i) + \/ \E w \in Workers : Take(w) + \/ \E w \in Workers : Complete(w) + +Spec == Init /\ [][Next]_vars /\ WF_vars(Next) + +\* F1: no worker ever started background work while frame work was waiting. +NoBadTake == badTake = FALSE + +\* F2: the gate never fires before every frame item is done. +GateNotEarly == fired => FrameItems \subseteq done + +\* F2: the gate fires once, never twice. +GateOnce == fires <= 1 + +============================================================================= diff --git a/Modules/scheduler/Model/FrameGate_buggy_bgfirst.cfg b/Modules/scheduler/Model/FrameGate_buggy_bgfirst.cfg new file mode 100644 index 0000000..4169e67 --- /dev/null +++ b/Modules/scheduler/Model/FrameGate_buggy_bgfirst.cfg @@ -0,0 +1,16 @@ +\* Non-vacuity probe for F1: a worker may start background work while frame work +\* waits. Expected: NoBadTake is violated. +CONSTANT Workers = {w1, w2} +CONSTANT FrameItems = {1, 2} +CONSTANT BgItems = {3, 4} +CONSTANT Bug = "bgFirst" + +SPECIFICATION Spec + +\* Every item finished is a legitimate terminal state, not a deadlock. +CHECK_DEADLOCK FALSE + +INVARIANT TypeOK +INVARIANT NoBadTake +INVARIANT GateNotEarly +INVARIANT GateOnce diff --git a/Modules/scheduler/Model/FrameGate_buggy_countbg.cfg b/Modules/scheduler/Model/FrameGate_buggy_countbg.cfg new file mode 100644 index 0000000..11e3060 --- /dev/null +++ b/Modules/scheduler/Model/FrameGate_buggy_countbg.cfg @@ -0,0 +1,17 @@ +\* Non-vacuity probe for F2 only: a background completion also advances the +\* gate. NoBadTake is deliberately not listed here — this bug also lets +\* background work start early, and that violation would mask the one this +\* config exists to show. Expected: GateNotEarly is violated. +CONSTANT Workers = {w1, w2} +CONSTANT FrameItems = {1, 2} +CONSTANT BgItems = {3, 4} +CONSTANT Bug = "countBg" + +SPECIFICATION Spec + +\* Every item finished is a legitimate terminal state, not a deadlock. +CHECK_DEADLOCK FALSE + +INVARIANT TypeOK +INVARIANT GateNotEarly +INVARIANT GateOnce diff --git a/Modules/scheduler/Model/FrameGate_gate.cfg b/Modules/scheduler/Model/FrameGate_gate.cfg new file mode 100644 index 0000000..4ca1364 --- /dev/null +++ b/Modules/scheduler/Model/FrameGate_gate.cfg @@ -0,0 +1,15 @@ +\* The design as intended: both rules hold. This is the gate config. +CONSTANT Workers = {w1, w2} +CONSTANT FrameItems = {1, 2} +CONSTANT BgItems = {3, 4} +CONSTANT Bug = "none" + +SPECIFICATION Spec + +\* Every item finished is a legitimate terminal state, not a deadlock. +CHECK_DEADLOCK FALSE + +INVARIANT TypeOK +INVARIANT NoBadTake +INVARIANT GateNotEarly +INVARIANT GateOnce diff --git a/Modules/scheduler/Model/check-models.sh b/Modules/scheduler/Model/check-models.sh new file mode 100755 index 0000000..5125605 --- /dev/null +++ b/Modules/scheduler/Model/check-models.sh @@ -0,0 +1,43 @@ +#!/bin/sh +# Runs the scheduler's TLA+ model. +# +# FrameGate_gate.cfg must finish with no error +# FrameGate_buggy_bgfirst.cfg must violate NoBadTake (rule F1) +# FrameGate_buggy_countbg.cfg must violate GateNotEarly (rule F2) +# +# A buggy config that passes is a vacuous model: the invariant would hold even +# if the code did the wrong thing, so it proves nothing. +set -u +cd "$(dirname "$0")" || exit 1 + +fail=0 + +check() { + cfg=$1 + want=$2 + out=$(tlc -config "$cfg.cfg" FrameGate 2>&1) + if [ "$want" = "pass" ]; then + if printf '%s\n' "$out" | grep -q "No error has been found"; then + echo "PASS $cfg (no error)" + else + echo "FAIL $cfg (expected no error)" + printf '%s\n' "$out" | tail -5 + fail=1 + fi + else + if printf '%s\n' "$out" | grep -q "Invariant $want is violated"; then + echo "PASS $cfg ($want violated as expected)" + else + echo "FAIL $cfg (expected $want to be violated)" + printf '%s\n' "$out" | tail -5 + fail=1 + fi + fi +} + +check FrameGate_gate pass +check FrameGate_buggy_bgfirst NoBadTake +check FrameGate_buggy_countbg GateNotEarly + +rm -rf states +exit $fail diff --git a/Modules/scheduler/build.gradle b/Modules/scheduler/build.gradle new file mode 100644 index 0000000..c4d1070 --- /dev/null +++ b/Modules/scheduler/build.gradle @@ -0,0 +1,17 @@ +// The TLA+ gate for this module's model. It runs the green configuration only: +// the buggy configurations fail by design and are run by Model/check-models.sh, +// because a probe that passes proves the invariant is vacuous. + +tasks.register('tlaCheck', Exec) { + group = 'verification' + description = 'Model-checks Model/FrameGate.tla with the gate configuration.' + workingDir = layout.projectDirectory.dir('Model') + commandLine 'tlc', '-config', 'FrameGate_gate.cfg', 'FrameGate' +} + +// Opt-in, like the Maven profile it replaces: ./gradlew -Ptla check +if (providers.gradleProperty('tla').isPresent()) { + tasks.named('check') { + dependsOn tasks.named('tlaCheck') + } +} diff --git a/Modules/scheduler/src/main/java/eu/svjatoslav/aukio/sched/Scheduler.java b/Modules/scheduler/src/main/java/eu/svjatoslav/aukio/sched/Scheduler.java new file mode 100644 index 0000000..d21fab0 --- /dev/null +++ b/Modules/scheduler/src/main/java/eu/svjatoslav/aukio/sched/Scheduler.java @@ -0,0 +1,53 @@ +package eu.svjatoslav.aukio.sched; + +/** + * The one owner of the CPU budget. + */ +public final class Scheduler { + + /** + * The CPU budget: how many worker threads this process may use. This is the + * one number the scheduler exists to own — it decides how wide every + * parallel subsystem is allowed to be, so nothing else in the process keeps + * its own thread count. + */ + private volatile int threads; + + /** + * The share of the logical cores a scheduler claims by default. + */ + static final int BUDGET_PERCENT = 75; + + public Scheduler() { + this.threads = defaultThreadCount(); + } + + /** The budget this constructor would pick on this machine. */ + static int defaultThreadCount() { + final int cores = Runtime.getRuntime().availableProcessors(); + return Math.max(1, cores * BUDGET_PERCENT / 100); + } + + /** The current budget, in worker threads. */ + public int threadCount() { + return threads; + } + + /** + * Changes the budget of an already initialised scheduler. + * + * @param threads the new budget, in worker threads; must be at least 1 + * @throws IllegalArgumentException when {@code threads} is below 1 + */ + public void setThreadCount(final int threads) { + this.threads = requireValid(threads); + } + + private static int requireValid(final int threads) { + if (threads < 1) { + throw new IllegalArgumentException( + "threads must be >= 1: " + threads); + } + return threads; + } +} diff --git a/Modules/scheduler/src/main/java/eu/svjatoslav/aukio/sched/package-info.java b/Modules/scheduler/src/main/java/eu/svjatoslav/aukio/sched/package-info.java new file mode 100644 index 0000000..7a14f45 --- /dev/null +++ b/Modules/scheduler/src/main/java/eu/svjatoslav/aukio/sched/package-info.java @@ -0,0 +1,5 @@ +/** + * CPU scheduler: a fixed thread budget, work items that declare dependencies, + * a frame-completion signal, and admission control for optional work. + */ +package eu.svjatoslav.aukio.sched; diff --git a/Modules/scheduler/src/main/java/module-info.java b/Modules/scheduler/src/main/java/module-info.java new file mode 100644 index 0000000..b55cce5 --- /dev/null +++ b/Modules/scheduler/src/main/java/module-info.java @@ -0,0 +1,10 @@ +/** + * The scheduler module: a fixed thread budget for the whole process. + * + *

One exported package. Nothing else exists to export yet; when the queues + * and the frame gate arrive they belong to this same package, because this + * module's whole job is the budget and the order work runs in.

+ */ +module eu.svjatoslav.aukio.sched { + exports eu.svjatoslav.aukio.sched; +} diff --git a/Modules/scheduler/src/test/java/eu/svjatoslav/aukio/sched/SchedulerTest.java b/Modules/scheduler/src/test/java/eu/svjatoslav/aukio/sched/SchedulerTest.java new file mode 100644 index 0000000..42dedbe --- /dev/null +++ b/Modules/scheduler/src/test/java/eu/svjatoslav/aukio/sched/SchedulerTest.java @@ -0,0 +1,43 @@ +package eu.svjatoslav.aukio.sched; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** The budget: what it starts at, what it becomes, what is refused. */ +final class SchedulerTest { + + @Test + void aNewSchedulerTakesSeventyFivePercentOfTheCores() { + final int cores = Runtime.getRuntime().availableProcessors(); + final int expected = Math.max(1, cores * Scheduler.BUDGET_PERCENT / 100); + + assertEquals(expected, Scheduler.defaultThreadCount(), + "the default is 75% of the logical cores, rounded down"); + assertEquals(expected, new Scheduler().threadCount()); + assertTrue(new Scheduler().threadCount() <= cores, + "the budget must stay at or below the core count, never above it"); + } + + @Test + void theBudgetCanBeChangedOnAnInitialisedScheduler() { + final Scheduler scheduler = new Scheduler(); + scheduler.setThreadCount(18); + assertEquals(18, scheduler.threadCount()); + scheduler.setThreadCount(3); + assertEquals(3, scheduler.threadCount()); + } + + @Test + void aBudgetBelowOneIsRefused() { + final Scheduler scheduler = new Scheduler(); + final int before = scheduler.threadCount(); + + assertThrows(IllegalArgumentException.class, () -> scheduler.setThreadCount(0)); + assertThrows(IllegalArgumentException.class, () -> scheduler.setThreadCount(-4)); + assertEquals(before, scheduler.threadCount(), + "a refused change must not alter the budget"); + } +} diff --git a/Modules/swing/Documentation/index.org b/Modules/swing/Documentation/index.org new file mode 100644 index 0000000..ec21d82 --- /dev/null +++ b/Modules/swing/Documentation/index.org @@ -0,0 +1,104 @@ +#+SETUPFILE: ~/.emacs.d/org-styles/html/darksun.theme +#+TITLE: Swing adapter +#+LANGUAGE: en + +:PROPERTIES: +:CUSTOM_ID: swing-page +:END: + +#+OPTIONS: H:20 num:nil author:nil + +[[file:../../../Documentation/index.html#outline-container-swing][<- Back to index]] + +* What it owns +:PROPERTIES: +:CUSTOM_ID: swing-owns +:END: + +The component a host application puts in its own window, and the render loop +that feeds it. Everything a desktop application needs to show an Aukio scene, +and nothing a different host would have to remove. + +It is the Java module =eu.svjatoslav.aukio.swing=: it requires +=eu.svjatoslav.aukio.render= and =java.desktop=, and it is the only engine +module allowed to require the latter. The renderer never sees this module, so +the engine stays usable without a window at all - in a test, on a server, or +under another toolkit. + +* What it does not own +:PROPERTIES: +:CUSTOM_ID: swing-not-owns +:END: + +- No window of its own. A host that already has a frame, a tab or a split pane + needs only the component, so the frame stays the application's business. +- No scene, camera or passes. Those belong to the world and the renderer; this + module only drives them. +- No navigation policy and no input vocabulary. A frame of input is + =Modules/navigation='s record, so a policy can be tested with no toolkit present; + the adapter fills that record and calls the driver. +- No toolkit other than Swing. A different host gets its own adapter module next + to this one, not a flag inside it. + +* The three rules it exists to keep +:PROPERTIES: +:CUSTOM_ID: swing-rules +:END: + +1. The render thread publishes a complete frame by swapping a reference under a + lock; the event dispatch thread only copies the published frame. A + half-rendered frame must never reach the screen. +2. Input arrives as events and leaves as events. The component records them, a + pass consumes them, and nothing that reads input also consumes it - a mouse + delta that is read twice is a delta that is applied twice. +3. Rendering is on demand. No change to scene, camera or input means no frame is + computed, only a cheap poll; a static scene must cost almost nothing while + the window is idle. + +* What the build checks +:PROPERTIES: +:CUSTOM_ID: swing-checks +:END: + +=ModuleShapeTest= holds the shape: one package, files under 800 lines, imports +that reach into the renderer and the world and nowhere else in the engine, and a +descriptor that asks for =java.desktop= and the renderer. + +#+begin_src sh +export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64 +./gradlew --offline :swing:test # adapter alone, other modules absent +#+end_src + +* Implemented today +:PROPERTIES: +:CUSTOM_ID: swing-implemented +:END: + +=AukioView=, the panel a host embeds: hand it a =Scene=, a =Camera= and - when +the application wants to move - a =CameraDriver=, call =start()=, and it renders +on demand on its own daemon thread and blits the finished frame in +=paintComponent=. + +Input is recorded here and applied somewhere else. The key, pointer and wheel +listeners write into the =InputRecorder= that =Modules/navigation= owns; each +rendered frame the render thread drains exactly one =ViewInput= and hands it to +the =CameraDriver= it was given, which returns the pose for that frame. Keys and +3D-device deflection are levels and survive into every frame; the pointer delta +and the wheel notches are spent by the frame that reads them. That split is the +rule the previous engine learned the hard way - a value read and consumed in the +same place is a value applied twice - and here it is structural rather than a +convention. + +The component takes the focus back whenever its window gains it, because a host +owns the window and nothing else would hand the keyboard over; a lost focus drops +every held key, so a key released elsewhere cannot stick. Device deflection +arrives through =setDeviceMotion=, so a 3D mouse producer is one method call away +and needs no toolkit knowledge. + +Rendering is still on demand: a held key, a pointer movement or a deflected cap +keeps asking for frames at a fast poll, and an idle window falls back to a slow +one. + +A =JFrame= convenience is absent on purpose - an application that already owns a +window needs the panel, and the demo applications show what the few lines around +it look like. diff --git a/Modules/swing/build.gradle b/Modules/swing/build.gradle new file mode 100644 index 0000000..849cf3f --- /dev/null +++ b/Modules/swing/build.gradle @@ -0,0 +1,14 @@ +// The Swing adapter. It is the only engine module allowed to touch java.desktop, +// which is why it is a module of its own: the renderer stays headless and can +// run in a test, a server, or any other toolkit. + +dependencies { + // api, not implementation: a caller of the view passes renderer types + // (scene, camera) straight through, so those types are part of this + // module's own surface. + api project(':renderer') + // implementation: the view uses the driver contract and the input record, + // but nothing in this module's surface needs a caller to name them - an + // application that supplies its own driver requires navigation itself. + implementation project(':navigation') +} diff --git a/Modules/swing/src/main/java/eu/svjatoslav/aukio/swing/AukioView.java b/Modules/swing/src/main/java/eu/svjatoslav/aukio/swing/AukioView.java new file mode 100644 index 0000000..57b613a --- /dev/null +++ b/Modules/swing/src/main/java/eu/svjatoslav/aukio/swing/AukioView.java @@ -0,0 +1,370 @@ +package eu.svjatoslav.aukio.swing; + +import eu.svjatoslav.aukio.navigation.CameraDriver; +import eu.svjatoslav.aukio.navigation.InputRecorder; +import eu.svjatoslav.aukio.navigation.ViewInput; +import eu.svjatoslav.aukio.render.FrameBuffer; +import eu.svjatoslav.aukio.render.Renderer; +import eu.svjatoslav.aukio.world.Camera; +import eu.svjatoslav.aukio.world.Scene; + +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Window; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseMotionAdapter; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.image.BufferedImage; +import java.awt.image.DataBufferInt; +import java.awt.image.WritableRaster; + +/** + * The component a host application drops into its own window. + * + *

It owns no frame, no title and no menu: a host that already has a window, a + * tab or a split pane needs only this panel, and the panel needs only a scene, a + * camera pose and - when the application wants to move - a {@link CameraDriver}.

+ * + *

Three rules from the previous engine's shell are kept here rather than + * documented and forgotten. The render thread publishes a complete frame by + * swapping the reference under a lock, so the event dispatch thread only ever + * copies an image that is finished. Nothing renders on the event dispatch + * thread, which is what keeps a window responsive while a frame is computed. And + * input is recorded here and consumed there: the listeners write keys, pointer + * movement and device deflection into a {@link InputRecorder}, the render thread + * drains exactly one snapshot per frame and hands it to the driver. Nothing that + * records input also applies it, which is why the same pointer delta cannot be + * counted twice.

+ * + *

Rendering stays on demand. A key held, a pointer moving or a 3D device + * deflected keeps asking for frames; so does a resize or an explicit + * {@link #requestFrame()}. When nothing asks, the loop only wakes up to check.

+ * + *

Nothing is allocated per frame. Each surface is a small pair of a render + * buffer and the image whose own raster the buffer writes into - the same trick + * the first engine used: take the image's data buffer and render straight into + * it - so publishing a frame is a reference swap and the event dispatch thread + * blits an image that already holds the pixels. Three surfaces are kept: one + * may be published, one may be mid-blit, and the render thread still has a free + * one. They are allocated on a resize and then reused forever.

+ */ +public final class AukioView extends JPanel { + + private static final long serialVersionUID = 1L; + + /** How often an idle view checks whether anything asked for a frame. */ + private static final int IDLE_POLL_MILLIS = 30; + + /** How often a view that is being steered asks again, so motion looks continuous. */ + private static final int ACTIVE_POLL_MILLIS = 8; + + /** What a view shows before its first frame is ready. */ + private static final int EMPTY_ARGB = 0xFF000000; + + /** Longest frame the driver is told about; a stalled window must not teleport the camera. */ + private static final double MAX_FRAME_SECONDS = 0.25; + + /** + * Frames kept ready: one published, one possibly mid-blit, one being drawn. + * The count is what makes "never write the image being shown" free to satisfy. + */ + private static final int SURFACES = 3; + + private final Scene scene; + + private final InputRecorder recorder = new InputRecorder(); + + private volatile Camera camera; + + private volatile CameraDriver driver; + + private final Object publishLock = new Object(); + + /** The last complete frame, or null before the first one. Written under the lock. */ + private BufferedImage published; + + private volatile boolean requested = true; + + private volatile boolean running; + + /** The image the event dispatch thread is blitting right now, if any. */ + private volatile BufferedImage presenting; + + // Owned by the event dispatch thread. + private WindowAdapter windowFocus; + private int pointerX; + private int pointerY; + + // Owned by the render thread only. + private Surface[] surfaces; + private int nextSurface; + private int frameWidth; + private int frameHeight; + private long lastFrameNanos = -1; + + public AukioView(final Scene scene, final Camera camera) { + this.scene = scene; + this.camera = camera; + setOpaque(true); + setBackground(Color.BLACK); + setFocusable(true); + installInputRecording(); + } + + /** A new pose: the next poll renders exactly one frame. */ + public void setCamera(final Camera newCamera) { + this.camera = newCamera; + requested = true; + } + + /** The camera policy for this view, or null for a camera that never moves by itself. */ + public void setDriver(final CameraDriver newDriver) { + this.driver = newDriver; + requested = true; + } + + /** + * The current deflection of a 3D device, normalised to -1..1. Written by the + * device's own thread; a device that is being held keeps the view rendering + * until it is released and reports zero. + */ + public void setDeviceMotion(final double x, final double y, final double z, + final double yaw, final double pitch, final double roll) { + recorder.setDeviceMotion(x, y, z, yaw, pitch, roll); + } + + /** Asks for one more frame from the current pose and scene. */ + public void requestFrame() { + requested = true; + } + + /** Starts the render thread. Calling this twice starts nothing new. */ + public void start() { + if (running) { + return; + } + running = true; + final Thread thread = new Thread(this::renderLoop, "aukio-view"); + thread.setDaemon(true); + thread.start(); + } + + /** Asks the render thread to finish after its current frame. */ + public void stop() { + running = false; + } + + @Override + public void addNotify() { + super.addNotify(); + // The host owns the window and this component owns no frame, so it + // cannot assume it already holds the focus. A request made while the + // window is unfocused is refused rather than queued, so the focus is + // taken back every time the window itself gains it - otherwise the + // keyboard only works after the user happens to click the panel. + SwingUtilities.invokeLater(() -> { + final Window window = SwingUtilities.getWindowAncestor(this); + if (window != null && windowFocus == null) { + windowFocus = new WindowAdapter() { + @Override + public void windowGainedFocus(final WindowEvent event) { + requestFocusInWindow(); + } + }; + window.addWindowFocusListener(windowFocus); + } + requestFocusInWindow(); + }); + } + + @Override + public void removeNotify() { + for (final Window window : Window.getWindows()) { + if (windowFocus != null) { + window.removeWindowFocusListener(windowFocus); + } + } + windowFocus = null; + super.removeNotify(); + } + + @Override + protected void paintComponent(final Graphics graphics) { + final BufferedImage image; + synchronized (publishLock) { + image = published; + } + if (image == null) { + graphics.setColor(getBackground()); + graphics.fillRect(0, 0, getWidth(), getHeight()); + return; + } + // the host may have resized the panel since the frame was rendered, so + // the finished image is stretched rather than re-rendered on the event + // dispatch thread; the render thread catches up on the next poll + presenting = image; + try { + graphics.drawImage(image, 0, 0, getWidth(), getHeight(), null); + } finally { + presenting = null; + } + } + + private void installInputRecording() { + addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(final KeyEvent event) { + recorder.keyDown(event.getKeyCode()); + } + + @Override + public void keyReleased(final KeyEvent event) { + recorder.keyUp(event.getKeyCode()); + } + }); + addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(final MouseEvent event) { + requestFocusInWindow(); + pointerX = event.getX(); + pointerY = event.getY(); + } + }); + addMouseMotionListener(new MouseMotionAdapter() { + @Override + public void mouseDragged(final MouseEvent event) { + // the delta is measured from the previous event, not from the + // press, so a long drag stays in step with the pointer + recorder.addPointerDelta(event.getX() - pointerX, event.getY() - pointerY); + pointerX = event.getX(); + pointerY = event.getY(); + } + }); + addMouseWheelListener(event -> { + // notches, not pixels: AWT's own count keeps one notch on one notch + // across every platform, and the same accumulation rule applies as + // for the pointer - the frame that reads it spends it + recorder.addWheel(event.getWheelRotation()); + }); + addFocusListener(new FocusAdapter() { + @Override + public void focusLost(final FocusEvent event) { + // releases would never arrive after the focus is gone, and a + // stuck key is a camera that flies away on its own + recorder.clearKeys(); + } + }); + } + + private void renderLoop() { + while (running) { + final int width = getWidth(); + final int height = getHeight(); + final boolean resized = width != frameWidth || height != frameHeight; + if (width > 0 && height > 0 && (requested || resized || recorder.isActive())) { + requested = false; + final ViewInput input = recorder.drain(); + final double seconds = secondsSincePreviousFrame(); + final CameraDriver currentDriver = driver; + if (currentDriver != null) { + final Camera next = currentDriver.frame(input, seconds); + if (next != null) { + camera = next; + } + } + render(width, height); + } + if (!poll(recorder.isActive() ? ACTIVE_POLL_MILLIS : IDLE_POLL_MILLIS)) { + return; + } + } + } + + private double secondsSincePreviousFrame() { + final long now = System.nanoTime(); + final double seconds = lastFrameNanos < 0 ? 0.0 : (now - lastFrameNanos) / 1e9; + lastFrameNanos = now; + return Math.min(seconds, MAX_FRAME_SECONDS); + } + + private void render(final int width, final int height) { + ensureSurfaces(width, height); + final Surface surface = freeSurface(); + surface.frame.clear(EMPTY_ARGB); + Renderer.render(scene, camera, surface.frame); + synchronized (publishLock) { + published = surface.image; + } + repaint(); + } + + /** Allocated once per size and then reused: a frame must not cost an allocation. */ + private void ensureSurfaces(final int width, final int height) { + frameWidth = width; + frameHeight = height; + if (surfaces != null && surfaces[0].frame.width() == width && surfaces[0].frame.height() == height) { + return; + } + final Surface[] fresh = new Surface[SURFACES]; + for (int index = 0; index < SURFACES; index++) { + fresh[index] = new Surface(width, height); + } + surfaces = fresh; + nextSurface = 0; + } + + /** + * A surface that is neither on screen nor inside the blit the event dispatch + * thread is performing. Three of them make this always satisfiable, because + * at most one image is published and at most one is being blitted. + */ + private Surface freeSurface() { + for (int attempt = 0; attempt < SURFACES; attempt++) { + final Surface candidate = surfaces[nextSurface]; + nextSurface = (nextSurface + 1) % SURFACES; + if (candidate.image != published && candidate.image != presenting) { + return candidate; + } + } + return surfaces[nextSurface]; + } + + /** + * One reusable frame: the render buffer and the image that shares its pixels. + * + *

The image's raster is the render target, so there is no copy between + * rendering and showing - the same arrangement the first engine used, where + * the pixels array was the image's own data buffer.

+ */ + private static final class Surface { + + private final FrameBuffer frame; + private final BufferedImage image; + + private Surface(final int width, final int height) { + image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); + final WritableRaster raster = image.getRaster(); + final int[] pixels = ((DataBufferInt) raster.getDataBuffer()).getData(); + frame = new FrameBuffer(width, height, pixels); + } + } + + /** @return false when the thread was interrupted and must stop */ + private static boolean poll(final int millis) { + try { + Thread.sleep(millis); + return true; + } catch (final InterruptedException interrupted) { + Thread.currentThread().interrupt(); + return false; + } + } +} diff --git a/Modules/swing/src/main/java/eu/svjatoslav/aukio/swing/package-info.java b/Modules/swing/src/main/java/eu/svjatoslav/aukio/swing/package-info.java new file mode 100644 index 0000000..33851da --- /dev/null +++ b/Modules/swing/src/main/java/eu/svjatoslav/aukio/swing/package-info.java @@ -0,0 +1,24 @@ +/** + * The Swing adapter. + * + *

Its job is small on purpose: take a scene and a camera pose from the world, + * run a render thread, and paint the finished frame into a component. It owns + * no window of its own — a host that already has a frame, a tab or a split pane + * only needs the component — and it never renders on the event dispatch thread, + * because the EDT must stay free to repaint.

+ * + *

Rules that came out of the previous engine's shell, and that this module + * exists to keep:

+ * + *
    + *
  • The render thread publishes a complete frame by swapping a reference + * under a lock; the EDT only copies the published frame. A half-rendered + * frame must never reach the screen.
  • + *
  • Input arrives as events and leaves as events. The component records + * them; a pass consumes them. Nothing that reads input may also consume + * it, or the same mouse delta is applied twice or lost.
  • + *
  • Rendering is on demand: no change to scene, camera or input means no + * frame is computed, only a cheap poll.
  • + *
+ */ +package eu.svjatoslav.aukio.swing; diff --git a/Modules/swing/src/main/java/module-info.java b/Modules/swing/src/main/java/module-info.java new file mode 100644 index 0000000..ea16a02 --- /dev/null +++ b/Modules/swing/src/main/java/module-info.java @@ -0,0 +1,17 @@ +/** + * The Swing adapter: the component a host application drops into its own + * window, and the render loop that feeds it. + * + *

This module is the only place in the engine that may touch + * =java.desktop=. Everything below it - the renderer, the scene, the passes - + * stays headless, so the same engine can be driven from a test, a server or a + * different toolkit without a window existing anywhere.

+ */ +module eu.svjatoslav.aukio.swing { + requires eu.svjatoslav.aukio.render; + // The input record, its recorder and the driver contract live in navigation: + // what a frame of input is does not depend on a toolkit having produced it. + requires eu.svjatoslav.aukio.navigation; + requires java.desktop; + exports eu.svjatoslav.aukio.swing; +} diff --git a/Modules/swing/src/test/java/eu/svjatoslav/aukio/swing/ModuleShapeTest.java b/Modules/swing/src/test/java/eu/svjatoslav/aukio/swing/ModuleShapeTest.java new file mode 100644 index 0000000..e7f870a --- /dev/null +++ b/Modules/swing/src/test/java/eu/svjatoslav/aukio/swing/ModuleShapeTest.java @@ -0,0 +1,185 @@ +package eu.svjatoslav.aukio.swing; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * The adapter's shape, checked rather than promised: one public package, a + * descriptor that asks for the toolkit, the renderer and navigation and for + * nothing else in the engine, and no file longer than the agreed limit. + * + *

The direction matters as much as the list. This module may depend on the + * renderer; the renderer may never depend on this one, and the descriptor is + * where that is written down.

+ */ +class ModuleShapeTest { + + private static final int MAX_FILE_LINES = 800; + + private static final Path SOURCE_ROOT = Path.of("src", "main", "java"); + + private static final String MODULE_PACKAGE = "eu.svjatoslav.aukio.swing"; + + private static final String RENDERER_PACKAGE = "eu.svjatoslav.aukio.render"; + + // The renderer requires the world transitively, so the adapter may name + // world types (a scene, a camera pose) as well as renderer types. + private static final String WORLD_PACKAGE = "eu.svjatoslav.aukio.world"; + + // The input record and the driver contract are navigation's, not the + // adapter's: what a frame of input is does not depend on a toolkit having + // produced it, and a test or a device can fill the same record. + private static final String NAVIGATION_PACKAGE = "eu.svjatoslav.aukio.navigation"; + + private static final Pattern PACKAGE = Pattern.compile("^\\s*package\\s+([\\w.]+)\\s*;", Pattern.MULTILINE); + + private static final Pattern IMPORT = Pattern.compile("^\\s*import\\s+(?:static\\s+)?([\\w.*]+)\\s*;", Pattern.MULTILINE); + + private static final Pattern DECLARED_MODULE = Pattern.compile("^\\s*module\\s+([\\w.]+)\\s*\\{", Pattern.MULTILINE); + + private static final Pattern EXPORT = Pattern.compile("^\\s*exports\\s+([\\w.]+)\\s*;", Pattern.MULTILINE); + + private static final Pattern REQUIRES = Pattern.compile("^\\s*requires\\s+(?:transitive\\s+)?([\\w.]+)\\s*;", Pattern.MULTILINE); + + @Test + void sourcesLiveInExactlyOnePackage() throws IOException { + final List problems = new ArrayList<>(); + for (final Path file : sources()) { + final String declared = declaredPackage(file); + if (!MODULE_PACKAGE.equals(declared)) { + problems.add(relativize(file) + " declares package " + declared); + } + } + assertTrue(problems.isEmpty(), "one public package per module, found: " + problems); + } + + @Test + void theDescriptorAsksForTheToolkitTheRendererAndNavigationOnly() throws IOException { + final String descriptor = descriptor(); + assertEquals(MODULE_PACKAGE, firstMatch(DECLARED_MODULE, descriptor), + "the module name is derived from its package"); + final List required = allMatches(REQUIRES, descriptor); + assertTrue(required.contains("java.desktop"), + "this module exists to touch the toolkit, so its descriptor says so: " + required); + assertTrue(required.contains(RENDERER_PACKAGE), + "the adapter draws what the renderer produces: " + required); + assertTrue(required.contains(NAVIGATION_PACKAGE), + "the adapter records input into navigation's recorder: " + required); + for (final String module : required) { + final boolean ours = module.startsWith("eu.svjatoslav.aukio."); + if (ours && !module.equals(RENDERER_PACKAGE) && !module.equals(NAVIGATION_PACKAGE)) { + fail("the adapter requires no other engine module, found: " + module); + } + } + final List exports = allMatches(EXPORT, descriptor); + assertTrue(exports.size() <= 1, "one public package at most, found: " + exports); + for (final String exported : exports) { + assertEquals(MODULE_PACKAGE, exported, "only the module's own package may be exported"); + } + } + + @Test + void noFileExceedsTheLineLimit() throws IOException { + final List tooLong = new ArrayList<>(); + for (final Path file : sources()) { + final int lines = Files.readAllLines(file, StandardCharsets.UTF_8).size(); + if (lines > MAX_FILE_LINES) { + tooLong.add(relativize(file) + " " + lines + " lines"); + } + } + assertTrue(tooLong.isEmpty(), "over " + MAX_FILE_LINES + " lines: " + tooLong); + } + + @Test + void importsReachIntoTheRendererAndTheWorldOnly() throws IOException { + final List foreign = new ArrayList<>(); + for (final Path file : sources()) { + for (final String imported : imports(file)) { + if (imported.startsWith("eu.svjatoslav.aukio.") + && !imported.startsWith(MODULE_PACKAGE) + && !imported.startsWith(RENDERER_PACKAGE) + && !imported.startsWith(WORLD_PACKAGE) + && !imported.startsWith(NAVIGATION_PACKAGE)) { + foreign.add(relativize(file) + " imports " + imported); + } + } + } + assertTrue(foreign.isEmpty(), "the adapter may see the renderer, the world and navigation, nothing else: " + foreign); + } + + @Test + void theModuleItselfHasSources() throws IOException { + assertFalse(sources().isEmpty(), "no sources under " + SOURCE_ROOT + " - the checks above would be vacuous"); + } + + private static List sources() throws IOException { + if (!Files.isDirectory(SOURCE_ROOT)) { + fail("run from the module directory: " + SOURCE_ROOT.toAbsolutePath() + " does not exist"); + } + try (Stream walk = Files.walk(SOURCE_ROOT)) { + return walk.filter(Files::isRegularFile) + .filter(path -> path.toString().endsWith(".java")) + .filter(path -> !path.getFileName().toString().equals("module-info.java")) + .sorted() + .toList(); + } + } + + private static String descriptor() throws IOException { + final Path file = SOURCE_ROOT.resolve("module-info.java"); + if (!Files.isRegularFile(file)) { + fail("the module declares no descriptor: " + relativize(file) + " is missing"); + } + return Files.readString(file, StandardCharsets.UTF_8); + } + + private static String declaredPackage(final Path file) throws IOException { + final String text = Files.readString(file, StandardCharsets.UTF_8); + final Matcher matcher = PACKAGE.matcher(text); + if (!matcher.find()) { + return ""; + } + assertEquals(1, countMatches(PACKAGE, text), "more than one package declaration in " + relativize(file)); + return matcher.group(1); + } + + private static List imports(final Path file) throws IOException { + return allMatches(IMPORT, Files.readString(file, StandardCharsets.UTF_8)); + } + + private static String firstMatch(final Pattern pattern, final String text) { + final List found = allMatches(pattern, text); + return found.isEmpty() ? "" : found.get(0); + } + + private static List allMatches(final Pattern pattern, final String text) { + final List found = new ArrayList<>(); + final Matcher matcher = pattern.matcher(text); + while (matcher.find()) { + found.add(matcher.group(1)); + } + return found; + } + + private static int countMatches(final Pattern pattern, final String text) { + return allMatches(pattern, text).size(); + } + + private static String relativize(final Path path) { + return Path.of("").toAbsolutePath().relativize(path.toAbsolutePath()).toString(); + } +} diff --git a/Modules/world/Documentation/index.org b/Modules/world/Documentation/index.org new file mode 100644 index 0000000..c4c2045 --- /dev/null +++ b/Modules/world/Documentation/index.org @@ -0,0 +1,110 @@ +#+SETUPFILE: ~/.emacs.d/org-styles/html/darksun.theme +#+TITLE: World +#+LANGUAGE: en + +:PROPERTIES: +:CUSTOM_ID: world-page +:END: + +#+OPTIONS: H:20 num:nil author:nil + +[[file:../../../Documentation/index.html#outline-container-world][<- Back to index]] + +* What it owns +:PROPERTIES: +:CUSTOM_ID: world-owns +:END: + +The scene as data: geometry, transforms, the object tree, triangle storage in +object space, the primitives, and the camera pose. Everything a scene *is*, +before anything is drawn. + +It is the Java module =eu.svjatoslav.aukio.world=, and it requires nothing at +all - not the renderer, not the toolkit, not the scheduler. That is a property +the build enforces rather than promises: a =requires= on any other engine module +fails to compile, so the bottom of the engine cannot quietly stop being the +bottom. + +* A pose is data, a projection is not +:PROPERTIES: +:CUSTOM_ID: world-pose +:END: + +The camera's position and rotation live here; the =scale = width / 3= that turns +them into screen coordinates does not. Projection needs the viewport, and the +viewport is a property of the picture being painted, so it belongs to the +renderer. + +That single rule is what keeps the arrow one-way. The moment the world needed to +know how wide the window is, the two modules would be one module again. + +* The seams inside it +:PROPERTIES: +:CUSTOM_ID: world-seams +:END: + +One package, concerns kept apart by class: + +| Seam | Owns | +|----------+-------------------------------------------------------------| +| geometry | vectors, quaternions, matrices, boxes, =Transform= and chain | +| scene | nodes: transform, children, optional mesh, group | +| mesh | triangles in object space; a published mesh is immutable | +| shapes | primitives in local coordinates | +| camera | a pose, nothing more | + +* Invariants +:PROPERTIES: +:CUSTOM_ID: world-invariants +:END: + +- Local coordinates never leave this module uncomposed. A node's geometry is + local, its world matrix is derived, and anything downstream receives world + space. +- A pose writes node transforms, never mesh vertices. A mesh is published once + and may be shared, so anything derived from it - an index, a baked light - + stays valid while the scene moves. + +* What does not belong here +:PROPERTIES: +:CUSTOM_ID: world-not-here +:END: + +Loading, streaming, file formats, light, and anything that owns a clock or a +thread. Those read from outside the process and belong to modules that can be +absent; the world stays testable as plain data. + +* What the build checks +:PROPERTIES: +:CUSTOM_ID: world-checks +:END: + +=ModuleShapeTest= holds the shape: one package, a descriptor that requires no +other engine module, files under 800 lines, and imports that never leave the +module. + +#+begin_src sh +export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64 +./gradlew --offline :world:test # the world alone, other modules absent +#+end_src + +* Implemented today +:PROPERTIES: +:CUSTOM_ID: world-implemented +:END: + +Geometry, the object tree, one primitive and the camera pose: + +| Type | What it is | +|-------------+---------------------------------------------------------------| +| =Vec3= | an immutable point or direction | +| =Transform= | a translation and a rotation, held as a matrix so chains compose | +| =Mesh= | flat triangle storage in object space, immutable once published | +| =Boxes= | the box primitive, six quads wound outwards | +| =Node= | a pose, an optional mesh and children posed inside it | +| =Scene= | the tree, and the one place local coordinates become world ones | +| =Camera= | a position, a yaw and a pitch; no viewport, no field of view | + +Still to come: quaternions and axis-aligned boxes as published types, the other +primitives (cylinder, sphere, cone, arrow, grid), and per-node bounds for the +renderer's per-node cull. diff --git a/Modules/world/build.gradle b/Modules/world/build.gradle new file mode 100644 index 0000000..8d18188 --- /dev/null +++ b/Modules/world/build.gradle @@ -0,0 +1,7 @@ +// The data model of a scene: geometry, transforms, the object tree and the +// primitives. It requires nothing at all - not the renderer, not the toolkit, +// not the scheduler - which is what lets it be tested as plain data. + +dependencies { + // none +} diff --git a/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Boxes.java b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Boxes.java new file mode 100644 index 0000000..83e3288 --- /dev/null +++ b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Boxes.java @@ -0,0 +1,37 @@ +package eu.svjatoslav.aukio.world; + +/** + * The box primitive, built in object space. + * + *

Six quads, each wound so its normal points out of the solid. That winding + * is the same one the first engine's box used, so a scene built from it looks + * the same under either engine; the renderer here does not cull backfaces, so a + * wrong winding would still show a solid, only inside out.

+ */ +public final class Boxes { + + private Boxes() { + } + + /** + * @param min corner with the smallest coordinates + * @param max corner with the largest coordinates + * @param argb flat colour of all twelve triangles + */ + public static Mesh box(final Vec3 min, final Vec3 max, final int argb) { + final double x0 = min.x(); + final double y0 = min.y(); + final double z0 = min.z(); + final double x1 = max.x(); + final double y1 = max.y(); + final double z1 = max.z(); + final Mesh.Builder mesh = Mesh.builder(); + mesh.quad(new Vec3(x0, y0, z1), new Vec3(x1, y0, z1), new Vec3(x1, y1, z1), new Vec3(x0, y1, z1), argb); + mesh.quad(new Vec3(x1, y0, z0), new Vec3(x0, y0, z0), new Vec3(x0, y1, z0), new Vec3(x1, y1, z0), argb); + mesh.quad(new Vec3(x0, y1, z1), new Vec3(x1, y1, z1), new Vec3(x1, y1, z0), new Vec3(x0, y1, z0), argb); + mesh.quad(new Vec3(x0, y0, z0), new Vec3(x1, y0, z0), new Vec3(x1, y0, z1), new Vec3(x0, y0, z1), argb); + mesh.quad(new Vec3(x1, y0, z1), new Vec3(x1, y0, z0), new Vec3(x1, y1, z0), new Vec3(x1, y1, z1), argb); + mesh.quad(new Vec3(x0, y0, z0), new Vec3(x0, y0, z1), new Vec3(x0, y1, z1), new Vec3(x0, y1, z0), argb); + return mesh.build(); + } +} diff --git a/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Camera.java b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Camera.java new file mode 100644 index 0000000..eed8516 --- /dev/null +++ b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Camera.java @@ -0,0 +1,46 @@ +package eu.svjatoslav.aukio.world; + +/** + * A camera pose: where it stands and which way it looks. Nothing else. + * + *

There is no viewport here and no field of view, because a pose is world + * data while a projection needs the picture width. Turning this into screen + * coordinates is the renderer's job; that split is what keeps the world free of + * any knowledge of screens.

+ * + *

Angles follow the module convention: +Y is up, yaw = pitch = 0 looks along + * +Z, positive yaw turns towards +X, positive pitch looks up.

+ */ +public final class Camera { + + private final Vec3 position; + private final double yaw; + private final double pitch; + + private Camera(final Vec3 position, final double yaw, final double pitch) { + this.position = position; + this.yaw = yaw; + this.pitch = pitch; + } + + public static Camera of(final Vec3 position, final double yaw, final double pitch) { + return new Camera(position, yaw, pitch); + } + + /** Level camera looking along +Z. */ + public static Camera at(final Vec3 position) { + return new Camera(position, 0, 0); + } + + public Vec3 position() { + return position; + } + + public double yaw() { + return yaw; + } + + public double pitch() { + return pitch; + } +} diff --git a/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Mesh.java b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Mesh.java new file mode 100644 index 0000000..9fbc260 --- /dev/null +++ b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Mesh.java @@ -0,0 +1,84 @@ +package eu.svjatoslav.aukio.world; + +import java.util.Arrays; + +/** + * Triangles in object space, stored flat and never mutated after publication. + * + *

Nine doubles per triangle plus one colour per triangle: this engine is + * flat shaded, so a triangle carries a colour rather than a material. A + * published mesh is immutable, which is what lets several nodes share one and + * keeps any index derived from it valid while the scene moves - a pose writes + * node transforms, never vertices.

+ */ +public final class Mesh { + + private final double[] positions; + private final int[] colors; + + private Mesh(final double[] positions, final int[] colors) { + this.positions = positions; + this.colors = colors; + } + + public static Builder builder() { + return new Builder(); + } + + public int triangleCount() { + return colors.length; + } + + /** + * One coordinate of one vertex. + * + * @param triangle triangle index, 0-based + * @param vertex vertex of that triangle, 0..2 + * @param axis 0 = x, 1 = y, 2 = z + */ + public double position(final int triangle, final int vertex, final int axis) { + return positions[triangle * 9 + vertex * 3 + axis]; + } + + public int color(final int triangle) { + return colors[triangle]; + } + + /** Collects triangles, then publishes them as one immutable mesh. */ + public static final class Builder { + + private double[] positions = new double[9 * 16]; + private int[] colors = new int[16]; + private int triangles; + + public Builder triangle(final Vec3 a, final Vec3 b, final Vec3 c, final int argb) { + if ((triangles + 1) * 9 > positions.length) { + positions = Arrays.copyOf(positions, Math.max(positions.length * 2, triangles * 9 + 9)); + colors = Arrays.copyOf(colors, colors.length * 2); + } + final int base = triangles * 9; + positions[base] = a.x(); + positions[base + 1] = a.y(); + positions[base + 2] = a.z(); + positions[base + 3] = b.x(); + positions[base + 4] = b.y(); + positions[base + 5] = b.z(); + positions[base + 6] = c.x(); + positions[base + 7] = c.y(); + positions[base + 8] = c.z(); + colors[triangles] = argb; + triangles++; + return this; + } + + /** Adds a quad as two triangles, keeping the winding of the four points. */ + public Builder quad(final Vec3 a, final Vec3 b, final Vec3 c, final Vec3 d, final int argb) { + triangle(a, b, c, argb); + return triangle(a, c, d, argb); + } + + public Mesh build() { + return new Mesh(Arrays.copyOf(positions, triangles * 9), Arrays.copyOf(colors, triangles)); + } + } +} diff --git a/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Node.java b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Node.java new file mode 100644 index 0000000..e70caa7 --- /dev/null +++ b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Node.java @@ -0,0 +1,52 @@ +package eu.svjatoslav.aukio.world; + +import java.util.List; + +/** + * One object in the tree: a pose, optionally a mesh, and children posed inside + * this node's space. + * + *

A node without a mesh is a group, which is how a pile of parts is moved as + * one thing. A mesh is shared, never copied: two nodes may name the same mesh + * and only their transforms differ, which is what instancing is here.

+ */ +public final class Node { + + private final Transform transform; + private final Mesh mesh; + private final List children; + + private Node(final Transform transform, final Mesh mesh, final List children) { + this.transform = transform; + this.mesh = mesh; + this.children = List.copyOf(children); + } + + /** A leaf: one mesh at the given pose. */ + public static Node of(final Transform transform, final Mesh mesh) { + return new Node(transform, mesh, List.of()); + } + + /** One mesh at the identity pose, the common case. */ + public static Node mesh(final Mesh mesh) { + return new Node(Transform.IDENTITY, mesh, List.of()); + } + + /** A pose with children under it, no geometry of its own. */ + public static Node group(final Transform transform, final Node... children) { + return new Node(transform, null, List.of(children)); + } + + public Transform transform() { + return transform; + } + + /** @return the mesh, or null when this node only groups. */ + public Mesh mesh() { + return mesh; + } + + public List children() { + return children; + } +} diff --git a/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Scene.java b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Scene.java new file mode 100644 index 0000000..a3a0dee --- /dev/null +++ b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Scene.java @@ -0,0 +1,63 @@ +package eu.svjatoslav.aukio.world; + +/** + * The root of the object tree, and the one place where local coordinates become + * world coordinates. + * + *

A caller never sees a local vertex: {@link #forEachTriangle} composes the + * transform chain down to each node and reports world-space triangles in a + * fixed order. That order is part of the contract, because the renderer's + * output is only reproducible while the walk is.

+ */ +public final class Scene { + + /** Receives one world-space triangle at a time. */ + @FunctionalInterface + public interface TriangleConsumer { + void triangle(double x0, double y0, double z0, + double x1, double y1, double z1, + double x2, double y2, double z2, + int argb); + } + + private final Node root; + + public Scene(final Node root) { + this.root = root; + } + + public Node root() { + return root; + } + + /** Walks the whole tree, depth first, in child order. */ + public void forEachTriangle(final TriangleConsumer consumer) { + visit(root, Transform.IDENTITY, consumer); + } + + private static void visit(final Node node, final Transform parent, + final TriangleConsumer consumer) { + final Transform world = parent.then(node.transform()); + final Mesh mesh = node.mesh(); + if (mesh != null) { + for (int triangle = 0; triangle < mesh.triangleCount(); triangle++) { + final Vec3 a = world.apply(vertex(mesh, triangle, 0)); + final Vec3 b = world.apply(vertex(mesh, triangle, 1)); + final Vec3 c = world.apply(vertex(mesh, triangle, 2)); + consumer.triangle(a.x(), a.y(), a.z(), + b.x(), b.y(), b.z(), + c.x(), c.y(), c.z(), + mesh.color(triangle)); + } + } + for (final Node child : node.children()) { + visit(child, world, consumer); + } + } + + private static Vec3 vertex(final Mesh mesh, final int triangle, final int vertex) { + return new Vec3(mesh.position(triangle, vertex, 0), + mesh.position(triangle, vertex, 1), + mesh.position(triangle, vertex, 2)); + } +} diff --git a/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Transform.java b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Transform.java new file mode 100644 index 0000000..b0f1533 --- /dev/null +++ b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Transform.java @@ -0,0 +1,97 @@ +package eu.svjatoslav.aukio.world; + +/** + * A pose: a rotation followed by a translation, applied to object-space + * coordinates to produce the parent's coordinates. + * + *

The rotation is held as a matrix, not as a yaw/pitch pair. Two yaw/pitch + * pairs do not compose back into a yaw/pitch pair once a node has been turned + * about both axes, so the pair is only how a pose is written down while the + * matrix is what the chain multiplies.

+ * + *

Axis convention, shared with the camera: +Y is up, yaw = pitch = 0 maps + * object axes onto parent axes, positive yaw turns object +Z towards +X (the + * right), and positive pitch tilts object +Z towards +Y (up).

+ */ +public final class Transform { + + /** Leaves a point exactly where it is. */ + public static final Transform IDENTITY = + new Transform(Vec3.ORIGIN, new double[]{1, 0, 0, 0, 1, 0, 0, 0, 1}); + + private final Vec3 translation; + + /** Row-major 3x3: object space in, parent space out. */ + private final double[] rotation; + + private Transform(final Vec3 translation, final double[] rotation) { + this.translation = translation; + this.rotation = rotation; + } + + /** A pure translation. */ + public static Transform at(final Vec3 translation) { + return new Transform(translation, IDENTITY.rotation); + } + + /** A translation and a rotation, written the way a pose is spoken. */ + public static Transform of(final Vec3 translation, final double yaw, final double pitch) { + return new Transform(translation, rotation(yaw, pitch)); + } + + public Vec3 translation() { + return translation; + } + + /** Object space to parent space. */ + public Vec3 apply(final Vec3 local) { + return new Vec3( + rotation[0] * local.x() + rotation[1] * local.y() + rotation[2] * local.z() + translation.x(), + rotation[3] * local.x() + rotation[4] * local.y() + rotation[5] * local.z() + translation.y(), + rotation[6] * local.x() + rotation[7] * local.y() + rotation[8] * local.z() + translation.z()); + } + + /** + * This pose applied after {@code child}'s own: the child is posed in this + * node's space, which is what makes a chain of parts out of one mesh. + */ + public Transform then(final Transform child) { + final double[] a = rotation; + final double[] b = child.rotation; + final double[] composed = new double[9]; + for (int row = 0; row < 3; row++) { + for (int column = 0; column < 3; column++) { + composed[row * 3 + column] = + a[row * 3] * b[column] + + a[row * 3 + 1] * b[3 + column] + + a[row * 3 + 2] * b[6 + column]; + } + } + final Vec3 moved = new Vec3( + a[0] * child.translation.x() + a[1] * child.translation.y() + a[2] * child.translation.z() + + translation.x(), + a[3] * child.translation.x() + a[4] * child.translation.y() + a[5] * child.translation.z() + + translation.y(), + a[6] * child.translation.x() + a[7] * child.translation.y() + a[8] * child.translation.z() + + translation.z()); + return new Transform(moved, composed); + } + + /** + * Ry(yaw) * Rx(-pitch): the inverse of the rotation the renderer applies + * when it turns a world point into a camera-space one, so a node posed with + * yaw and pitch faces the same way a camera with the same angles looks. + */ + private static double[] rotation(final double yaw, final double pitch) { + final double cosYaw = Math.cos(yaw); + final double sinYaw = Math.sin(yaw); + // Rx(-pitch): b = -pitch + final double cosPitch = Math.cos(-pitch); + final double sinPitch = Math.sin(-pitch); + return new double[]{ + cosYaw, sinYaw * sinPitch, sinYaw * cosPitch, + 0, cosPitch, -sinPitch, + -sinYaw, cosYaw * sinPitch, cosYaw * cosPitch + }; + } +} diff --git a/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Vec3.java b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Vec3.java new file mode 100644 index 0000000..b48f875 --- /dev/null +++ b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/Vec3.java @@ -0,0 +1,27 @@ +package eu.svjatoslav.aukio.world; + +/** + * A point or a direction in three dimensions. + * + *

Immutable and unitless. The same type is a world position, an object-space + * position and a direction, because nothing in this module needs to tell them + * apart: which one a value is, is a property of where it is used, not of the + * number.

+ */ +public record Vec3(double x, double y, double z) { + + /** The origin of whichever coordinate system a value is read in. */ + public static final Vec3 ORIGIN = new Vec3(0, 0, 0); + + public Vec3 plus(final Vec3 other) { + return new Vec3(x + other.x, y + other.y, z + other.z); + } + + public Vec3 minus(final Vec3 other) { + return new Vec3(x - other.x, y - other.y, z - other.z); + } + + public Vec3 scaled(final double factor) { + return new Vec3(x * factor, y * factor, z * factor); + } +} diff --git a/Modules/world/src/main/java/eu/svjatoslav/aukio/world/package-info.java b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/package-info.java new file mode 100644 index 0000000..6872743 --- /dev/null +++ b/Modules/world/src/main/java/eu/svjatoslav/aukio/world/package-info.java @@ -0,0 +1,31 @@ +/** + * The world: everything a scene is before anything is drawn. + * + *

The module holds the data model and nothing that behaves like a device. + * Its concerns, kept apart by class rather than by package:

+ * + *
    + *
  • geometry - vectors, quaternions, matrices, axis-aligned boxes, + * {@code Transform} and the chain that composes them.
  • + *
  • scene - the object tree: nodes carrying a transform, children, an + * optional mesh and a group; world matrices are composed here and + * nowhere else.
  • + *
  • mesh - triangles in object space. A published mesh is immutable and + * may be shared by many nodes.
  • + *
  • shapes - primitives built in local coordinates: box, box frame, + * cylinder, sphere, cone, arrow, grid.
  • + *
  • camera - a pose, nothing more. The viewport and the projection belong + * to the renderer, so this module never needs to know a screen size.
  • + *
+ * + *

Two invariants cross every concern. Local coordinates never leave this + * module uncomposed: a node's geometry is local, its world matrix is derived, + * and anything downstream receives world space. And a pose writes node + * transforms, never mesh vertices, so a shared mesh stays shared and any index + * or baked light derived from it stays valid while the scene moves.

+ * + *

What does not belong here, however convenient: loading, streaming, file + * formats, light, and anything that owns a clock or a thread. Those read from + * outside and belong to modules that can be absent.

+ */ +package eu.svjatoslav.aukio.world; diff --git a/Modules/world/src/main/java/module-info.java b/Modules/world/src/main/java/module-info.java new file mode 100644 index 0000000..4b9e2a6 --- /dev/null +++ b/Modules/world/src/main/java/module-info.java @@ -0,0 +1,13 @@ +/** + * The world module: the scene as data - geometry, transforms, the object tree + * and the primitives - with no knowledge of screens, windows or threads. + * + *

A pose lives here; a projection does not. The camera's position and + * rotation are world data, while turning them into screen coordinates needs the + * viewport and therefore belongs to the renderer. That one rule is what keeps + * the arrow pointing one way: the renderer reads the world, and the world has + * never heard of the renderer.

+ */ +module eu.svjatoslav.aukio.world { + exports eu.svjatoslav.aukio.world; +} diff --git a/Modules/world/src/test/java/eu/svjatoslav/aukio/world/BoxesTest.java b/Modules/world/src/test/java/eu/svjatoslav/aukio/world/BoxesTest.java new file mode 100644 index 0000000..4bfb442 --- /dev/null +++ b/Modules/world/src/test/java/eu/svjatoslav/aukio/world/BoxesTest.java @@ -0,0 +1,68 @@ +package eu.svjatoslav.aukio.world; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The box primitive: twelve triangles, inside its corners, wound outwards. + * + *

The outward winding is checked because nothing downstream would notice if + * it broke, and the first engine's meshes are compared against this geometry by + * eye and by pixel.

+ */ +class BoxesTest { + + private static final Vec3 CORNER = new Vec3(-50, -50, -50); + private static final Vec3 OPPOSITE = new Vec3(50, 50, 50); + + @Test + void aBoxIsTwelveTriangles() { + assertEquals(12, Boxes.box(CORNER, OPPOSITE, 0xFFFF0000).triangleCount()); + } + + @Test + void everyVertexLiesOnOneOfItsCorners() { + final Mesh box = Boxes.box(CORNER, OPPOSITE, 0xFFFF0000); + for (int triangle = 0; triangle < box.triangleCount(); triangle++) { + for (int vertex = 0; vertex < 3; vertex++) { + for (int axis = 0; axis < 3; axis++) { + final double value = box.position(triangle, vertex, axis); + assertTrue(value >= -50 && value <= 50, "coordinate " + value + " outside the box"); + assertTrue(value == -50 || value == 50, "a box vertex sits on a corner, not at " + value); + } + } + } + } + + @Test + void everyTriangleFacesOutOfTheSolid() { + final Mesh box = Boxes.box(CORNER, OPPOSITE, 0xFFFF0000); + for (int triangle = 0; triangle < box.triangleCount(); triangle++) { + final Vec3 a = vertex(box, triangle, 0); + final Vec3 b = vertex(box, triangle, 1); + final Vec3 c = vertex(box, triangle, 2); + final Vec3 normal = cross(b.minus(a), c.minus(a)); + final Vec3 centroid = new Vec3((a.x() + b.x() + c.x()) / 3, + (a.y() + b.y() + c.y()) / 3, + (a.z() + b.z() + c.z()) / 3); + final double outward = normal.x() * centroid.x() + + normal.y() * centroid.y() + + normal.z() * centroid.z(); + assertTrue(outward > 0, "triangle " + triangle + " faces inwards, its normal is " + normal); + } + } + + private static Vec3 vertex(final Mesh mesh, final int triangle, final int vertex) { + return new Vec3(mesh.position(triangle, vertex, 0), + mesh.position(triangle, vertex, 1), + mesh.position(triangle, vertex, 2)); + } + + private static Vec3 cross(final Vec3 a, final Vec3 b) { + return new Vec3(a.y() * b.z() - a.z() * b.y(), + a.z() * b.x() - a.x() * b.z(), + a.x() * b.y() - a.y() * b.x()); + } +} diff --git a/Modules/world/src/test/java/eu/svjatoslav/aukio/world/ModuleShapeTest.java b/Modules/world/src/test/java/eu/svjatoslav/aukio/world/ModuleShapeTest.java new file mode 100644 index 0000000..86b5ae3 --- /dev/null +++ b/Modules/world/src/test/java/eu/svjatoslav/aukio/world/ModuleShapeTest.java @@ -0,0 +1,161 @@ +package eu.svjatoslav.aukio.world; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * The world's shape, checked rather than promised: one public package, one + * descriptor, no requirement on any other engine module, and no file longer + * than the agreed limit. + * + *

The requirement list is the important one here. The world is the bottom of + * the engine: if it ever requires the renderer, the layering is gone and the + * two modules have become one with extra ceremony.

+ */ +class ModuleShapeTest { + + private static final int MAX_FILE_LINES = 800; + + private static final Path SOURCE_ROOT = Path.of("src", "main", "java"); + + private static final String MODULE_PACKAGE = "eu.svjatoslav.aukio.world"; + + private static final Pattern PACKAGE = Pattern.compile("^\\s*package\\s+([\\w.]+)\\s*;", Pattern.MULTILINE); + + private static final Pattern IMPORT = Pattern.compile("^\\s*import\\s+(?:static\\s+)?([\\w.*]+)\\s*;", Pattern.MULTILINE); + + private static final Pattern DECLARED_MODULE = Pattern.compile("^\\s*module\\s+([\\w.]+)\\s*\\{", Pattern.MULTILINE); + + private static final Pattern EXPORT = Pattern.compile("^\\s*exports\\s+([\\w.]+)\\s*;", Pattern.MULTILINE); + + private static final Pattern REQUIRES = Pattern.compile("^\\s*requires\\s+(?:transitive\\s+)?([\\w.]+)\\s*;", Pattern.MULTILINE); + + @Test + void sourcesLiveInExactlyOnePackage() throws IOException { + final List problems = new ArrayList<>(); + for (final Path file : sources()) { + final String declared = declaredPackage(file); + if (!MODULE_PACKAGE.equals(declared)) { + problems.add(relativize(file) + " declares package " + declared); + } + } + assertTrue(problems.isEmpty(), "one public package per module, found: " + problems); + } + + @Test + void theDescriptorRequiresNoEngineModule() throws IOException { + final String descriptor = descriptor(); + assertEquals(MODULE_PACKAGE, firstMatch(DECLARED_MODULE, descriptor), + "the module name is derived from its package"); + for (final String required : allMatches(REQUIRES, descriptor)) { + assertFalse(required.startsWith("eu.svjatoslav.aukio."), + "the world is the bottom of the engine and requires no other module, found: " + required); + } + final List exports = allMatches(EXPORT, descriptor); + assertTrue(exports.size() <= 1, "one public package at most, found: " + exports); + for (final String exported : exports) { + assertEquals(MODULE_PACKAGE, exported, "only the module's own package may be exported"); + } + } + + @Test + void noFileExceedsTheLineLimit() throws IOException { + final List tooLong = new ArrayList<>(); + for (final Path file : sources()) { + final int lines = Files.readAllLines(file, StandardCharsets.UTF_8).size(); + if (lines > MAX_FILE_LINES) { + tooLong.add(relativize(file) + " " + lines + " lines"); + } + } + assertTrue(tooLong.isEmpty(), "over " + MAX_FILE_LINES + " lines: " + tooLong); + } + + @Test + void importsStayInsideThisModule() throws IOException { + final List foreign = new ArrayList<>(); + for (final Path file : sources()) { + for (final String imported : imports(file)) { + if (imported.startsWith("eu.svjatoslav.aukio.") && !imported.startsWith(MODULE_PACKAGE)) { + foreign.add(relativize(file) + " imports " + imported); + } + } + } + assertTrue(foreign.isEmpty(), "the world imports no other engine module: " + foreign); + } + + @Test + void theModuleItselfHasSources() throws IOException { + assertFalse(sources().isEmpty(), "no sources under " + SOURCE_ROOT + " - the checks above would be vacuous"); + } + + private static List sources() throws IOException { + if (!Files.isDirectory(SOURCE_ROOT)) { + fail("run from the module directory: " + SOURCE_ROOT.toAbsolutePath() + " does not exist"); + } + try (Stream walk = Files.walk(SOURCE_ROOT)) { + return walk.filter(Files::isRegularFile) + .filter(path -> path.toString().endsWith(".java")) + .filter(path -> !path.getFileName().toString().equals("module-info.java")) + .sorted() + .toList(); + } + } + + private static String descriptor() throws IOException { + final Path file = SOURCE_ROOT.resolve("module-info.java"); + if (!Files.isRegularFile(file)) { + fail("the module declares no descriptor: " + relativize(file) + " is missing"); + } + return Files.readString(file, StandardCharsets.UTF_8); + } + + private static String declaredPackage(final Path file) throws IOException { + final String text = Files.readString(file, StandardCharsets.UTF_8); + final Matcher matcher = PACKAGE.matcher(text); + if (!matcher.find()) { + return ""; + } + assertEquals(1, countMatches(PACKAGE, text), "more than one package declaration in " + relativize(file)); + return matcher.group(1); + } + + private static List imports(final Path file) throws IOException { + return allMatches(IMPORT, Files.readString(file, StandardCharsets.UTF_8)); + } + + private static String firstMatch(final Pattern pattern, final String text) { + final List found = allMatches(pattern, text); + return found.isEmpty() ? "" : found.get(0); + } + + private static List allMatches(final Pattern pattern, final String text) { + final List found = new ArrayList<>(); + final Matcher matcher = pattern.matcher(text); + while (matcher.find()) { + found.add(matcher.group(1)); + } + return found; + } + + private static int countMatches(final Pattern pattern, final String text) { + return allMatches(pattern, text).size(); + } + + private static String relativize(final Path path) { + return Path.of("").toAbsolutePath().relativize(path.toAbsolutePath()).toString(); + } +} diff --git a/Modules/world/src/test/java/eu/svjatoslav/aukio/world/TransformTest.java b/Modules/world/src/test/java/eu/svjatoslav/aukio/world/TransformTest.java new file mode 100644 index 0000000..b7b8318 --- /dev/null +++ b/Modules/world/src/test/java/eu/svjatoslav/aukio/world/TransformTest.java @@ -0,0 +1,56 @@ +package eu.svjatoslav.aukio.world; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * The pose convention, pinned: a yaw turns object +Z towards +X, a pitch tilts + * it towards +Y, and a chain applies the child first. + * + *

These are the numbers a camera and a node must agree on for a scene to + * look the same as it did in the previous engine, so they are asserted rather + * than described.

+ */ +class TransformTest { + + private static final double EPSILON = 1e-9; + + private static final Vec3 FORWARD = new Vec3(0, 0, 1); + + @Test + void identityLeavesAPointWhereItIs() { + final Vec3 point = new Vec3(3, -4, 5); + assertVec(point, Transform.IDENTITY.apply(point)); + } + + @Test + void yawTurnsForwardTowardsTheRight() { + assertVec(new Vec3(1, 0, 0), Transform.of(Vec3.ORIGIN, Math.PI / 2, 0).apply(FORWARD)); + } + + @Test + void pitchTiltsForwardUpwards() { + assertVec(new Vec3(0, 1, 0), Transform.of(Vec3.ORIGIN, 0, Math.PI / 2).apply(FORWARD)); + } + + @Test + void translationIsAppliedAfterRotation() { + assertVec(new Vec3(1, 10, 0), Transform.of(new Vec3(0, 10, 0), Math.PI / 2, 0).apply(FORWARD)); + } + + @Test + void aChainAppliesTheChildBeforeItsParent() { + final Transform parent = Transform.of(new Vec3(100, 0, 0), 0, 0); + final Transform child = Transform.of(new Vec3(0, 0, 5), Math.PI / 2, 0); + // forward, turned right and pushed five along the child's own +Z, then + // slid a hundred along the parent's +X + assertVec(new Vec3(101, 0, 5), parent.then(child).apply(FORWARD)); + } + + private static void assertVec(final Vec3 expected, final Vec3 actual) { + assertEquals(expected.x(), actual.x(), EPSILON, "x"); + assertEquals(expected.y(), actual.y(), EPSILON, "y"); + assertEquals(expected.z(), actual.z(), EPSILON, "z"); + } +} diff --git a/README.org b/README.org new file mode 100644 index 0000000..d3e316e --- /dev/null +++ b/README.org @@ -0,0 +1,41 @@ +#+TITLE: Aukio V3 +#+AUTHOR: Svjatoslav Agejenko +#+STARTUP: overview +#+OPTIONS: toc:nil num:nil + +:PROPERTIES: +:CUSTOM_ID: aukio-readme +:END: + +* Modules + +| Path | What it is | +|---------------------+---------------------| +| =Modules/scheduler/= | CPU time scheduler. | +| =Modules/world/= | Scene data: geometry, object tree. | +| =Modules/gi/= | Light: direct, indirect, lightmaps. | +| =Modules/renderer/= | Projection, culling, rasterisation. | +| =Modules/navigation/= | Input record and camera policy. | +| =Modules/swing/= | Embeddable view component. | +| =Modules/hid/= | 3D input devices read off /dev/hidraw. | + + +* Apps + +| Path | What it is | +|---------------+--------------------| +| =Applications/demos/= | Demo app launcher. | + + +* Build + +#+begin_src sh +export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64 +./gradlew --offline build +#+end_src + +Gradle 8.7 through the wrapper, offline: every dependency comes from +=~/.m2= via =mavenLocal()=. Each module also builds alone: +=./gradlew --offline :renderer:build=. + + diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..9f32be4 --- /dev/null +++ b/build.gradle @@ -0,0 +1,47 @@ +// Every module in this build is a Java library with the same compiler settings +// and the same test platform. A module carries its own build.gradle only when it +// has a dependency or a task of its own. + +subprojects { + apply plugin: 'java-library' + + // Compile and test on the oldest JDK the artifacts claim to support, not on + // whatever JVM happened to launch Gradle: a suite that is green on a newer + // JDK can hide a regression that only bites a host running 21. The daemon + // may still run on a newer JVM; only the compiler and the test workers move. + java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } + } + + group = 'eu.svjatoslav' + version = '3.0.0-SNAPSHOT' + + base { + archivesName = "aukio-${project.name}" + } + + repositories { + // Dependencies are already in the local Maven repository, so the build + // runs without network access. + mavenLocal() + } + + dependencies { + testImplementation platform('org.junit:junit-bom:5.11.4') + testImplementation 'org.junit.jupiter:junit-jupiter' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + } + + tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' + options.release = 21 + } + + // A module's own tests run with the modules it does not depend on absent + // from its classpath - that is the isolation proof AGENTS.org asks for. + tasks.named('test') { + useJUnitPlatform() + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..df2d1df --- /dev/null +++ b/gradle.properties @@ -0,0 +1,4 @@ +# This build is meant to run offline against toolchains already installed on the +# machine. When the JDK the build asks for is missing, fail with a readable +# message instead of trying to download it. +org.gradle.java.installations.auto-download=false diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..e6441136f3d4ba8a0da8d277868979cfbc8ad796 GIT binary patch literal 43453 zcma&N1CXTcmMvW9vTb(Rwr$&4wr$(C?dmSu>@vG-+vuvg^_??!{yS%8zW-#zn-LkA z5&1^$^{lnmUON?}LBF8_K|(?T0Ra(xUH{($5eN!MR#ZihR#HxkUPe+_R8Cn`RRs(P z_^*#_XlXmGv7!4;*Y%p4nw?{bNp@UZHv1?Um8r6)Fei3p@ClJn0ECfg1hkeuUU@Or zDaPa;U3fE=3L}DooL;8f;P0ipPt0Z~9P0)lbStMS)ag54=uL9ia-Lm3nh|@(Y?B`; zx_#arJIpXH!U{fbCbI^17}6Ri*H<>OLR%c|^mh8+)*h~K8Z!9)DPf zR2h?lbDZQ`p9P;&DQ4F0sur@TMa!Y}S8irn(%d-gi0*WxxCSk*A?3lGh=gcYN?FGl z7D=Js!i~0=u3rox^eO3i@$0=n{K1lPNU zwmfjRVmLOCRfe=seV&P*1Iq=^i`502keY8Uy-WNPwVNNtJFx?IwAyRPZo2Wo1+S(xF37LJZ~%i)kpFQ3Fw=mXfd@>%+)RpYQLnr}B~~zoof(JVm^^&f zxKV^+3D3$A1G;qh4gPVjhrC8e(VYUHv#dy^)(RoUFM?o%W-EHxufuWf(l*@-l+7vt z=l`qmR56K~F|v<^Pd*p~1_y^P0P^aPC##d8+HqX4IR1gu+7w#~TBFphJxF)T$2WEa zxa?H&6=Qe7d(#tha?_1uQys2KtHQ{)Qco)qwGjrdNL7thd^G5i8Os)CHqc>iOidS} z%nFEDdm=GXBw=yXe1W-ShHHFb?Cc70+$W~z_+}nAoHFYI1MV1wZegw*0y^tC*s%3h zhD3tN8b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U@PT4T><2OVamoK;wJ}3X0L$vX zgd7gNa359*nc)R-0!`2X@FOTB`+oETOPc=ubp5R)VQgY+5BTZZJ2?9QwnO=dnulIUF3gFn;BODC2)65)HeVd%t86sL7Rv^Y+nbn+&l z6BAJY(ETvwI)Ts$aiE8rht4KD*qNyE{8{x6R|%akbTBzw;2+6Echkt+W+`u^XX z_z&x%n '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..25da30d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/pom.xml b/pom.xml deleted file mode 100644 index d15d786..0000000 --- a/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - 4.0.0 - eu.svjatoslav - aukio - 2.0.0-SNAPSHOT - pom - Aukio - Spatial computing environment on Aukio 3D 2 - - - UTF-8 - UTF-8 - 21 - - - - svjatoslav.eu - http://svjatoslav.eu - - - - - workspace-v2 - - - - - svjatoslav.eu - svjatoslav.eu - scpexe://svjatoslav.eu:10006/srv/maven - - - svjatoslav.eu - svjatoslav.eu - scpexe://svjatoslav.eu:10006/srv/maven - - - - - - svjatoslav.eu - Svjatoslav repository - https://www3.svjatoslav.eu/maven/ - - - - - scm:git:ssh://n0@svjatoslav.eu:10006/home/n0/git/aukio.git - scm:git:ssh://n0@svjatoslav.eu:10006/home/n0/git/aukio.git - HEAD - - diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..5d495a8 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,14 @@ +rootProject.name = 'aukio' + +// Flat project names, directory layout kept: Modules/ and Applications/ are +// folders, not projects, so no empty jar is built for them. +include 'scheduler', 'world', 'gi', 'renderer', 'navigation', 'swing', 'hid', 'demos' + +project(':scheduler').projectDir = file('Modules/scheduler') +project(':world').projectDir = file('Modules/world') +project(':gi').projectDir = file('Modules/gi') +project(':renderer').projectDir = file('Modules/renderer') +project(':navigation').projectDir = file('Modules/navigation') +project(':swing').projectDir = file('Modules/swing') +project(':hid').projectDir = file('Modules/hid') +project(':demos').projectDir = file('Applications/demos') diff --git a/verify.sh b/verify.sh deleted file mode 100755 index 3ae8946..0000000 --- a/verify.sh +++ /dev/null @@ -1,130 +0,0 @@ -#!/usr/bin/env bash -# THE GATE. Nothing is reported fixed until this prints GATE PASS. -# -# ./verify.sh unit suites + every scenario in verification/scenarios.tsv -# ./verify.sh --quick unit suites only (no game data, ~1.5 min) -# ./verify.sh --list show the registered scenarios -# -# Rules this script exists to enforce (AGENTS.org, "Streaming coverage"): -# - a scenario drives the PRODUCTION code over time; a screenshot cannot -# distinguish "did not load" from "loaded and hidden" -# - every bug report becomes a scenario here, with the reporter's pose -# - a subsystem fix that breaks another subsystem's scenario fails the gate -# -# Exit code 0 = everything passed. -set -uo pipefail - -HERE="$(cd "$(dirname "$0")" && pwd)" -ENGINE="$HERE/../aukio-3d-2" -FO4="$HERE/../aukio-environment-fo4-2" -SCENARIOS="$HERE/verification/scenarios.tsv" -KNOWN_FAILURES="$HERE/verification/known-failures.tsv" -CLASSES="$HOME/.hermes/cache/scratch/verify-gate/classes" -LOGS="$HOME/.hermes/cache/scratch/verify-gate/logs" -JAVA_HOME_21="${JAVA_HOME_21:-/usr/lib/jvm/java-21-openjdk-amd64}" -JAVA_BIN="${JAVA_BIN:-/usr/lib/jvm/java-25-openjdk-amd64/bin/java}" - -mkdir -p "$CLASSES" "$LOGS" - -MODE="${1:-all}" -if [ "$MODE" = "--list" ]; then - cat "$SCENARIOS" - exit 0 -fi - -fail=0 -declare -a ROWS - -step() { # name, command-string - local name="$1"; shift - local log="$LOGS/$(echo "$name" | tr ' /' '__').log" - local start; start=$(date +%s) - if "$@" > "$log" 2>&1; then - local took=$(( $(date +%s) - start )) - ROWS+=("$(printf '%-34s PASS %4ds' "$name" "$took")") - printf '%-34s PASS %4ds\n' "$name" "$took" - return 0 - fi - local took=$(( $(date +%s) - start )) - ROWS+=("$(printf '%-34s FAIL %4ds %s' "$name" "$took" "$log")") - printf '%-34s FAIL %4ds %s\n' "$name" "$took" "$log" - tail -20 "$log" | sed 's/^/ /' - fail=1 - return 1 -} - -echo "== unit suites ==" -step "engine tests (aukio-3d-2)" \ - bash -c "cd '$ENGINE' && xvfb-run -a mvn -o -q test" -step "engine install" \ - bash -c "cd '$ENGINE' && mvn -o -q -DskipTests install" -step "fo4 tests (fo4-2)" \ - bash -c "cd '$FO4' && xvfb-run -a mvn -o -q test" -# The memory model: TLC proves the protocol, jcstress proves the ORDERING the -# protocol relies on on real CPUs (one writer, one reader, C2 stress flags). -# A forbidden outcome here is a lost update or a hole, not a crash. -step "memory model (jcstress)" \ - bash -c "'$ENGINE/verification/jcstress/run.sh'" -# The model registry: every active TLA+ model must have a gate config, a -# non-vacuity config and a Maven execution, or it silently stops being checked. -step "model registry (TLA+) engine" \ - bash -c "cd '$ENGINE/Model' && ./check-models.sh" -# The FO4 environment owns its own models (streaming coverage, atomic -# replacement, the triangle budget, the residency plan). They used to live in -# the engine repo, which meant FO4 policies were gated by a repo they do not -# belong to — and a model could be added on one side and never run. -step "model registry (TLA+) fo4" \ - bash -c "cd '$FO4/Model' && ./check-models.sh" - -if [ "$MODE" = "--quick" ]; then - [ "$fail" -eq 0 ] && echo && echo "GATE PASS (quick: unit suites only)" - exit "$fail" -fi - -echo -echo "== scenarios (verification/scenarios.tsv) ==" -CP="$FO4/target/classes:$(cat "$FO4/target/cp.txt" 2>/dev/null):$CLASSES" -step "compile scenario drivers" \ - bash -c "'$JAVA_HOME_21/bin/javac' -cp '$CP' -d '$CLASSES' '$FO4'/verification/*.java" - -while IFS=$'\t' read -r name class args opts timeout; do - case "$name" in ''|'#'*) continue ;; esac - # Scenarios open a REAL window. Run them on a VIRTUAL display unless the - # caller already provided one: the gate must never put a window on the - # user's screen (it steals focus and, on a shared desktop, corrupts what - # the user is doing). - step "scenario $name" \ - bash -c "cd '$FO4' && xvfb-run -a -s '-screen 0 3840x2160x24' timeout ${timeout:-300} '$JAVA_BIN' -Xmx20g -cp '$CP' $opts $class $args" -done < "$SCENARIOS" - -# KNOWN FAILURES: reproduced, user-visible defects that are NOT fixed yet. -# They are run and reported, and the gate does NOT pass them off as green — -# but an entry that STARTS PASSING is an error too: either the fix landed and -# the row must move to scenarios.tsv, or the row became vacuous. -knownFail=0 -unexpectedPass=0 -if [ -f "$KNOWN_FAILURES" ]; then - echo - echo "== known failures (reported, not green) ==" - while IFS=$'\t' read -r name class args opts timeout; do - case "$name" in ''|'#'*) continue ;; esac - log="$LOGS/known_$(echo "$name" | tr ' /' '__').log" - if (cd "$FO4" && xvfb-run -a -s '-screen 0 3840x2160x24' \ - timeout ${timeout:-300} "$JAVA_BIN" -Xmx20g -cp "$CP" $opts $class $args) \ - > "$log" 2>&1; then - unexpectedPass=$((unexpectedPass + 1)) - printf '%-34s UNEXPECTED PASS — move it to scenarios.tsv\n' "known-fail $name" - else - knownFail=$((knownFail + 1)) - printf '%-34s KNOWN-FAIL %s\n' "known-fail $name" "$log" - fi - done < "$KNOWN_FAILURES" -fi - -echo -if [ "$fail" -eq 0 ] && [ "$unexpectedPass" -eq 0 ]; then - echo "GATE PASS${knownFail:+ (known failures: $knownFail)}" -else - echo "GATE FAIL — logs in $LOGS" -fi -exit "$(( fail + unexpectedPass ))" -- 2.20.1