Initial commit
This commit is contained in:
+38
@@ -0,0 +1,38 @@
|
||||
target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
!**/src/main/**/target/
|
||||
!**/src/test/**/target/
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea/modules.xml
|
||||
.idea/jarRepositories.xml
|
||||
.idea/compiler.xml
|
||||
.idea/libraries/
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### Eclipse ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
build/
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
|
||||
### Mac OS ###
|
||||
.DS_Store
|
||||
@@ -0,0 +1,236 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>ru.fokinatorr.sparkle</groupId>
|
||||
<artifactId>sparkle-core</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>Sparkle Framework core module</name>
|
||||
<description>
|
||||
The core module of SFNS (code name Sparkle).
|
||||
|
||||
Sparkle is a framework for creating graphical applications, with an API similar to the functionality MIT Scratch
|
||||
offers. The primary difference
|
||||
from Scratch is writing Java code instead of code blocks; there is also a lot more features and customization
|
||||
support.
|
||||
|
||||
To run Sparkle, you only need this module; if you want additional functionality, see other modules with group ID
|
||||
"${project.groupId}".
|
||||
</description>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>25</maven.compiler.source>
|
||||
<maven.compiler.target>25</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<lwjgl.version>3.4.1</lwjgl.version>
|
||||
<lombok.version>1.18.44</lombok.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.14.0</version>
|
||||
<configuration>
|
||||
<release>25</release>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<!-- <editor-fold desc="LWJGL profiles" defaultstate="collapsed"> -->
|
||||
<profile>
|
||||
<id>lwjgl-natives-linux-amd64</id>
|
||||
<activation>
|
||||
<os>
|
||||
<family>unix</family>
|
||||
<name>linux</name>
|
||||
<arch>amd64</arch>
|
||||
</os>
|
||||
</activation>
|
||||
<properties>
|
||||
<lwjgl.natives>natives-linux</lwjgl.natives>
|
||||
</properties>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>lwjgl-natives-macos-x86_64</id>
|
||||
<activation>
|
||||
<os>
|
||||
<family>mac</family>
|
||||
<arch>x86_64</arch>
|
||||
</os>
|
||||
</activation>
|
||||
<properties>
|
||||
<lwjgl.natives>natives-macos</lwjgl.natives>
|
||||
</properties>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>lwjgl-natives-macos-aarch64</id>
|
||||
<activation>
|
||||
<os>
|
||||
<family>mac</family>
|
||||
<arch>aarch64</arch>
|
||||
</os>
|
||||
</activation>
|
||||
<properties>
|
||||
<lwjgl.natives>natives-macos-arm64</lwjgl.natives>
|
||||
</properties>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>lwjgl-natives-windows-amd64</id>
|
||||
<activation>
|
||||
<os>
|
||||
<family>windows</family>
|
||||
<arch>amd64</arch>
|
||||
</os>
|
||||
</activation>
|
||||
<properties>
|
||||
<lwjgl.natives>natives-windows</lwjgl.natives>
|
||||
</properties>
|
||||
</profile>
|
||||
<!-- </editor-fold> -->
|
||||
</profiles>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.lwjgl</groupId>
|
||||
<artifactId>lwjgl-bom</artifactId>
|
||||
<version>${lwjgl.version}</version>
|
||||
<scope>import</scope>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<!-- <editor-fold desc="LWJGL dependencies" defaultstate="collapsed"> -->
|
||||
<dependency>
|
||||
<groupId>org.lwjgl</groupId>
|
||||
<artifactId>lwjgl</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.lwjgl</groupId>
|
||||
<artifactId>lwjgl-glfw</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.lwjgl</groupId>
|
||||
<artifactId>lwjgl-nanovg</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.lwjgl</groupId>
|
||||
<artifactId>lwjgl-openal</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.lwjgl</groupId>
|
||||
<artifactId>lwjgl-opengl</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.lwjgl</groupId>
|
||||
<artifactId>lwjgl-shaderc</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.lwjgl</groupId>
|
||||
<artifactId>lwjgl-stb</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.lwjgl</groupId>
|
||||
<artifactId>lwjgl</artifactId>
|
||||
<classifier>${lwjgl.natives}</classifier>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.lwjgl</groupId>
|
||||
<artifactId>lwjgl-glfw</artifactId>
|
||||
<classifier>${lwjgl.natives}</classifier>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.lwjgl</groupId>
|
||||
<artifactId>lwjgl-nanovg</artifactId>
|
||||
<classifier>${lwjgl.natives}</classifier>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.lwjgl</groupId>
|
||||
<artifactId>lwjgl-openal</artifactId>
|
||||
<classifier>${lwjgl.natives}</classifier>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.lwjgl</groupId>
|
||||
<artifactId>lwjgl-opengl</artifactId>
|
||||
<classifier>${lwjgl.natives}</classifier>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.lwjgl</groupId>
|
||||
<artifactId>lwjgl-shaderc</artifactId>
|
||||
<classifier>${lwjgl.natives}</classifier>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.lwjgl</groupId>
|
||||
<artifactId>lwjgl-stb</artifactId>
|
||||
<classifier>${lwjgl.natives}</classifier>
|
||||
</dependency>
|
||||
<!-- </editor-fold> -->
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>it.unimi.dsi</groupId>
|
||||
<artifactId>fastutil</artifactId>
|
||||
<version>8.5.15</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>2.0.16</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<!-- SLF4J implementation -->
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>1.5.18</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jspecify</groupId>
|
||||
<artifactId>jspecify</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.joml</groupId>
|
||||
<artifactId>joml</artifactId>
|
||||
<version>1.10.8</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ru.fokinatorr</groupId>
|
||||
<artifactId>lwjgl-exceptions</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.github.hakky54</groupId>
|
||||
<artifactId>logcaptor</artifactId>
|
||||
<version>2.12.6</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.11.4</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl.surface;
|
||||
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import ru.fokinatorr.sparkle.graphics.PixelReader;
|
||||
import ru.fokinatorr.sparkle.graphics.PixelWriter;
|
||||
import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer;
|
||||
|
||||
import static lombok.AccessLevel.PRIVATE;
|
||||
|
||||
/**
|
||||
* A {@code VKSurfaceKHR} frame buffer.
|
||||
*/
|
||||
@FieldDefaults(level = PRIVATE)
|
||||
public class VKSurfaceFramebuffer implements Framebuffer {
|
||||
|
||||
final int width, height;
|
||||
final long vkSurface; // pointer
|
||||
|
||||
|
||||
@Override
|
||||
public int getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PixelReader createPixelReader() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PixelWriter createPixelWriter() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
|
||||
}
|
||||
}
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl.surface;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.lwjgl.glfw.GLFWVidMode;
|
||||
import ru.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
|
||||
import ru.fokinatorr.sparkle.event.input.Key;
|
||||
import ru.fokinatorr.sparkle.event.input.KeyboardEvent;
|
||||
import ru.fokinatorr.sparkle.event.input.MouseButton;
|
||||
import ru.fokinatorr.sparkle.event.input.MouseEvent;
|
||||
import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer;
|
||||
import ru.fokinatorr.sparkle.graphics.render.surface.WindowSurface;
|
||||
import ru.fokinatorr.sparkle.phys2d.Point2D;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
import ru.fokinatorr.sparkle.util.concurrent.atomic.AtomicDouble;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import static org.lwjgl.glfw.GLFW.*;
|
||||
import static org.lwjgl.system.MemoryUtil.NULL;
|
||||
|
||||
/**
|
||||
* A GLFW window rendering surface, providing Vulkan framebuffers.
|
||||
*/
|
||||
@Slf4j
|
||||
@FieldDefaults(level = AccessLevel.PRIVATE)
|
||||
public final class VK_GLFWWindowSurface implements WindowSurface {
|
||||
/**
|
||||
* The GLFW window pointer.
|
||||
*/
|
||||
@Getter
|
||||
final long glfwWindow; // pointer
|
||||
final List<ResizeListener> resizeCallback = new LinkedList<>();
|
||||
int[] oldXYWH = null;
|
||||
boolean closed;
|
||||
|
||||
|
||||
/**
|
||||
* @throws NullPointerException if any argument is {@code null}
|
||||
*/
|
||||
@SuppressWarnings("resource")
|
||||
VK_GLFWWindowSurface(long glfwWindow, EventDispatcher dispatcher, Stage stage) {
|
||||
if (glfwWindow == NULL) {
|
||||
throw new NullPointerException("glfwWindow");
|
||||
}
|
||||
this.glfwWindow = glfwWindow;
|
||||
Objects.requireNonNull(dispatcher, "dispatcher");
|
||||
Objects.requireNonNull(stage, "stage");
|
||||
|
||||
glfwSetKeyCallback(glfwWindow, (_, keyCode, scancode, action, modifiers) -> {
|
||||
Key key = GLFWToPublicAPI.KEYS_MAP.get(keyCode);
|
||||
if (key != null) {
|
||||
switch (action) {
|
||||
case GLFW_PRESS -> {
|
||||
if (dispatcher.hasListenersFor(KeyboardEvent.KeyPressedEvent.class)) {
|
||||
dispatcher.fireEvent(new KeyboardEvent.KeyPressedEvent(stage, key, modifiers));
|
||||
}
|
||||
}
|
||||
case GLFW_RELEASE -> {
|
||||
if (dispatcher.hasListenersFor(KeyboardEvent.KeyReleasedEvent.class)) {
|
||||
dispatcher.fireEvent(new KeyboardEvent.KeyReleasedEvent(stage, key, modifiers));
|
||||
}
|
||||
}
|
||||
case GLFW_REPEAT -> {
|
||||
if (dispatcher.hasListenersFor(KeyboardEvent.KeyRepeatedEvent.class)) {
|
||||
dispatcher.fireEvent(new KeyboardEvent.KeyRepeatedEvent(stage, key, modifiers));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log.warn(
|
||||
"Unknown key with scancode {} {}",
|
||||
scancode,
|
||||
switch (action) {
|
||||
case GLFW_PRESS -> "pressed";
|
||||
case GLFW_RELEASE -> "released";
|
||||
case GLFW_REPEAT -> "repeated";
|
||||
default -> "<unknown action>";
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
glfwSetCharCallback(glfwWindow, (_, codePoint) -> {
|
||||
if (dispatcher.hasListenersFor(KeyboardEvent.CharInputEvent.class)) {
|
||||
dispatcher.fireEvent(new KeyboardEvent.CharInputEvent(stage, codePoint));
|
||||
}
|
||||
});
|
||||
|
||||
AtomicLong lastMousePress = new AtomicLong(-1);
|
||||
glfwSetMouseButtonCallback(glfwWindow, (_, buttonCode, action, _) -> {
|
||||
MouseButton button = GLFWToPublicAPI.MOUSE_BUTTONS_MAP.get(buttonCode);
|
||||
double[] realX = {0}, realY = {0};
|
||||
glfwGetCursorPos(glfwWindow, realX, realY);
|
||||
double x = realX[0] - stage.getWidth() / 2d;
|
||||
double y = realY[0] - stage.getHeight() / 2d;
|
||||
switch (action) {
|
||||
case GLFW_PRESS -> {
|
||||
lastMousePress.set(System.nanoTime());
|
||||
if (dispatcher.hasListenersFor(MouseEvent.MousePressedEvent.class)) {
|
||||
dispatcher.fireEvent(new MouseEvent.MousePressedEvent(button, stage, x, y));
|
||||
}
|
||||
}
|
||||
case GLFW_RELEASE -> {
|
||||
if (dispatcher.hasListenersFor(MouseEvent.MouseReleasedEvent.class)) {
|
||||
dispatcher.fireEvent(new MouseEvent.MouseReleasedEvent(button, stage, x, y));
|
||||
}
|
||||
if (lastMousePress.get() > 0) {
|
||||
long pressDurationNs = System.nanoTime() - lastMousePress.getAndSet(-1);
|
||||
if (dispatcher.hasListenersFor(MouseEvent.MouseClickedEvent.class)
|
||||
&& pressDurationNs <= 500_000_000L) { // TODO configurable?
|
||||
dispatcher.fireEvent(new MouseEvent.MouseClickedEvent(button, stage, x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
AtomicDouble lastMouseX = new AtomicDouble(-1);
|
||||
AtomicDouble lastMouseY = new AtomicDouble(-1);
|
||||
glfwSetCursorPosCallback(glfwWindow, (_, newRealX, newRealY) -> {
|
||||
double oldRealX = lastMouseX.getAndSet(newRealX);
|
||||
double oldRealY = lastMouseY.getAndSet(newRealY);
|
||||
if (dispatcher.hasListenersFor(MouseEvent.MouseCursorMovedEvent.class) && oldRealX >= 0 && oldRealY >= 0) {
|
||||
double
|
||||
oldX = oldRealX - stage.getWidth() / 2d,
|
||||
oldY = oldRealY - stage.getWidth() / 2d,
|
||||
newX = newRealX - stage.getWidth() / 2d,
|
||||
newY = newRealY - stage.getWidth() / 2d;
|
||||
Set<MouseButton> pressedButtons = EnumSet.noneOf(MouseButton.class);
|
||||
for (int mb : GLFWToPublicAPI.MOUSE_BUTTONS_MAP.keySet()) {
|
||||
if (glfwGetMouseButton(glfwWindow, mb) == GLFW_PRESS) {
|
||||
pressedButtons.add(GLFWToPublicAPI.MOUSE_BUTTONS_MAP.get(mb));
|
||||
}
|
||||
}
|
||||
|
||||
dispatcher.fireEvent(new MouseEvent.MouseCursorMovedEvent(stage, oldX, oldY, newX, newY, pressedButtons));
|
||||
}
|
||||
});
|
||||
|
||||
glfwSetScrollCallback(glfwWindow, (_, dx, dy) -> {
|
||||
if (dispatcher.hasListenersFor(MouseEvent.MouseScrolledEvent.class)) {
|
||||
double[] realX = {0}, realY = {0};
|
||||
glfwGetCursorPos(glfwWindow, realX, realY);
|
||||
double x = realX[0] - stage.getWidth() / 2d;
|
||||
double y = realY[0] - stage.getHeight() / 2d;
|
||||
dispatcher.fireEvent(new MouseEvent.MouseScrolledEvent(stage, x, y, dx, dy));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new non-fullscreen window.
|
||||
*
|
||||
* @param title the window title
|
||||
* @param dispatcher the event dispatcher to use for sending window events
|
||||
* @param stage the stage to use for sending window events
|
||||
* @return a new window surface
|
||||
*/
|
||||
public static VK_GLFWWindowSurface create(String title, EventDispatcher dispatcher, Stage stage, boolean translucent) {
|
||||
if (translucent) {
|
||||
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_TRUE);
|
||||
glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
|
||||
}
|
||||
VK_GLFWWindowSurface result = new VK_GLFWWindowSurface(
|
||||
glfwCreateWindow(stage.getWidth(), stage.getHeight(), title, NULL, NULL),
|
||||
dispatcher, stage
|
||||
);
|
||||
if (translucent) {
|
||||
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_FALSE);
|
||||
glfwWindowHint(GLFW_DECORATED, GLFW_TRUE);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new fullscreen window.
|
||||
*
|
||||
* @param title the window title
|
||||
* @param monitor the GLFW monitor on which the window should be fullscreen
|
||||
* @param dispatcher the event dispatcher to use for sending window events
|
||||
* @param stage the stage to use for sending window events
|
||||
* @return a new window surface
|
||||
*/
|
||||
public static VK_GLFWWindowSurface createFullscreen(String title, long monitor /*pointer*/,
|
||||
EventDispatcher dispatcher, Stage stage,
|
||||
boolean translucent) {
|
||||
if (translucent) {
|
||||
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_TRUE);
|
||||
glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
|
||||
}
|
||||
VK_GLFWWindowSurface result = new VK_GLFWWindowSurface(
|
||||
glfwCreateWindow(stage.getWidth(), stage.getHeight(), title, monitor, NULL),
|
||||
dispatcher, stage
|
||||
);
|
||||
if (translucent) {
|
||||
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_FALSE);
|
||||
glfwWindowHint(GLFW_DECORATED, GLFW_TRUE);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int getWidth() {
|
||||
ensureOpen();
|
||||
int[] w = {0};
|
||||
glfwGetWindowSize(glfwWindow, w, null);
|
||||
return w[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHeight() {
|
||||
ensureOpen();
|
||||
int[] h = {0};
|
||||
glfwGetWindowSize(glfwWindow, null, h);
|
||||
return h[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public Point2D getSize() {
|
||||
ensureOpen();
|
||||
int[] w = {0}, h = {0};
|
||||
glfwGetWindowSize(glfwWindow, w, h);
|
||||
return new Point2D(w[0], h[0]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pollEvents() {
|
||||
ensureOpen();
|
||||
glfwPollEvents();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Framebuffer acquireBuffer() {
|
||||
// TODO
|
||||
}
|
||||
|
||||
@Override
|
||||
public void present(Framebuffer frameBuffer) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldClose() {
|
||||
ensureOpen();
|
||||
return glfwWindowShouldClose(glfwWindow);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResize(ResizeListener callback) {
|
||||
ensureOpen();
|
||||
resizeCallback.add(callback);
|
||||
glfwSetWindowSizeCallback(glfwWindow, (_, width, height) -> {
|
||||
for (var cb : resizeCallback) {
|
||||
cb.resized(this, width, height);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Feature> getFeatures() {
|
||||
return Collections.unmodifiableSet(EnumSet.of(
|
||||
Feature.RESIZABLE,
|
||||
Feature.MOVABLE,
|
||||
Feature.HIDEABLE,
|
||||
Feature.NAMEABLE,
|
||||
Feature.FULLSCREENABLE,
|
||||
Feature.TRANSLUCENT
|
||||
));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSize(int newWidth, int newHeight) {
|
||||
ensureOpen();
|
||||
glfwSetWindowSize(glfwWindow, newWidth, newHeight);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getX() {
|
||||
ensureOpen();
|
||||
int[] x = {0};
|
||||
glfwGetWindowPos(glfwWindow, x, null);
|
||||
return x[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getY() {
|
||||
ensureOpen();
|
||||
int[] y = {0};
|
||||
glfwGetWindowPos(glfwWindow, null, y);
|
||||
return y[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public Point2D getPos() {
|
||||
ensureOpen();
|
||||
int[] x = {0}, y = {0};
|
||||
glfwGetWindowPos(glfwWindow, x, y);
|
||||
return new Point2D(x[0], y[0]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPos(int newX, int newY) {
|
||||
ensureOpen();
|
||||
glfwSetWindowPos(glfwWindow, newX, newY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHidden() {
|
||||
ensureOpen();
|
||||
return glfwGetWindowAttrib(glfwWindow, GLFW_VISIBLE) == GLFW_TRUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void show() {
|
||||
ensureOpen();
|
||||
glfwShowWindow(glfwWindow);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void hide() {
|
||||
ensureOpen();
|
||||
glfwHideWindow(glfwWindow);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
ensureOpen();
|
||||
return glfwGetWindowTitle(glfwWindow);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setName(String name) {
|
||||
ensureOpen();
|
||||
glfwSetWindowTitle(glfwWindow, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isFullscreen() {
|
||||
ensureOpen();
|
||||
return glfwGetWindowMonitor(glfwWindow) != NULL;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setFullscreen(boolean fullscreen) {
|
||||
ensureOpen();
|
||||
GLFWVidMode vidMode = glfwGetVideoMode(glfwGetPrimaryMonitor());
|
||||
if (vidMode == null) {
|
||||
throw new IllegalStateException("GLFW error");
|
||||
}
|
||||
if (fullscreen) {
|
||||
Point2D pos = getPos(), dimensions = getSize();
|
||||
oldXYWH = new int[] {(int) pos.x(), (int) pos.y(), (int) dimensions.x(), (int) dimensions.y()};
|
||||
glfwSetWindowMonitor(
|
||||
glfwWindow,
|
||||
glfwGetPrimaryMonitor(),
|
||||
0, 0,
|
||||
vidMode.width(), vidMode.height(),
|
||||
vidMode.refreshRate()
|
||||
);
|
||||
} else {
|
||||
glfwSetWindowMonitor(
|
||||
glfwWindow,
|
||||
NULL,
|
||||
oldXYWH[0], oldXYWH[1],
|
||||
oldXYWH[2], oldXYWH[3],
|
||||
vidMode.refreshRate()
|
||||
);
|
||||
oldXYWH = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isTranslucent() {
|
||||
ensureOpen();
|
||||
return glfwGetWindowAttrib(glfwWindow, GLFW_TRANSPARENT_FRAMEBUFFER) == GLFW_TRUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!closed) {
|
||||
glfwDestroyWindow(glfwWindow);
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureOpen() {
|
||||
if (closed) {
|
||||
throw new IllegalStateException("Window closed");
|
||||
}
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl;
|
||||
|
||||
import it.unimi.dsi.fastutil.objects.ObjectIntPair;
|
||||
import lombok.Getter;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import lombok.experimental.NonFinal;
|
||||
import org.lwjgl.PointerBuffer;
|
||||
import org.lwjgl.vulkan.*;
|
||||
import ru.fokinatorr.sparkle.context.AppContext;
|
||||
import ru.fokinatorr.sparkle.graphics.render.RenderingContext;
|
||||
import ru.fokinatorr.sparkle.graphics.render.renderer.RendererRegistry;
|
||||
import ru.fokinatorr.sparkle.graphics.render.surface.RenderingSurface;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import static lombok.AccessLevel.*;
|
||||
import static org.lwjgl.system.MemoryStack.stackPush;
|
||||
import static org.lwjgl.vulkan.VK14.*;
|
||||
|
||||
/**
|
||||
* A Vulkan rendering context.
|
||||
*/
|
||||
@FieldDefaults(makeFinal = true, level = PROTECTED)
|
||||
@Getter
|
||||
public abstract class AbstractVKContext implements RenderingContext {
|
||||
AppContext context;
|
||||
RenderingSurface surface;
|
||||
Stage stage;
|
||||
VKRenderCanvas canvas;
|
||||
@NonFinal
|
||||
@Getter(NONE)
|
||||
boolean closed;
|
||||
|
||||
// Vulkan handles
|
||||
VkDevice vkDevice;
|
||||
VkQueue vkQ;
|
||||
|
||||
protected AbstractVKContext(
|
||||
AppContext context,
|
||||
RenderingSurface surface,
|
||||
Stage stage,
|
||||
VkDevice vkDevice, int qFamilyIndex
|
||||
) {
|
||||
this.context = Objects.requireNonNull(context, "context");
|
||||
this.surface = Objects.requireNonNull(surface, "surface");
|
||||
this.stage = Objects.requireNonNull(stage, "stage");
|
||||
this.vkDevice = Objects.requireNonNull(vkDevice, "VkDevice");
|
||||
|
||||
try (var stack = stackPush()) {
|
||||
// <editor-fold desc="Create graphics queue" defaultstate="collapsed">
|
||||
PointerBuffer qPtrBuf = stack.callocPointer(1); // NULL by default
|
||||
vkGetDeviceQueue(vkDevice, qFamilyIndex, 0, qPtrBuf);
|
||||
this.vkQ = new VkQueue(qPtrBuf.get(0), vkDevice);
|
||||
// </editor-fold>
|
||||
this.canvas = createCanvas();
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract VKRenderCanvas createCanvas();
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!closed) {
|
||||
canvas.close();
|
||||
surface.close();
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
protected void ensureOpen() {
|
||||
if (closed) {
|
||||
throw new IllegalStateException("This context is closed");
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
protected void renderStage(boolean renderControlBar) {
|
||||
RendererRegistry registry = context.get(RendererRegistry.class);
|
||||
for (ObjectIntPair<String> spriteId : stage.getSpriteLayers()) {
|
||||
Object renderable = stage.getSprite(spriteId.left(), spriteId.rightInt()); // TODO allow Stage to store not only sprites
|
||||
registry.get((Class<Object>) renderable.getClass()).render(renderable, canvas);
|
||||
}
|
||||
if (renderControlBar) {
|
||||
// TODO render stage's control bar
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl;
|
||||
|
||||
import org.lwjgl.vulkan.VkDevice;
|
||||
import ru.fokinatorr.sparkle.context.AppContext;
|
||||
import ru.fokinatorr.sparkle.graphics.render.surface.EmbeddedSurface;
|
||||
import ru.fokinatorr.sparkle.graphics.render.surface.RenderingSurface;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
|
||||
/**
|
||||
* A VK context for embedded surfaces.
|
||||
*/
|
||||
public class VKEmbeddedContext extends AbstractVKContext {
|
||||
protected VKEmbeddedContext(AppContext context, EmbeddedSurface surface, Stage stage, VkDevice vkDevice, int qFamilyIndex) {
|
||||
super(context, surface, stage, vkDevice, qFamilyIndex);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected VKRenderCanvas createCanvas() {
|
||||
// TODO
|
||||
}
|
||||
|
||||
@Override
|
||||
public void present() {
|
||||
ensureOpen();
|
||||
|
||||
EmbeddedSurface s = getSurface();
|
||||
var fb = s.acquireBuffer();
|
||||
canvas.attachTarget(fb);
|
||||
renderStage(true);
|
||||
canvas.flush();
|
||||
s.present(fb);
|
||||
}
|
||||
|
||||
@Override
|
||||
public EmbeddedSurface getSurface() {
|
||||
return (EmbeddedSurface) surface;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl;
|
||||
|
||||
import ru.fokinatorr.sparkle.graphics.render.RenderCanvas;
|
||||
import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer;
|
||||
|
||||
public class VKRenderCanvas implements RenderCanvas {
|
||||
// TODO everything
|
||||
// TODO below methods are stubs
|
||||
|
||||
public void attachTarget(Framebuffer frameBuffer) {
|
||||
|
||||
}
|
||||
|
||||
public void flush() {
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+285
@@ -0,0 +1,285 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl;
|
||||
|
||||
import it.unimi.dsi.fastutil.Pair;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectIntImmutablePair;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectIntPair;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.objects.ReferenceReferenceImmutablePair;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import lombok.experimental.NonFinal;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.lwjgl.PointerBuffer;
|
||||
import org.lwjgl.glfw.GLFW;
|
||||
import org.lwjgl.glfw.GLFWErrorCallback;
|
||||
import org.lwjgl.glfw.GLFWVulkan;
|
||||
import org.lwjgl.system.MemoryStack;
|
||||
import org.lwjgl.vulkan.*;
|
||||
import ru.fokinatorr.sparkle.context.AppContext;
|
||||
import ru.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
|
||||
import ru.fokinatorr.sparkle.graphics.GraphicsManager;
|
||||
import ru.fokinatorr.sparkle.graphics.impl.surface.VK_GLFWWindowSurface;
|
||||
import ru.fokinatorr.sparkle.graphics.render.RenderingContext;
|
||||
import ru.fokinatorr.sparkle.graphics.render.surface.EmbeddedSurface;
|
||||
import ru.fokinatorr.sparkle.graphics.render.surface.RenderingSurface;
|
||||
import ru.fokinatorr.sparkle.graphics.render.surface.WindowSurface;
|
||||
import ru.fokinatorr.sparkle.internal.access.SharedSecrets;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
import ru.fokinatorr.sparkle.stage.StageCreator;
|
||||
import ru.fokinatorr.sparkle.util.Version;
|
||||
|
||||
import java.nio.IntBuffer;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.Queue;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static lombok.AccessLevel.PRIVATE;
|
||||
import static org.lwjgl.glfw.GLFW.*;
|
||||
import static org.lwjgl.system.MemoryStack.stackPush;
|
||||
import static org.lwjgl.vulkan.VK14.*;
|
||||
|
||||
/**
|
||||
* A Vulkan + GLFW graphics manager.
|
||||
*/
|
||||
@Slf4j
|
||||
@FieldDefaults(makeFinal = true, level = PRIVATE)
|
||||
public class VK_GLFWGraphicsManager implements GraphicsManager {
|
||||
|
||||
Map<Stage, AbstractVKContext> vkContexts = new Reference2ReferenceOpenHashMap<>();
|
||||
AppContext context;
|
||||
Queue<Runnable> workQueue = new ConcurrentLinkedQueue<>();
|
||||
@NonFinal boolean closed;
|
||||
|
||||
// Vulkan global handles
|
||||
VkInstance vk;
|
||||
VkPhysicalDevice vkPhysDev;
|
||||
VkDevice vkLogDev;
|
||||
int qFamilyIndex;
|
||||
|
||||
/**
|
||||
* <b>Important note</b>: call the constructor and {@link #tick()} methods from the <i>same</i> thread,
|
||||
* because GLFW's main thread is the one that called {@link GLFW#glfwInit() glfwInit()}!
|
||||
*/
|
||||
public VK_GLFWGraphicsManager(AppContext context) {
|
||||
this.context = context;
|
||||
|
||||
// Initialize GLFW
|
||||
GLFWErrorCallback.createPrint(System.err).set();
|
||||
if (!glfwInit()) {
|
||||
throw new IllegalStateException("Failed to initialize GLFW");
|
||||
}
|
||||
if (!GLFWVulkan.glfwVulkanSupported()) {
|
||||
throw new IllegalStateException("Vulkan not supported by GLFW");
|
||||
}
|
||||
glfwDefaultWindowHints();
|
||||
// Critical: no OpenGL context — Vulkan manages rendering
|
||||
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
|
||||
|
||||
// Init global VK handles
|
||||
try (var stack = stackPush()) {
|
||||
this.vk = createVkInstance(stack);
|
||||
var physDevAndQFamilyIdx = pickVkPhysicalDevice(stack);
|
||||
this.vkPhysDev = physDevAndQFamilyIdx.left();
|
||||
this.qFamilyIndex = physDevAndQFamilyIdx.rightInt();
|
||||
this.vkLogDev = createVkLogicalDevice(stack);
|
||||
}
|
||||
// Most VK initialization done in VKContexts
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick() {
|
||||
ensureOpen();
|
||||
runTasks();
|
||||
for (AbstractVKContext vkContext : vkContexts.values()) {
|
||||
vkContext.pollEvents();
|
||||
vkContext.present();
|
||||
if (vkContext.shouldClose()) {
|
||||
vkContext.getStage().stop().thenRun(() -> {
|
||||
// close and remove the context
|
||||
vkContext.close();
|
||||
vkContexts.remove(vkContext.getStage());
|
||||
});
|
||||
}
|
||||
// TODO
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!closed) {
|
||||
vkContexts.values().forEach(AbstractVKContext::close);
|
||||
vkContexts.clear();
|
||||
vkDestroyDevice(vkLogDev, null);
|
||||
vkDestroyInstance(vk, null);
|
||||
glfwTerminate();
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Pair<Stage, RenderingContext> createWindowContext(String title, StageCreator stageCreator,
|
||||
boolean translucent, boolean fullscreen) {
|
||||
ensureOpen();
|
||||
Stage stage = SharedSecrets.getStageAccess().newStage(stageCreator, context);
|
||||
VK_GLFWWindowSurface window = fullscreen
|
||||
? VK_GLFWWindowSurface.createFullscreen(title, glfwGetPrimaryMonitor(), context.get(EventDispatcher.class), stage, translucent)
|
||||
: VK_GLFWWindowSurface.create(title, context.get(EventDispatcher.class), stage, translucent);
|
||||
return createAndPutWindowContext(window, stage);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Pair<Stage, RenderingContext> createContext(RenderingSurface surface, StageCreator stageCreator) {
|
||||
ensureOpen();
|
||||
if (surface instanceof WindowSurface) {
|
||||
if (surface instanceof VK_GLFWWindowSurface glfw) {
|
||||
return createAndPutWindowContext(glfw, SharedSecrets.getStageAccess().newStage(stageCreator, context));
|
||||
} else {
|
||||
throw new UnsupportedOperationException("Unsupported window surface: " + surface.getClass());
|
||||
}
|
||||
} else if (!(surface instanceof EmbeddedSurface embedded)) {
|
||||
throw new UnsupportedOperationException("Unsupported rendering surface: " + surface.getClass());
|
||||
} else {
|
||||
return createAndPutEmbeddedContext(embedded, SharedSecrets.getStageAccess().newStage(stageCreator, context));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractVKContext getContext(Stage boundStage) {
|
||||
ensureOpen();
|
||||
return vkContexts.get(Objects.requireNonNull(boundStage, "bound stage"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasActiveContexts() {
|
||||
return !(closed || vkContexts.isEmpty());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void runLater(Runnable run) {
|
||||
Objects.requireNonNull(run, "run");
|
||||
if (!workQueue.offer(run)) {
|
||||
throw new IllegalStateException("Work queue overflow");
|
||||
}
|
||||
}
|
||||
|
||||
// Private implementation
|
||||
|
||||
private void runTasks() {
|
||||
Runnable task;
|
||||
while ((task = workQueue.poll()) != null) {
|
||||
try {
|
||||
task.run();
|
||||
} catch (Exception e) {
|
||||
log.error("Exception in graphics task", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureOpen() {
|
||||
if (closed) {
|
||||
throw new IllegalStateException("Graphics manager already closed");
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized Pair<Stage, RenderingContext> createAndPutEmbeddedContext(EmbeddedSurface surface, Stage stage) {
|
||||
AbstractVKContext vkContext = new VKEmbeddedContext(context, surface, stage, vkLogDev, qFamilyIndex);
|
||||
vkContexts.put(stage, vkContext);
|
||||
return new ReferenceReferenceImmutablePair<>(stage, vkContext);
|
||||
}
|
||||
|
||||
private synchronized Pair<Stage, RenderingContext> createAndPutWindowContext(VK_GLFWWindowSurface surface, Stage stage) {
|
||||
AbstractVKContext vkContext = null; // TODO
|
||||
vkContexts.put(stage, vkContext);
|
||||
return new ReferenceReferenceImmutablePair<>(stage, vkContext);
|
||||
}
|
||||
|
||||
|
||||
private static int getVkVersion(Version version) {
|
||||
return VK_MAKE_VERSION(version.getMajor(), version.getMinor(), version.getPatch());
|
||||
}
|
||||
|
||||
private VkInstance createVkInstance(MemoryStack stack) {
|
||||
VkApplicationInfo appInfo = VkApplicationInfo.calloc(stack)
|
||||
.sType(VK_STRUCTURE_TYPE_APPLICATION_INFO)
|
||||
.pApplicationName(stack.ASCII("SparkleApp"))
|
||||
.applicationVersion(getVkVersion(Version.current()))
|
||||
.apiVersion(VK_API_VERSION_1_4);
|
||||
|
||||
VkInstanceCreateInfo createInfo = VkInstanceCreateInfo.calloc(stack)
|
||||
.sType(VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO)
|
||||
.pApplicationInfo(appInfo)
|
||||
.flags(0)
|
||||
.ppEnabledExtensionNames(GLFWVulkan.glfwGetRequiredInstanceExtensions());
|
||||
|
||||
PointerBuffer instancePtrBuf = stack.mallocPointer(1);
|
||||
int resultCode = vkCreateInstance(createInfo, null, instancePtrBuf);
|
||||
|
||||
if (resultCode != VK_SUCCESS) {
|
||||
throw new IllegalStateException("Failed to initialize Vulkan (error code " + resultCode + ")");
|
||||
}
|
||||
|
||||
return new VkInstance(instancePtrBuf.get(), createInfo);
|
||||
}
|
||||
|
||||
private ObjectIntPair<VkPhysicalDevice> pickVkPhysicalDevice(MemoryStack stack) {
|
||||
IntBuffer deviceCount = stack.mallocInt(1);
|
||||
vkEnumeratePhysicalDevices(vk, deviceCount, null);
|
||||
if (deviceCount.get(0) <= 0) {
|
||||
throw new IllegalStateException("VK error: No suitable GPUs found");
|
||||
}
|
||||
|
||||
PointerBuffer physDevices = stack.mallocPointer(deviceCount.get(0));
|
||||
vkEnumeratePhysicalDevices(vk, deviceCount, physDevices);
|
||||
physDevices.rewind();
|
||||
VkPhysicalDevice physDevice = null;
|
||||
int qFamilyIndex = -1;
|
||||
while (physDevices.hasRemaining()) {
|
||||
// Basically, we're looking for a physical device whose queues support graphics.
|
||||
// Shouldn't all GPUs have it? Their second name is "graphics card" after all :P
|
||||
VkPhysicalDevice pdHandle = new VkPhysicalDevice(physDevices.get(), vk);
|
||||
|
||||
IntBuffer qFamilyPropsCount = stack.callocInt(1);
|
||||
vkGetPhysicalDeviceQueueFamilyProperties(pdHandle, qFamilyPropsCount, null);
|
||||
VkQueueFamilyProperties.Buffer qFamilyPropsBuff = VkQueueFamilyProperties.malloc(qFamilyPropsCount.get(0), stack);
|
||||
vkGetPhysicalDeviceQueueFamilyProperties(pdHandle, qFamilyPropsCount, qFamilyPropsBuff);
|
||||
|
||||
OptionalInt qFamilyIndexOpt = IntStream.range(0, qFamilyPropsBuff.capacity())
|
||||
.filter(idx -> (qFamilyPropsBuff.get(idx).queueFlags() & VK_QUEUE_GRAPHICS_BIT) != 0)
|
||||
.findFirst();
|
||||
|
||||
if (qFamilyIndexOpt.isPresent()) {
|
||||
physDevice = pdHandle;
|
||||
qFamilyIndex = qFamilyIndexOpt.getAsInt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (physDevice == null) {
|
||||
throw new IllegalStateException("VK error: Couldn't find GPU with graphics queue support");
|
||||
}
|
||||
return new ObjectIntImmutablePair<>(physDevice, qFamilyIndex);
|
||||
}
|
||||
|
||||
private VkDevice createVkLogicalDevice(MemoryStack stack) {
|
||||
VkDeviceQueueCreateInfo.Buffer qCreateInfos = VkDeviceQueueCreateInfo.calloc(1, stack)
|
||||
.sType(VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO)
|
||||
.queueFamilyIndex(qFamilyIndex)
|
||||
.pQueuePriorities(stack.callocFloat(1).put(0, 1f));
|
||||
|
||||
VkPhysicalDeviceFeatures physDeviceFeatures = VkPhysicalDeviceFeatures.calloc(stack);
|
||||
vkGetPhysicalDeviceFeatures(vkPhysDev, physDeviceFeatures);
|
||||
|
||||
VkDeviceCreateInfo logDeviceCreateInfo = VkDeviceCreateInfo.calloc(stack)
|
||||
.sType(VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO)
|
||||
.pQueueCreateInfos(qCreateInfos)
|
||||
.pEnabledFeatures(physDeviceFeatures);
|
||||
|
||||
PointerBuffer logDevicePtrBuf = stack.callocPointer(1); // NULL by default because using calloc
|
||||
int resultCode = vkCreateDevice(vkPhysDev, logDeviceCreateInfo, null, logDevicePtrBuf);
|
||||
if (resultCode != VK_SUCCESS) {
|
||||
throw new IllegalStateException("VK error: Failed to create logical device (error code " + resultCode + ")");
|
||||
}
|
||||
return new VkDevice(logDevicePtrBuf.get(0), vkPhysDev, logDeviceCreateInfo);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* The core module of Project Sparkle, where base API and implementation resides.
|
||||
* <p>This module is always required to use the Sparkle framework. You can optionally connect other Sparkle modules
|
||||
* for additional functionality.
|
||||
*/
|
||||
module ru.fokinatorr.sparkle.core {
|
||||
requires it.unimi.dsi.fastutil;
|
||||
requires static lombok;
|
||||
requires org.slf4j;
|
||||
requires java.desktop;
|
||||
requires org.lwjgl;
|
||||
requires org.lwjgl.glfw;
|
||||
requires org.lwjgl.openal;
|
||||
requires org.lwjgl.opengl;
|
||||
requires org.lwjgl.nanovg;
|
||||
requires org.lwjgl.stb;
|
||||
requires ru.fokinatorr.lwjgl.util.exceptions;
|
||||
requires java.compiler;
|
||||
requires java.management;
|
||||
requires org.joml;
|
||||
requires com.google.j2objc.annotations;
|
||||
requires org.checkerframework.checker.qual;
|
||||
|
||||
exports ru.fokinatorr.sparkle.assets;
|
||||
exports ru.fokinatorr.sparkle.audio;
|
||||
exports ru.fokinatorr.sparkle.audio.io;
|
||||
exports ru.fokinatorr.sparkle.context;
|
||||
exports ru.fokinatorr.sparkle.effect;
|
||||
exports ru.fokinatorr.sparkle.effect.graphics;
|
||||
exports ru.fokinatorr.sparkle.effect.sounds;
|
||||
exports ru.fokinatorr.sparkle.event;
|
||||
exports ru.fokinatorr.sparkle.event.annotation;
|
||||
exports ru.fokinatorr.sparkle.event.dispatcher;
|
||||
exports ru.fokinatorr.sparkle.event.input;
|
||||
exports ru.fokinatorr.sparkle.event.lifecycle;
|
||||
exports ru.fokinatorr.sparkle.graphics;
|
||||
exports ru.fokinatorr.sparkle.graphics.font;
|
||||
exports ru.fokinatorr.sparkle.graphics.image;
|
||||
exports ru.fokinatorr.sparkle.graphics.io;
|
||||
exports ru.fokinatorr.sparkle.graphics.render;
|
||||
exports ru.fokinatorr.sparkle.graphics.render.framebuffer;
|
||||
exports ru.fokinatorr.sparkle.graphics.render.surface;
|
||||
exports ru.fokinatorr.sparkle.graphics.render.renderer;
|
||||
exports ru.fokinatorr.sparkle.graphics.vector;
|
||||
exports ru.fokinatorr.sparkle.phys2d;
|
||||
exports ru.fokinatorr.sparkle.stage;
|
||||
exports ru.fokinatorr.sparkle.stage.sprite;
|
||||
exports ru.fokinatorr.sparkle.util;
|
||||
exports ru.fokinatorr.sparkle.util.stopwatch;
|
||||
exports ru.fokinatorr.sparkle.util.concurrent;
|
||||
exports ru.fokinatorr.sparkle.util.concurrent.atomic;
|
||||
exports ru.fokinatorr.sparkle.variable;
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package ru.fokinatorr.sparkle.assets;
|
||||
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntFunction;
|
||||
import ru.fokinatorr.sparkle.util.Constants;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.util.function.Predicate.not;
|
||||
|
||||
/**
|
||||
* A set of assets (textures and sounds) with names. Can be queried by name and index.
|
||||
* <p><i>Note for Scratchers: The indexes, unlike in Scratch, are starting from {@code 0} and <b>NOT</b> {@code 1}.
|
||||
* Also, this interface is used both by stages and sprites, so the respective asset names (<b>costumes</b>
|
||||
* for sprites, <b>backdrops</b> for stages) are unified under the term "textures".</i>
|
||||
* @see Constants#ROOT
|
||||
*/
|
||||
public interface Assets {
|
||||
|
||||
/**
|
||||
* Returns an immutable list of textures.
|
||||
*
|
||||
* @return textures to query by index
|
||||
*/
|
||||
List<NamedAsset> texturesByIndex();
|
||||
|
||||
/**
|
||||
* Returns a function that maps texture names to texture indexes,
|
||||
* and returns value less than {@code 0} for absent names.
|
||||
* @return indexes to query by name
|
||||
*/
|
||||
Object2IntFunction<String> texturesIndexesByName();
|
||||
|
||||
/**
|
||||
* Returns an immutable list of sounds.
|
||||
*
|
||||
* @return sounds to query by index
|
||||
*/
|
||||
List<NamedAsset> soundsByIndex();
|
||||
|
||||
/**
|
||||
* Returns a function that maps sound names to sound indexes,
|
||||
* and returns value less than {@code 0} for absent names.
|
||||
* @return sound indexes to query by name
|
||||
*/
|
||||
Object2IntFunction<String> soundsIndexesByName();
|
||||
|
||||
/**
|
||||
* An asset pointer with a name.
|
||||
*
|
||||
* @param name the asset name
|
||||
* @param location the location of the asset
|
||||
*/
|
||||
record NamedAsset(String name, Path location) {}
|
||||
|
||||
/**
|
||||
* Creates and returns a {@code Assets} instance with contents of the given lists.
|
||||
*
|
||||
* @param textures the texture list
|
||||
* @param sounds the sound list
|
||||
* @return a new {@code Assets}
|
||||
* @throws NullPointerException if one of the elements is {@code null}
|
||||
* @throws IllegalArgumentException if there was a duplicate texture/sound name
|
||||
*/
|
||||
static Assets fromLoaded(List<? extends NamedAsset> textures, List<? extends NamedAsset> sounds) {
|
||||
return new DefaultAssets(textures, sounds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and returns a {@code Assets} instance with resolved assets from the given textures and sounds directories.
|
||||
* The name of each asset will be the same as the file name, but without the last filename extension.
|
||||
* <p>Note: files will only be read directly from the given directories, not recursively. The order of assets will be undefined.
|
||||
* <p><i>Special handling for empty textures' directory: there will be only one empty SVG texture.</i>
|
||||
*
|
||||
* @param texturesDir path to the textures directory
|
||||
* @param soundsDir path to the sounds directory
|
||||
* @return a new resolved {@code Assets}
|
||||
* @throws IllegalArgumentException if one of the given paths does not locate a directory
|
||||
* @throws NullPointerException if one of the paths is {@code null}
|
||||
* @throws UncheckedIOException if one of the directories could not be opened
|
||||
*/
|
||||
static Assets resolve(Path texturesDir, Path soundsDir) {
|
||||
checkIfDirectory(Objects.requireNonNull(texturesDir, "textures path"));
|
||||
checkIfDirectory(Objects.requireNonNull(soundsDir, "sounds path"));
|
||||
List<NamedAsset> texturesList, soundsList;
|
||||
try (Stream<Path> textures = Files.list(texturesDir);
|
||||
Stream<Path> sounds = Files.list(soundsDir)) {
|
||||
texturesList = createAssets(textures);
|
||||
soundsList = createAssets(sounds);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
return fromLoaded(texturesList, soundsList);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an empty assets instance (one empty texture named {@code default} and no sounds).
|
||||
* @return empty assets
|
||||
*/
|
||||
static Assets empty() {
|
||||
return DefaultAssets.EMPTY_ASSETS;
|
||||
}
|
||||
|
||||
private static void checkIfDirectory(Path path) {
|
||||
if (!Files.isDirectory(path)) {
|
||||
throw new IllegalArgumentException("Not a directory: " + path.normalize());
|
||||
}
|
||||
}
|
||||
|
||||
private static List<NamedAsset> createAssets(Stream<Path> fromPaths) {
|
||||
return fromPaths.filter(not(Files::isDirectory))
|
||||
.map(path -> {
|
||||
String fileName = path.getFileName().toString();
|
||||
int lastDotIndex = fileName.lastIndexOf('.');
|
||||
String name = lastDotIndex > 0
|
||||
? fileName.substring(0, lastDotIndex)
|
||||
: fileName; // no extension
|
||||
return new NamedAsset(name, path);
|
||||
})
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package ru.fokinatorr.sparkle.assets;
|
||||
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntMap;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntMaps;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import static ru.fokinatorr.sparkle.util.Constants.ROOT;
|
||||
|
||||
/**
|
||||
* Default implementation of {@link Assets}.
|
||||
*/
|
||||
record DefaultAssets(
|
||||
List<NamedAsset> texturesByIndex,
|
||||
Object2IntMap<String> texturesIndexesByName,
|
||||
List<NamedAsset> soundsByIndex,
|
||||
Object2IntMap<String> soundsIndexesByName
|
||||
) implements Assets {
|
||||
|
||||
DefaultAssets {
|
||||
if (texturesByIndex.isEmpty()) {
|
||||
texturesByIndex = List.of(EMPTY_TEXTURE);
|
||||
texturesIndexesByName = Object2IntMaps.singleton(EMPTY_NAME, 0);
|
||||
}
|
||||
}
|
||||
|
||||
static final String EMPTY_NAME = "default";
|
||||
static final NamedAsset EMPTY_TEXTURE = new NamedAsset(EMPTY_NAME, ROOT.resolve("assets/textures/empty.svg"));
|
||||
static final DefaultAssets EMPTY_ASSETS = new DefaultAssets(
|
||||
List.of(EMPTY_TEXTURE),
|
||||
Object2IntMaps.singleton(EMPTY_NAME, 0),
|
||||
List.of(),
|
||||
Object2IntMaps.emptyMap()
|
||||
);
|
||||
|
||||
DefaultAssets(List<? extends NamedAsset> costumes, List<? extends NamedAsset> sounds) {
|
||||
Objects.requireNonNull(costumes, "Costumes list cannot be null");
|
||||
Objects.requireNonNull(sounds, "Sounds list cannot be null");
|
||||
this(costumes.isEmpty() ? List.of() : List.copyOf(costumes), mapNamesToIndexes(costumes),
|
||||
List.copyOf(sounds), mapNamesToIndexes(sounds));
|
||||
}
|
||||
|
||||
private static Object2IntMap<String> mapNamesToIndexes(List<? extends NamedAsset> assets) {
|
||||
Object2IntMap<String> map = new Object2IntOpenHashMap<>(assets.size());
|
||||
map.defaultReturnValue(-1);
|
||||
for (int i = 0; i < assets.size(); i++) {
|
||||
NamedAsset asset = assets.get(i);
|
||||
if (map.put(asset.name(), i) >= 0) {
|
||||
throw new IllegalArgumentException("Duplicate asset name: " + asset.name());
|
||||
}
|
||||
}
|
||||
// Return immutable map
|
||||
return Object2IntMaps.unmodifiable(map);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package ru.fokinatorr.sparkle.audio;
|
||||
|
||||
import it.unimi.dsi.fastutil.Pair;
|
||||
import ru.fokinatorr.sparkle.audio.io.SoundDecoder;
|
||||
import ru.fokinatorr.sparkle.stage.sprite.Sprite;
|
||||
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* An audio manager is responsible for sound loading and managing {@link SoundInstance sound instances}.
|
||||
* <p><i>Note: Do not manually close sound instance objects returned by an audio manager. Instead, use
|
||||
* the </i><b>{@link #destroySoundInstance(String)}</b><i> method for proper cleanup.</i>
|
||||
*/
|
||||
public interface AudioManager extends NonThrowingAutoCloseable {
|
||||
|
||||
/**
|
||||
* Loads a sound from file at the given path. If a sound is already loaded at the given path, it is closed, removed and replaced with a new one.
|
||||
* The sprite/stage assets are loaded automatically, so there's usually no need to call this method manually.
|
||||
* <p><b>See {@link SoundDecoder} for supported formats list.</b>
|
||||
*
|
||||
* @param path the path to the sound file
|
||||
* @throws IOException if something goes wrong during loading, or if the file format isn't recognized
|
||||
* @see #loadSounds(Path...)
|
||||
* @see #loadSounds(Iterable)
|
||||
* @see SoundDecoder
|
||||
*/
|
||||
void loadSound(Path path) throws IOException;
|
||||
|
||||
/**
|
||||
* Array bulk version of {@link #loadSound(Path)}.
|
||||
* The sprite/stage assets are loaded automatically, so there's usually no need to call this method manually.
|
||||
*
|
||||
* @param paths the paths to sound files
|
||||
* @throws IOException if something goes wrong during loading, or if the file format isn't recognized
|
||||
* @implNote By default, if loading of a sound file fails, this method will continue loading other files
|
||||
* and then throw the exception. If multiple sound files fail to load, their exceptions will get suppressed into one.
|
||||
* @see #loadSound(Path)
|
||||
*/
|
||||
default void loadSounds(Path... paths) throws IOException {
|
||||
IOException ex = null;
|
||||
for (Path path : paths) {
|
||||
try {
|
||||
loadSound(path);
|
||||
} catch (IOException e) {
|
||||
if (ex == null) {
|
||||
ex = e;
|
||||
} else {
|
||||
ex.addSuppressed(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ex != null) {
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link Iterable} bulk version of {@link #loadSound(Path)}.
|
||||
* The sprite/stage assets are loaded automatically, so there's usually no need to call this method manually.
|
||||
*
|
||||
* @param paths the paths to sound files
|
||||
* @throws IOException if something goes wrong during loading, or if the file format isn't recognized
|
||||
* @implNote By default, if loading of a sound file fails, this method will continue loading other files
|
||||
* and then throw the exception. If multiple sound files fail to load, their exceptions will get suppressed into one.
|
||||
* @see #loadSound(Path)
|
||||
*/
|
||||
default void loadSounds(Iterable<? extends Path> paths) throws IOException {
|
||||
IOException ex = null;
|
||||
for (Path path : paths) {
|
||||
try {
|
||||
loadSound(path);
|
||||
} catch (IOException e) {
|
||||
if (ex == null) {
|
||||
ex = e;
|
||||
} else {
|
||||
ex.addSuppressed(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ex != null) {
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether a sound is already loaded from file at the given path. This can be useful
|
||||
* to prevent unnecessary sound reloading.
|
||||
* This is always true for sprite/stage assets since they're loaded automatically.
|
||||
* @param path the file path
|
||||
* @return {@code true} if a sound from file at the given path is already loaded by this manager, {@code false}
|
||||
* otherwise.
|
||||
*/
|
||||
boolean hasLoadedSound(Path path);
|
||||
|
||||
/**
|
||||
* Creates a new sound instance from the loaded sound at the given path.
|
||||
* <p>This is ideal for short sounds like sound effects or UI feedback that should load quickly and play immediately.
|
||||
* <p>A sound must be loaded at the given path using {@link #loadSound(Path)} before calling this method. (For sprite/stage assets,
|
||||
* this is done automatically.)
|
||||
* <p><i>Note for Scratchers: "Static" sound instances are similar to how all sounds work in Scratch.
|
||||
* The sound is fully loaded into memory, so it starts playing instantly and can be played multiple times efficiently.
|
||||
* <p>To play a sound just like it's done in Scratch (from a sprite's assets, one-shot), it's better
|
||||
* to use the {@code startSound(...)} methods of {@link Sprite}. They handle the sound instance's lifecycle automatically.</i>
|
||||
*
|
||||
* @param filePath the path to the (already loaded!) sound file
|
||||
* @return a {@link Pair} containing:
|
||||
* <ul>
|
||||
* <li><b>Key:</b> The unique ID of the new sound instance</li>
|
||||
* <li><b>Value:</b> The sound instance itself, ready to play</li>
|
||||
* </ul>
|
||||
* @throws IllegalArgumentException if no sound is loaded at the given path
|
||||
* @throws IllegalStateException if this audio manager is closed
|
||||
*/
|
||||
Pair<String, ? extends SoundInstance<?>> createStaticSoundInstance(Path filePath);
|
||||
|
||||
/**
|
||||
* Creates a new "streaming" sound instance from the loaded sound at the given path.
|
||||
* <p>Streaming sound instances are dynamic; they don't store their data all at once but instead request chunks on demand.
|
||||
* This works well with long ambient music tracks, since they don't get loaded entirely immediately, which would cause lags.
|
||||
* <p>A sound must be loaded at the given path using {@link #loadSound(Path)} before calling this method. (For sprite/stage assets,
|
||||
* this is done automatically.)
|
||||
* <p><i>Note for Scratchers: This is different from how sounds work in Scratch. In Scratch, all sounds are loaded fully before playing.
|
||||
* Here, streaming allows very long sounds (like background music) to play without delay and with low memory usage.
|
||||
* Use this for tracks longer than ~30 seconds.</i>
|
||||
*
|
||||
* @param filePath the path to the (already loaded!) sound file
|
||||
* @param loop whether the sound instance must loop
|
||||
* @return a {@link Pair} containing:
|
||||
* <ul>
|
||||
* <li><b>Key:</b> The unique ID of the new sound instance</li>
|
||||
* <li><b>Value:</b> The sound instance itself, ready to play</li>
|
||||
* </ul>
|
||||
* @throws IllegalArgumentException if no sound is loaded at the given path
|
||||
* @throws IllegalStateException if this audio manager is closed
|
||||
*/
|
||||
Pair<String, ? extends SoundInstance<?>> createStreamingSoundInstance(Path filePath, boolean loop);
|
||||
|
||||
/**
|
||||
* Returns a sound source by the given ID, if any, otherwise returns {@code null}.
|
||||
*
|
||||
* @param id the ID
|
||||
* @return the respective sound source or {@code null}
|
||||
* @throws IllegalStateException if the audio manager is closed
|
||||
*/
|
||||
SoundInstance<?> getSoundInstance(String id);
|
||||
|
||||
/**
|
||||
* If a sound source with the given ID exists, stops, closes and removes it, otherwise does nothing.
|
||||
*
|
||||
* @param id the ID
|
||||
* @throws IllegalStateException if the audio manager is closed
|
||||
*/
|
||||
void destroySoundInstance(String id);
|
||||
|
||||
/**
|
||||
* Advances the audio manager by one tick. This method is called regularly from the audio loop, no
|
||||
* need to call in manually in your code.
|
||||
*
|
||||
* @throws IllegalStateException if the audio manager is closed
|
||||
*/
|
||||
void tick();
|
||||
|
||||
/**
|
||||
* Destroys this audio manager. The manager can not be used after call to this method.
|
||||
* Calling this method more than once does not have any effect.
|
||||
*/
|
||||
@Override
|
||||
void close();
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package ru.fokinatorr.sparkle.audio;
|
||||
|
||||
import ru.fokinatorr.sparkle.effect.EffectMap;
|
||||
import ru.fokinatorr.sparkle.effect.sounds.SoundEffect;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* A playable sound instance. It has a {@link State state} and may have {@link SoundEffect sound effects}.
|
||||
* <p><i>This interface is implemented by the internal APIs, which expect a concrete implementation,
|
||||
* and thus this interface must not be implemented directly or indirectly by other classes.</i>
|
||||
* @param <SELF> the type of this sound instance
|
||||
*/
|
||||
public interface SoundInstance<SELF extends SoundInstance<SELF>> {
|
||||
|
||||
// Sound state
|
||||
|
||||
/**
|
||||
* A state of a sound instance.
|
||||
*/
|
||||
enum State {
|
||||
/**
|
||||
* The initial state. The sound position is at the beginning, and the sound is not playing.
|
||||
* This state does not guarantee that the sound was never played yet.
|
||||
*/
|
||||
INITIAL,
|
||||
/**
|
||||
* The playing state. The sound is currently playing.
|
||||
*/
|
||||
PLAYING,
|
||||
/**
|
||||
* The paused state. The sound position is at where the sound was paused, and the sound is not playing.
|
||||
* Changing from this state to playing state will resume the sound.
|
||||
*/
|
||||
PAUSED,
|
||||
/**
|
||||
* The stopped state. The sound position is at the beginning, and the sound is not playing.
|
||||
* This state guarantees that the sound has already been played at least once.
|
||||
*/
|
||||
STOPPED
|
||||
}
|
||||
|
||||
/**
|
||||
* If this sound is stopped, firstly {@link #rewind() rewinds} it, then plays.
|
||||
* Otherwise, if it is already playing, does nothing, otherwise plays it.
|
||||
*/
|
||||
void play();
|
||||
|
||||
/**
|
||||
* If this sound is playing, pauses it, otherwise does nothing.
|
||||
*/
|
||||
void pause();
|
||||
|
||||
/**
|
||||
* If this sound is in initial state or stopped, does nothing, otherwise
|
||||
* stops this sound.
|
||||
*/
|
||||
void stop();
|
||||
|
||||
/**
|
||||
* If the state of this sound is already initial, does nothing. If this sound
|
||||
* is playing or paused, firstly {@link #stop() stops} it, then rewinds it and sets the state to initial.
|
||||
* If this sound is stopped, just sets the state to initial.
|
||||
*/
|
||||
void rewind();
|
||||
|
||||
/**
|
||||
* Calls one of the state changing methods depending on the given state enum.
|
||||
* <ul>
|
||||
* <li>If the given state is {@link State#PLAYING}, calls {@link #play()} on this sound;</li>
|
||||
* <li>For {@link State#PAUSED}, calls {@link #pause()};</li>
|
||||
* <li>For {@link State#STOPPED}, calls {@link #stop()};</li>
|
||||
* <li>For {@link State#INITIAL}, calls {@link #rewind()}.</li>
|
||||
* </ul>
|
||||
* @param newState the new state
|
||||
* @return the actual current state after calling the corresponding method
|
||||
* @throws NullPointerException if the state is {@code null}
|
||||
*/
|
||||
default State setState(State newState) {
|
||||
switch (Objects.requireNonNull(newState)) {
|
||||
case PLAYING -> play();
|
||||
case PAUSED -> pause();
|
||||
case STOPPED -> stop();
|
||||
case INITIAL -> rewind();
|
||||
}
|
||||
return getState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current state of this sound.
|
||||
* @return the current state
|
||||
*/
|
||||
State getState();
|
||||
|
||||
|
||||
// Properties
|
||||
|
||||
/**
|
||||
* Sets the given effect to the given value, which is normalized according to the given effect's rules.
|
||||
* @param effect the effect
|
||||
* @param value the new value
|
||||
* @throws NullPointerException if the given sound effect is {@code null}
|
||||
* @return this sound instance
|
||||
*/
|
||||
SELF effect(SoundEffect effect, double value);
|
||||
|
||||
/**
|
||||
* Sets the volume for this sound. The given new volume value is normalized according to the rules of the volume effect.
|
||||
* @param newVolume the new volume
|
||||
* @return this sound instance
|
||||
*/
|
||||
default SELF volume(double newVolume) {
|
||||
return effect(SoundEffect.VOLUME, newVolume);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the pitch for this sound. The given new pitch value is normalized according to the rules of the pitch effect.
|
||||
* @param newPitch the new pitch
|
||||
* @return this sound instance
|
||||
*/
|
||||
default SELF pitch(double newPitch) {
|
||||
return effect(SoundEffect.PITCH, newPitch);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the pan for this sound. The given new pan value is normalized according to the rules of the pan effect.
|
||||
* @param newPan the new pan
|
||||
* @return this sound instance
|
||||
*/
|
||||
default SELF pan(double newPan) {
|
||||
return effect(SoundEffect.PAN, newPan);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the given effect's value for this sound.
|
||||
* @param effect the effect
|
||||
* @return the effect's value
|
||||
* @throws NullPointerException if the effect is {@code null}
|
||||
*/
|
||||
double effect(SoundEffect effect);
|
||||
|
||||
/**
|
||||
* Returns the volume of this sound.
|
||||
* @return the volume
|
||||
*/
|
||||
default double volume() {
|
||||
return effect(SoundEffect.VOLUME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the pitch of this sound.
|
||||
* @return the pitch
|
||||
*/
|
||||
default double pitch() {
|
||||
return effect(SoundEffect.PITCH);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the pan of this sound.
|
||||
* @return the pan
|
||||
*/
|
||||
default double pan() {
|
||||
return effect(SoundEffect.PAN);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the sound effects to this sound.
|
||||
*
|
||||
* @param soundEffects the sound effects to copy
|
||||
* @return this sound instance
|
||||
* @throws NullPointerException if the given sound effect map is {@code null}
|
||||
*/
|
||||
SELF copyPropertiesFrom(EffectMap<? super SoundEffect> soundEffects);
|
||||
|
||||
/**
|
||||
* Attaches the sound effects to this sound. The values from this map will be copied
|
||||
* to this sound constantly.
|
||||
* @param soundEffects the sound effect map to listen to
|
||||
* @return this sound instance
|
||||
* @throws NullPointerException if the given sound effect map is {@code null}
|
||||
*/
|
||||
SELF attachProperties(EffectMap<? super SoundEffect> soundEffects);
|
||||
|
||||
/**
|
||||
* Detaches the sound effects from this sound. The properties of this sound will no longer
|
||||
* be constantly changing after calling this method.
|
||||
*
|
||||
* @return this sound instance
|
||||
*/
|
||||
SELF detachProperties();
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
package ru.fokinatorr.sparkle.audio.impl;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
//import lombok.extern.lwjgl.ALCheckError;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import ru.fokinatorr.sparkle.audio.SoundInstance;
|
||||
import ru.fokinatorr.sparkle.effect.EffectMap;
|
||||
import ru.fokinatorr.sparkle.effect.sounds.SoundEffect;
|
||||
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
|
||||
|
||||
import java.nio.FloatBuffer;
|
||||
import java.util.Objects;
|
||||
|
||||
import static ru.fokinatorr.lwjgl.util.openal.AL10errchk.*;
|
||||
import static org.lwjgl.system.MemoryUtil.memAllocFloat;
|
||||
import static org.lwjgl.system.MemoryUtil.memDuplicate;
|
||||
import static ru.fokinatorr.sparkle.util.BufferUtils.*;
|
||||
|
||||
/**
|
||||
* Base interface for managing OpenAL sound sources.
|
||||
*
|
||||
* @param <SELF> the type of this sound buffer
|
||||
*/
|
||||
@Slf4j
|
||||
@Getter
|
||||
//@ALCheckError
|
||||
public abstract class BaseSoundSource<SELF extends BaseSoundSource<SELF>> implements NonThrowingAutoCloseable, SoundInstance<SELF> {
|
||||
|
||||
/**
|
||||
* The OpenAL source ID.
|
||||
* <p> -- GETTER --
|
||||
* <p> Returns the OpenAL source ID.
|
||||
*
|
||||
* @return the source ID
|
||||
*/
|
||||
@SuppressWarnings("JavadocDeclaration") // @return used by getter
|
||||
protected final int sourceId;
|
||||
/**
|
||||
* The attached sound effect map that will be listened. Ignored if {@code null}.
|
||||
*/
|
||||
protected EffectMap<? super SoundEffect> attachedEffects;
|
||||
|
||||
/**
|
||||
* Constructor for subclasses to call.
|
||||
*/
|
||||
protected BaseSoundSource(int sourceId) {
|
||||
this.sourceId = sourceId;
|
||||
alSourcei(sourceId, AL_SOURCE_RELATIVE, AL_FALSE);
|
||||
alSource3f(sourceId, AL_POSITION, 0.0f, 0.0f, 0.0f);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enum class representing an OpenAL sound source state.
|
||||
*/
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
|
||||
public enum SourceState {
|
||||
INITIAL(AL_INITIAL),
|
||||
PLAYING(AL_PLAYING),
|
||||
PAUSED(AL_PAUSED),
|
||||
STOPPED(AL_STOPPED);
|
||||
|
||||
/**
|
||||
* The corresponding OpenAL source state.
|
||||
*/
|
||||
int openALSourceState;
|
||||
|
||||
/**
|
||||
* Returns a source state corresponding to the given OpenAL source state.
|
||||
*
|
||||
* @param openALSourceState the OpenAL source state
|
||||
* @return the corresponding source state instance
|
||||
* @throws IllegalArgumentException if there is no such source state
|
||||
*/
|
||||
public static SourceState valueOf(int openALSourceState) {
|
||||
return switch (openALSourceState) {
|
||||
case AL_INITIAL -> INITIAL;
|
||||
case AL_PLAYING -> PLAYING;
|
||||
case AL_PAUSED -> PAUSED;
|
||||
case AL_STOPPED -> STOPPED;
|
||||
default -> throw new IllegalArgumentException("Unexpected source state: " + openALSourceState);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts this OpenAL source state to a {@link SoundInstance.State}.
|
||||
* @return the corresponding {@link SoundInstance.State} to this source state
|
||||
*/
|
||||
public SoundInstance.State toPublicAPIState() {
|
||||
return switch (this) {
|
||||
case INITIAL -> SoundInstance.State.INITIAL;
|
||||
case PLAYING -> SoundInstance.State.PLAYING;
|
||||
case PAUSED -> SoundInstance.State.PAUSED;
|
||||
case STOPPED -> SoundInstance.State.STOPPED;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method must return this sound source.
|
||||
*
|
||||
* @return this sound source
|
||||
*/
|
||||
protected abstract SELF self();
|
||||
|
||||
/**
|
||||
* If the state of this source is stopped, firstly sets it to initial, then to playing.
|
||||
* Otherwise, if the state is not already playing, sets it to playing.
|
||||
* <p>If the state was paused, the source is resumed, i.e. starts playing from the
|
||||
* current sampling offset. Otherwise, the source starts playing from the beginning.
|
||||
*/
|
||||
@Override
|
||||
public void play() {
|
||||
// alSourcePlay applied to a stopped sound changes the state
|
||||
// firstly to initial, then to playing, so allow for potential rewind() overrides
|
||||
if (getALState() == SourceState.STOPPED) {
|
||||
rewind();
|
||||
}
|
||||
// alSourcePlay applied to an already playing source will reset
|
||||
// the source's sampling offset, i.e. start playing it from the beginning.
|
||||
// We change that to a NOP to avoid confusion and encourage explicit stopping for that purpose
|
||||
if (getALState() != SourceState.PLAYING) {
|
||||
alSourcePlay(sourceId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If the state of this source is playing, sets it to paused, otherwise does nothing.
|
||||
*/
|
||||
@Override
|
||||
public void pause() {
|
||||
alSourcePause(sourceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* If the state of this source is initial or stopped, does nothing, otherwise
|
||||
* sets the state of this source to stopped.
|
||||
*/
|
||||
@Override
|
||||
public void stop() {
|
||||
alSourceStop(sourceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* If the state of this source is already initial, does nothing. If the state
|
||||
* is playing or paused, firstly {@link #stop() stops} this source, then sets the state
|
||||
* to initial. If the state is stopped, just sets the state to initial.
|
||||
*/
|
||||
@Override
|
||||
public void rewind() {
|
||||
// alSourceRewind applied to a playing or paused sound changes the state
|
||||
// firstly to stopped, then to initial, so allow for potential stop() overrides
|
||||
SourceState alState = getALState();
|
||||
if (alState == SourceState.PAUSED || alState == SourceState.PLAYING) {
|
||||
stop();
|
||||
}
|
||||
alSourceRewind(sourceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the OpenAL source state of this source.
|
||||
* @return the source state
|
||||
*/
|
||||
public SourceState getALState() {
|
||||
return SourceState.valueOf(alGetSourcei(sourceId, AL_SOURCE_STATE));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public SoundInstance.State getState() {
|
||||
return getALState().toPublicAPIState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the pitch for this sound source.
|
||||
*
|
||||
* @param newPitch the new pitch
|
||||
* @return this sound source
|
||||
*/
|
||||
public SELF alPitch(float newPitch) {
|
||||
alSourcef(sourceId, AL_PITCH, newPitch);
|
||||
return self();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the gain for this sound source.
|
||||
*
|
||||
* @param newGain the new gain
|
||||
* @return this sound source
|
||||
*/
|
||||
public SELF alGain(float newGain) {
|
||||
alSourcef(sourceId, AL_GAIN, newGain);
|
||||
return self();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the position for this sound source (relative to the listener's position).
|
||||
*
|
||||
* @param x the X coordinate
|
||||
* @param y the Y coordinate
|
||||
* @param z the Z coordinate
|
||||
* @return this sound source
|
||||
*/
|
||||
public SELF alPosition(float x, float y, float z) {
|
||||
alSource3f(
|
||||
sourceId, AL_POSITION,
|
||||
x, y, z
|
||||
);
|
||||
return self();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @param effect {@inheritDoc}
|
||||
* @param value {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public SELF effect(SoundEffect effect, double value) {
|
||||
Objects.requireNonNull(effect, "sound effect");
|
||||
value = effect.normalize(value);
|
||||
return switch (effect) {
|
||||
case VOLUME -> alGain((float) (value / 100d));
|
||||
case PITCH -> alPitch((float) PitchConversion.toALPitch(value));
|
||||
case PAN -> alPosition((float) (value / 100d), 0f, 0f);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @param effect {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
* @throws NullPointerException {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public double effect(SoundEffect effect) {
|
||||
return switch (Objects.requireNonNull(effect, "sound effect")) {
|
||||
case VOLUME -> alGain() * 100d;
|
||||
case PITCH -> PitchConversion.fromALPitch(alPitch());
|
||||
case PAN -> alPosition()[0] * 100d;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @param soundEffects {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
* @throws NullPointerException {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public SELF copyPropertiesFrom(EffectMap<? super SoundEffect> soundEffects) {
|
||||
Objects.requireNonNull(soundEffects, "sound effects");
|
||||
return alPitch((float) PitchConversion.toALPitch(soundEffects.getDouble(SoundEffect.PITCH)))
|
||||
.alGain((float) (soundEffects.getDouble(SoundEffect.VOLUME) / 100d))
|
||||
.alPosition((float) (soundEffects.getDouble(SoundEffect.PAN) / 100d), 0f, 0f);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @param soundEffects {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
* @throws NullPointerException {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public SELF attachProperties(EffectMap<? super SoundEffect> soundEffects) {
|
||||
this.attachedEffects = Objects.requireNonNull(
|
||||
soundEffects,
|
||||
"Sound effects map cannot be null"
|
||||
);
|
||||
return self();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public SELF detachProperties() {
|
||||
this.attachedEffects = null;
|
||||
return self();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the pitch of this sound source}
|
||||
*/
|
||||
public float alPitch() {
|
||||
return alGetSourcef(sourceId, AL_PITCH);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the gain of this sound source}
|
||||
*/
|
||||
public float alGain() {
|
||||
return alGetSourcef(sourceId, AL_GAIN);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a {@code float} array with length {@code 3}, where the 0th element represents the X position
|
||||
* of this sound source, the 1st element represents the Y position of this sound source and
|
||||
* the 2nd element represents the Z position of this sound source. Changing the contents of the array
|
||||
* will not affect this sound source.
|
||||
*
|
||||
* @return the position of this sound source
|
||||
*/
|
||||
public float[] alPosition() {
|
||||
FloatBuffer pos = memAllocFloat(3);
|
||||
try (var _ = freeing(pos)) {
|
||||
alGetSource3f(
|
||||
sourceId, AL_POSITION,
|
||||
pos,
|
||||
memDuplicate(pos).position(1),
|
||||
memDuplicate(pos).position(2)
|
||||
);
|
||||
pos.clear();
|
||||
return new float[]{pos.get(), pos.get(), pos.get()};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ticks this source. This method is executed repeatedly for each {@link SourceState#PLAYING playing} sound source in the audio engine loop.
|
||||
*/
|
||||
public void tick() {
|
||||
if (attachedEffects != null) {
|
||||
//noinspection resource
|
||||
copyPropertiesFrom(attachedEffects);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroys this sound source and releases all associated resources.
|
||||
* The sound source should not be able to be used after calling this method.
|
||||
* Calling this method more than once should not have any effect.
|
||||
*/
|
||||
@Override
|
||||
public abstract void close(); // Overrides JavaDoc
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
package ru.fokinatorr.sparkle.audio.impl;
|
||||
|
||||
import it.unimi.dsi.fastutil.Pair;
|
||||
import it.unimi.dsi.fastutil.ints.Int2IntMap;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectObjectImmutablePair;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.experimental.ExtensionMethod;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
//import lombok.extern.lwjgl.ALCheckError;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.lwjgl.BufferUtils;
|
||||
import org.lwjgl.openal.AL;
|
||||
import org.lwjgl.openal.ALCCapabilities;
|
||||
import ru.fokinatorr.sparkle.audio.AudioManager;
|
||||
import ru.fokinatorr.sparkle.audio.impl.bufferprovider.SoundBufferProvider;
|
||||
import ru.fokinatorr.sparkle.audio.impl.io.ParsedSoundImpl;
|
||||
import ru.fokinatorr.sparkle.audio.io.SoundDecoder;
|
||||
import ru.fokinatorr.sparkle.context.AppContext;
|
||||
import ru.fokinatorr.sparkle.util.GUID;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.IntBuffer;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static org.lwjgl.openal.ALC.*;
|
||||
import static org.lwjgl.openal.ALC10.*;
|
||||
import static org.lwjgl.system.MemoryUtil.NULL;
|
||||
import static ru.fokinatorr.lwjgl.util.openal.AL10errchk.*;
|
||||
import static ru.fokinatorr.sparkle.audio.impl.BaseSoundSource.SourceState.PLAYING;
|
||||
|
||||
/**
|
||||
* The entry point for creating an OpenAL audio engine.
|
||||
* <p>
|
||||
* The audio manager is <b>not thread-safe</b>. All methods except {@link #close()}
|
||||
* should be called from the same thread that calls {@link #tick()} (usually the main/game loop).
|
||||
* <p><i>Note: Do not manually close sound source objects returned by an instance of this class. Instead, use
|
||||
* the </i><b>{@link #destroySoundInstance(String)}</b><i> method for proper cleanup.</i>
|
||||
*/
|
||||
@Slf4j
|
||||
@ExtensionMethod(OpenALAudioManager.class)
|
||||
@FieldDefaults(level = AccessLevel.PRIVATE)
|
||||
//@ALCheckError
|
||||
public class OpenALAudioManager implements AudioManager {
|
||||
|
||||
private static final int DEFAULT_STREAMING_BUFFER_SIZE = 8192;
|
||||
// Look along negative Z (standard right-handed coordinate system)
|
||||
private static final float[] DEFAULT_ORIENTATION =
|
||||
{0.0f, 0.0f, -1.0f, // look direction
|
||||
0.0f, 1.0f, 0.0f}; // up vector
|
||||
|
||||
private static final AtomicBoolean CREATE_LOCK = new AtomicBoolean();
|
||||
|
||||
long device; // pointer
|
||||
long alcContext; // pointer
|
||||
final Map<Path, ParsedSoundImpl> parsedSounds = new HashMap<>();
|
||||
final Map<String, BaseSoundSource<?>> sources = new HashMap<>();
|
||||
final AppContext appContext;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new audio engine that opens the default audio device.
|
||||
*
|
||||
* @param appContext the application context (used to get sound decoders)
|
||||
* @throws IllegalStateException if initialization fails for any reason
|
||||
*/
|
||||
public OpenALAudioManager(AppContext appContext) {
|
||||
if (!CREATE_LOCK.compareAndSet(false,true)) {
|
||||
throw new IllegalStateException("OpenALAudioManager is a singleton, only one instance allowed");
|
||||
}
|
||||
|
||||
this.appContext = appContext;
|
||||
|
||||
device = alcOpenDevice((ByteBuffer) null); // null = default device
|
||||
if (device == NULL) {
|
||||
throw new IllegalStateException("Could not open an audio device");
|
||||
}
|
||||
ALCCapabilities deviceCaps = createCapabilities(device);
|
||||
alcContext = alcCreateContext(device, createContextAttributes(null));
|
||||
if (alcContext == NULL) {
|
||||
throw new IllegalStateException("Could not create OpenAL device context");
|
||||
}
|
||||
alcMakeContextCurrent(alcContext);
|
||||
AL.createCapabilities(deviceCaps);
|
||||
alListener3f(AL_POSITION, 0.0f, 0.0f, 0.0f);
|
||||
alListenerfv(AL_ORIENTATION, DEFAULT_ORIENTATION);
|
||||
}
|
||||
|
||||
// Loading sound data (only OGG support so far)
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @param path {@inheritDoc}
|
||||
* @throws IOException {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void loadSound(Path path) throws IOException {
|
||||
IOException ex = null;
|
||||
ParsedSoundImpl newSound = null;
|
||||
if (device != NULL && alcContext != NULL) {
|
||||
for (SoundDecoder decoder : appContext.getAll(SoundDecoder.class)) {
|
||||
try {
|
||||
newSound = ParsedSoundImpl.fromPublicAPI(decoder.parseFile(path));
|
||||
if (decoder.getSupportedExtensions().stream().noneMatch(ext -> path.getFileName().toString().endsWith(ext))) {
|
||||
logWrongFilenameExt(decoder.getFormatName(), decoder.getSupportedExtensions(), path);
|
||||
}
|
||||
break;
|
||||
} catch (IOException e) {
|
||||
log.debug("Could not read '{}' as {}", path.getFileName(), decoder.getFormatName(), e);
|
||||
if (ex == null) {
|
||||
ex = e;
|
||||
} else {
|
||||
ex.addSuppressed(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (newSound == null) {
|
||||
if (ex != null) {
|
||||
log.error("Could not load '{}' as audio; either not an audio file or the format is unsupported", path.getFileName(), ex);
|
||||
throw ex;
|
||||
} else {
|
||||
log.error("Could not load '{}' as audio; no sound decoders available", path.getFileName());
|
||||
throw new IOException("No supported formats found");
|
||||
}
|
||||
} else {
|
||||
ParsedSoundImpl oldSound = parsedSounds.put(path, newSound);
|
||||
if (oldSound != null) {
|
||||
oldSound.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @param path {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean hasLoadedSound(Path path) {
|
||||
return parsedSounds.containsKey(path);
|
||||
}
|
||||
|
||||
// Creating/managing sound sources
|
||||
|
||||
/**
|
||||
* Creates a new {@link StaticSoundSource} from the loaded sound at the given path. A sound must be
|
||||
* loaded with {@link #loadSound(Path)} before calling this method.
|
||||
*
|
||||
* @param path the path to the loaded sound
|
||||
* @return a pair containing the ID of the new sound source and the sound source itself
|
||||
* @throws IllegalArgumentException if no sound is loaded at the given path
|
||||
* @throws IllegalStateException if the audio manager is closed
|
||||
*/
|
||||
@Override
|
||||
public Pair<String, StaticSoundSource> createStaticSoundInstance(Path path) {
|
||||
ensureOpen();
|
||||
ensureContext();
|
||||
ParsedSoundImpl parsed = getParsedSound(path);
|
||||
SoundBuffer buffer = parsed.createStandAloneBuffer();
|
||||
|
||||
String id = GUID.generate();
|
||||
StaticSoundSource source = new StaticSoundSource(buffer);
|
||||
sources.put(id, source);
|
||||
return new ObjectObjectImmutablePair<>(id, source);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @param path {@inheritDoc}
|
||||
* @param loop {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
* @throws IllegalArgumentException {@inheritDoc}
|
||||
* @throws IllegalStateException {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public Pair<String, StreamingSoundSource> createStreamingSoundInstance(Path path, boolean loop) {
|
||||
return createStreamingSoundInstance(path, DEFAULT_STREAMING_BUFFER_SIZE, loop);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new streaming sound source from the loaded sound at the given path. A sound must be
|
||||
* loaded with {@link #loadSound(Path)} before calling this method.
|
||||
*
|
||||
* @param path the path to the loaded sound
|
||||
* @param maxBufferSize the maximum size (in samples per channel) for each streamed buffer
|
||||
* @param loop whether the source should loop
|
||||
* @return a pair containing the ID of the new sound source and the sound source itself
|
||||
* @throws IllegalArgumentException if no sound is loaded at the given path
|
||||
* @throws IllegalStateException if the audio manager is closed
|
||||
*/
|
||||
public Pair<String, StreamingSoundSource> createStreamingSoundInstance(Path path, int maxBufferSize, boolean loop) {
|
||||
ensureOpen();
|
||||
ensureContext();
|
||||
ParsedSoundImpl parsed = getParsedSound(path);
|
||||
SoundBufferProvider provider = parsed.createProvider(maxBufferSize, loop);
|
||||
|
||||
String id = GUID.generate();
|
||||
StreamingSoundSource source = new StreamingSoundSource(provider, 3);
|
||||
sources.put(id, source);
|
||||
return new ObjectObjectImmutablePair<>(id, source);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a sound source by the given ID, if any, otherwise returns {@code null}.
|
||||
*
|
||||
* @param id the ID
|
||||
* @return the respective sound source or {@code null}
|
||||
* @throws IllegalStateException if the audio manager is closed
|
||||
*/
|
||||
@Override
|
||||
public BaseSoundSource<?> getSoundInstance(String id) {
|
||||
ensureOpen();
|
||||
return sources.get(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* If a sound source with the given ID exists, stops, closes and removes it, otherwise does nothing.
|
||||
*
|
||||
* @param id the ID
|
||||
* @throws IllegalStateException if the audio manager is closed
|
||||
*/
|
||||
@Override
|
||||
public void destroySoundInstance(String id) {
|
||||
ensureOpen();
|
||||
ensureContext();
|
||||
if (sources.containsKey(id)) {
|
||||
BaseSoundSource<?> source = sources.remove(id);
|
||||
// The source is stopped in close() in all current implementations,
|
||||
// but maybe a new one will appear, and we'll forget about adding stop() there
|
||||
source.stop();
|
||||
source.close();
|
||||
}
|
||||
}
|
||||
|
||||
// Engine state management
|
||||
|
||||
/**
|
||||
* Advances the audio manager by one tick. Should be called regularly from the main/game loop.
|
||||
*
|
||||
* @throws IllegalStateException if the audio manager is closed
|
||||
*/
|
||||
@Override
|
||||
public void tick() {
|
||||
ensureOpen();
|
||||
ensureContext();
|
||||
for (BaseSoundSource<?> source : sources.values()) {
|
||||
if (source.getALState() == PLAYING) source.tick();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
parsedSounds.values().forEach(ParsedSoundImpl::close);
|
||||
parsedSounds.clear();
|
||||
sources.values().forEach(BaseSoundSource::close);
|
||||
sources.clear();
|
||||
if (alcContext != NULL) {
|
||||
alcMakeContextCurrent(NULL);
|
||||
alcDestroyContext(alcContext);
|
||||
alcContext = NULL;
|
||||
}
|
||||
if (device != NULL) {
|
||||
alcCloseDevice(device);
|
||||
device = NULL;
|
||||
}
|
||||
CREATE_LOCK.set(false);
|
||||
}
|
||||
|
||||
// Private methods
|
||||
|
||||
private void ensureOpen() {
|
||||
if (device == NULL || alcContext == NULL) {
|
||||
throw new IllegalStateException("AudioManager is closed");
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureContext() {
|
||||
if (alcContext != NULL && alcGetCurrentContext() == NULL) {
|
||||
alcMakeContextCurrent(alcContext);
|
||||
}
|
||||
}
|
||||
|
||||
private ParsedSoundImpl getParsedSound(Path path) {
|
||||
if (hasLoadedSound(path)) {
|
||||
return parsedSounds.get(path);
|
||||
}
|
||||
throw new IllegalArgumentException("No sound loaded at path: " + path);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws OutOfMemoryError if there is not enough space for the buffer
|
||||
*/
|
||||
@SuppressWarnings("SameParameterValue")
|
||||
private static IntBuffer createContextAttributes(Int2IntMap source) {
|
||||
if (source == null || source.isEmpty()) return null;
|
||||
|
||||
IntBuffer result = BufferUtils.createIntBuffer(source.size() * 2 + 1);
|
||||
for (Int2IntMap.Entry entry : source.int2IntEntrySet()) {
|
||||
result.put(entry.getIntKey())
|
||||
.put(entry.getIntValue());
|
||||
}
|
||||
return result.put(0) // null-terminate the buffer
|
||||
.flip();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Logs a warning about an incorrect filename extension.
|
||||
*/
|
||||
private static void logWrongFilenameExt(String formatName, Collection<String> correctExt, Path filePath) {
|
||||
log.warn(
|
||||
"Loaded {} audio from '{}', but file has non-standard extension.",
|
||||
formatName, filePath.getFileName()
|
||||
);
|
||||
log.warn(
|
||||
"This is not a fatal error, but the filename may cause confusion. Consider giving it one of these extensions: {} for clarity.",
|
||||
correctExt
|
||||
);
|
||||
log.warn("Full file path: {}", filePath);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package ru.fokinatorr.sparkle.audio.impl;
|
||||
|
||||
import lombok.experimental.UtilityClass;
|
||||
|
||||
/**
|
||||
* Sound effect value conversion utils.
|
||||
*/
|
||||
@UtilityClass
|
||||
class PitchConversion {
|
||||
// OpenAL pitch formula is 2^octaves
|
||||
// Pitch effect value formula is 10*semitones
|
||||
|
||||
/**
|
||||
* Number of 0.1-semitone units per octave (12 semitones * 10). (The pitch effect unit
|
||||
* is {@code 0.1} semitones, and OpenAL requires octaves)
|
||||
*/
|
||||
private final double STEPS_PER_OCTAVE = 120.0;
|
||||
/**
|
||||
* Precomputed scale factor: {@code ln(2) / }{@link #STEPS_PER_OCTAVE}.
|
||||
* <p>
|
||||
* Used to convert {@code ln(alPitch)} to {@code log₂(alPitch) * STEPS_PER_OCTAVE} via division:
|
||||
* <pre><code>
|
||||
* log₂(alPitch) * STEPS_PER_OCTAVE =
|
||||
* = ln(alPitch) / ln(2) * STEPS_PER_OCTAVE =
|
||||
* = ln(alPitch) / (ln(2) / STEPS_PER_OCTAVE) =
|
||||
* = ln(alPitch) / LOG_TO_PITCH_SCALE
|
||||
* </code></pre>
|
||||
*/
|
||||
private final double LOG_TO_PITCH_SCALE = Math.log(2) / STEPS_PER_OCTAVE;
|
||||
|
||||
/**
|
||||
* Converts the given {@link ru.fokinatorr.sparkle.effect.sounds.SoundEffect#PITCH pitch sound effect} value to a valid OpenAL pitch.
|
||||
* @param pitch the pitch effect value
|
||||
* @return the corresponding OpenAL pitch value
|
||||
* @throws IllegalArgumentException if the given argument is infinite or NaN
|
||||
*/
|
||||
double toALPitch(double pitch) {
|
||||
if (Double.isNaN(pitch) || Double.isInfinite(pitch)) {
|
||||
throw new IllegalArgumentException("Invalid pitch: " + pitch);
|
||||
}
|
||||
// OpenAL's pitch value formula is 2^octaves
|
||||
return Math.pow(2.0, pitch / STEPS_PER_OCTAVE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given OpenAL pitch value to a sound effect pitch value (not normalized).
|
||||
* @param alPitch the AL pitch value
|
||||
* @return the corresponding sound effect pitch value
|
||||
* @throws IllegalArgumentException if the given argument is infinite, NaN or non-positive
|
||||
*/
|
||||
double fromALPitch(double alPitch) {
|
||||
if (alPitch <= 0.0 || Double.isNaN(alPitch) || Double.isInfinite(alPitch)) {
|
||||
throw new IllegalArgumentException("Invalid AL pitch: " + alPitch);
|
||||
}
|
||||
// The below expression is effectively equal to log₂(alPitch) * STEPS_PER_OCTAVE
|
||||
return Math.log(alPitch) / LOG_TO_PITCH_SCALE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package ru.fokinatorr.sparkle.audio.impl;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import lombok.experimental.NonFinal;
|
||||
//import lombok.extern.lwjgl.ALCheckError;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
|
||||
|
||||
import java.nio.ShortBuffer;
|
||||
import java.util.Objects;
|
||||
|
||||
import static ru.fokinatorr.lwjgl.util.openal.AL10errchk.*;
|
||||
import static org.lwjgl.system.MemoryUtil.*;
|
||||
|
||||
/**
|
||||
* Manages an OpenAL sound buffer.
|
||||
*/
|
||||
@Slf4j
|
||||
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
|
||||
//@ALCheckError
|
||||
public class SoundBuffer implements NonThrowingAutoCloseable {
|
||||
/**
|
||||
* The OpenAL buffer ID.
|
||||
*/
|
||||
@Getter
|
||||
int bufferId;
|
||||
ShortBuffer pcm;
|
||||
|
||||
@NonFinal
|
||||
volatile boolean open;
|
||||
|
||||
/**
|
||||
* Creates a new {@code SoundBuffer}.
|
||||
* @param pcmData the raw PCM data
|
||||
* @param format the buffer data format
|
||||
* @param frequency the data frequency, in Hz
|
||||
* @throws NullPointerException if any argument is {@code null}
|
||||
*/
|
||||
public SoundBuffer(ShortBuffer pcmData, DataFormat format, int frequency) {
|
||||
this.bufferId = alGenBuffers();
|
||||
this.pcm = memDuplicate(Objects.requireNonNull(pcmData, "PCM data"));
|
||||
alBufferData(
|
||||
bufferId,
|
||||
Objects.requireNonNull(format, "format").getOpenALFormat(),
|
||||
this.pcm,
|
||||
frequency
|
||||
);
|
||||
open = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the raw PCM data associated with this sound buffer. The returned buffer is read-only.
|
||||
* @return the raw PCM data
|
||||
*/
|
||||
public ShortBuffer getPCMData() {
|
||||
return pcm.asReadOnlyBuffer().rewind();
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroys this sound buffer and releases all associated resources. The sound buffer can
|
||||
* not be used after calling this method. Calling this method more than once does not have any effect.
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
if (open) {
|
||||
try {
|
||||
alDeleteBuffers(bufferId);
|
||||
} finally {
|
||||
memFree(pcm);
|
||||
open = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The data format of a sound buffer.
|
||||
*/
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
|
||||
public enum DataFormat {
|
||||
MONO_8BIT(AL_FORMAT_MONO8),
|
||||
MONO_16BIT(AL_FORMAT_MONO16),
|
||||
STEREO_8BIT(AL_FORMAT_STEREO8),
|
||||
STEREO_16BIT(AL_FORMAT_STEREO16);
|
||||
|
||||
/**
|
||||
* The corresponding OpenAL format value.
|
||||
*/
|
||||
int openALFormat;
|
||||
|
||||
/**
|
||||
* Returns a {@code DataFormat} with the given OpenAL format.
|
||||
* @param openALFormat the OpenAL format value
|
||||
* @return the corresponding {@code DataFormat}
|
||||
* @throws IllegalArgumentException if there is no such OpenAL format
|
||||
*/
|
||||
public static DataFormat valueOf(int openALFormat) {
|
||||
return switch (openALFormat) {
|
||||
case AL_FORMAT_MONO8 -> MONO_8BIT;
|
||||
case AL_FORMAT_STEREO8 -> STEREO_8BIT;
|
||||
case AL_FORMAT_MONO16 -> MONO_16BIT;
|
||||
case AL_FORMAT_STEREO16 -> STEREO_16BIT;
|
||||
default -> throw new IllegalArgumentException("Unknown OpenAL data format: " + openALFormat);
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package ru.fokinatorr.sparkle.audio.impl;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
//import lombok.extern.lwjgl.ALCheckError;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import static ru.fokinatorr.lwjgl.util.openal.AL10errchk.*;
|
||||
|
||||
/**
|
||||
* Manages a static OpenAL sound source, a sound source with only one static buffer.
|
||||
*/
|
||||
//@ALCheckError
|
||||
@FieldDefaults(level = AccessLevel.PRIVATE)
|
||||
public class StaticSoundSource extends BaseSoundSource<StaticSoundSource> {
|
||||
|
||||
SoundBuffer buffer;
|
||||
boolean open = true;
|
||||
|
||||
/**
|
||||
* Creates a new {@code SoundSource} with the given buffer attached.
|
||||
*
|
||||
* @param buffer the buffer
|
||||
* @throws NullPointerException if the buffer is {@code null}
|
||||
*/
|
||||
public StaticSoundSource(SoundBuffer buffer) {
|
||||
super(alGenSources());
|
||||
this.buffer = Objects.requireNonNull(buffer);
|
||||
alSourcei(sourceId, AL_BUFFER, buffer.getBufferId());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
protected StaticSoundSource self() {
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets this sound source to be looping if the given value is {@code true}, or sets
|
||||
* this sound source not to be looping if the given value is {@code false}.
|
||||
*
|
||||
* @param newLooping the new looping value
|
||||
* @return this sound source
|
||||
*/
|
||||
public StaticSoundSource looping(boolean newLooping) {
|
||||
alSourcei(sourceId, AL_LOOPING, newLooping ? AL_TRUE : AL_FALSE);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether this sound source is looping when played. Returns {@code true}
|
||||
* if so, or {@code false} otherwise.
|
||||
*
|
||||
* @return whether this sound source is looping
|
||||
*/
|
||||
public boolean looping() {
|
||||
return alGetSourcei(sourceId, AL_LOOPING) == AL_TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
if (open) {
|
||||
stop();
|
||||
try {
|
||||
alDeleteSources(sourceId);
|
||||
} finally {
|
||||
try {
|
||||
buffer.close();
|
||||
} finally {
|
||||
buffer = null;
|
||||
open = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package ru.fokinatorr.sparkle.audio.impl;
|
||||
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectLinkedOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
//import lombok.extern.lwjgl.ALCheckError;
|
||||
import ru.fokinatorr.sparkle.audio.impl.bufferprovider.*;
|
||||
|
||||
import java.nio.IntBuffer;
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static ru.fokinatorr.lwjgl.util.openal.AL10errchk.*;
|
||||
import static org.lwjgl.system.MemoryUtil.memAllocInt;
|
||||
import static ru.fokinatorr.sparkle.util.BufferUtils.*;
|
||||
|
||||
/**
|
||||
* Manages a streaming OpenAL sound source. The buffers should be queued.
|
||||
* <p>Buffers are taken from a {@link SoundBufferProvider} instance supplied in constructor. There are ready-to-use implementations,
|
||||
* see below reference links; to create your own implementation, refer to {@code SoundBufferProvider}'s Javadoc.</p>
|
||||
*
|
||||
* @see SoundBufferProvider
|
||||
* @see IterableSoundBufferProvider
|
||||
* @see SamplesSoundBufferProvider
|
||||
*/
|
||||
@SuppressWarnings("UnusedReturnValue")
|
||||
@FieldDefaults(level = AccessLevel.PRIVATE)
|
||||
//@ALCheckError
|
||||
public class StreamingSoundSource extends BaseSoundSource<StreamingSoundSource> {
|
||||
|
||||
/**
|
||||
* How much ticks to wait before updating the queue.
|
||||
*/
|
||||
private static final int WAIT_BEFORE_UPDATE_TICKS = 25;
|
||||
private static final int UPDATE_BUFFER_COUNT = 3;
|
||||
|
||||
final Int2ObjectMap<SoundBuffer> bufferQueue = new Int2ObjectLinkedOpenHashMap<>();
|
||||
final SoundBufferProvider provider;
|
||||
final SoundBufferProvider.Iterator bufferItr;
|
||||
final int enqueueStart;
|
||||
int requeueWaitTicks = WAIT_BEFORE_UPDATE_TICKS;
|
||||
boolean open = true;
|
||||
|
||||
/**
|
||||
* Creates a new {@code SoundSource} with the given sound buffers enqueued.
|
||||
*
|
||||
* @param provider the provider to use for getting buffers
|
||||
* @throws NullPointerException if the given buffer array is {@code null}
|
||||
*/
|
||||
public StreamingSoundSource(SoundBufferProvider provider, int enqueueStart) {
|
||||
super(alGenSources());
|
||||
this.provider = provider;
|
||||
this.bufferItr = provider.iterator();
|
||||
this.enqueueStart = enqueueStart;
|
||||
//noinspection resource
|
||||
enqueueBuffers(
|
||||
Stream.generate(this::nextBuffer)
|
||||
.limit(enqueueStart)
|
||||
.toArray(SoundBuffer[]::new)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueues the given sound buffers to this sound source.
|
||||
*
|
||||
* @param queue the buffers to enqueue; {@code null} elements are ignored
|
||||
* @return this sound source
|
||||
* @throws NullPointerException if the given buffer array is {@code null}
|
||||
*/
|
||||
private StreamingSoundSource enqueueBuffers(SoundBuffer... queue) {
|
||||
queue = Arrays.stream(queue)
|
||||
.filter(Objects::nonNull)
|
||||
.toArray(SoundBuffer[]::new);
|
||||
if (queue.length > 0) {
|
||||
alSourceQueueBuffers(sourceId,
|
||||
Arrays.stream(queue)
|
||||
.peek(buf -> bufferQueue.put(buf.getBufferId(), buf))
|
||||
.mapToInt(SoundBuffer::getBufferId)
|
||||
.toArray()
|
||||
);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dequeues the given count of buffers from this sound source.
|
||||
*
|
||||
* @param count the count of buffers to dequeue
|
||||
* @return an array of dequeued buffers of the specified size
|
||||
* @throws NegativeArraySizeException if the count is negative
|
||||
*/
|
||||
private SoundBuffer[] dequeueBuffers(int count) {
|
||||
IntBuffer bufferIds = memAllocInt(count);
|
||||
try (var _ = freeing(bufferIds)) {
|
||||
alSourceUnqueueBuffers(sourceId, bufferIds);
|
||||
return stream(bufferIds)
|
||||
.mapToObj(bufferQueue::remove)
|
||||
.toArray(SoundBuffer[]::new);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroys this sound source, i.e. releases all associated resources. The sound source can
|
||||
* not be used after calling this method. Calling this method more than once does not have any effect.
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
if (open) {
|
||||
stop();
|
||||
try {
|
||||
dequeueBuffers(alGetSourcei(sourceId, AL_BUFFERS_QUEUED));
|
||||
provider.close();
|
||||
alDeleteSources(sourceId);
|
||||
} finally {
|
||||
try {
|
||||
bufferQueue.values().forEach(SoundBuffer::close);
|
||||
bufferQueue.clear();
|
||||
} finally {
|
||||
open = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void rewind() {
|
||||
super.rewind();
|
||||
// clear the queue
|
||||
dequeueBuffers(alGetSourcei(sourceId, AL_BUFFERS_QUEUED));
|
||||
requeueWaitTicks = WAIT_BEFORE_UPDATE_TICKS;
|
||||
bufferItr.startOver();
|
||||
//noinspection resource
|
||||
enqueueBuffers(
|
||||
Stream.generate(() -> bufferItr.hasNext() ? bufferItr.next() : null)
|
||||
.limit(enqueueStart)
|
||||
.toArray(SoundBuffer[]::new)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void tick() {
|
||||
super.tick();
|
||||
if (--requeueWaitTicks <= 0) {
|
||||
requeueWaitTicks = WAIT_BEFORE_UPDATE_TICKS;
|
||||
dequeueBuffers(alGetSourcei(sourceId, AL_BUFFERS_PROCESSED));
|
||||
//noinspection resource
|
||||
enqueueBuffers(Stream.generate(this::nextBuffer)
|
||||
.limit(UPDATE_BUFFER_COUNT)
|
||||
.toArray(SoundBuffer[]::new)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// null indicates no more buffers must be queued
|
||||
private SoundBuffer nextBuffer() {
|
||||
if (bufferItr.hasNext()) {
|
||||
return bufferItr.next();
|
||||
}
|
||||
if (provider.mustLoop()) {
|
||||
bufferItr.startOver();
|
||||
if (bufferItr.hasNext()) {
|
||||
return bufferItr.next();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
protected StreamingSoundSource self() {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package ru.fokinatorr.sparkle.audio.impl.bufferprovider;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NonNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import ru.fokinatorr.sparkle.audio.impl.SoundBuffer;
|
||||
|
||||
/**
|
||||
* A {@link SoundBufferProvider} backed by an {@link Iterable}.
|
||||
*/
|
||||
@FieldDefaults(level = AccessLevel.PRIVATE)
|
||||
@RequiredArgsConstructor
|
||||
public final class IterableSoundBufferProvider implements SoundBufferProvider {
|
||||
@NonNull Iterable<SoundBuffer> iterable;
|
||||
final boolean mustLoop;
|
||||
boolean closed = false;
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public Iterator iterator() {
|
||||
if (closed) {
|
||||
throw new IllegalStateException("The provider is closed");
|
||||
}
|
||||
return new StandardJavaProviderIterator(iterable);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
if (!closed) {
|
||||
iterable.forEach(SoundBuffer::close);
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the backing iterable.
|
||||
* @return the iterable
|
||||
*/
|
||||
public Iterable<SoundBuffer> getIterable() {
|
||||
if (closed) {
|
||||
throw new IllegalStateException("The provider is closed");
|
||||
}
|
||||
return iterable;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean mustLoop() {
|
||||
return mustLoop;
|
||||
}
|
||||
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package ru.fokinatorr.sparkle.audio.impl.bufferprovider;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import lombok.experimental.NonFinal;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import ru.fokinatorr.sparkle.audio.impl.SoundBuffer;
|
||||
|
||||
import java.nio.ShortBuffer;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
|
||||
import static org.lwjgl.system.MemoryUtil.memAllocShort;
|
||||
import static org.lwjgl.system.MemoryUtil.memDuplicate;
|
||||
|
||||
/**
|
||||
* A {@link SoundBufferProvider} that uses a PCM sample buffer as a sound buffer source.
|
||||
*/
|
||||
@Slf4j
|
||||
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
|
||||
@RequiredArgsConstructor
|
||||
public final class SamplesSoundBufferProvider implements SoundBufferProvider {
|
||||
/**
|
||||
* The parsed PCM samples.
|
||||
*/
|
||||
ShortBuffer samples;
|
||||
/**
|
||||
* The data format to use for creating sound buffers.
|
||||
*/
|
||||
SoundBuffer.DataFormat dataFormat;
|
||||
/**
|
||||
* The frequency of the PCm data, in Hz, to use for creating sound buffers.
|
||||
*/
|
||||
int frequency;
|
||||
/**
|
||||
* The maximal buffer size.
|
||||
*/
|
||||
int bufferSize;
|
||||
/**
|
||||
* Whether a sound source that uses this provider must loop.
|
||||
*/
|
||||
boolean mustLoop;
|
||||
/**
|
||||
* The sound buffer cache.
|
||||
*/
|
||||
List<SoundBuffer> cache = new LinkedList<>();
|
||||
@NonFinal boolean closed = false;
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public Iterator iterator() {
|
||||
if (closed) {
|
||||
throw new IllegalStateException("Provider is closed");
|
||||
}
|
||||
fillCacheIfNeeded();
|
||||
return new StandardJavaProviderIterator(cache);
|
||||
}
|
||||
|
||||
private void fillCacheIfNeeded() {
|
||||
if (cache.isEmpty()) {
|
||||
ShortBuffer samples = memDuplicate(this.samples).rewind();
|
||||
ListIterator<SoundBuffer> itr = cache.listIterator();
|
||||
while (samples.hasRemaining()) {
|
||||
ShortBuffer segment = memAllocShort(bufferSize);
|
||||
while (segment.hasRemaining() && samples.hasRemaining()) {
|
||||
segment.put(samples.get());
|
||||
}
|
||||
itr.add(new SoundBuffer(
|
||||
segment.flip(),
|
||||
dataFormat,
|
||||
frequency
|
||||
));
|
||||
}
|
||||
}
|
||||
log.debug("Buffer count: {}", cache.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
if (!closed) {
|
||||
if (!cache.isEmpty()) {
|
||||
cache.forEach(SoundBuffer::close);
|
||||
cache.clear();
|
||||
}
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean mustLoop() {
|
||||
return mustLoop;
|
||||
}
|
||||
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package ru.fokinatorr.sparkle.audio.impl.bufferprovider;
|
||||
|
||||
import ru.fokinatorr.sparkle.audio.impl.SoundBuffer;
|
||||
import ru.fokinatorr.sparkle.audio.impl.StreamingSoundSource;
|
||||
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/**
|
||||
* Provides sound buffers for a streaming sound source.
|
||||
* <p>Providers are expected to hold references to all buffers they ever create and close all of them in their
|
||||
* {@link #close()} method. Otherwise, memory leaks are likely to occur, since {@link StreamingSoundSource}
|
||||
* only does a best-effort attempt at closing the buffers.
|
||||
* @see StreamingSoundSource
|
||||
*/
|
||||
public interface SoundBufferProvider extends NonThrowingAutoCloseable {
|
||||
|
||||
/**
|
||||
* Determines whether a sound source that uses this provider must loop. Returns {@code true} if so,
|
||||
* and {@code false} otherwise.
|
||||
* @return {@code true} if a sound source that uses this provider must loop, and {@code false} otherwise
|
||||
*/
|
||||
boolean mustLoop();
|
||||
|
||||
/**
|
||||
* Returns an iterator over this provider.
|
||||
* @return a new iterator instance
|
||||
*/
|
||||
Iterator iterator();
|
||||
|
||||
/**
|
||||
* Closes this provider, and any remaining sound buffers. The provider should not be usable after call to
|
||||
* this method. Calling this method more than once must not have any effect.
|
||||
*/
|
||||
@Override
|
||||
void close();
|
||||
|
||||
/**
|
||||
* An iterator over a {@link SoundBufferProvider}. It differs from {@link java.util.Iterator}
|
||||
* since it supports starting over and doesn't have a {@code remove()} operation.
|
||||
*/
|
||||
interface Iterator {
|
||||
|
||||
/**
|
||||
* Determines whether there are more buffers left in this iterator. Returns {@code true} if so,
|
||||
* and {@code false} otherwise. (In other words, returns {@code true} if the method
|
||||
* {@link #next()} would return normally, and {@code false} if that method
|
||||
* would throw an exception.)
|
||||
* @return {@code true} if has more buffers, and {@code false} otherwise
|
||||
*/
|
||||
boolean hasNext();
|
||||
|
||||
/**
|
||||
* Returns the next sound buffer, if any, otherwise throws a {@link NoSuchElementException}.
|
||||
* @return the next sound buffer
|
||||
* @throws NoSuchElementException if there are no more buffers left
|
||||
*/
|
||||
SoundBuffer next();
|
||||
|
||||
/**
|
||||
* Starts iterating from the beginning. More formally, sets the iterator's position
|
||||
* to the starting position.
|
||||
*/
|
||||
void startOver();
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package ru.fokinatorr.sparkle.audio.impl.bufferprovider;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import ru.fokinatorr.sparkle.audio.impl.SoundBuffer;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
/**
|
||||
* A {@link SoundBufferProvider.Iterator} that uses the standard Java {@link Iterable}
|
||||
* and {@link java.util.Iterator Iterator} API.
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
@FieldDefaults(level = AccessLevel.PRIVATE)
|
||||
public final class StandardJavaProviderIterator implements SoundBufferProvider.Iterator {
|
||||
|
||||
final Iterable<? extends SoundBuffer> iterable;
|
||||
Iterator<? extends SoundBuffer> iterator;
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return getIterator().hasNext();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public SoundBuffer next() {
|
||||
return getIterator().next();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void startOver() {
|
||||
iterator = null; // Will be lazily recomputed when needed
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the iterator, creating it if necessary.
|
||||
* @return the backing iterator
|
||||
*/
|
||||
private synchronized Iterator<? extends SoundBuffer> getIterator() {
|
||||
if (iterator == null) {
|
||||
iterator = iterable.iterator();
|
||||
}
|
||||
return iterator;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
package ru.fokinatorr.sparkle.audio.impl.io;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.NonNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import lombok.experimental.NonFinal;
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
import ru.fokinatorr.sparkle.audio.impl.SoundBuffer;
|
||||
import ru.fokinatorr.sparkle.audio.impl.bufferprovider.SamplesSoundBufferProvider;
|
||||
import ru.fokinatorr.sparkle.audio.impl.bufferprovider.SoundBufferProvider;
|
||||
import ru.fokinatorr.sparkle.audio.io.ParsedSound;
|
||||
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
|
||||
|
||||
import java.nio.Buffer;
|
||||
import java.nio.ShortBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import static org.lwjgl.system.MemoryUtil.memAllocShort;
|
||||
import static org.lwjgl.system.MemoryUtil.memFree;
|
||||
|
||||
/**
|
||||
* An intermediate representation of a loaded sound (in PCM) which is ready to be converted into any of:
|
||||
* <ul>
|
||||
* <li>a stand-alone {@link SoundBuffer};</li>
|
||||
* <li>a list of {@link SoundBuffer}s;</li>
|
||||
* <li>a {@link SoundBufferProvider} that generates buffers from the loaded data.</li>
|
||||
* </ul>
|
||||
*/
|
||||
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) // private final
|
||||
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
|
||||
@Getter
|
||||
public class ParsedSoundImpl implements NonThrowingAutoCloseable {
|
||||
|
||||
/**
|
||||
* The raw sound data samples.
|
||||
*/
|
||||
@NonNull
|
||||
ShortBuffer pcmData;
|
||||
/**
|
||||
* Whether to explicitly free the {@link #pcmData} buffer. Must be {@code true}
|
||||
* for buffers allocated using {@link MemoryUtil}, and {@code false} for buffers
|
||||
* allocated with standard Java API (static allocator methods in the {@link Buffer} classes).
|
||||
*/
|
||||
@Getter(AccessLevel.NONE)
|
||||
boolean freePcmData;
|
||||
/**
|
||||
* The data format to use for creating sound buffers.
|
||||
*/
|
||||
@NonNull
|
||||
SoundBuffer.DataFormat dataFormat;
|
||||
/**
|
||||
* The frequency (in Hz) to use for creating sound buffers.
|
||||
*/
|
||||
int frequency;
|
||||
@NonFinal
|
||||
boolean closed = false;
|
||||
|
||||
/**
|
||||
* Converts a {@link ParsedSound} record to a {@code ParsedSoundImpl} instance.
|
||||
* @param ps the source object
|
||||
* @return a new {@code ParsedSoundImpl} instance
|
||||
*/
|
||||
public static ParsedSoundImpl fromPublicAPI(ParsedSound ps) {
|
||||
Objects.requireNonNull(ps, "source object");
|
||||
SoundBuffer.DataFormat format = switch (ps.dataFormat()) {
|
||||
case MONO_8BIT -> SoundBuffer.DataFormat.MONO_8BIT;
|
||||
case MONO_16BIT -> SoundBuffer.DataFormat.MONO_16BIT;
|
||||
case STEREO_8BIT -> SoundBuffer.DataFormat.STEREO_8BIT;
|
||||
case STEREO_16BIT -> SoundBuffer.DataFormat.STEREO_16BIT;
|
||||
};
|
||||
return new ParsedSoundImpl(
|
||||
ps.pcm(),
|
||||
ps.freePcm(),
|
||||
format,
|
||||
ps.frequency()
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// Sound buffer creation
|
||||
|
||||
/**
|
||||
* Creates and returns a stand-alone {@link SoundBuffer} from this instance.
|
||||
* The data buffer is cloned, so the created buffer will be independent of this instance.
|
||||
*
|
||||
* @return a stand-alone {@link SoundBuffer} from this parsed sound
|
||||
*/
|
||||
public SoundBuffer createStandAloneBuffer() {
|
||||
ShortBuffer orig = getPcmData();
|
||||
ShortBuffer clone = memAllocShort(orig.remaining())
|
||||
.put(orig)
|
||||
.flip();
|
||||
return new SoundBuffer(clone, dataFormat, frequency);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates and returns a list of {@link SoundBuffer}s from this instance, given
|
||||
* the maximal buffer count. The returned list will have at most the given count of sound buffers.
|
||||
* The data buffer is cloned, so the created buffers will be independent of this instance.
|
||||
*
|
||||
* @param maxBufferCount the maximal buffer count, must be positive
|
||||
* @return a list of sound buffers from this parsed sound
|
||||
*/
|
||||
public List<SoundBuffer> createBuffersByCount(int maxBufferCount) {
|
||||
ShortBuffer pcm = getPcmData();
|
||||
if (maxBufferCount <= 0) {
|
||||
throw new IllegalArgumentException("Buffer count must be positive, found:" + maxBufferCount);
|
||||
}
|
||||
List<SoundBuffer> result = new ArrayList<>(maxBufferCount);
|
||||
fillList(
|
||||
result, pcm,
|
||||
maxBufferCount,
|
||||
(int) Math.ceil((double) pcm.remaining() / maxBufferCount) * channels()
|
||||
);
|
||||
return Collections.unmodifiableList(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and returns a list of {@link SoundBuffer}s from this instance, given
|
||||
* the maximal buffer size. Every sound buffer in the returned list will have at most the given count of samples multiplied
|
||||
* by the {@link #channels() channel count}.
|
||||
* The data buffer is cloned, so the created buffers will be independent of this instance.
|
||||
*
|
||||
* @param maxBufferSize the maximal buffer size for each buffer (will be multiplied by the channel count),
|
||||
* must be positive
|
||||
* @return a list of sound buffers from this parsed sound
|
||||
*/
|
||||
public List<SoundBuffer> createBuffersBySize(int maxBufferSize) {
|
||||
ShortBuffer pcm = getPcmData();
|
||||
if (maxBufferSize <= 0) {
|
||||
throw new IllegalArgumentException("Buffer size must be positive, found:" + maxBufferSize);
|
||||
}
|
||||
int maxBufferCount = (int) Math.ceil((double) pcm.remaining() / maxBufferSize / channels());
|
||||
List<SoundBuffer> result = new ArrayList<>(maxBufferCount);
|
||||
fillList(
|
||||
result, pcm,
|
||||
maxBufferCount,
|
||||
maxBufferSize * channels()
|
||||
);
|
||||
return Collections.unmodifiableList(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared logic for {@link #createBuffersByCount} and {@link #createBuffersBySize}.
|
||||
*
|
||||
* @param list the list to fill
|
||||
* @param pcmData the copied PCM data buffer
|
||||
*/
|
||||
private void fillList(List<? super SoundBuffer> list, ShortBuffer pcmData, int bufferCount, int bufferSize) {
|
||||
for (int i = 0; i < bufferCount; i++) {
|
||||
ShortBuffer buf = memAllocShort(bufferSize);
|
||||
while (buf.hasRemaining() && pcmData.hasRemaining()) {
|
||||
buf.put(pcmData.get());
|
||||
}
|
||||
if (!pcmData.hasRemaining()) {
|
||||
break;
|
||||
}
|
||||
list.add(new SoundBuffer(
|
||||
buf.flip(),
|
||||
dataFormat,
|
||||
frequency
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and returns a {@link SoundBufferProvider} from this instance, given the maximal buffer size,
|
||||
* and whether the provider should loop. Each buffer emitted by the provider will have at most the given
|
||||
* count of samples multiplied by the {@link #channels() channel count}.
|
||||
* @param maxBufferSize the maximal buffer size
|
||||
* @param mustLoop whether the provider must loop
|
||||
* @return a new {@link SoundBufferProvider} from this parsed sound
|
||||
*/
|
||||
public SoundBufferProvider createProvider(int maxBufferSize, boolean mustLoop) {
|
||||
return new SamplesSoundBufferProvider(
|
||||
getPcmData(),
|
||||
dataFormat,
|
||||
frequency,
|
||||
maxBufferSize * channels(),
|
||||
mustLoop
|
||||
);
|
||||
}
|
||||
|
||||
// Info
|
||||
|
||||
/**
|
||||
* Returns the underlying PCM data buffer.
|
||||
*
|
||||
* @return the PCM data
|
||||
*/
|
||||
public ShortBuffer getPcmData() {
|
||||
return pcmData.asReadOnlyBuffer().rewind();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the total sound length, in samples.
|
||||
*
|
||||
* @return the sound length
|
||||
*/
|
||||
public int length() {
|
||||
return pcmData.remaining() / channels();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the channel count of this sound.
|
||||
*
|
||||
* @return the channel count
|
||||
*/
|
||||
public int channels() {
|
||||
return switch (dataFormat) {
|
||||
case MONO_8BIT, MONO_16BIT -> 1;
|
||||
case STEREO_8BIT, STEREO_16BIT -> 2;
|
||||
};
|
||||
}
|
||||
|
||||
// AutoCloseable
|
||||
|
||||
/**
|
||||
* Releases all associated resources of this instance. The instance cannot be used
|
||||
* to create buffers after call to this method. Calling this method more than once has
|
||||
* no effect.
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
if (!closed) {
|
||||
if (freePcmData) {
|
||||
memFree(pcmData);
|
||||
}
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package ru.fokinatorr.sparkle.audio.impl.io;
|
||||
|
||||
import org.lwjgl.stb.STBVorbisInfo;
|
||||
import ru.fokinatorr.sparkle.audio.impl.SoundBuffer;
|
||||
import ru.fokinatorr.sparkle.audio.io.ParsedSound;
|
||||
import ru.fokinatorr.sparkle.audio.io.SoundDecoder;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ShortBuffer;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.lwjgl.stb.STBVorbis.*;
|
||||
import static org.lwjgl.system.MemoryUtil.*;
|
||||
|
||||
/**
|
||||
* A sound decoder that reads and parses Ogg Vorbis sounds into {@link ParsedSoundImpl ParsedSounds}. Uses
|
||||
* libstb for decoding.
|
||||
*
|
||||
* @see SoundDecoder
|
||||
* @see org.lwjgl.stb.STBVorbis
|
||||
*/
|
||||
public enum VorbisSoundDecoder implements SoundDecoder {
|
||||
INSTANCE;
|
||||
|
||||
/**
|
||||
* Attempts to read an Ogg Vorbis sound from file represented by the given path into a {@link ParsedSoundImpl}.
|
||||
*
|
||||
* @param path {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
* @throws NullPointerException {@inheritDoc}
|
||||
* @throws IOException {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public ParsedSound parseFile(Path path) throws IOException {
|
||||
pathCheck(path);
|
||||
try (STBVorbisInfo info = STBVorbisInfo.malloc()) {
|
||||
return doParse(info, createVorbisDecoder(path) /*pointer*/);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to read an Ogg Vorbis sound from memory represented by the given path into a {@link ParsedSoundImpl}.
|
||||
* The caller <b>must ensure</b> that the buffer is properly prepared for reading.
|
||||
*
|
||||
* @param bb {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
* @throws NullPointerException {@inheritDoc}
|
||||
* @throws IOException {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public ParsedSound parseBytes(ByteBuffer bb) throws IOException {
|
||||
Objects.requireNonNull(bb, "byte buffer");
|
||||
try (STBVorbisInfo info = STBVorbisInfo.malloc()) {
|
||||
return doParse(info, createVorbisDecoder(bb) /*pointer*/);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public Set<String> getSupportedExtensions() {
|
||||
return Set.of(".ogg");
|
||||
}
|
||||
|
||||
private static ParsedSound doParse(STBVorbisInfo info, long decoder /*pointer*/) {
|
||||
stb_vorbis_get_info(decoder, info);
|
||||
int channels = info.channels();
|
||||
ShortBuffer pcm = memAllocShort(stb_vorbis_stream_length_in_samples(decoder) * channels);
|
||||
pcm.limit(stb_vorbis_get_samples_short_interleaved(decoder, channels, pcm) * channels);
|
||||
ParsedSound sound = new ParsedSound(
|
||||
pcm.rewind().asReadOnlyBuffer(),
|
||||
true,
|
||||
channels == 1 ? ParsedSound.DataFormat.MONO_16BIT : ParsedSound.DataFormat.STEREO_16BIT,
|
||||
info.sample_rate()
|
||||
);
|
||||
stb_vorbis_close(decoder);
|
||||
return sound;
|
||||
}
|
||||
|
||||
|
||||
private static void pathCheck(Path path) throws IOException {
|
||||
Objects.requireNonNull(path, "path");
|
||||
if (!Files.exists(path)) {
|
||||
throw new FileNotFoundException(path.toString());
|
||||
}
|
||||
if (Files.isDirectory(path)) {
|
||||
throw new IOException("Is a directory: " + path);
|
||||
}
|
||||
}
|
||||
|
||||
// pointer
|
||||
private static long createVorbisDecoder(Path path) throws IOException {
|
||||
int[] error = new int[1];
|
||||
long decoder = stb_vorbis_open_filename(path.toString(), error, null); // pointer
|
||||
throwIfDecoderNull(decoder, "Cannot open path " + path, error[0]);
|
||||
return decoder;
|
||||
}
|
||||
|
||||
// pointer
|
||||
private static long createVorbisDecoder(ByteBuffer bb) throws IOException {
|
||||
int[] error = new int[1];
|
||||
long decoder = stb_vorbis_open_memory(bb, error, null); // pointer
|
||||
throwIfDecoderNull(
|
||||
decoder,
|
||||
"Cannot open memory at 0x" + Long.toHexString(memAddress(bb)).toUpperCase() + " (buffer state: " + bb + ")",
|
||||
error[0]
|
||||
);
|
||||
return decoder;
|
||||
}
|
||||
|
||||
private static void throwIfDecoderNull(long decoder /*pointer*/, String prefix, int errorCode) throws IOException {
|
||||
if (decoder == NULL) {
|
||||
String message = prefix + ": " + switch (errorCode) {
|
||||
case VORBIS_invalid_first_page -> "Invalid first Ogg page";
|
||||
case VORBIS_too_many_channels -> "Too many channels in the sound";
|
||||
case VORBIS_outofmem -> "Not enough memory";
|
||||
case VORBIS_unexpected_eof -> "Unexpected end of Ogg stream";
|
||||
case VORBIS_invalid_setup -> "Invalid libstb setup"; // TODO add a more descriptive string
|
||||
case VORBIS_feature_not_supported -> "Feature not supported";
|
||||
case VORBIS_file_open_failure -> "Unknown file open failure";
|
||||
default -> "[STB Vorbis error code " + errorCode + "]";
|
||||
};
|
||||
throw new IOException(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package ru.fokinatorr.sparkle.audio.io;
|
||||
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
|
||||
import java.nio.ShortBuffer;
|
||||
import java.util.Objects;
|
||||
|
||||
import static lombok.AccessLevel.PRIVATE;
|
||||
|
||||
/**
|
||||
* A sound parsed to PCM.
|
||||
* @param pcm the PCM data samples
|
||||
* @param freePcm whether {@code pcm} was allocated using {@link MemoryUtil}'s methods and must be explicitly freed
|
||||
* (handling of this flag is implemented internally)
|
||||
* @param dataFormat the audio's data format (channel count and sample size)
|
||||
* @param frequency the frequency (samples per second) of the sound
|
||||
* @see SoundDecoder
|
||||
*/
|
||||
public record ParsedSound(ShortBuffer pcm, boolean freePcm, DataFormat dataFormat, int frequency) {
|
||||
/**
|
||||
* Creates a new {@code ParsedSound}.
|
||||
* @throws NullPointerException if any argument is {@code null}
|
||||
* @see ParsedSound Parameters' descriptions
|
||||
*/
|
||||
public ParsedSound {
|
||||
pcm = Objects.requireNonNull(pcm, "PCM data").asReadOnlyBuffer().rewind();
|
||||
Objects.requireNonNull(dataFormat, "data format");
|
||||
}
|
||||
|
||||
/**
|
||||
* Supported data formats of a PCM sound.
|
||||
*/
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
@FieldDefaults(makeFinal = true, level = PRIVATE)
|
||||
public enum DataFormat {
|
||||
MONO_8BIT(1, 1),
|
||||
MONO_16BIT(1, 2),
|
||||
STEREO_8BIT(2, 1),
|
||||
STEREO_16BIT(2, 2);
|
||||
|
||||
/**
|
||||
* The channel count.
|
||||
*/
|
||||
int channels;
|
||||
|
||||
/**
|
||||
* The sample size in bytes.
|
||||
*/
|
||||
int sampleSize;
|
||||
/**
|
||||
* Attempts to find an appropriate instance for given parameters.
|
||||
* @param channels the channel count
|
||||
* @param sampleSize the sample size in bytes
|
||||
* @return a data format with the given characteristics, if any
|
||||
* @throws IllegalArgumentException if there is no respective instance found
|
||||
*/
|
||||
public static DataFormat valueOf(int channels, int sampleSize) {
|
||||
Int2ObjectMap<DataFormat> bySampleSize = ValueOfMapHolder.MAP.get(channels);
|
||||
if (bySampleSize == null) {
|
||||
throw new IllegalArgumentException("Unexpected channel count: " + channels);
|
||||
}
|
||||
DataFormat result = bySampleSize.get(sampleSize);
|
||||
if (result == null) {
|
||||
throw new IllegalArgumentException("Unexpected sample size: " + sampleSize);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Holds the properties-to-instance map. Declared in a separate class for lazy initialization.
|
||||
*/
|
||||
private static final class ValueOfMapHolder {
|
||||
static final Int2ObjectMap<Int2ObjectMap<DataFormat>> MAP = new Int2ObjectOpenHashMap<>();
|
||||
|
||||
static {
|
||||
for (DataFormat format : DataFormat.values()) {
|
||||
MAP.computeIfAbsent(format.channels, _ -> new Int2ObjectOpenHashMap<>()).putIfAbsent(format.sampleSize, format);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package ru.fokinatorr.sparkle.audio.io;
|
||||
|
||||
import ru.fokinatorr.sparkle.context.AppContextHolder;
|
||||
import ru.fokinatorr.sparkle.util.BufferUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* A sound decoder can decode a {@link Path file}, a {@link InputStream stream of bytes}, or a {@link ByteBuffer byte buffer}
|
||||
* into a {@link ParsedSound} (PCM data).
|
||||
* <p><b>Currently supported formats:
|
||||
* <ul>
|
||||
* <li>OGG Vorbis (.ogg)</li>
|
||||
* </ul></b>
|
||||
* <p><i>Note for Scratchers: Unlike Scratch, which supports many formats (including MP3 and WAV),
|
||||
* we currently only support OGG Vorbis. This keeps the core lightweight and focused on free, open formats.
|
||||
* If you have sounds in other formats that you want to use:
|
||||
* <ol>
|
||||
* <li>
|
||||
* <b>Easy way (recommended)</b>: convert them to one of the supported formats
|
||||
* using tools like <a href="https://www.audacityteam.org/">Audacity</a>, and they're ready to use!
|
||||
* </li>
|
||||
* <li>
|
||||
* <b>Advanced way</b>: implement this interface yourself and register your custom implementation in an
|
||||
* application context like this:
|
||||
* <pre><code>
|
||||
* context.register(SoundDecoder.class, new MySoundDecoder());
|
||||
* </code></pre>
|
||||
* You can get the context using {@link AppContextHolder} utilities.
|
||||
* </li>
|
||||
* </ol></i>
|
||||
* @see ParsedSound
|
||||
*/
|
||||
public interface SoundDecoder {
|
||||
|
||||
/**
|
||||
* Parses the data from file at the given path into PCM.
|
||||
* @param path the file path
|
||||
* @return a new parsed sound
|
||||
* @throws IOException if an I/O or parse error occurs
|
||||
* @throws NullPointerException if path is {@code null}
|
||||
*/
|
||||
ParsedSound parseFile(Path path) throws IOException;
|
||||
|
||||
/**
|
||||
* Parses the data from memory into PCM. The caller <b>must ensure</b> that the buffer is properly prepared for reading.
|
||||
* @param bb the loaded unparsed sound bytes
|
||||
* @return a new parsed sound
|
||||
* @throws IOException if a parse error occurs
|
||||
* @throws NullPointerException if byte buffer is {@code null}
|
||||
*/
|
||||
ParsedSound parseBytes(ByteBuffer bb) throws IOException;
|
||||
|
||||
/**
|
||||
* Parses the bytes emitted by the given input stream into PCM.
|
||||
* @param in the input stream
|
||||
* @return a new parsed sound
|
||||
* @throws IOException if an I/O or parse error occurs
|
||||
* @throws NullPointerException if input stream is {@code null}
|
||||
* @implNote The default implementation reads all remaining bytes of the
|
||||
* input stream into an off-heap buffer, parses them and then frees the buffer.
|
||||
*/
|
||||
default ParsedSound parseStream(InputStream in) throws IOException {
|
||||
Objects.requireNonNull(in, "input stream");
|
||||
ByteBuffer bb = BufferUtils.readFully(in);
|
||||
try (var _ = BufferUtils.freeing(bb)) {
|
||||
return parseBytes(bb);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all file extensions of audio formats supported by this decoder, if available, otherwise returns an empty set.
|
||||
* @return file extensions supported by this decoder (immutable)
|
||||
*/
|
||||
default Set<String> getSupportedExtensions() {
|
||||
return Set.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of the format this decoder is used to handle, if available,
|
||||
* otherwise a string telling the format is unknown, e.g. {@code "<unknown>"}.
|
||||
* @return the name of the format this decoder can handle, if any
|
||||
*/
|
||||
default String getFormatName() {
|
||||
return "<unknown>";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package ru.fokinatorr.sparkle.context;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import ru.fokinatorr.sparkle.util.Global;
|
||||
|
||||
/**
|
||||
* Represents a lightweight runtime environment for an application.
|
||||
* Contains services such as graphics, audio, input, and asset management.
|
||||
* <p>Registered services are also called "components" or "beans" in documentation of this interface's methods.
|
||||
*
|
||||
* @see AppContextHolder
|
||||
* @see Global
|
||||
*/
|
||||
public interface AppContext extends AutoCloseable {
|
||||
// Not using Spring context; it's too heavy and loads slowly - this is unacceptable for desktop app development, especially games
|
||||
|
||||
// Accessors
|
||||
|
||||
/**
|
||||
* Gets a bean instance by its type (usually an interface type). There's no guarantee to which bean will be returned
|
||||
* if multiple beans were registered under that type.
|
||||
*
|
||||
* @param type the type that was used to register the bean
|
||||
* @param <T> the type of the bean
|
||||
* @return the bean instance
|
||||
* @throws IllegalArgumentException if no beans were registered under the given type
|
||||
* @throws NullPointerException if type is {@code null}, or if there's a lazy bean registered under that type
|
||||
* and its factory function returns {@code null}
|
||||
* @see #getAll(Class)
|
||||
*/
|
||||
<T> T get(Class<T> type);
|
||||
|
||||
/**
|
||||
* Gets all registered beans by the given type.
|
||||
*
|
||||
* @param type the type
|
||||
* @param <T> the common supertype of the beans
|
||||
* @return all beans registered under that type
|
||||
* @throws IllegalArgumentException if no beans were registered under the given type
|
||||
* @throws NullPointerException if type is {@code null}, or if there's a lazy bean registered under that type
|
||||
* and its factory function returns {@code null}
|
||||
* @see #get(Class)
|
||||
*/
|
||||
<T> Collection<T> getAll(Class<T> type);
|
||||
|
||||
/**
|
||||
* Returns the count of beans registered under the given type.
|
||||
* <p>This method doesn't initialize lazy beans, so it can be used instead of {@code getAll(type).size()}
|
||||
* to avoid initialization when only the count of them is needed.
|
||||
* @param type the type
|
||||
* @return the count of beans registered under the given type
|
||||
* @throws NullPointerException if type is {@code null}
|
||||
*/
|
||||
int count(Class<?> type);
|
||||
|
||||
/**
|
||||
* Determines whether there is at least one bean registered under the given type.
|
||||
* Returns {@code true} if so and {@code false} otherwise.
|
||||
* <p>This method doesn't initialize lazy beans, so it can be used instead of {@code !getAll(type).isEmpty()}
|
||||
* to avoid initialization when only needed to check presence.
|
||||
* <p>Implementations may choose to return {@code false} instead of throwing a {@link NullPointerException}
|
||||
* when the given type is {@code null}.
|
||||
* @param type the type
|
||||
* @return whether any beans are registered under the given type
|
||||
* @throws NullPointerException (optional) if type is {@code null}
|
||||
*/
|
||||
default boolean has(Class<?> type) {
|
||||
return count(type) > 0;
|
||||
}
|
||||
|
||||
// Mutators
|
||||
|
||||
/**
|
||||
* Registers a new component under the given type. Multiple components can
|
||||
* be registered under the same type.
|
||||
*
|
||||
* @param type the type (usually an interface type implemented by the component)
|
||||
* @param instance the component instance to register
|
||||
* @param <T> the type of the component
|
||||
* @return this context, for chaining calls
|
||||
* @throws NullPointerException if any argument is {@code null}
|
||||
* @see #registerLazy(Class, Function)
|
||||
* @see #registerOverride(Class, Object)
|
||||
*/
|
||||
<T> AppContext register(Class<T> type, T instance);
|
||||
|
||||
/**
|
||||
* Registers a new component under the given type, guaranteeing that {@link #get(Class)} returns
|
||||
* that component instance after call to this method.
|
||||
*
|
||||
* @param type the type (usually an interface type implemented by the component)
|
||||
* @param instance the component instance to register, overriding other instances with the same type
|
||||
* @param <T> the type of the component
|
||||
* @return this context, for chaining calls
|
||||
* @throws NullPointerException if any argument is {@code null}
|
||||
* @see #registerLazy(Class, Function)
|
||||
*/
|
||||
<T> AppContext registerOverride(Class<T> type, T instance);
|
||||
|
||||
/**
|
||||
* Registers a lazy-initialized component under the given type.
|
||||
* Lazy components are not initialized until they're requested with {@link #get(Class)} or similar methods.
|
||||
* <p>This is useful for registering heavy beans that might never be used, or beans that do some irreversible changes once created.
|
||||
*
|
||||
* @param type the type (usually an interface type implemented by the component)
|
||||
* @param factory a factory function that accepts this context and produces a new component instance
|
||||
* @param <T> the type of the component
|
||||
* @return this context, for chaining calls
|
||||
* @throws NullPointerException if any argument is {@code null} (does not check for the factory's return value)
|
||||
* @see #registerLazy(Class, Supplier)
|
||||
*/
|
||||
<T> AppContext registerLazy(Class<T> type, Function<? super AppContext, ? extends T> factory);
|
||||
|
||||
/**
|
||||
* Registers a lazy-initialized component under the given type.
|
||||
* Lazy components are not initialized until they're requested with {@link #get(Class)} or similar methods.
|
||||
* <p>This is useful for registering heavy beans that might never be used, or beans that do some irreversible changes once created.
|
||||
* <p>This method is a version of {@link #registerLazy(Class, Function)} where the factory
|
||||
* function does not accept arguments.
|
||||
*
|
||||
* @param type the type (usually an interface type implemented by the component)
|
||||
* @param factory a factory function that produces a new component instance
|
||||
* @param <T> the type of the component
|
||||
* @return this context, for chaining calls
|
||||
* @throws NullPointerException if any argument is {@code null} (does not check for the factory's return value)
|
||||
* @see #registerLazy(Class, Function)
|
||||
*/
|
||||
default <T> AppContext registerLazy(Class<T> type, Supplier<? extends T> factory) {
|
||||
return registerLazy(type, _ -> factory.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes this context and releases beans that implement {@link AutoCloseable}.
|
||||
* The context cannot be used after calling this method.
|
||||
* Calling this method more than once does not have any effect.
|
||||
* @throws Exception {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
void close() throws Exception;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package ru.fokinatorr.sparkle.context;
|
||||
|
||||
import lombok.experimental.UtilityClass;
|
||||
import ru.fokinatorr.sparkle.util.Global;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* A thread-local holder for the {@link AppContext application context}.
|
||||
* <p>For each thread, it can only be initialized once.
|
||||
* @see AppContext
|
||||
* @see ThreadLocal
|
||||
* @see Global
|
||||
*/
|
||||
@UtilityClass
|
||||
public class AppContextHolder {
|
||||
|
||||
private static final ThreadLocal<AppContext> CONTEXT = new ThreadLocal<>();
|
||||
// not using InheritableThreadLocal so that other potential inheritable thread locals are not inherited if not needed
|
||||
|
||||
/**
|
||||
* Returns the application context of the current thread, or {@code null} if none.
|
||||
* @return the application context, if any, otherwise {@code null}
|
||||
*/
|
||||
public AppContext getContext() {
|
||||
return CONTEXT.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns this application context of the current thread, requiring it to be present.
|
||||
* That means, returns the context if it's not {@code null} and throws an exception otherwise.
|
||||
* @return the application context, if any
|
||||
* @throws IllegalStateException if there is no context for the current thread
|
||||
*/
|
||||
public AppContext getContextOrThrow() {
|
||||
AppContext context = CONTEXT.get();
|
||||
if (context == null) {
|
||||
throw new IllegalStateException("AppContext is not initialized for " + Thread.currentThread());
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the application context for the current thread, if not yet done.
|
||||
* @param ctx the application context to initialize with
|
||||
* @throws IllegalStateException if context was already initialized for the current thread
|
||||
* @throws NullPointerException if context is not initialized for the current thread and the given one is {@code null}
|
||||
*/
|
||||
public void initContext(AppContext ctx) {
|
||||
if (CONTEXT.get() == null) {
|
||||
Objects.requireNonNull(ctx, "app context");
|
||||
CONTEXT.set(ctx);
|
||||
} else {
|
||||
throw new IllegalStateException("AppContext is already initialized for " + Thread.currentThread());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
package ru.fokinatorr.sparkle.context;
|
||||
|
||||
import lombok.*;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import ru.fokinatorr.sparkle.audio.AudioManager;
|
||||
import ru.fokinatorr.sparkle.audio.impl.OpenALAudioManager;
|
||||
import ru.fokinatorr.sparkle.audio.impl.io.VorbisSoundDecoder;
|
||||
import ru.fokinatorr.sparkle.audio.io.SoundDecoder;
|
||||
import ru.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
|
||||
import ru.fokinatorr.sparkle.graphics.GraphicsManager;
|
||||
import ru.fokinatorr.sparkle.graphics.font.FontProvider;
|
||||
import ru.fokinatorr.sparkle.graphics.impl.OpenGLGraphicsManager;
|
||||
import ru.fokinatorr.sparkle.graphics.render.renderer.RendererRegistry;
|
||||
import ru.fokinatorr.sparkle.util.GUID;
|
||||
import ru.fokinatorr.sparkle.util.concurrent.ContextInheritingThreadFactory;
|
||||
import ru.fokinatorr.sparkle.util.concurrent.ThreadType;
|
||||
|
||||
import java.lang.ref.Cleaner;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
/**
|
||||
* Default implementation of {@link AppContext}.
|
||||
* Uses insertion order with override-by-prepend semantics:
|
||||
* <ul>
|
||||
* <li>{@link #register(Class, Object)} → appends</li>
|
||||
* <li>{@link #registerOverride(Class, Object)} → prepends</li>
|
||||
* <li>{@link #get(Class)} → returns first match</li>
|
||||
* </ul>
|
||||
*/
|
||||
@FieldDefaults(level = AccessLevel.PRIVATE)
|
||||
@Slf4j
|
||||
public class DefaultAppContext implements AppContext {
|
||||
|
||||
/**
|
||||
* The ID of this context. Useful for debugging purposes.
|
||||
*/
|
||||
@Getter
|
||||
@Setter(AccessLevel.PACKAGE)
|
||||
String id = GUID.generate();
|
||||
|
||||
final Map<Class<?>, List<Entry<?>>> components = new ConcurrentHashMap<>();
|
||||
final Set<AutoCloseable> disposables = ConcurrentHashMap.newKeySet();
|
||||
|
||||
// Context implementation
|
||||
|
||||
@Override
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
public <T> T get(@NonNull Class<T> type) {
|
||||
requireNonNull(type, "type");
|
||||
List<Entry<T>> entries = (List) components.get(type);
|
||||
if (entries == null || entries.isEmpty()) {
|
||||
throw new NullPointerException("No components registered for " + type.getName());
|
||||
}
|
||||
T result = entries.stream()
|
||||
.map(e -> e.get(this))
|
||||
.findFirst().orElseThrow();
|
||||
log.trace("[DefaultAppContext id={}] Resolved '{}' -> {}", id, type.getSimpleName(), result);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
public <T> Collection<T> getAll(@NonNull Class<T> type) {
|
||||
requireNonNull(type, "type");
|
||||
List<Entry<T>> entries = (List) components.get(type);
|
||||
if (entries == null || entries.isEmpty()) {
|
||||
throw new IllegalArgumentException("No components registered for " + type.getName());
|
||||
}
|
||||
List<T> result = entries.stream()
|
||||
.map(e -> e.get(this))
|
||||
.collect(Collectors.toList());
|
||||
log.trace("[DefaultAppContext id={}] Resolved all '{}' -> {}", id, type.getSimpleName(), result);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int count(@NonNull Class<?> type) {
|
||||
requireNonNull(type, "type");
|
||||
List<Entry<?>> entries = components.get(type);
|
||||
return entries != null ? entries.size() : 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean has(Class<?> type) {
|
||||
if (type == null) {
|
||||
return false;
|
||||
}
|
||||
List<Entry<?>> entries = components.get(type);
|
||||
return entries != null && !entries.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> DefaultAppContext register(Class<T> type, T instance) {
|
||||
return doRegister(type, new Entry<>(instance), false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> DefaultAppContext registerOverride(Class<T> type, T instance) {
|
||||
return doRegister(type, new Entry<>(instance), true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> DefaultAppContext registerLazy(Class<T> type, Function<? super AppContext, ? extends T> factory) {
|
||||
return doRegister(type, new Entry<>(() -> factory.apply(this)), false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> DefaultAppContext registerLazy(Class<T> type, Supplier<? extends T> factory) {
|
||||
return doRegister(type, new Entry<>(factory), false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
log.info("[DefaultAppContext id={}] Shutting down context...", id);
|
||||
List<Exception> exceptions = new ArrayList<>();
|
||||
for (AutoCloseable disposable : disposables) {
|
||||
try {
|
||||
log.trace("[DefaultAppContext id={}] Closing component {}", id, disposable);
|
||||
disposable.close();
|
||||
} catch (Exception e) {
|
||||
log.error("[DefaultAppContext id={}] Failed to close {}", id, disposable, e);
|
||||
exceptions.add(e);
|
||||
}
|
||||
}
|
||||
if (!exceptions.isEmpty()) {
|
||||
throw multipleExceptions(exceptions);
|
||||
}
|
||||
log.info("[DefaultAppContext id={}] Context terminated.", id);
|
||||
}
|
||||
|
||||
|
||||
// Factory methods
|
||||
|
||||
/**
|
||||
* Creates a new application context with default services pre-registered.
|
||||
*
|
||||
* @return a new context
|
||||
*/
|
||||
public static DefaultAppContext createWithDefaults() {
|
||||
DefaultAppContext result = new DefaultAppContext()
|
||||
.registerLazy(ScheduledExecutorService.class, DefaultAppContext::createDefaultExecutor)
|
||||
.register(EventDispatcher.class, EventDispatcher.newDefault())
|
||||
.registerLazy(Cleaner.class, () -> Cleaner.create(new ContextInheritingThreadFactory("cleaner-worker", ThreadType.VIRTUAL)))
|
||||
.registerLazy(AudioManager.class, OpenALAudioManager::new)
|
||||
.register(SoundDecoder.class, VorbisSoundDecoder.INSTANCE)
|
||||
.registerLazy(GraphicsManager.class, OpenGLGraphicsManager::new)
|
||||
.register(RendererRegistry.class, RendererRegistry.withDefaults())
|
||||
.register(FontProvider.class, FontProvider.defaultProvider());
|
||||
log.info("Created headful DefaultAppContext, id={}", result.id);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new headless application context (without audio or graphics services).
|
||||
*
|
||||
* @return a new context
|
||||
*/
|
||||
public static DefaultAppContext createHeadless() {
|
||||
DefaultAppContext result = new DefaultAppContext()
|
||||
.registerLazy(ScheduledExecutorService.class, DefaultAppContext::createDefaultExecutor)
|
||||
.register(EventDispatcher.class, EventDispatcher.newDefault())
|
||||
.registerLazy(Cleaner.class, () -> Cleaner.create(new ContextInheritingThreadFactory("cleaner-worker", ThreadType.VIRTUAL)));
|
||||
log.info("Created headless DefaultAppContext (no graphics/audio components), id={}", result.id);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
// Private implementation
|
||||
|
||||
/**
|
||||
* Creates an executor service to use in the default services.
|
||||
*
|
||||
* @return the default executor service
|
||||
*/
|
||||
private static ScheduledExecutorService createDefaultExecutor() {
|
||||
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(
|
||||
Runtime.getRuntime().availableProcessors(),
|
||||
new ContextInheritingThreadFactory("scheduler-worker", ThreadType.VIRTUAL)
|
||||
);
|
||||
executor.setRemoveOnCancelPolicy(true);
|
||||
return executor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the given component under the given type.
|
||||
*
|
||||
* @param type the type
|
||||
* @param entry the component entry (initialized value or lazy supplier)
|
||||
* @param prepend if {@code true} then add to the beginning of the bean list rather than end
|
||||
* @param <T> the type of the bean
|
||||
* @return this context
|
||||
*/
|
||||
private <T> DefaultAppContext doRegister(Class<T> type, Entry<T> entry, boolean prepend) {
|
||||
requireNonNull(type, "type");
|
||||
// If the type is not an interface or abstract class and has an abstract supertype (interface or an abstract class) in the hierarchy, consider it a concrete type
|
||||
if (!type.isInterface() && (type.getModifiers() & Modifier.ABSTRACT) == 0 && hasAbstractSupertype(type)) {
|
||||
log.warn(
|
||||
"[DefaultAppContext id={}] Registering bean under concrete type '{}'. " +
|
||||
"Prefer registering under interfaces or abstract types where possible.",
|
||||
id, type.getSimpleName()
|
||||
);
|
||||
}
|
||||
|
||||
List<Entry<?>> entries = components.computeIfAbsent(type, _ -> new CopyOnWriteArrayList<>());
|
||||
if (prepend) {
|
||||
entries.addFirst(entry);
|
||||
log.debug("[DefaultAppContext id={}] Registered override entry {} under type {}", id, entry, type);
|
||||
} else {
|
||||
entries.addLast(entry);
|
||||
log.debug("[DefaultAppContext id={}] Registered entry {} under type {}", id, entry, type);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
private static boolean hasAbstractSupertype(Class<?> type) {
|
||||
while (type.isArray()) {
|
||||
type = type.getComponentType();
|
||||
}
|
||||
if (type.getInterfaces().length == 0) {
|
||||
type = type.getSuperclass();
|
||||
while (type != null) {
|
||||
if (type.getInterfaces().length > 0 || (type.getModifiers() & Modifier.ABSTRACT) != 0) {
|
||||
return true;
|
||||
}
|
||||
type = type.getSuperclass();
|
||||
}
|
||||
return false;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Combines the given exceptions into a single one by suppressing.
|
||||
*
|
||||
* @param exceptions the exceptions
|
||||
* @return a combined exception
|
||||
*/
|
||||
private static Exception multipleExceptions(List<Exception> exceptions) {
|
||||
Exception first = exceptions.getFirst();
|
||||
for (int i = 1; i < exceptions.size(); i++) {
|
||||
first.addSuppressed(exceptions.get(i));
|
||||
}
|
||||
return first;
|
||||
}
|
||||
|
||||
/**
|
||||
* An internal component holder that can be used to store either initialized values
|
||||
* or lazily-supplied ones.
|
||||
*
|
||||
* @param <T> the type of the value
|
||||
*/
|
||||
@FieldDefaults(makeFinal = true)
|
||||
private static final class Entry<T> {
|
||||
|
||||
Supplier<T> supplier;
|
||||
AtomicReference<T> val;
|
||||
|
||||
/**
|
||||
* Creates an uninitialized lazy entry.
|
||||
*
|
||||
* @param supplier the initialization function
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
Entry(Supplier<? extends T> supplier) {
|
||||
this.supplier = (Supplier<T>) Objects.requireNonNull(supplier, "supplier");
|
||||
this.val = new AtomicReference<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an initialized entry.
|
||||
*
|
||||
* @param val the value
|
||||
*/
|
||||
Entry(T val) {
|
||||
this.val = new AtomicReference<>(Objects.requireNonNull(val, "instance"));
|
||||
this.supplier = () -> val;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the stored component, initializing it and updating
|
||||
* the context's disposable list as necessary.
|
||||
*
|
||||
* @param ctx the context to maybe update
|
||||
* @return the stored object
|
||||
*/
|
||||
T get(DefaultAppContext ctx) {
|
||||
T result = val.get();
|
||||
if (result == null) {
|
||||
T init = supplier.get();
|
||||
if (init == null) {
|
||||
log.error("[DefaultAppContext id={}] Factory function {} returned null", ctx.id, supplier);
|
||||
throw new NullPointerException("Factory function returned null");
|
||||
}
|
||||
if (val.compareAndSet(null, init)) {
|
||||
// won race
|
||||
result = init;
|
||||
log.debug(
|
||||
"[DefaultAppContext id={}] Initialized lazy component {} (factory function: {})",
|
||||
ctx.id, result, supplier
|
||||
);
|
||||
if (result instanceof AutoCloseable disposable && !(result instanceof AppContext)) {
|
||||
ctx.disposables.add(disposable);
|
||||
}
|
||||
} else {
|
||||
// lost race
|
||||
// double object creation occurred; the instance that won might be invalid now
|
||||
// still, attempt to close the leaked instance
|
||||
result = val.get();
|
||||
if (init instanceof AutoCloseable) {
|
||||
try {
|
||||
((AutoCloseable) init).close();
|
||||
} catch (Exception e) {
|
||||
log.error("[DefaultAppContext id={}] Failed to close leaked component: {}", ctx.id, init, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return val.get() == null
|
||||
? "Entry[<uninitialized>]"
|
||||
: "Entry[<initialized: " + val.get() + ">]";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
package ru.fokinatorr.sparkle.effect;
|
||||
|
||||
import it.unimi.dsi.fastutil.doubles.AbstractDoubleCollection;
|
||||
import it.unimi.dsi.fastutil.doubles.AbstractDoubleIterator;
|
||||
import it.unimi.dsi.fastutil.doubles.DoubleCollection;
|
||||
import it.unimi.dsi.fastutil.doubles.DoubleIterator;
|
||||
import it.unimi.dsi.fastutil.objects.*;
|
||||
import lombok.Data;
|
||||
import lombok.NonNull;
|
||||
import ru.fokinatorr.sparkle.util.concurrent.atomic.AtomicDoubleArray;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static java.lang.reflect.Array.newInstance;
|
||||
|
||||
/**
|
||||
* An object mapping effects to their values.
|
||||
* <p>Null keys are not supported.
|
||||
* The map contains all the possible keys, so removing a key effectively sets the associated value to
|
||||
* {@link K#getDefaultValue() its default value}.
|
||||
* <p>The default return value of an effect map is {@code 0.0} and it can't be changed.
|
||||
* @param <K> the effect type
|
||||
*/
|
||||
public abstract class EffectMap<K extends NormalizableEffect> extends AbstractObject2DoubleMap<K> {
|
||||
|
||||
/**
|
||||
* The values array. Similarly to {@link java.util.EnumMap}, maps enum ordinal to value.
|
||||
*/
|
||||
protected final AtomicDoubleArray values;
|
||||
/**
|
||||
* The effect class, stored because of type erasure
|
||||
*/
|
||||
protected final Class<K> kClass;
|
||||
/**
|
||||
* All the possible effect values.
|
||||
*/
|
||||
protected final K[] effects;
|
||||
|
||||
/**
|
||||
* Creates a new empty {@code EffectMap} with the given possible effect values.
|
||||
* @param effects the possible effect values
|
||||
* @throws IllegalArgumentException if the effect array size is {@code 0}
|
||||
* @throws NullPointerException if the effects array is {@code null}
|
||||
*/
|
||||
protected EffectMap(K[] effects) {
|
||||
defRetValue = 0.0d;
|
||||
Objects.requireNonNull(effects, "effect array");
|
||||
if (effects.length == 0) {
|
||||
throw new IllegalArgumentException("No effects provided");
|
||||
}
|
||||
values = new AtomicDoubleArray(effects.length);
|
||||
this.effects = effects;
|
||||
//noinspection unchecked
|
||||
kClass = (Class<K>) effects.getClass().componentType();
|
||||
clear(); // Set all values to default
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public int size() {
|
||||
return values.length();
|
||||
}
|
||||
|
||||
/**
|
||||
* An effect map is never empty.
|
||||
*
|
||||
* @return {@code false}
|
||||
*/
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Associates the given effect with the given value.
|
||||
*
|
||||
* @param key the effect (must not be {@code null})
|
||||
* @param value the new value
|
||||
* @return the old value of the effect
|
||||
* @throws NullPointerException if the key is {@code null}
|
||||
*/
|
||||
@Override
|
||||
public double put(K key, double value) {
|
||||
Objects.requireNonNull(key, "effect");
|
||||
return values.getAndSet(key.ordinal(), key.normalize(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments the given effect's value by the given delta.
|
||||
* @param key the effect
|
||||
* @param delta the delta
|
||||
* @return the old effect value
|
||||
*/
|
||||
public double increment(K key, double delta) {
|
||||
Objects.requireNonNull(key, "effect");
|
||||
return values.getAndUpdate(key.ordinal(), oldVal -> key.normalize(oldVal + delta));
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrements the given effect's value by the given delta.
|
||||
* @param key the effect
|
||||
* @param delta the delta
|
||||
* @return the old effect value
|
||||
*/
|
||||
public double decrement(K key, double delta) {
|
||||
Objects.requireNonNull(key, "effect");
|
||||
return values.getAndUpdate(key.ordinal(), oldVal -> key.normalize(oldVal - delta));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of the given effect.
|
||||
*
|
||||
* @param key the key
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public double getDouble(Object key) {
|
||||
return kClass.isInstance(key) ? values.get(kClass.cast(key).ordinal()) : defRetValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the given effect to its default value.
|
||||
*
|
||||
* @param key the effect
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public double removeDouble(Object key) {
|
||||
return kClass.isInstance(key)
|
||||
? values.getAndSet(kClass.cast(key).ordinal(), kClass.cast(key).getDefaultValue())
|
||||
: defRetValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Effectively sets all effect values to their respective default values.
|
||||
*/
|
||||
@Override
|
||||
public void clear() {
|
||||
for (int i = 0; i < values.length(); i++) {
|
||||
values.set(i, effects[i].getDefaultValue());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and returns a deep copy of this effect map. The copied map's contents are independent of this map's contents.
|
||||
* @return a deep copy of this map
|
||||
*/
|
||||
public abstract EffectMap<K> copy();
|
||||
|
||||
/**
|
||||
* All keys of type {@link K} are present in the map.
|
||||
*
|
||||
* @param k {@inheritDoc}
|
||||
* @return {@code true} if the given value is not {@code null} and is an instance of {@link K}.
|
||||
*/
|
||||
@Override
|
||||
public boolean containsKey(Object k) {
|
||||
return kClass.isInstance(k);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @param v the value
|
||||
*/
|
||||
@Override
|
||||
public boolean containsValue(double v) {
|
||||
final AtomicBoolean result = new AtomicBoolean(false);
|
||||
values.forEach(value_ -> {
|
||||
if (value_ == v) {
|
||||
result.set(true);
|
||||
}
|
||||
});
|
||||
return result.get();
|
||||
}
|
||||
|
||||
// keySet
|
||||
|
||||
private transient ObjectSet<K> keySet;
|
||||
|
||||
@Override
|
||||
public @NonNull ObjectSet<K> keySet() {
|
||||
var ks = keySet;
|
||||
return ks == null ? (keySet = new KeySet()) : ks;
|
||||
}
|
||||
|
||||
private class KeySet extends AbstractObjectSet<K> {
|
||||
// Generally, something similar to set from values array but with "remove" options
|
||||
|
||||
private class KeyItr extends AbstractObjectIterator<K> {
|
||||
// Iterator over an array with "removing" capability
|
||||
int cursor = 0;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return cursor < effects.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public K next() {
|
||||
if (cursor >= effects.length) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
return effects[cursor++];
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
int cursor = this.cursor;
|
||||
if (cursor == 0) {
|
||||
throw new IllegalStateException("next() has not been yet called");
|
||||
}
|
||||
values.set(cursor - 1, effects[cursor - 1].getDefaultValue());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull ObjectIterator<K> iterator() {
|
||||
return new KeyItr();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return EffectMap.this.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
EffectMap.this.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public K @NonNull [] toArray() {
|
||||
return effects.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T @NonNull [] toArray(T @NonNull [] a) {
|
||||
int size = size();
|
||||
if (a.length < size)
|
||||
//noinspection unchecked
|
||||
a = (T[]) newInstance(a.getClass().componentType(), size);
|
||||
if (a.length > size)
|
||||
a[size] = null;
|
||||
//noinspection ReassignedVariable, SuspiciousSystemArraycopy
|
||||
System.arraycopy(effects, 0, a, 0, effects.length);
|
||||
return a;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(Object o) {
|
||||
return containsKey(o);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean remove(Object o) {
|
||||
boolean result = containsKey(o);
|
||||
EffectMap.this.removeDouble(o);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
// values
|
||||
|
||||
private transient DoubleCollection valuesCollection;
|
||||
|
||||
@Override
|
||||
public @NonNull DoubleCollection values() {
|
||||
var vals = valuesCollection;
|
||||
return vals == null ? (valuesCollection = new Values()) : vals;
|
||||
}
|
||||
|
||||
private class Values extends AbstractDoubleCollection {
|
||||
|
||||
@Override
|
||||
public @NonNull DoubleIterator iterator() {
|
||||
return new ValueItr();
|
||||
}
|
||||
|
||||
private class ValueItr extends AbstractDoubleIterator {
|
||||
int cursor;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return cursor < values.length();
|
||||
}
|
||||
|
||||
@Override
|
||||
public double nextDouble() {
|
||||
if (cursor >= values.length()) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
return values.get(cursor++);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
int cursor = this.cursor;
|
||||
if (cursor == 0) {
|
||||
throw new IllegalStateException("next() has not been yet called");
|
||||
}
|
||||
values.set(cursor - 1, effects[cursor - 1].getDefaultValue());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return EffectMap.this.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
EffectMap.this.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public double[] toDoubleArray() {
|
||||
double[] result = new double[values.length()];
|
||||
for (int i = 0; i < result.length; i++) {
|
||||
result[i] = values.get(i);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(double k) {
|
||||
return containsValue(k);
|
||||
}
|
||||
}
|
||||
|
||||
// entrySet
|
||||
|
||||
private transient ObjectSet<Object2DoubleMap.Entry<K>> entrySet;
|
||||
|
||||
@Override
|
||||
public ObjectSet<Object2DoubleMap.Entry<K>> object2DoubleEntrySet() {
|
||||
var es = entrySet;
|
||||
return es == null ? (entrySet = new EntrySet()) : es;
|
||||
}
|
||||
|
||||
private class EntrySet extends AbstractObjectSet<Object2DoubleMap.Entry<K>> {
|
||||
|
||||
final Object[] entries = new Object[values.length()];
|
||||
|
||||
EntrySet() {
|
||||
for (int i = 0; i < entries.length; i++) {
|
||||
entries[i] = new Entry(i);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull ObjectIterator<Object2DoubleMap.Entry<K>> iterator() {
|
||||
return new EntryItr();
|
||||
}
|
||||
|
||||
class EntryItr extends AbstractObjectIterator<Object2DoubleMap.Entry<K>> {
|
||||
int cursor = 0;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return cursor < entries.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object2DoubleMap.Entry<K> next() {
|
||||
if (cursor >= entries.length) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
//noinspection unchecked
|
||||
return (Entry) entries[cursor++];
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
int cursor = this.cursor;
|
||||
if (cursor == 0) {
|
||||
throw new IllegalStateException("next() has not been yet called");
|
||||
}
|
||||
values.set(cursor - 1, effects[cursor - 1].getDefaultValue());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return EffectMap.this.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
EffectMap.this.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object @NonNull [] toArray() {
|
||||
return entries.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T @NonNull [] toArray(T @NonNull [] a) {
|
||||
int size = size();
|
||||
if (a.length < size)
|
||||
//noinspection unchecked
|
||||
a = (T[]) newInstance(a.getClass().componentType(), size);
|
||||
if (a.length > size)
|
||||
a[size] = null;
|
||||
//noinspection ReassignedVariable, SuspiciousSystemArraycopy
|
||||
System.arraycopy(entries, 0, a, 0, entries.length);
|
||||
return a;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(Object o) {
|
||||
return o instanceof Object2DoubleMap.Entry<?> entry
|
||||
&& kClass.isInstance(entry.getKey())
|
||||
&& EffectMap.this.getDouble(entry.getKey()) == entry.getDoubleValue();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean remove(Object o) {
|
||||
if (o != null) {
|
||||
for (Object object : entries) {
|
||||
//noinspection unchecked
|
||||
Entry entry = (Entry) object;
|
||||
if (entry.equals(o)) {
|
||||
entry.setValue(entry.getKey().getDefaultValue());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Data
|
||||
private class Entry implements Object2DoubleMap.Entry<K> {
|
||||
final int index;
|
||||
|
||||
@Override
|
||||
public K getKey() {
|
||||
return effects[index];
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getDoubleValue() {
|
||||
return values.get(index);
|
||||
}
|
||||
|
||||
@Override
|
||||
public double setValue(double value) {
|
||||
return EffectMap.this.put(effects[index], value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o instanceof Object2DoubleMap.Entry<?> object2DoubleEntry) {
|
||||
// No instanceof because of compile error
|
||||
//noinspection RedundantClassCall
|
||||
if (Entry.class.isInstance(object2DoubleEntry)) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Entry entry = (Entry) object2DoubleEntry;
|
||||
return entry.index == this.index
|
||||
&& entry.getDoubleValue() == this.getDoubleValue();
|
||||
}
|
||||
return object2DoubleEntry.getKey() instanceof NormalizableEffect effect
|
||||
&& effect.ordinal() == index
|
||||
&& object2DoubleEntry.getDoubleValue() == this.getDoubleValue();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return getKey().hashCode() ^ Double.hashCode(getDoubleValue());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws {@link UnsupportedOperationException}.
|
||||
*
|
||||
* @param rv ignored
|
||||
* @throws UnsupportedOperationException always
|
||||
*/
|
||||
@Override
|
||||
public final void defaultReturnValue(double rv) {
|
||||
throw new UnsupportedOperationException("defaultReturnValue() is not supported for EffectMap. This map always contains all " + kClass.getSimpleName() + " keys each with its own default value.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package ru.fokinatorr.sparkle.effect;
|
||||
|
||||
/**
|
||||
* An effect that supports normalizing its values.
|
||||
*/
|
||||
public interface NormalizableEffect {
|
||||
|
||||
/**
|
||||
* Normalizes the given value to be suitable for this effect.
|
||||
* @param value the value to normalize
|
||||
* @return the normalized value
|
||||
*/
|
||||
double normalize(double value);
|
||||
|
||||
/**
|
||||
* Returns the ordinal of this effect instance (in case it's an enum, its position
|
||||
* in its enum declaration, where the initial constant is assigned
|
||||
* an ordinal of zero).
|
||||
* @return the ordinal of this effect instance
|
||||
*/
|
||||
int ordinal();
|
||||
|
||||
/**
|
||||
* Returns the default value of this effect instance.
|
||||
* @return the default effect value
|
||||
*/
|
||||
double getDefaultValue();
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package ru.fokinatorr.sparkle.effect.graphics;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import ru.fokinatorr.sparkle.effect.NormalizableEffect;
|
||||
import ru.fokinatorr.sparkle.util.Mth;
|
||||
|
||||
/**
|
||||
* A graphic effect.
|
||||
* <p>Some graphic effects can only be applied to rasterized content (images)
|
||||
*/
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
|
||||
public enum GraphicEffect implements NormalizableEffect {
|
||||
/**
|
||||
* The hue-shift graphic effect.
|
||||
* <p><i>Note for Scratchers: This effect is similar to the "color" effect in Scratch.
|
||||
* Unlike in Scratch, the max meaningful value of this effect is {@code 360} and not {@code 200}.</i>
|
||||
*/
|
||||
HUE_SHIFT(0, 360, true),
|
||||
/**
|
||||
* The bulge graphic effect.
|
||||
* <p><i>Note for Scratchers: This effect is similar to the "fisheye" effect in Scratch.</i>
|
||||
*/
|
||||
BULGE,
|
||||
/**
|
||||
* The whirl graphic effect.
|
||||
*/
|
||||
WHIRL,
|
||||
/**
|
||||
* The skew graphic effect. Skew is performed along the X axis.
|
||||
*/
|
||||
SKEW_X,
|
||||
/**
|
||||
* The skew graphic effect. Skew is performed along the Y axis.
|
||||
*/
|
||||
SKEW_Y,
|
||||
/**
|
||||
* The pixelation graphic effect.
|
||||
* <p><i>Note for Scratchers: This effect is similar to the "pixelate" effect in Scratch.</i>
|
||||
*/
|
||||
PIXELATION(0, Double.POSITIVE_INFINITY, false),
|
||||
/**
|
||||
* The mosaic graphic effect.
|
||||
*/
|
||||
MOSAIC(0, Double.POSITIVE_INFINITY, false),
|
||||
/**
|
||||
* The brightness graphic effect.
|
||||
*/
|
||||
BRIGHTNESS(-100, 100, false),
|
||||
/**
|
||||
* The opacity graphic effect.
|
||||
* <p><i>Note for Scratchers: This effect is similar to the "ghost" effect in Scratch.</i>
|
||||
*/
|
||||
OPACITY(0, 100, false);
|
||||
|
||||
/**
|
||||
* The minimal value of this effect.
|
||||
*/
|
||||
double min;
|
||||
/**
|
||||
* The maximal value of this effect.
|
||||
*/
|
||||
double max;
|
||||
/**
|
||||
* If {@code true} then uses wrap-around clamping in normalization, otherwise normal clamping.
|
||||
*/
|
||||
boolean useWrapClamp;
|
||||
|
||||
/**
|
||||
* Constructor for effects without range
|
||||
*/
|
||||
GraphicEffect() {
|
||||
this(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @param value {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public double normalize(double value) {
|
||||
return useWrapClamp ? Mth.wrapClamp(value, min, max) : Mth.clamp(value, min, max);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public double getDefaultValue() {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package ru.fokinatorr.sparkle.effect.graphics;
|
||||
|
||||
import ru.fokinatorr.sparkle.effect.EffectMap;
|
||||
import ru.fokinatorr.sparkle.graphics.render.renderer.Renderable;
|
||||
|
||||
/**
|
||||
* An effect map that stores a {@link Renderable}'s graphic effects.
|
||||
*/
|
||||
public class GraphicEffectMap extends EffectMap<GraphicEffect> {
|
||||
/**
|
||||
* Creates a new empty {@code GraphicEffectMap} with all effect values set to respective default ones.
|
||||
*/
|
||||
public GraphicEffectMap() {
|
||||
super(GraphicEffect.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public GraphicEffectMap copy() {
|
||||
GraphicEffectMap copy = new GraphicEffectMap();
|
||||
for (int i = 0; i < values.length(); i++) {
|
||||
copy.values.set(i, values.get(i));
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,466 @@
|
||||
package ru.fokinatorr.sparkle.effect.graphics;
|
||||
|
||||
import it.unimi.dsi.fastutil.doubles.AbstractDoubleCollection;
|
||||
import it.unimi.dsi.fastutil.doubles.AbstractDoubleIterator;
|
||||
import it.unimi.dsi.fastutil.doubles.DoubleCollection;
|
||||
import it.unimi.dsi.fastutil.doubles.DoubleIterator;
|
||||
import it.unimi.dsi.fastutil.objects.*;
|
||||
import lombok.Data;
|
||||
import ru.fokinatorr.sparkle.util.concurrent.atomic.AtomicDoubleArray;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static java.lang.reflect.Array.newInstance;
|
||||
|
||||
/**
|
||||
* An object mapping graphic effects to their values.
|
||||
* <p>Null keys are not supported.
|
||||
* The map contains all the possible keys, so removing a key effectively sets the associated value to {@code 0.0}.
|
||||
*/
|
||||
public class GraphicEffectMap extends AbstractObject2DoubleMap<GraphicEffect> {
|
||||
|
||||
/**
|
||||
* The values array. Similarly to {@link java.util.EnumMap}, maps enum ordinal to value.
|
||||
*/
|
||||
private final AtomicDoubleArray values = new AtomicDoubleArray(GRAPHIC_EFFECTS.length);
|
||||
/**
|
||||
* All the graphic effect values, cached for performance.
|
||||
*/
|
||||
private static final GraphicEffect[] GRAPHIC_EFFECTS = GraphicEffect.values();
|
||||
|
||||
/**
|
||||
* Creates a new empty {@code GraphicEffectMap}.
|
||||
*/
|
||||
public GraphicEffectMap() {
|
||||
defRetValue = 0.0;
|
||||
clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new {@code GraphicEffectMap} with the given map's contents.
|
||||
*/
|
||||
public GraphicEffectMap(Map<? extends GraphicEffect, ? extends Double> m) {
|
||||
this();
|
||||
putAll(m);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public int size() {
|
||||
return values.length();
|
||||
}
|
||||
|
||||
/**
|
||||
* A graphic effect map is never empty.
|
||||
*
|
||||
* @return {@code false}
|
||||
*/
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Associates the given graphic effect with the given value.
|
||||
*
|
||||
* @param key the graphic effect (must not be {@code null})
|
||||
* @param value the new value
|
||||
* @return the old value of the effect
|
||||
* @throws NullPointerException if the key is {@code null}
|
||||
*/
|
||||
@Override
|
||||
public double put(GraphicEffect key, double value) {
|
||||
Objects.requireNonNull(key, "graphic effect");
|
||||
return values.getAndSet(key.ordinal(), key.normalize(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments the given graphic effect's value by the given delta.
|
||||
* @param key the graphic effect
|
||||
* @param delta the delta
|
||||
* @return the old effect value
|
||||
*/
|
||||
public double increment(GraphicEffect key, double delta) {
|
||||
Objects.requireNonNull(key, "graphic effect");
|
||||
return values.getAndUpdate(key.ordinal(), oldVal -> key.normalize(oldVal + delta));
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrements the given graphic effect's value by the given delta.
|
||||
* @param key the graphic effect
|
||||
* @param delta the delta
|
||||
* @return the old effect value
|
||||
*/
|
||||
public double decrement(GraphicEffect key, double delta) {
|
||||
Objects.requireNonNull(key, "graphic effect");
|
||||
return values.getAndUpdate(key.ordinal(), oldVal -> key.normalize(oldVal - delta));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of the given graphic effect.
|
||||
*
|
||||
* @param key the key
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public double getDouble(Object key) {
|
||||
return key instanceof GraphicEffect graphicEffect ? values.get(graphicEffect.ordinal()) : defRetValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the given graphic effect to {@code 0.0}.
|
||||
*
|
||||
* @param key the graphic effect
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public double removeDouble(Object key) {
|
||||
return key instanceof GraphicEffect graphicEffect
|
||||
? values.getAndSet(graphicEffect.ordinal(), 0.0)
|
||||
: defRetValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Effectively sets all effect values to {@code 0.0}.
|
||||
*/
|
||||
@Override
|
||||
public void clear() {
|
||||
for (int i = 0; i < values.length(); i++) {
|
||||
values.set(i, defRetValue);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* All keys of type {@link GraphicEffect} are present in the map.
|
||||
*
|
||||
* @param k {@inheritDoc}
|
||||
* @return {@code true} if the given value is not {@code null} and is an instance of {@link GraphicEffect}.
|
||||
*/
|
||||
@Override
|
||||
public boolean containsKey(Object k) {
|
||||
return k instanceof GraphicEffect;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @param v the value
|
||||
*/
|
||||
@Override
|
||||
public boolean containsValue(double v) {
|
||||
final AtomicBoolean result = new AtomicBoolean(false);
|
||||
values.forEach(value -> {
|
||||
if (value == v) {
|
||||
result.set(true);
|
||||
}
|
||||
});
|
||||
return result.get();
|
||||
}
|
||||
|
||||
// keySet
|
||||
|
||||
private transient ObjectSet<GraphicEffect> keySet;
|
||||
|
||||
@Override
|
||||
public ObjectSet<GraphicEffect> keySet() {
|
||||
var ks = keySet;
|
||||
return ks == null ? (keySet = new KeySet()) : ks;
|
||||
}
|
||||
|
||||
private class KeySet extends AbstractObjectSet<GraphicEffect> {
|
||||
// Generally, something similar to set from values array but with "remove" options
|
||||
|
||||
private class KeyItr extends AbstractObjectIterator<GraphicEffect> {
|
||||
// Iterator over an array with "removing" capability
|
||||
int cursor = 0;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return cursor < GRAPHIC_EFFECTS.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GraphicEffect next() {
|
||||
if (cursor >= GRAPHIC_EFFECTS.length) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
return GRAPHIC_EFFECTS[cursor++];
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
int cursor = this.cursor;
|
||||
if (cursor == 0) {
|
||||
throw new IllegalStateException("next() has not been yet called");
|
||||
}
|
||||
values.set(cursor - 1, defRetValue);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ObjectIterator<GraphicEffect> iterator() {
|
||||
return new KeyItr();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return GraphicEffectMap.this.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
GraphicEffectMap.this.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public GraphicEffect[] toArray() {
|
||||
return GRAPHIC_EFFECTS.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T[] toArray(T[] a) {
|
||||
int size = size();
|
||||
if (a.length < size)
|
||||
//noinspection unchecked
|
||||
a = (T[]) newInstance(a.getClass().componentType(), size);
|
||||
if (a.length > size)
|
||||
a[size] = null;
|
||||
//noinspection ReassignedVariable
|
||||
System.arraycopy(GRAPHIC_EFFECTS, 0, a, 0, GRAPHIC_EFFECTS.length);
|
||||
return a;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(Object o) {
|
||||
return containsKey(o);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean remove(Object o) {
|
||||
boolean result = containsKey(o);
|
||||
GraphicEffectMap.this.removeDouble(o);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
// values
|
||||
|
||||
private transient DoubleCollection valuesCollection;
|
||||
|
||||
@Override
|
||||
public DoubleCollection values() {
|
||||
var vals = valuesCollection;
|
||||
return vals == null ? (valuesCollection = new Values()) : vals;
|
||||
}
|
||||
|
||||
private class Values extends AbstractDoubleCollection {
|
||||
|
||||
@Override
|
||||
public DoubleIterator iterator() {
|
||||
return new ValueItr();
|
||||
}
|
||||
|
||||
private class ValueItr extends AbstractDoubleIterator {
|
||||
int cursor;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return cursor < values.length();
|
||||
}
|
||||
|
||||
@Override
|
||||
public double nextDouble() {
|
||||
if (cursor >= values.length()) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
return values.get(cursor++);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
int cursor = this.cursor;
|
||||
if (cursor == 0) {
|
||||
throw new IllegalStateException("next() has not been yet called");
|
||||
}
|
||||
values.set(cursor - 1, defRetValue);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return GraphicEffectMap.this.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
GraphicEffectMap.this.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public double[] toDoubleArray() {
|
||||
double[] result = new double[values.length()];
|
||||
for (int i = 0; i < result.length; i++) {
|
||||
result[i] = values.get(i);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(double k) {
|
||||
return containsValue(k);
|
||||
}
|
||||
}
|
||||
|
||||
// entrySet
|
||||
|
||||
private transient ObjectSet<Object2DoubleMap.Entry<GraphicEffect>> entrySet;
|
||||
|
||||
@Override
|
||||
public ObjectSet<Object2DoubleMap.Entry<GraphicEffect>> object2DoubleEntrySet() {
|
||||
var es = entrySet;
|
||||
return es == null ? (entrySet = new EntrySet()) : es;
|
||||
}
|
||||
|
||||
private class EntrySet extends AbstractObjectSet<Object2DoubleMap.Entry<GraphicEffect>> {
|
||||
|
||||
final Entry[] entries = new Entry[values.length()];
|
||||
|
||||
EntrySet() {
|
||||
for (int i = 0; i < entries.length; i++) {
|
||||
entries[i] = new Entry(i);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ObjectIterator<Object2DoubleMap.Entry<GraphicEffect>> iterator() {
|
||||
return new EntryItr();
|
||||
}
|
||||
|
||||
class EntryItr extends AbstractObjectIterator<Object2DoubleMap.Entry<GraphicEffect>> {
|
||||
int cursor = 0;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return cursor < entries.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object2DoubleMap.Entry<GraphicEffect> next() {
|
||||
if (cursor >= entries.length) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
return entries[cursor++];
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
int cursor = this.cursor;
|
||||
if (cursor == 0) {
|
||||
throw new IllegalStateException("next() has not been yet called");
|
||||
}
|
||||
values.set(cursor - 1, defRetValue);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return GraphicEffectMap.this.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
GraphicEffectMap.this.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Entry[] toArray() {
|
||||
return entries.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T[] toArray(T[] a) {
|
||||
int size = size();
|
||||
if (a.length < size)
|
||||
//noinspection unchecked
|
||||
a = (T[]) newInstance(a.getClass().componentType(), size);
|
||||
if (a.length > size)
|
||||
a[size] = null;
|
||||
//noinspection ReassignedVariable
|
||||
System.arraycopy(entries, 0, a, 0, entries.length);
|
||||
return a;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(Object o) {
|
||||
return o instanceof Object2DoubleMap.Entry<?> entry
|
||||
&& entry.getKey() instanceof GraphicEffect graphicEffect
|
||||
&& GraphicEffectMap.this.getDouble(graphicEffect) == entry.getDoubleValue();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean remove(Object o) {
|
||||
if (o != null) {
|
||||
for (Entry entry : entries) {
|
||||
if (entry.equals(o)) {
|
||||
entry.setValue(defRetValue);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Data
|
||||
private class Entry implements Object2DoubleMap.Entry<GraphicEffect> {
|
||||
final int index;
|
||||
|
||||
@Override
|
||||
public GraphicEffect getKey() {
|
||||
return GRAPHIC_EFFECTS[index];
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getDoubleValue() {
|
||||
return values.get(index);
|
||||
}
|
||||
|
||||
@Override
|
||||
public double setValue(double value) {
|
||||
return GraphicEffectMap.this.put(GRAPHIC_EFFECTS[index], value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o instanceof Object2DoubleMap.Entry<?> object2DoubleEntry) {
|
||||
if (o instanceof Entry entry) {
|
||||
return entry.index == this.index
|
||||
&& entry.getDoubleValue() == this.getDoubleValue();
|
||||
}
|
||||
return object2DoubleEntry.getKey() instanceof GraphicEffect graphicEffect
|
||||
&& graphicEffect.ordinal() == index
|
||||
&& object2DoubleEntry.getDoubleValue() == this.getDoubleValue();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws {@link UnsupportedOperationException}.
|
||||
*
|
||||
* @param rv ignored
|
||||
* @throws UnsupportedOperationException always
|
||||
*/
|
||||
@Override
|
||||
public void defaultReturnValue(double rv) {
|
||||
throw new UnsupportedOperationException("defaultReturnValue() is not supported for GraphicEffectMap. This map always contains all GraphicEffect keys with a default value of 0.0.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package ru.fokinatorr.sparkle.effect.sounds;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import ru.fokinatorr.sparkle.effect.NormalizableEffect;
|
||||
import ru.fokinatorr.sparkle.util.Mth;
|
||||
|
||||
/**
|
||||
* A sound effect.
|
||||
*/
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
|
||||
public enum SoundEffect implements NormalizableEffect {
|
||||
/**
|
||||
* The volume sound effect.
|
||||
* <p><i>Note for Scratchers: Unlike in Scratch, the volume is a sound effect rather than a separate property.</i>
|
||||
*/
|
||||
VOLUME(0, 100, 100),
|
||||
/**
|
||||
* The pitch sound effect.
|
||||
* <p><i>Note for Scratchers: The effect is similar to the "pitch" sound effect in Scratch. The only thing different
|
||||
* from Scratch's "pitch" effect is the value range, being as in TurboWarp when "Remove Miscellaneous Limits" is enabled.</i>
|
||||
*/
|
||||
PITCH(-1000, 1000, 0),
|
||||
/**
|
||||
* The left-right pan sound effect. This is only guaranteed to work with mono sounds.
|
||||
* <p><i>Note for Scratchers: The effect is similar to the "pan left/right" sound effect in Scratch.</i>
|
||||
*/
|
||||
PAN(-100, 100, 0);
|
||||
|
||||
double min;
|
||||
double max;
|
||||
double defaultValue;
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @param value {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public double normalize(double value) {
|
||||
return Mth.clamp(value, min, max);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package ru.fokinatorr.sparkle.effect.sounds;
|
||||
|
||||
import ru.fokinatorr.sparkle.effect.EffectMap;
|
||||
|
||||
/**
|
||||
* An effect map that stores sound effects.
|
||||
*/
|
||||
public class SoundEffectMap extends EffectMap<SoundEffect> {
|
||||
/**
|
||||
* Creates a new {@code SoundEffectMap} with all effect values set to respective default ones.
|
||||
*/
|
||||
public SoundEffectMap() {
|
||||
super(SoundEffect.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public SoundEffectMap copy() {
|
||||
SoundEffectMap copy = new SoundEffectMap();
|
||||
for (int i = 0; i < values.length(); i++) {
|
||||
copy.values.set(i, values.get(i));
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package ru.fokinatorr.sparkle.event;
|
||||
|
||||
/**
|
||||
* This class provides the functionality of a cancellable event.
|
||||
*/
|
||||
public abstract class AbstractCancellableEvent implements CancellableEvent {
|
||||
|
||||
/**
|
||||
* The "cancelled" flag. Declared {@code private} to prevent unauthorized changes; should only be modified with
|
||||
* {@link CancellableEvent}'s API.
|
||||
*/
|
||||
private boolean cancelled;
|
||||
|
||||
/**
|
||||
* Constructor for subclasses to call.
|
||||
*/
|
||||
protected AbstractCancellableEvent() {
|
||||
cancelled = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isCancelled() {
|
||||
return cancelled;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void cancel() {
|
||||
cancelled = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package ru.fokinatorr.sparkle.event;
|
||||
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NonNull;
|
||||
import lombok.Value;
|
||||
import lombok.experimental.NonFinal;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Interface for events that indicate a stage's backdrop change.
|
||||
* <p><i>Note for Scratchers: This event is similar to "when backdrop switches to </i>[ v]<i>" event in Scratch.</i>
|
||||
*/
|
||||
public sealed interface BackdropChangeEvent extends Event
|
||||
permits BackdropChangeEvent.Before,
|
||||
BackdropChangeEvent.After {
|
||||
|
||||
/**
|
||||
* {@return the stage whose backdrop is changed}
|
||||
*/
|
||||
Stage stage();
|
||||
|
||||
/**
|
||||
* {@return the old backdrop ID}
|
||||
*/
|
||||
int oldBackdropId();
|
||||
|
||||
/**
|
||||
* {@return the new backdrop ID}
|
||||
*/
|
||||
int newBackdropId();
|
||||
|
||||
/**
|
||||
* This event is fired before a backdrop is changed.
|
||||
*/
|
||||
@Value
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
class Before extends AbstractCancellableEvent implements BackdropChangeEvent {
|
||||
@NonNull
|
||||
Stage stage;
|
||||
int oldBackdropId;
|
||||
@NonFinal
|
||||
int newBackdropId;
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public Stage stage() {
|
||||
return stage;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public int oldBackdropId() {
|
||||
return oldBackdropId;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public int newBackdropId() {
|
||||
return newBackdropId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the new backdrop ID.
|
||||
*
|
||||
* @param newBackdropId the new backdrop ID
|
||||
* @throws IndexOutOfBoundsException if there is no such backdrop ID
|
||||
*/
|
||||
public void setNewBackdropId(int newBackdropId) {
|
||||
Objects.checkIndex(newBackdropId, stage.getAssets().texturesByIndex().size());
|
||||
this.newBackdropId = newBackdropId;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return a string representation of this event}
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return "BackdropChangeEvent.Before{" +
|
||||
"stage=" + stage + ", " +
|
||||
"oldCostumeId=" + oldBackdropId + ", " +
|
||||
"newCostumeId=" + newBackdropId + '}';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* This event is fired after a backdrop was changed.
|
||||
*
|
||||
* @param stage the stage whose backdrop was changed
|
||||
* @param oldBackdropId the old backdrop ID
|
||||
* @param newBackdropId the new backdrop ID
|
||||
*/
|
||||
record After(
|
||||
@NonNull Stage stage,
|
||||
int oldBackdropId,
|
||||
int newBackdropId
|
||||
) implements BackdropChangeEvent {
|
||||
/**
|
||||
* {@return a string representation of this event}
|
||||
*/
|
||||
@Override
|
||||
@NonNull
|
||||
public String toString() {
|
||||
return "BackdropChangeEvent.After{" +
|
||||
"stage=" + stage +
|
||||
", oldCostumeId=" + oldBackdropId +
|
||||
", newCostumeId=" + newBackdropId +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package ru.fokinatorr.sparkle.event;
|
||||
|
||||
/**
|
||||
* Represents a cancellable event.
|
||||
*/
|
||||
public interface CancellableEvent extends Event {
|
||||
|
||||
/**
|
||||
* {@return whether this event is cancelled} {@code false} means {@link #cancel()} haven't ever been called
|
||||
* on this event instance yet.
|
||||
*/
|
||||
boolean isCancelled();
|
||||
|
||||
/**
|
||||
* Cancels this event. After that, the {@link #isCancelled()} method should not return {@code false} for this
|
||||
* event instance ever again.
|
||||
*/
|
||||
void cancel();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package ru.fokinatorr.sparkle.event;
|
||||
|
||||
/**
|
||||
* Marker interface for all events, like starting or keyboard/mouse events.
|
||||
* <p>Events can also carry some useful info and are generally immutable. One
|
||||
* of the exceptions is the cancelled flag in {@link CancellableEvent}, which can be changed once.
|
||||
*/
|
||||
public interface Event {
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package ru.fokinatorr.sparkle.event;
|
||||
|
||||
import lombok.NonNull;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* This event is fired when a message is broadcasted.
|
||||
* <p><i>Note for Scratchers: This event is similar to "when I receive </i>[ v]<i>" event in Scratch.</i>
|
||||
*
|
||||
* @param messageId the message's ID. Not necessary to be registered, unlike in Scratch.
|
||||
* @param receivedData an optional data of the message
|
||||
*/
|
||||
public record MessageEvent(
|
||||
@NonNull String messageId,
|
||||
@NonNull Optional<?> receivedData
|
||||
) implements Event {
|
||||
|
||||
/**
|
||||
* Creates a new {@code MessageEvent}. This is an alternative constructor which constructs an {@link Optional}
|
||||
* by itself.
|
||||
* @param messageId the message's ID
|
||||
* @param receivedData the received data; may be {@code null}
|
||||
* @throws NullPointerException if message ID is {@code null}
|
||||
*/
|
||||
public MessageEvent(String messageId, Object receivedData) {
|
||||
this(messageId, Optional.ofNullable(receivedData));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new {@code MessageEvent} without received data.
|
||||
* @param messageId the message ID
|
||||
* @throws NullPointerException if message ID is {@code null}
|
||||
*/
|
||||
public MessageEvent(String messageId) {
|
||||
this(messageId, Optional.empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package ru.fokinatorr.sparkle.event.annotation;
|
||||
|
||||
import ru.fokinatorr.sparkle.event.Event;
|
||||
import ru.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
import java.lang.reflect.InaccessibleObjectException;
|
||||
|
||||
/**
|
||||
* Annotation used by {@link EventDispatcher#register(Object)} that indicates the annotated method should be registered as a listener in the event dispatcher.
|
||||
* <p><h3>Valid Method Signature</h3>
|
||||
* <ul>
|
||||
* <li>
|
||||
* The method should only accept a single argument of type {@link Event} or subinterface/implementing class,
|
||||
* otherwise an {@link IllegalArgumentException} will be thrown;
|
||||
* </li>
|
||||
* <li>
|
||||
* The return value is ignored and can be of any type.
|
||||
* </li>
|
||||
* </ul>
|
||||
* <p><i>Note: If you use named modules and a class containing a method annotated with this annotation is not
|
||||
* exported outside the module, or the method and/or class are not public, you should export/open the
|
||||
* containing package (respectively) to module {@code ru.fokinatorr.sparkle.core}, otherwise an {@link InaccessibleObjectException}
|
||||
* will likely be thrown by a dispatcher.</i>
|
||||
*
|
||||
* @see EventDispatcher#register(Object)
|
||||
*/
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface EventListener {
|
||||
|
||||
/**
|
||||
* Specifies the priority of the listener. Default value is equal to {@link EventDispatcher#DEFAULT_PRIORITY}.
|
||||
* Higher priority listeners (the ones with less priority value) are executed first.
|
||||
*
|
||||
* @return the listener's priority
|
||||
* @see EventDispatcher#MAX_PRIORITY
|
||||
* @see EventDispatcher#MIN_PRIORITY
|
||||
* @see EventDispatcher#DEFAULT_PRIORITY
|
||||
*/
|
||||
byte priority() default EventDispatcher.DEFAULT_PRIORITY;
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package ru.fokinatorr.sparkle.event.dispatcher;
|
||||
|
||||
import ru.fokinatorr.sparkle.event.Event;
|
||||
import ru.fokinatorr.sparkle.event.annotation.EventListener;
|
||||
import ru.fokinatorr.sparkle.event.dispatcher.impl.DefaultEventDispatcher;
|
||||
import ru.fokinatorr.sparkle.event.input.MouseEvent;
|
||||
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
|
||||
|
||||
import java.lang.reflect.InaccessibleObjectException;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* An event dispatcher that can be used to fire/listen to events.
|
||||
* <p>Implementations are not required to throw a {@link NullPointerException} if a {@code null} reference was passed to any
|
||||
* method; they are allowed to silently ignore it and/or just log that a {@code null} reference was passed.
|
||||
* <p>Some implementations might need to perform cleanup when they're no longer needed, so this interface extends {@link NonThrowingAutoCloseable}.
|
||||
* <p><i>Warning: event listeners <b>should not</b> fire the same event they received, or events that cause
|
||||
* the same event to be re-fired. This can (and will in most cases) lead to infinite loops and unpredictable
|
||||
* behaviour. Implementations may try to prevent re-firing the same event, but are NOT required to.</i>
|
||||
*/
|
||||
public interface EventDispatcher extends NonThrowingAutoCloseable {
|
||||
/**
|
||||
* The maximal listener priority.
|
||||
*/
|
||||
byte MAX_PRIORITY = Byte.MIN_VALUE;
|
||||
/**
|
||||
* The minimal listener priority.
|
||||
*/
|
||||
byte MIN_PRIORITY = Byte.MAX_VALUE;
|
||||
/**
|
||||
* The default listener priority.
|
||||
*/
|
||||
byte DEFAULT_PRIORITY = 0;
|
||||
|
||||
/**
|
||||
* Adds a listener for event of the given type or any of its subclasses.
|
||||
* <p>
|
||||
* If the given event listener was already present, then its priority is set to {@link #DEFAULT_PRIORITY default value}.
|
||||
*
|
||||
* @param eventClass the type of the event
|
||||
* @param listener the listener to add
|
||||
* @return an object that can be used to remove the listener
|
||||
* @throws NullPointerException if any argument is {@code null} (optional)
|
||||
*/
|
||||
<E extends Event> ListenerRemover addListener(Class<E> eventClass, Consumer<? super E> listener);
|
||||
|
||||
/**
|
||||
* Adds a listener for event of the given type or any of its subclasses.
|
||||
* <p>
|
||||
* If the given event listener was already present, then its priority is set to the given one.
|
||||
*
|
||||
* @param eventClass the type of the event
|
||||
* @param priority the priority of the listener
|
||||
* @param listener the listener to add
|
||||
* @return an object that can be used to remove the listener
|
||||
* @throws NullPointerException if any argument is {@code null} (optional)
|
||||
* @see #MAX_PRIORITY
|
||||
* @see #MIN_PRIORITY
|
||||
*/
|
||||
<E extends Event> ListenerRemover addListener(Class<E> eventClass, byte priority, Consumer<? super E> listener);
|
||||
|
||||
/**
|
||||
* Registers all <b>instance</b> methods annotated with {@link EventListener @EventListener} of the given object's class as event listeners.
|
||||
* Or, if the given object is a {@link Class}, all its <b>static</b> methods annotated with {@link EventListener @EventListener}
|
||||
* are registered as listeners.
|
||||
*
|
||||
* @param o the object
|
||||
* @return an object that can be used to remove the listeners
|
||||
* @throws IllegalArgumentException if a method annotated with {@link EventListener @EventListener} has invalid arguments
|
||||
* @throws InaccessibleObjectException if a method could not be reflectively accessed for any reason
|
||||
* @throws NullPointerException if the object is {@code null} (optional)
|
||||
* @see EventListener
|
||||
*/
|
||||
ListenerRemover register(Object o);
|
||||
|
||||
/**
|
||||
* Determines whether there are registered event listeners that listen for the given event class or superclass.
|
||||
* This method can be used to determine whether firing an event has any effect. Useful to avoid firing an event
|
||||
* that is fired a lot of times (like {@link MouseEvent.MouseCursorMovedEvent MouseCursorMovedEvent}),
|
||||
* thus optimizing the CPU usage.
|
||||
* @param eventClass the event class to check for
|
||||
* @throws NullPointerException if the given class object is {@code null} (optional)
|
||||
* @return {@code true} if there are any registered listeners that listen for the given event class (or superclass),
|
||||
* {@code false} otherwise
|
||||
*/
|
||||
boolean hasListenersFor(Class<? extends Event> eventClass);
|
||||
|
||||
/**
|
||||
* Fires the given event, i.e. activates all listeners that listen to events of the given event's type or supertypes,
|
||||
* returning immediately.
|
||||
* <p>Be aware that listeners may change the mutable state of the given event.
|
||||
*
|
||||
* @param event the event to fire
|
||||
* @return a {@link CompletableFuture} that completes when all event handlers are done
|
||||
* @throws NullPointerException if the given event is {@code null} (optional)
|
||||
*/
|
||||
CompletableFuture<Void> fireEvent(Event event);
|
||||
|
||||
/**
|
||||
* Fires the given event, i.e. activates all listeners that listen to events of the given event's type or supertypes,
|
||||
* and waits until all event listeners are executed.
|
||||
* <p>Be aware that listeners may change the mutable state of the given event.
|
||||
*
|
||||
* @param event the event to fire
|
||||
* @throws NullPointerException if the given event is {@code null} (optional)
|
||||
*/
|
||||
default void fireEventAndWait(Event event) {
|
||||
fireEvent(event).join();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new default implementation of {@code EventDispatcher}.
|
||||
*
|
||||
* @return a new {@code EventDispatcher}
|
||||
*/
|
||||
static EventDispatcher newDefault() {
|
||||
return new DefaultEventDispatcher();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @implNote By default, this method does nothing. An event dispatcher doesn't usually have closeable resources.
|
||||
*/
|
||||
@Override
|
||||
default void close() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package ru.fokinatorr.sparkle.event.dispatcher;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* An object that knows how to remove a listener from a dispatcher. Extends {@link Runnable} for
|
||||
* convenience.
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface ListenerRemover extends Runnable {
|
||||
|
||||
/**
|
||||
* Removes the listener from the dispatcher. If the listener is already removed, will not have any effect.
|
||||
*/
|
||||
void remove();
|
||||
|
||||
/**
|
||||
* {@inheritDoc} Equivalent to {@link #remove()}.
|
||||
*/
|
||||
@Override
|
||||
default void run() {
|
||||
remove();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new {@code ListenerRemover} that firstly calls the {@link #remove()} method
|
||||
* of this {@code ListenerRemover}, then the {@link #remove()} method of the given one.
|
||||
* @param other the {@code ListenerRemover} to call after this one
|
||||
* @throws NullPointerException if the given {@code ListenerRemover} is {@code null}
|
||||
* @return a new composed {@code ListenerRemover}
|
||||
*/
|
||||
default ListenerRemover andThen(ListenerRemover other) {
|
||||
Objects.requireNonNull(other, "other");
|
||||
return () -> {
|
||||
try {
|
||||
remove();
|
||||
} finally {
|
||||
other.remove();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
package ru.fokinatorr.sparkle.event.dispatcher.impl;
|
||||
|
||||
import it.unimi.dsi.fastutil.bytes.Byte2ObjectRBTreeMap;
|
||||
import it.unimi.dsi.fastutil.bytes.Byte2ObjectSortedMap;
|
||||
import lombok.NonNull;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import ru.fokinatorr.sparkle.event.Event;
|
||||
import ru.fokinatorr.sparkle.event.annotation.EventListener;
|
||||
import ru.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
|
||||
import ru.fokinatorr.sparkle.event.dispatcher.ListenerRemover;
|
||||
import ru.fokinatorr.sparkle.util.concurrent.ContextInheritingThreadFactory;
|
||||
import ru.fokinatorr.sparkle.util.concurrent.ThreadType;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.lang.reflect.Parameter;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* Default implementation of {@link EventDispatcher}.
|
||||
*/
|
||||
// Not public API
|
||||
@Slf4j
|
||||
public class DefaultEventDispatcher implements EventDispatcher {
|
||||
|
||||
private record PrioritizedEventListener<E extends Event>(
|
||||
byte priority,
|
||||
@NonNull Consumer<? super E> listener
|
||||
) implements Consumer<E>, Comparable<PrioritizedEventListener<?>> {
|
||||
@Override
|
||||
public void accept(E e) {
|
||||
listener.accept(e);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(@NonNull PrioritizedEventListener<?> that) {
|
||||
return Byte.compare(that.priority, this.priority);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (!(o instanceof PrioritizedEventListener<?>(_, Consumer<?> listener1))) return false;
|
||||
return listener == listener1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return listener.hashCode();
|
||||
}
|
||||
}
|
||||
|
||||
private final EventListeners eventListeners = new EventListeners();
|
||||
// Use dedicated ExecutorService instead of common to prevent thread starvation
|
||||
private final ExecutorService dispatchEventExecutor = Executors.newCachedThreadPool(new ContextInheritingThreadFactory(
|
||||
"event-dispatcher-" + hashCode() + "-worker",
|
||||
ThreadType.VIRTUAL // virtual threads to avoid system overloading
|
||||
));
|
||||
private final Lock listenersLock = new ReentrantLock();
|
||||
|
||||
private static class EventListeners {
|
||||
|
||||
private final Map<Class<? extends Event>, NavigableSet<PrioritizedEventListener<?>>>
|
||||
map = new HashMap<>();
|
||||
|
||||
<E extends Event> NavigableSet<PrioritizedEventListener<? super E>> getOrCreate(Class<? extends E> eventClass) {
|
||||
//noinspection unchecked, RedundantCast
|
||||
return (NavigableSet<PrioritizedEventListener<? super E>>) (Object)
|
||||
map.computeIfAbsent(eventClass, _ -> new ConcurrentSkipListSet<>());
|
||||
}
|
||||
|
||||
<E extends Event> NavigableSet<PrioritizedEventListener<? super E>> getOrEmpty(Class<? extends E> eventClass) {
|
||||
return map.containsKey(eventClass) ? getOrCreate(eventClass) : Collections.emptyNavigableSet();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E extends Event> ListenerRemover addListener(Class<E> eventClass, Consumer<? super E> listener) {
|
||||
Objects.requireNonNull(eventClass, "event class");
|
||||
Objects.requireNonNull(listener, "listener");
|
||||
listenersLock.lock();
|
||||
try {
|
||||
return implAddListener(eventClass, listener, DEFAULT_PRIORITY);
|
||||
} finally {
|
||||
listenersLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E extends Event> ListenerRemover addListener(Class<E> eventClass, byte priority, Consumer<? super E> listener) {
|
||||
Objects.requireNonNull(eventClass, "event class");
|
||||
Objects.requireNonNull(listener, "listener");
|
||||
listenersLock.lock();
|
||||
try {
|
||||
return implAddListener(eventClass, listener, priority);
|
||||
} finally {
|
||||
listenersLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenerRemover register(Object o) {
|
||||
Objects.requireNonNull(o, "the object");
|
||||
Class<?> clazz;
|
||||
Object target;
|
||||
Predicate<Method> methodPredicate;
|
||||
ListenerRemover listenerRemover = null;
|
||||
if (o instanceof Class<?> cls) { // Register only static methods
|
||||
clazz = cls;
|
||||
target = null; // Static methods do not have an instance target
|
||||
methodPredicate = method -> Modifier.isStatic(method.getModifiers());
|
||||
} else { // Register instance methods
|
||||
clazz = o.getClass();
|
||||
target = o;
|
||||
methodPredicate = method -> !Modifier.isStatic(method.getModifiers());
|
||||
}
|
||||
listenersLock.lock();
|
||||
try {
|
||||
for (Method method : clazz.getDeclaredMethods()) {
|
||||
if (methodPredicate.test(method)) {
|
||||
EventListener eventListener = method.getAnnotation(EventListener.class);
|
||||
if (eventListener != null) {
|
||||
Class<? extends Event> eventClass = getListenedEvent(method);
|
||||
// if we're here the signature is valid
|
||||
method.setAccessible(true);
|
||||
ListenerRemover addend = implAddListener(
|
||||
eventClass,
|
||||
asEventListener(method, target),
|
||||
eventListener.priority()
|
||||
);
|
||||
if (listenerRemover == null) {
|
||||
listenerRemover = addend;
|
||||
} else {
|
||||
listenerRemover = listenerRemover.andThen(addend);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (listenerRemover == null) {
|
||||
listenerRemover = () -> {
|
||||
};
|
||||
log.warn("No @EventListener methods were found in {}", clazz);
|
||||
}
|
||||
return listenerRemover;
|
||||
} finally {
|
||||
listenersLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasListenersFor(Class<? extends Event> eventClass) {
|
||||
Objects.requireNonNull(eventClass, "event class");
|
||||
return eventListeners.map.keySet().stream().anyMatch(cls -> cls.isAssignableFrom(eventClass));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> fireEvent(Event event) {
|
||||
Objects.requireNonNull(event, "event");
|
||||
|
||||
listenersLock.lock();
|
||||
try {
|
||||
// Recollect listeners by priority, in order from highest to lowest
|
||||
Byte2ObjectSortedMap<List<Consumer<Event>>> listenersByPriority = new Byte2ObjectRBTreeMap<>();
|
||||
Set<Class<? extends Event>> handledTypes = new HashSet<>();
|
||||
|
||||
for (var entry : eventListeners.map.entrySet()) {
|
||||
Class<? extends Event> eventClass = entry.getKey();
|
||||
NavigableSet<PrioritizedEventListener<?>> listeners = entry.getValue();
|
||||
|
||||
if (handledTypes.add(eventClass) && !listeners.isEmpty() && eventClass.isAssignableFrom(event.getClass())) {
|
||||
for (PrioritizedEventListener<?> listener : listeners) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Consumer<Event> typedListener = (Consumer<Event>) listener.listener();
|
||||
listenersByPriority
|
||||
.computeIfAbsent(listener.priority(), _ -> new ArrayList<>())
|
||||
.add(typedListener);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CompletableFuture<Void> chain = CompletableFuture.completedFuture(null);
|
||||
if (!listenersByPriority.isEmpty()) {
|
||||
for (var groupListeners : listenersByPriority.values()) {
|
||||
// Different priority listeners get executed sequentially, from highest to lowest
|
||||
chain = chain.thenCompose(_ -> {
|
||||
List<CompletableFuture<Void>> futures = groupListeners.stream()
|
||||
.map(listener -> CompletableFuture.runAsync(
|
||||
() -> listener.accept(event),
|
||||
dispatchEventExecutor
|
||||
))
|
||||
.toList();
|
||||
|
||||
// Same priority listeners get executed concurrently
|
||||
return CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new));
|
||||
});
|
||||
}
|
||||
} // else silently ignore the event and return an empty future
|
||||
return chain;
|
||||
} finally {
|
||||
listenersLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
// We need cleanup
|
||||
dispatchEventExecutor.close();
|
||||
}
|
||||
|
||||
// Assumes null checks were done
|
||||
private <E extends Event> ListenerRemover implAddListener(Class<E> eventClass, Consumer<? super E> cons, byte priority) {
|
||||
NavigableSet<PrioritizedEventListener<? super E>> set = eventListeners.getOrCreate(eventClass);
|
||||
PrioritizedEventListener<? super E> listener = new PrioritizedEventListener<>(priority, cons);
|
||||
// If there was such a listener, call remove and then add to replace the priority
|
||||
set.remove(listener);
|
||||
set.add(listener);
|
||||
log.info("Registered a listener for event {}: {}", eventClass.getName(), listener);
|
||||
return () -> {
|
||||
set.remove(listener);
|
||||
log.info("Unregistered a listener for event {}: {}", eventClass.getName(), listener);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws IllegalArgumentException if the signature of the method is invalid
|
||||
*/
|
||||
private static Class<? extends Event> getListenedEvent(Method method) {
|
||||
Parameter[] parameters = method.getParameters();
|
||||
if (parameters.length != 1) {
|
||||
throw new IllegalArgumentException(
|
||||
"Illegal @EventListener method parameter count; expected 1, found " + parameters.length
|
||||
+ " (in method " + method + ")"
|
||||
);
|
||||
}
|
||||
Class<?> cls = parameters[0].getType();
|
||||
if (!Event.class.isAssignableFrom(cls)) {
|
||||
throw new IllegalArgumentException(
|
||||
"Illegal @EventListener method parameter type: expected " + Event.class.getName()
|
||||
+ " or subinterface/implementation, found " + cls.getName() + " (in method " + method + ")"
|
||||
);
|
||||
}
|
||||
return cls.asSubclass(Event.class);
|
||||
}
|
||||
|
||||
private static <E extends Event> Consumer<E> asEventListener(Method method, Object target) {
|
||||
return e -> {
|
||||
try {
|
||||
method.invoke(target, e);
|
||||
} catch (InvocationTargetException ex) {
|
||||
log.error("Listener threw exception", ex.getCause());
|
||||
} catch (IllegalAccessException ex) {
|
||||
throw new AssertionError(
|
||||
"Unexpected IllegalAccessException thrown, method should have been setAccessible(true)",
|
||||
ex
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package ru.fokinatorr.sparkle.event.input;
|
||||
|
||||
import ru.fokinatorr.sparkle.event.Event;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
|
||||
/**
|
||||
* Base interface for events representing a user input (keyboard, mouse, etc.)
|
||||
*/
|
||||
public interface InputEvent extends Event {
|
||||
|
||||
/**
|
||||
* Returns the stage on which the input was performed.
|
||||
* @return the target stage
|
||||
*/
|
||||
Stage stage();
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package ru.fokinatorr.sparkle.event.input;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
|
||||
/**
|
||||
* Represents a key on the keyboard. This enum class should generally not be used to determine
|
||||
* the actual typed character.
|
||||
* <p>Note that there are different names and/or typical behaviour for several modifier keys and the
|
||||
* {@link #MENU Menu} key, as listed below:
|
||||
* <table style="width: 100%; table-layout: fixed;">
|
||||
* <tr>
|
||||
* <td style="width: 13%"><b>Key named as it is in this class</b></td>
|
||||
* <td style="width: 20%"><b>Windows</b></td>
|
||||
* <td style="width: 20%"><b>Linux</b></td>
|
||||
* <td style="width: 20%"><b>macOS</b></td>
|
||||
* <td style="width: 27%"><b>Notes</b></td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>{@link #LEFT_SHIFT Shift}</td>
|
||||
* <td>Shift</td>
|
||||
* <td>Shift</td>
|
||||
* <td>Shift</td>
|
||||
* <td>Same function across all OSes.</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>{@link #LEFT_CONTROL Control}</td>
|
||||
* <td>Control</td>
|
||||
* <td>Control</td>
|
||||
* <td>Control</td>
|
||||
* <td>Less common for app shortcuts on macOS.</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>{@link #LEFT_ALT Alt}</td>
|
||||
* <td>Alt</td>
|
||||
* <td>Alt</td>
|
||||
* <td>Option</td>
|
||||
* <td>Generally the same function.</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>{@link #LEFT_META Meta}</td>
|
||||
* <td>Windows</td>
|
||||
* <td>Super (typically)</td>
|
||||
* <td>Command</td>
|
||||
* <td>Key used for OS-level functions, the main shortcut key on macOS.</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>{@link #MENU Menu}</td>
|
||||
* <td>Context menu/Application key</td>
|
||||
* <td>Menu</td>
|
||||
* <td>N/A</td>
|
||||
* <td>This key is typically not present on macOS, where the context menu functionality is accessed differently.
|
||||
* Pressing this key still can be detected on macOS, though.</td>
|
||||
* </tr>
|
||||
* </table>
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
|
||||
public enum Key {
|
||||
|
||||
// printable keys
|
||||
|
||||
// spec. symbol keys
|
||||
SPACE(' '),
|
||||
APOSTROPHE('\''),
|
||||
COMMA(','),
|
||||
MINUS('-'),
|
||||
PERIOD('.'),
|
||||
SLASH('/'),
|
||||
SEMICOLON(';'),
|
||||
EQUALS('='),
|
||||
LEFT_SQUARE_BRACKET('['),
|
||||
RIGHT_SQUARE_BRACKET(']'),
|
||||
BACKSLASH('\\'),
|
||||
GRAVE_ACCENT('`'),
|
||||
/**
|
||||
* This key does not have a US mapping, and has different meanings on different layouts.
|
||||
*/
|
||||
WORLD_1('\0'), // non-US #1
|
||||
/**
|
||||
* This key does not have a US mapping, and has different meanings on different layouts.
|
||||
*/
|
||||
WORLD_2('\0'), // non-US #2
|
||||
|
||||
// digit keys
|
||||
KEY_0('0'),
|
||||
KEY_1('1'),
|
||||
KEY_2('2'),
|
||||
KEY_3('3'),
|
||||
KEY_4('4'),
|
||||
KEY_5('5'),
|
||||
KEY_6('6'),
|
||||
KEY_7('7'),
|
||||
KEY_8('8'),
|
||||
KEY_9('9'),
|
||||
|
||||
// letter keys
|
||||
A('A'),
|
||||
B('B'),
|
||||
C('C'),
|
||||
D('D'),
|
||||
E('E'),
|
||||
F('F'),
|
||||
G('G'),
|
||||
H('H'),
|
||||
I('I'),
|
||||
J('J'),
|
||||
K('K'),
|
||||
L('L'),
|
||||
M('M'),
|
||||
N('N'),
|
||||
O('O'),
|
||||
P('P'),
|
||||
Q('Q'),
|
||||
R('R'),
|
||||
S('S'),
|
||||
T('T'),
|
||||
U('U'),
|
||||
V('V'),
|
||||
W('W'),
|
||||
X('X'),
|
||||
Y('Y'),
|
||||
Z('Z'),
|
||||
|
||||
// function keys
|
||||
|
||||
ESCAPE,
|
||||
ENTER,
|
||||
TAB('\t', true),
|
||||
BACKSPACE,
|
||||
INSERT,
|
||||
DELETE,
|
||||
// arrow keys
|
||||
RIGHT, LEFT, UP, DOWN,
|
||||
// navigation keys
|
||||
PAGE_UP, PAGE_DOWN, HOME, END,
|
||||
// ... Lock keys
|
||||
CAPS_LOCK, SCROLL_LOCK, NUM_LOCK,
|
||||
PRINT_SCREEN,
|
||||
PAUSE,
|
||||
// F... keys
|
||||
F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24, F25,
|
||||
// Numpad keys, these are function keys according to GLFW
|
||||
NUMPAD_0('0', true),
|
||||
NUMPAD_1('1', true),
|
||||
NUMPAD_2('2', true),
|
||||
NUMPAD_3('3', true),
|
||||
NUMPAD_4('4', true),
|
||||
NUMPAD_5('5', true),
|
||||
NUMPAD_6('6', true),
|
||||
NUMPAD_7('7', true),
|
||||
NUMPAD_8('8', true),
|
||||
NUMPAD_9('9', true),
|
||||
NUMPAD_DECIMAL_POINT('.', true),
|
||||
NUMPAD_DIVIDE('/', true),
|
||||
NUMPAD_MULTIPLY('*', true),
|
||||
NUMPAD_SUBTRACT('-', true),
|
||||
NUMPAD_ADD('+', true),
|
||||
NUMPAD_ENTER,
|
||||
NUMPAD_EQUALS('=', true),
|
||||
|
||||
// modifier keys
|
||||
LEFT_SHIFT, RIGHT_SHIFT,
|
||||
LEFT_CONTROL, RIGHT_CONTROL,
|
||||
// AKA Option key on Mac
|
||||
LEFT_ALT, RIGHT_ALT,
|
||||
// AKA Windows key on Windows, Super key on Linux, Command key on Mac
|
||||
LEFT_META, RIGHT_META,
|
||||
|
||||
/**
|
||||
* The menu (AKA Context menu or Application (on Windows)) key. Typically not present on Mac.
|
||||
*/
|
||||
MENU;
|
||||
|
||||
/**
|
||||
* Constructor for non-function keys with US mapping.
|
||||
* @param character the character
|
||||
*/
|
||||
Key(char character) {
|
||||
this(character, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor for function keys without US mapping.
|
||||
*/
|
||||
Key() {
|
||||
this('\0', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* The character, is equal to {@code 0} if this key does not have a US mapping
|
||||
*/
|
||||
char character;
|
||||
/**
|
||||
* {@code true} if this key is a function key, {@code false} if this key is a printable key.
|
||||
*/
|
||||
@Getter
|
||||
boolean functionKey;
|
||||
|
||||
/**
|
||||
* Returns the US mapping for this key, if any, else throws an exception. Most printable keys
|
||||
* have a US mapping, but not all of them; most function keys do not have a US mapping, but not all of them.
|
||||
* @return the US mapping for this key, if any
|
||||
* @throws IllegalStateException if there is no US mapping for the given key
|
||||
*/
|
||||
public char getUSMapping() {
|
||||
if (character == 0) {
|
||||
throw new IllegalStateException("Key " + name() + " does not have a US mapping.");
|
||||
}
|
||||
return character;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether this key has a US mapping character. In other words, {@code true}
|
||||
* if {@link #getUSMapping()} would return a value, or {@code false} if it would throw an
|
||||
* exception.
|
||||
* @return {@code true} if this key has a US mapping, {@code false} otherwise
|
||||
*/
|
||||
public boolean hasUSMapping() {
|
||||
return character != 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package ru.fokinatorr.sparkle.event.input;
|
||||
|
||||
import lombok.NonNull;
|
||||
import lombok.experimental.NonFinal;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Base interface for events representing a keyboard event.
|
||||
* <p><i>Note for Scratchers: This event is similar to the "when [ v] key pressed" in Scratch. Unfortunately,
|
||||
* there is no universal event type for every single key. See the JavaDoc of the subinterfaces & implementations
|
||||
* to see which event type you need.</i>
|
||||
*/
|
||||
public sealed interface KeyboardEvent extends InputEvent
|
||||
permits KeyboardEvent.KeyEvent,
|
||||
KeyboardEvent.CharInputEvent {
|
||||
|
||||
/**
|
||||
* Returns the stage on which the event was done.
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
Stage stage();
|
||||
|
||||
/**
|
||||
* Base interface for events representing a physical key input. This event can be used
|
||||
* to detect function keys.
|
||||
* <p><i>Important note: This interface should NOT be used to input a character since physical
|
||||
* keys can not be mapped 1:1 to characters. The character value depends on the keyboard layout,
|
||||
* modifier keys held, etc. Most function keys do not even have a character representation. Use
|
||||
* {@link KeyboardEvent.CharInputEvent CharInputEvent} for that purpose.</i>
|
||||
*/
|
||||
non-sealed interface KeyEvent extends KeyboardEvent {
|
||||
// Modifier bits
|
||||
/**
|
||||
* If this bit is set in modifiers, one or more Shift keys were held down.
|
||||
*/
|
||||
int MOD_SHIFT = 0x1;
|
||||
/**
|
||||
* If this bit is set in modifiers, one or more Control keys were held down.
|
||||
*/
|
||||
int MOD_CONTROL = 0x2;
|
||||
/**
|
||||
* If this bit is set in modifiers, one or more Alt (AKA Option on Mac) keys were held down.
|
||||
*/
|
||||
int MOD_ALT = 0x4;
|
||||
/**
|
||||
* If this bit is set in modifiers, one or more Meta (AKA Windows on Windows, Super on Linux, Command on Mac)
|
||||
* keys were held down.
|
||||
*/
|
||||
int MOD_META = 0x8;
|
||||
/**
|
||||
* If this bit is set in modifiers, the Caps Lock key is enabled.
|
||||
*/
|
||||
int MOD_CAPS_LOCK = 0x10;
|
||||
/**
|
||||
* If this bit is set in modifiers, the Num Lock key is enabled.
|
||||
*/
|
||||
int MOD_NUM_LOCK = 0x20;
|
||||
|
||||
/**
|
||||
* Returns the physical key this event is associated with.
|
||||
* @return the key
|
||||
*/
|
||||
Key key();
|
||||
|
||||
/**
|
||||
* Returns the bitfield describing which modifier keys were held down.
|
||||
* <p>Example of checking if a modifier was present:
|
||||
* <blockquote><pre>
|
||||
* // ...
|
||||
* int mod = event.modifiers();
|
||||
* if ((mod & KeyEvent.MOD_SHIFT) != 0) {
|
||||
* // do something if the Shift key was down
|
||||
* }
|
||||
* if ((mod & KeyEvent.MOD_NUM_LOCK) != 0) {
|
||||
* // do something if Num Lock was enabled
|
||||
* }
|
||||
* if ((mod & KeyEvent.MOD_ALT) == KeyEvent.MOD_ALT) {
|
||||
* // do something if ONLY the Alt/Option key was down
|
||||
* }
|
||||
* // ...
|
||||
* </pre></blockquote>
|
||||
* @return the modifier keys that were held/enabled
|
||||
* @see #MOD_SHIFT
|
||||
* @see #MOD_CONTROL
|
||||
* @see #MOD_ALT
|
||||
* @see #MOD_META
|
||||
* @see #MOD_CAPS_LOCK
|
||||
* @see #MOD_NUM_LOCK
|
||||
*/
|
||||
int modifiers();
|
||||
|
||||
/**
|
||||
* Returns whether one of the Shift keys was held down.
|
||||
* @return whether Shift was held down
|
||||
* @see Key
|
||||
* @see Key#LEFT_SHIFT
|
||||
* @see Key#RIGHT_SHIFT
|
||||
*/
|
||||
default boolean isShiftDown() {
|
||||
return (modifiers() & MOD_SHIFT) != 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether one of the Control keys was held down.
|
||||
* @return whether Control was held down
|
||||
* @see Key
|
||||
* @see Key#LEFT_CONTROL
|
||||
* @see Key#RIGHT_CONTROL
|
||||
*/
|
||||
default boolean isControlDown() {
|
||||
return (modifiers() & MOD_CONTROL) != 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether one of the Alt keys was held down.
|
||||
* @return whether Alt was held down
|
||||
* @see Key
|
||||
* @see Key#LEFT_ALT
|
||||
* @see Key#RIGHT_ALT
|
||||
*/
|
||||
default boolean isAltDown() {
|
||||
return (modifiers() & MOD_ALT) != 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether one of the Meta keys was held down.
|
||||
* @return whether Meta was held down
|
||||
* @see Key
|
||||
* @see Key#LEFT_META
|
||||
* @see Key#RIGHT_META
|
||||
*/
|
||||
default boolean isMetaDown() {
|
||||
return (modifiers() & MOD_META) != 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return whether Caps Lock was enabled}
|
||||
* @see Key#CAPS_LOCK
|
||||
*/
|
||||
default boolean isCapsLockOn() {
|
||||
return (modifiers() & MOD_CAPS_LOCK) != 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return whether Num Lock was enabled}
|
||||
* @see Key#NUM_LOCK
|
||||
*/
|
||||
default boolean isNumLockOn() {
|
||||
return (modifiers() & MOD_NUM_LOCK) != 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This event is fired when a key is pressed.
|
||||
* @param stage the stage on which the key was pressed
|
||||
* @param key the physical key that was pressed
|
||||
* @param modifiers the modifier key bitfield
|
||||
*/
|
||||
record KeyPressedEvent(@NonNull Stage stage, @NonNull Key key, int modifiers) implements KeyEvent {
|
||||
}
|
||||
|
||||
/**
|
||||
* This event is fired when a key is released.
|
||||
* @param stage the stage on which the key was released
|
||||
* @param key the physical key that was released
|
||||
* @param modifiers the modifier key bitfield
|
||||
*/
|
||||
record KeyReleasedEvent(@NonNull Stage stage, @NonNull Key key, int modifiers) implements KeyEvent {
|
||||
}
|
||||
|
||||
/**
|
||||
* This event is fired when a key was held long enough to be repeated. This event indicates that the
|
||||
* key is still held down.
|
||||
* @param stage the stage on which the key was repeated
|
||||
* @param key the physical key that was repeated
|
||||
* @param modifiers the modifier key bitfield
|
||||
*/
|
||||
record KeyRepeatedEvent(@NonNull Stage stage, @NonNull Key key, int modifiers) implements KeyEvent {
|
||||
}
|
||||
|
||||
/**
|
||||
* This event is fired when a character is emitted because a key was pressed or some key combination was used.
|
||||
* @param stage the stage on which the character was emitted
|
||||
* @param codePoint the character Unicode code point, always in range between {@link Character#MIN_CODE_POINT}
|
||||
* and {@link Character#MAX_CODE_POINT} (both inclusive)
|
||||
*/
|
||||
record CharInputEvent(@NonNull Stage stage, int codePoint) implements KeyboardEvent {
|
||||
|
||||
/**
|
||||
* Constructs a new {@code CharInputEvent}.
|
||||
* @throws NullPointerException if the target stage is {@code null}
|
||||
* @param codePoint the character Unicode code point; must be between {@link Character#MIN_CODE_POINT}
|
||||
* and {@link Character#MAX_CODE_POINT} (both inclusive)
|
||||
* @throws IllegalArgumentException if the provided code point is not in the valid range
|
||||
*/
|
||||
public CharInputEvent {
|
||||
Objects.requireNonNull(stage, "target stage");
|
||||
// Character.isValidCodePoint(int) is an optimized version of:
|
||||
// codePoint >= MIN_CODE_POINT && codePoint <= MAX_CODE_POINT
|
||||
if (!Character.isValidCodePoint(codePoint)) {
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid Unicode code point: U+" + Integer.toHexString(codePoint).toUpperCase(Locale.ENGLISH)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the character representation of the stored {@link #codePoint() Unicode code point}.
|
||||
* For code points within the Basic Multilingual Plane (BMP), i.e. characters within the range
|
||||
* {@code [U+0000; U+FFFF]}, there will be a single character in the returned string's char array.
|
||||
* For code points outside the BMP, there will be a surrogate character pair in the returned string's char array.
|
||||
* @return the {@link String} representation of the stored code point
|
||||
*/
|
||||
@SuppressWarnings("SpellCheckingInspection")
|
||||
public String character() {
|
||||
return Character.toString(codePoint);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package ru.fokinatorr.sparkle.event.input;
|
||||
|
||||
/**
|
||||
* Represents a mouse button.
|
||||
*/
|
||||
public enum MouseButton {
|
||||
/**
|
||||
* The left (button 1) mouse button.
|
||||
*/
|
||||
LEFT,
|
||||
/**
|
||||
* The middle (button 3, usually the wheel) mouse button.
|
||||
*/
|
||||
MIDDLE,
|
||||
/**
|
||||
* The right (button 2) mouse button.
|
||||
*/
|
||||
RIGHT,
|
||||
|
||||
BUTTON_4,
|
||||
BUTTON_5,
|
||||
BUTTON_6,
|
||||
BUTTON_7,
|
||||
BUTTON_8
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package ru.fokinatorr.sparkle.event.input;
|
||||
|
||||
import lombok.NonNull;
|
||||
import ru.fokinatorr.sparkle.phys2d.Point2D;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.EnumSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Base interface for events representing a mouse/cursor user input.
|
||||
*/
|
||||
public sealed interface MouseEvent extends InputEvent
|
||||
permits MouseEvent.MouseButtonEvent, MouseEvent.MouseCursorMovedEvent, MouseEvent.MouseScrolledEvent {
|
||||
|
||||
/**
|
||||
* Returns the stage on which the event was done.
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
Stage stage();
|
||||
|
||||
/**
|
||||
* Returns the X coordinate on the stage where this event was performed.
|
||||
* @return the X coordinate
|
||||
*/
|
||||
double x();
|
||||
|
||||
/**
|
||||
* Returns the Y coordinate on the stage where this event was performed.
|
||||
* @return the Y coordinate
|
||||
*/
|
||||
double y();
|
||||
|
||||
/**
|
||||
* Returns the position on the stage where this event was performed.
|
||||
* @return the position
|
||||
*/
|
||||
default Point2D position() {
|
||||
return new Point2D(x(), y());
|
||||
}
|
||||
|
||||
/**
|
||||
* Base interface for events representing a mouse button state (pressed/released) change.
|
||||
*/
|
||||
non-sealed interface MouseButtonEvent extends MouseEvent {
|
||||
/**
|
||||
* Returns the mouse button which this event is related to.
|
||||
* @return the mouse button
|
||||
*/
|
||||
MouseButton button();
|
||||
|
||||
/**
|
||||
* Determines whether the mouse button was pressed at the moment when this event was fired.
|
||||
* @return {@code true} if the button is pressed, {@code false} otherwise
|
||||
*/
|
||||
boolean isPressed();
|
||||
}
|
||||
|
||||
// Generic events
|
||||
|
||||
/**
|
||||
* This event is fired when a mouse button was pressed on a stage.
|
||||
* @param button the mouse button that was pressed
|
||||
* @param stage the stage on which the mouse button was pressed
|
||||
* @param x the X coordinate of the cursor when the mouse button was pressed
|
||||
* @param y the Y coordinate of the cursor when the mouse button was pressed
|
||||
*/
|
||||
record MousePressedEvent(@NonNull MouseButton button, @NonNull Stage stage, double x, double y) implements MouseButtonEvent {
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isPressed() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This event is fired when a mouse button was released on a stage.
|
||||
* @param button the mouse button that was released
|
||||
* @param stage the stage on which the mouse button was released
|
||||
* @param x the X coordinate of the cursor when the mouse button was released
|
||||
* @param y the Y coordinate of the cursor when the mouse button was released
|
||||
*/
|
||||
record MouseReleasedEvent(@NonNull MouseButton button, @NonNull Stage stage, double x, double y) implements MouseButtonEvent {
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isPressed() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This event is fired when mouse cursor was moved on a stage.
|
||||
* @param stage the stage on which the cursor was moved
|
||||
* @param oldX the old X coordinate of the cursor
|
||||
* @param oldY the old Y coordinate of the cursor
|
||||
* @param newX the new X coordinate of the cursor
|
||||
* @param newY the new Y coordinate of the cursor
|
||||
* @param pressedButtons the buttons that were pressed when the cursor was moved (immutable)
|
||||
*/
|
||||
record MouseCursorMovedEvent(
|
||||
Stage stage,
|
||||
double oldX, double oldY,
|
||||
double newX, double newY,
|
||||
Set<MouseButton> pressedButtons
|
||||
) implements MouseEvent {
|
||||
|
||||
/**
|
||||
* Constructs a new {@code MouseCursorMovedEvent}.
|
||||
* @throws NullPointerException if any argument is {@code null}, or if {@code pressedButtons} contains {@code null}s
|
||||
*/
|
||||
public MouseCursorMovedEvent {
|
||||
Objects.requireNonNull(stage, "stage");
|
||||
Objects.requireNonNull(pressedButtons, "pressed buttons");
|
||||
// null elements not allowed in an EnumSet
|
||||
pressedButtons = Collections.unmodifiableSet(EnumSet.copyOf(pressedButtons));
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new {@code MouseCursorMovedEvent}.
|
||||
* @param stage the stage on which the mouse was moved
|
||||
* @param oldX the old X coordinate of the mouse
|
||||
* @param oldY the old Y coordinate of the mouse
|
||||
* @param newX the new X coordinate of the mouse
|
||||
* @param newY the new Y coordinate of the mouse
|
||||
* @param pressedButtons the buttons that were pressed when the mouse was moved
|
||||
* @throws NullPointerException if any argument is {@code null}, or if {@code pressedButtons} contains {@code null}s
|
||||
*/
|
||||
public MouseCursorMovedEvent(Stage stage, double oldX, double oldY, double newX, double newY, MouseButton... pressedButtons) {
|
||||
this(stage, oldX, oldY, newX, newY,
|
||||
// implicit null element check
|
||||
Objects.requireNonNull(pressedButtons, "pressed buttons").length == 0
|
||||
? EnumSet.noneOf(MouseButton.class)
|
||||
: EnumSet.of(pressedButtons[0], pressedButtons)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc} For this event, it's equal to the new X coordinate.
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public double x() {
|
||||
return newX;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc} For this event, it's equal to the new Y coordinate.
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public double y() {
|
||||
return newY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the difference between the new and the old X coordinate of the mouse.
|
||||
* @return delta movement along the X axis
|
||||
*/
|
||||
public double deltaX() {
|
||||
return newX - oldX;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the difference between the new and the old Y coordinate of the mouse.
|
||||
* @return delta movement along the Y axis
|
||||
*/
|
||||
public double deltaY() {
|
||||
return newY - oldY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the old position of the mouse.
|
||||
* @return the old position
|
||||
*/
|
||||
public Point2D oldPosition() {
|
||||
return new Point2D(oldX, oldY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the new position of the mouse.
|
||||
* @return the new position
|
||||
*/
|
||||
public Point2D newPosition() {
|
||||
return new Point2D(newX, newY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Point2D position() {
|
||||
return newPosition();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the delta movement vector from the old position to the new one.
|
||||
* @return the delta movement vector
|
||||
* @see #deltaX()
|
||||
* @see #deltaY()
|
||||
*/
|
||||
public Point2D deltaMovement() {
|
||||
return new Point2D(deltaX(), deltaY());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This event a fired when one of the mouse wheels were scrolled on a stage.
|
||||
* <p>Typically older mice have only a vertical scroll wheel; some modern mice have an additional horizontal one.
|
||||
* @param stage the stage on which the mouse was scrolled
|
||||
* @param x the X coordinate of the mouse cursor
|
||||
* @param y the Y coordinate of the mouse cursor
|
||||
* @param dx the horizontal scroll delta
|
||||
* @param dy the vertical scroll delta
|
||||
*/
|
||||
record MouseScrolledEvent(
|
||||
@NonNull Stage stage,
|
||||
double x, double y,
|
||||
double dx, double dy
|
||||
) implements MouseEvent {
|
||||
|
||||
/**
|
||||
* Returns a vector representing total scroll delta.
|
||||
* @return the delta scroll in each direction
|
||||
*/
|
||||
public Point2D deltaScroll() {
|
||||
return new Point2D(dx, dy);
|
||||
}
|
||||
}
|
||||
|
||||
// Composite events
|
||||
|
||||
/**
|
||||
* This event is fired when a mouse button was clicked on a stage, i.e. pressed and quickly released.
|
||||
* @param button the mouse button that was clicked
|
||||
* @param stage the stage on which the mouse button was clicked
|
||||
* @param x the X coordinate on which the mouse button was clicked
|
||||
* @param y the Y coordinate on which the mouse button was clicked
|
||||
*/
|
||||
record MouseClickedEvent(@NonNull MouseButton button, @NonNull Stage stage, double x, double y) implements MouseButtonEvent {
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isPressed() {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package ru.fokinatorr.sparkle.event.lifecycle;
|
||||
|
||||
import lombok.Value;
|
||||
import ru.fokinatorr.sparkle.event.Event;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
|
||||
/**
|
||||
* Base interface for events that are fired when a stage's state is changed.
|
||||
*/
|
||||
public sealed interface StageStateChangeEvent extends Event
|
||||
permits StageStateChangeEvent.StartEvent,
|
||||
StageStateChangeEvent.StopEvent {
|
||||
|
||||
/**
|
||||
* Returns the state which is set within a stage before this event is fired.
|
||||
*
|
||||
* @return the state
|
||||
*/
|
||||
Stage.State getState();
|
||||
|
||||
/**
|
||||
* Returns the stage whose state was changed.
|
||||
*
|
||||
* @return the stage
|
||||
*/
|
||||
Stage getStage();
|
||||
|
||||
/**
|
||||
* This event is fired when the start button is clicked.
|
||||
* <p><i>Note for Scratchers: This event is similar to "when green flag clicked" event in Scratch.</i>
|
||||
*/
|
||||
@Value
|
||||
class StartEvent implements StageStateChangeEvent {
|
||||
Stage stage;
|
||||
|
||||
/**
|
||||
* @param stage the stage on which the start button was clicked
|
||||
*/
|
||||
StartEvent(Stage stage) {
|
||||
this.stage = stage;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public Stage.State getState() {
|
||||
return Stage.State.RUNNING;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public Stage getStage() {
|
||||
return stage;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// There is no event for pause button; it just calls DebugUtils.debugSuspend()
|
||||
|
||||
/**
|
||||
* This event is fired when the stop button is clicked, or
|
||||
*/
|
||||
@Value
|
||||
class StopEvent implements StageStateChangeEvent {
|
||||
Stage stage;
|
||||
|
||||
/**
|
||||
* @param stage the stage on which the stop button is clicked
|
||||
*/
|
||||
StopEvent(Stage stage) {
|
||||
this.stage = stage;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public Stage.State getState() {
|
||||
return Stage.State.STOPPING;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public Stage getStage() {
|
||||
return stage;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package ru.fokinatorr.sparkle.event.lifecycle;
|
||||
|
||||
import lombok.*;
|
||||
import ru.fokinatorr.sparkle.event.AbstractCancellableEvent;
|
||||
import ru.fokinatorr.sparkle.internal.access.EventLifecycleAccess;
|
||||
import ru.fokinatorr.sparkle.internal.access.SharedSecrets;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
|
||||
import static lombok.AccessLevel.NONE;
|
||||
|
||||
/**
|
||||
* This event is fired every stage loop tick, up to {@link Stage#getFPSLimit()} times per second.
|
||||
* <p>If one of this event instances gets cancelled, the loop will be stopped and a {@link StageStateChangeEvent.StopEvent} will be fired.
|
||||
* <p><i>Note for Scratchers: This event is similar to the "forever" block in Scratch, and you should use it instead of
|
||||
* {@code while (true) {...}} loops without {@code break} statements for code that must run every cycle.</i>
|
||||
*/
|
||||
@Value
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@AllArgsConstructor(access = NONE)
|
||||
@RequiredArgsConstructor
|
||||
public class TickEvent extends AbstractCancellableEvent {
|
||||
|
||||
static {
|
||||
SharedSecrets.setEventLifecycleAccess(new EventLifecycleAccess() {
|
||||
@Override
|
||||
public StageStateChangeEvent.StartEvent newStartEvent(Stage stage) {
|
||||
return new StageStateChangeEvent.StartEvent(stage);
|
||||
}
|
||||
|
||||
@Override
|
||||
public StageStateChangeEvent.StopEvent newStopEvent(Stage stage) {
|
||||
return new StageStateChangeEvent.StopEvent(stage);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The stage being ticked.
|
||||
*/
|
||||
Stage stage;
|
||||
/**
|
||||
* The time between the current and the previous tick in milliseconds.
|
||||
*/
|
||||
double deltaTime;
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
package ru.fokinatorr.sparkle.graphics;
|
||||
|
||||
import lombok.experimental.UtilityClass;
|
||||
|
||||
/**
|
||||
* Utility methods that help treating an {@code int} value as a ARGB-format color.
|
||||
* <p>
|
||||
* ARGB stands for <span style="background-color: #000000;" color="rgba(255, 255, 255, 0.5)">Alpha</span> (opacity),
|
||||
* <span color="#FF0000">Red</span>,
|
||||
* <span color="#00FF00">Green</span>,
|
||||
* <span color="#0000FF">Blue</span>.
|
||||
* Each of these properties are called color components
|
||||
* or channels. Each component takes up 8 bits of the number, which means they range between 0 and 255 inclusive, and the
|
||||
* resulting component values in blending methods are clamped between that range.
|
||||
* <p>
|
||||
* The bits of an {@code int} value are treated as follows, assuming bit {@code 0} is
|
||||
* the most significant bit, and bit {@code 31} is the least significant bit:
|
||||
* <ul>
|
||||
* <li>bits from {@code 0} to {@code 7} representing alpha value,</li>
|
||||
* <li>bits from {@code 8} to {@code 15} representing red value,</li>
|
||||
* <li>bits from {@code 16} to {@code 23} representing green value,</li>
|
||||
* <li>bits from {@code 24} to {@code 31} representing blue value.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p><i>Note for Scratchers: Subtractive and multiplicative blendings have 2 different variations: layered ({@code rgbXxx()})
|
||||
* and true ({@code blendXxx()}). Layered variants always use additive blending for alpha channels - similarly to what Scratch does when
|
||||
* half-transparent sprites overlap. True variants use the same blending for all channels, which is what most modern software (including image
|
||||
* editors) do. <b>Be careful with true blendings; for example, using {@link #blendSubtract(int, int) true subtractive blending} on two opaque colors will
|
||||
* result in a fully transparent color!</b></i>
|
||||
*/
|
||||
@UtilityClass
|
||||
public class ARGB {
|
||||
|
||||
// Getting the color values
|
||||
|
||||
/**
|
||||
* Returns the alpha value of the given color (unsigned).
|
||||
*
|
||||
* @param color the color
|
||||
* @return the alpha value
|
||||
*/
|
||||
public byte alpha(int color) {
|
||||
return (byte) (color >>> 24);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the red value of the given color (unsigned).
|
||||
*
|
||||
* @param color the color
|
||||
* @return the red value
|
||||
*/
|
||||
public byte red(int color) {
|
||||
return (byte) (color >>> 16 & 0xFF);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the green value of the given color (unsigned).
|
||||
*
|
||||
* @param color the color
|
||||
* @return the green value
|
||||
*/
|
||||
public byte green(int color) {
|
||||
return (byte) (color >>> 8 & 0xFF);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the blue value of the given color (unsigned).
|
||||
*
|
||||
* @param color the color
|
||||
* @return the blue value
|
||||
*/
|
||||
public byte blue(int color) {
|
||||
return (byte) (color & 0xFF);
|
||||
}
|
||||
|
||||
// Setting color values
|
||||
|
||||
/**
|
||||
* Sets the alpha value for the given color.
|
||||
*
|
||||
* @param color the color
|
||||
* @param alpha the new alpha value
|
||||
* @return the new color
|
||||
*/
|
||||
public int alpha(int color, byte alpha) {
|
||||
return color & 0x00FFFFFF | (alpha & 0xFF) << 24;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the red value for the given color.
|
||||
*
|
||||
* @param color the color
|
||||
* @param red the new red value
|
||||
* @return the new color
|
||||
*/
|
||||
public int red(int color, byte red) {
|
||||
return color & 0xFF00FFFF | (red & 0xFF) << 16;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the green value for the given color.
|
||||
*
|
||||
* @param color the color
|
||||
* @param green the new green value
|
||||
* @return the new color
|
||||
*/
|
||||
public int green(int color, byte green) {
|
||||
return color & 0xFFFF00FF | (green & 0xFF) << 8;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the blue value for the given color.
|
||||
*
|
||||
* @param color the color
|
||||
* @param blue the new blue value
|
||||
* @return the new color
|
||||
*/
|
||||
public int blue(int color, byte blue) {
|
||||
return color & 0xFFFFFF00 | blue & 0xFF;
|
||||
}
|
||||
|
||||
// Construction
|
||||
|
||||
/**
|
||||
* Creates a new color with the given values.
|
||||
*
|
||||
* @param alpha the alpha value
|
||||
* @param red the red value
|
||||
* @param green the green value
|
||||
* @param blue the blue value
|
||||
* @return a new color
|
||||
*/
|
||||
public int color(byte alpha, byte red, byte green, byte blue) {
|
||||
return (alpha & 0xFF) << 24 | (red & 0xFF) << 16 | (green & 0xFF) << 8 | blue & 0xFF;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new, fully opaque color with the given values.
|
||||
*
|
||||
* @param red the red value
|
||||
* @param green the green value
|
||||
* @param blue the blue value
|
||||
* @return a new color
|
||||
*/
|
||||
public int opaqueColor(byte red, byte green, byte blue) {
|
||||
return 0xFF000000 | (red & 0xFF) << 16 | (green & 0xFF) << 8 | blue & 0xFF;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new, fully transparent color with the given values. No matter which values were passed,
|
||||
* the color will not be visible until its alpha value becomes greater than {@code 0}.
|
||||
*
|
||||
* @param red the red value
|
||||
* @param green the green value
|
||||
* @param blue the blue value
|
||||
* @return a new color
|
||||
*/
|
||||
public int transparentColor(byte red, byte green, byte blue) {
|
||||
return /* 0x00000000 | */(red & 0xFF) << 16 | (green & 0xFF) << 8 | blue & 0xFF;
|
||||
}
|
||||
|
||||
// Blending
|
||||
|
||||
/**
|
||||
* Sums the given two colors' components. The layered additive blending and true additive blending
|
||||
* do the same thing, so this method is responsible for both of these blending variants.
|
||||
*
|
||||
* @param color1 the first color
|
||||
* @param color2 the second color
|
||||
* @return the additive blending of the given colors
|
||||
*/
|
||||
public int add(int color1, int color2) {
|
||||
// @formatter:off
|
||||
byte alpha1 = alpha(color1), alpha2 = alpha(color2),
|
||||
red1 = red(color1), red2 = red(color2),
|
||||
green1 = green(color1), green2 = green(color2),
|
||||
blue1 = blue(color1), blue2 = blue(color2);
|
||||
|
||||
return Math.min(255, Byte.toUnsignedInt(alpha1) + Byte.toUnsignedInt(alpha2)) << 24
|
||||
| Math.min(255, Byte.toUnsignedInt(red1) + Byte.toUnsignedInt(red2)) << 16
|
||||
| Math.min(255, Byte.toUnsignedInt(green1) + Byte.toUnsignedInt(green2)) << 8
|
||||
| Math.min(255, Byte.toUnsignedInt(blue1) + Byte.toUnsignedInt(blue2));
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
/**
|
||||
* Subtracts the second color's RGB components from the first color's RGB components. The alpha channels get summed instead,
|
||||
* resulting in a layered blending.
|
||||
*
|
||||
* @param color1 the first color
|
||||
* @param color2 the second color
|
||||
* @return the layered subtractive blending of the given colors
|
||||
*/
|
||||
public int rgbSubtract(int color1, int color2) {
|
||||
// @formatter:off
|
||||
byte alpha1 = alpha(color1), alpha2 = alpha(color2),
|
||||
red1 = red(color1), red2 = red(color2),
|
||||
green1 = green(color1), green2 = green(color2),
|
||||
blue1 = blue(color1), blue2 = blue(color2);
|
||||
|
||||
return Math.min(255, Byte.toUnsignedInt(alpha1) + Byte.toUnsignedInt(alpha2)) << 24
|
||||
| Math.max(0, Byte.toUnsignedInt(red1) - Byte.toUnsignedInt(red2)) << 16
|
||||
| Math.max(0, Byte.toUnsignedInt(green1) - Byte.toUnsignedInt(green2)) << 8
|
||||
| Math.max(0, Byte.toUnsignedInt(blue1) - Byte.toUnsignedInt(blue2));
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
/**
|
||||
* Subtracts the second color's components from the first color's components. The alpha channels also get subtracted,
|
||||
* resulting in a true blending.
|
||||
*
|
||||
* @param color1 the first color
|
||||
* @param color2 the second color
|
||||
* @return the true subtractive blending of the given colors
|
||||
*/
|
||||
public int blendSubtract(int color1, int color2) {
|
||||
// @formatter:off
|
||||
byte alpha1 = alpha(color1), alpha2 = alpha(color2),
|
||||
red1 = red(color1), red2 = red(color2),
|
||||
green1 = green(color1), green2 = green(color2),
|
||||
blue1 = blue(color1), blue2 = blue(color2);
|
||||
|
||||
return Math.min(255, Byte.toUnsignedInt(alpha1) - Byte.toUnsignedInt(alpha2)) << 24
|
||||
| Math.max(0, Byte.toUnsignedInt(red1) - Byte.toUnsignedInt(red2)) << 16
|
||||
| Math.max(0, Byte.toUnsignedInt(green1) - Byte.toUnsignedInt(green2)) << 8
|
||||
| Math.max(0, Byte.toUnsignedInt(blue1) - Byte.toUnsignedInt(blue2));
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
/**
|
||||
* Multiplies the given two colors' RGB components. The alpha channels get summed instead,
|
||||
* resulting in a layered blending.
|
||||
*
|
||||
* @param color1 the first color
|
||||
* @param color2 the second color
|
||||
* @return the layered multiplicative blending of the given colors
|
||||
*/
|
||||
public int rgbMultiply(int color1, int color2) {
|
||||
// @formatter:off
|
||||
byte alpha1 = alpha(color1), alpha2 = alpha(color2),
|
||||
red1 = red(color1), red2 = red(color2),
|
||||
green1 = green(color1), green2 = green(color2),
|
||||
blue1 = blue(color1), blue2 = blue(color2);
|
||||
|
||||
return Math.min(255, Byte.toUnsignedInt(alpha1) + Byte.toUnsignedInt(alpha2) ) << 24
|
||||
| ( Byte.toUnsignedInt(red1) * Byte.toUnsignedInt(red2) + 127) / 255 << 16
|
||||
| ( Byte.toUnsignedInt(green1) * Byte.toUnsignedInt(green2) + 127) / 255 << 8
|
||||
| ( Byte.toUnsignedInt(blue1) * Byte.toUnsignedInt(blue2) + 127) / 255;
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
/**
|
||||
* Multiplies the given two colors' components. The alpha channels also get multiplied,
|
||||
* resulting in a true blending.
|
||||
*
|
||||
* @param color1 the first color
|
||||
* @param color2 the second color
|
||||
* @return the true multiplicative blending of the given colors
|
||||
*/
|
||||
public int blendMultiply(int color1, int color2) {
|
||||
// @formatter:off
|
||||
byte alpha1 = alpha(color1), alpha2 = alpha(color2),
|
||||
red1 = red(color1), red2 = red(color2),
|
||||
green1 = green(color1), green2 = green(color2),
|
||||
blue1 = blue(color1), blue2 = blue(color2);
|
||||
|
||||
return (Byte.toUnsignedInt(alpha1) * Byte.toUnsignedInt(alpha2) + 127) / 255 << 24
|
||||
| (Byte.toUnsignedInt(red1) * Byte.toUnsignedInt(red2) + 127) / 255 << 16
|
||||
| (Byte.toUnsignedInt(green1) * Byte.toUnsignedInt(green2) + 127) / 255 << 8
|
||||
| (Byte.toUnsignedInt(blue1) * Byte.toUnsignedInt(blue2) + 127) / 255;
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
// Misc
|
||||
|
||||
/**
|
||||
* Turns the given color into its fully opaque version.
|
||||
*
|
||||
* @param color the color
|
||||
* @return the new, fully opaque color
|
||||
*/
|
||||
public int opaque(int color) {
|
||||
return color | 0xFF000000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns the given color into its fully transparent version. The color will not be visible until its alpha
|
||||
* value becomes more than {@code 0}.
|
||||
*
|
||||
* @param color the color
|
||||
* @return the new, fully transparent color
|
||||
*/
|
||||
public int transparent(int color) {
|
||||
return color & 0x00FFFFFF;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package ru.fokinatorr.sparkle.graphics;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
|
||||
import java.util.function.IntBinaryOperator;
|
||||
|
||||
import static lombok.AccessLevel.PRIVATE;
|
||||
|
||||
/**
|
||||
* Enum representing different blending strategies for combining source and destination pixels.
|
||||
* Each blend mode uses a specific mathematical operation to compute the resulting color.
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
@FieldDefaults(makeFinal = true, level = PRIVATE)
|
||||
public enum BlendMode {
|
||||
/**
|
||||
* Sums the colors' components.
|
||||
* Suitable for glow and lighting effects.
|
||||
* @see ARGB#add(int, int)
|
||||
*/
|
||||
ADD(ARGB::add, BlendType.ARGB),
|
||||
/**
|
||||
* Subtracts the colors' components.
|
||||
* Produces inverted, transparent results.
|
||||
* @see ARGB#blendSubtract(int, int)
|
||||
*/
|
||||
BLEND_SUBTRACT(ARGB::blendSubtract, BlendType.ARGB),
|
||||
/**
|
||||
* Subtracts RGB color channels, summing alpha instead.
|
||||
* Produces more opaque results than {@link #BLEND_SUBTRACT}.
|
||||
* @see ARGB#rgbSubtract(int, int)
|
||||
*/
|
||||
RGB_SUBTRACT(ARGB::rgbSubtract, BlendType.RGB),
|
||||
/**
|
||||
* Multiplies the colors' components.
|
||||
* Produces darker results, useful for shadows and darkening effects.
|
||||
* @see ARGB#blendMultiply(int, int)
|
||||
*/
|
||||
BLEND_MULTIPLY(ARGB::blendMultiply, BlendType.ARGB),
|
||||
/**
|
||||
* Multiplies RGB color channels, summing alpha instead.
|
||||
* Produces more opaque results than {@link #BLEND_MULTIPLY}.
|
||||
* @see ARGB#rgbMultiply(int, int)
|
||||
*/
|
||||
RGB_MULTIPLY(ARGB::rgbMultiply, BlendType.RGB);
|
||||
|
||||
IntBinaryOperator op;
|
||||
/**
|
||||
* -- GETTER --
|
||||
* <p>
|
||||
* The blend type that determines how alpha channel is handled during blending.
|
||||
* @return the blend type (ARGB or RGB)
|
||||
* @see BlendType
|
||||
*/
|
||||
@Getter BlendType type;
|
||||
|
||||
/**
|
||||
* Applies this blend mode to two colors.
|
||||
*
|
||||
* @param color1 the source color
|
||||
* @param color2 the destination color
|
||||
* @return the blended color result
|
||||
*/
|
||||
public int apply(int color1, int color2) {
|
||||
return op.applyAsInt(color1, color2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enum representing how blending operations handle the alpha channel.
|
||||
*/
|
||||
public enum BlendType {
|
||||
/**
|
||||
* Applies the same blending operation to all channels including alpha.
|
||||
*/
|
||||
ARGB,
|
||||
/**
|
||||
* Applies blending only to RGB color channels while using additive blending for the alpha channel.
|
||||
*/
|
||||
RGB
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package ru.fokinatorr.sparkle.graphics;
|
||||
|
||||
import it.unimi.dsi.fastutil.Pair;
|
||||
import ru.fokinatorr.sparkle.audio.SoundInstance;
|
||||
import ru.fokinatorr.sparkle.graphics.image.Image;
|
||||
import ru.fokinatorr.sparkle.graphics.render.RenderingContext;
|
||||
import ru.fokinatorr.sparkle.graphics.render.surface.EmbeddedSurface;
|
||||
import ru.fokinatorr.sparkle.graphics.render.surface.RenderingSurface;
|
||||
import ru.fokinatorr.sparkle.graphics.render.surface.WindowSurface;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
import ru.fokinatorr.sparkle.stage.StageCreator;
|
||||
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* Manages rendering contexts and their lifecycle.
|
||||
* <p><i>Note: Do not manually close image instances returned by a graphics manager. Instead, use
|
||||
* the </i><b>{@link #destroyImage(Path)}</b><i> method for proper cleanup.</i>
|
||||
* @see RenderingContext
|
||||
*/
|
||||
public interface GraphicsManager extends NonThrowingAutoCloseable {
|
||||
|
||||
// Context creation & management
|
||||
|
||||
/**
|
||||
* Creates a new rendering context with a {@link WindowSurface} and a stage created using the given creator.
|
||||
*
|
||||
* @param title window title
|
||||
* @param stageCreator a stage creation strategy
|
||||
* @return a new rendering context and a stage bound to it
|
||||
* @throws IllegalStateException if graphics manager is closed
|
||||
* @throws NullPointerException if any argument is {@code null}
|
||||
*/
|
||||
default Pair<Stage, RenderingContext> createWindowContext(String title, StageCreator stageCreator) {
|
||||
return createWindowContext(title, stageCreator, false, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new rendering context with a {@link WindowSurface} and a stage created using the given creator.
|
||||
*
|
||||
* @param title window title
|
||||
* @param stageCreator a stage creation strategy
|
||||
* @param translucent whether the window should be transparent
|
||||
* @param fullscreen whether the window should be fullscreen
|
||||
* @return a new rendering context and a stage bound to it
|
||||
* @throws IllegalStateException if graphics manager is closed
|
||||
* @throws NullPointerException if any argument is {@code null}
|
||||
*/
|
||||
Pair<Stage, RenderingContext> createWindowContext(String title, StageCreator stageCreator, boolean translucent, boolean fullscreen);
|
||||
|
||||
/**
|
||||
* Creates a new rendering context with the given embedded rendering surface and a stage created using the given creator.
|
||||
* <p>To create a context with a window surface, use {@link #createWindowContext createWindowContext(...)}.
|
||||
*
|
||||
* @param surface the surface to render on
|
||||
* @param stageCreator a stage creation strategy
|
||||
* @return a new rendering context and a stage bound to it
|
||||
* @throws IllegalStateException if graphics manager is closed
|
||||
* @throws NullPointerException if any argument is {@code null}
|
||||
*/
|
||||
Pair<Stage, RenderingContext> createEmbeddedContext(EmbeddedSurface surface, StageCreator stageCreator);
|
||||
|
||||
/**
|
||||
* Returns an existing rendering context bound to the given stage.
|
||||
* @param boundStage the bound stage
|
||||
* @return the corresponding rendering context
|
||||
* @throws NullPointerException if stage is {@code null}
|
||||
*/
|
||||
RenderingContext getContext(Stage boundStage);
|
||||
|
||||
/**
|
||||
* Checks whether this manager currently has any active contexts.
|
||||
* @return whether there are active contexts
|
||||
*/
|
||||
boolean hasActiveContexts();
|
||||
|
||||
// Image loading
|
||||
|
||||
/**
|
||||
* Loads an image at the specified path. The image will automatically be closed with this manager.
|
||||
* If an image is already loaded at the given path, it is closed, removed and replaced with a new one.
|
||||
* The sprite/stage assets are loaded automatically, so there's usually no need to call this method manually.
|
||||
* @param path the file path
|
||||
* @param autoLoad whether to preload the image to all existing & future rendering contexts
|
||||
* @return the image
|
||||
* @throws IllegalStateException if graphics manager is closed
|
||||
*/
|
||||
Image loadImage(Path path, boolean autoLoad);
|
||||
|
||||
/**
|
||||
* Determines whether an image is already loaded at the given path. This can be useful
|
||||
* to prevent unnecessary image reloading.
|
||||
* This is always true for sprite/stage assets since they're loaded automatically.
|
||||
* @param path the file path
|
||||
* @return {@code true} if an image at the given path is already loaded by this manager, {@code false}
|
||||
* otherwise
|
||||
*/
|
||||
boolean hasLoadedImage(Path path);
|
||||
|
||||
/**
|
||||
* Returns an image previously loaded from the given path, if any, otherwise returns {@code null}.
|
||||
*
|
||||
* @param path the file path
|
||||
* @return the respective image or {@code null}
|
||||
* @throws IllegalStateException if graphics manager is closed
|
||||
*/
|
||||
Image getLoadedImage(Path path);
|
||||
|
||||
/**
|
||||
* If an image is loaded at the given path, closes and removes it, otherwise does nothing.
|
||||
*
|
||||
* @param path the file path
|
||||
* @throws IllegalStateException if graphics manager is closed
|
||||
*/
|
||||
void destroyImage(Path path);
|
||||
|
||||
|
||||
// Lifecycle
|
||||
|
||||
/**
|
||||
* Schedules the given task to run in the graphics loop.
|
||||
* <p>This is required for calling most {@link RenderingSurface} methods, since they can only change properties
|
||||
* & render within a single thread.
|
||||
* @param run the action
|
||||
* @throws NullPointerException if {@code run == null}
|
||||
* @throws IllegalStateException if the work queue cannot accept more tasks (optional)
|
||||
*/
|
||||
void runLater(Runnable run);
|
||||
|
||||
/**
|
||||
* Advances the graphics manager by one tick.
|
||||
* This method is called regularly from the graphics loop, no need to call in manually.
|
||||
* @throws IllegalStateException if graphics manager is closed
|
||||
*/
|
||||
void tick();
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package ru.fokinatorr.sparkle.graphics;
|
||||
|
||||
import lombok.experimental.UtilityClass;
|
||||
import ru.fokinatorr.sparkle.graphics.image.Image;
|
||||
import ru.fokinatorr.sparkle.graphics.render.RenderCanvas;
|
||||
import ru.fokinatorr.sparkle.internal.access.SharedSecrets;
|
||||
import ru.fokinatorr.sparkle.internal.access.StageAccess;
|
||||
import ru.fokinatorr.sparkle.phys2d.Point2D;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static ru.fokinatorr.sparkle.graphics.render.RenderCanvas.ORIGINAL_SIZE;
|
||||
|
||||
/**
|
||||
* Graphics-related utilities.
|
||||
*/
|
||||
@UtilityClass
|
||||
public class GraphicsUtils {
|
||||
private static final StageAccess stageAcc = SharedSecrets.getStageAccess();
|
||||
|
||||
/**
|
||||
* Draws an image on the given canvas as if the origin is in the center, not in the top-left corner.
|
||||
*
|
||||
* @param canvas the canvas to draw on
|
||||
* @param image the image to draw
|
||||
* @param x the X coordinate of center
|
||||
* @param y the Y coordinate of center
|
||||
* @param w the preferred width
|
||||
* @param h the preferred height
|
||||
* @see RenderCanvas#drawImage(Image, double, double, double, double)
|
||||
*/
|
||||
public void drawImageOriginCenter(RenderCanvas canvas, Image image,
|
||||
double x, double y,
|
||||
double w, double h) {
|
||||
Objects.requireNonNull(canvas, "canvas");
|
||||
Objects.requireNonNull(image, "image");
|
||||
|
||||
if (w == ORIGINAL_SIZE || h == ORIGINAL_SIZE) {
|
||||
if (!image.isReady()) image.prepare(); // perform lazy loading
|
||||
var reader = image.createPixelReader();
|
||||
if (w == ORIGINAL_SIZE) w = reader.getWidth();
|
||||
if (h == ORIGINAL_SIZE) h = reader.getHeight();
|
||||
}
|
||||
|
||||
Point2D dim = canvas.getDimensions();
|
||||
canvas.drawImage(
|
||||
image,
|
||||
(dim.x() - w) / 2 + x, (dim.y() - h) / 2 - y,
|
||||
w, h
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the given code, disabling redraws on the given stage.
|
||||
* <p><i>Note for Scratchers: This method's functionality is similar to "run without screen refresh" in
|
||||
* custom blocks, except you can use it with any code.</i>
|
||||
*
|
||||
* @param stage the stage to suppress redraws for
|
||||
* @param run what should be executed
|
||||
*/
|
||||
public void runWithoutStageRedraw(Stage stage, Runnable run) {
|
||||
stageAcc.setSuppressRedraw(stage, true);
|
||||
try {
|
||||
run.run();
|
||||
} finally {
|
||||
stageAcc.setSuppressRedraw(stage, false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the given code, disabling redraws on the given stage, and returns the code's result.
|
||||
* <p><i>Note for Scratchers: This method's functionality is similar to "run without screen refresh" in
|
||||
* custom blocks, except you can use it with any code.</i>
|
||||
*
|
||||
* @param stage the stage to suppress redraws for
|
||||
* @param run what should be executed
|
||||
* @param <T> the type of return value
|
||||
* @return the value returned by {@code run}
|
||||
*/
|
||||
public <T> T getWithoutStageRedraw(Stage stage, Supplier<T> run) {
|
||||
stageAcc.setSuppressRedraw(stage, true);
|
||||
try {
|
||||
return run.get();
|
||||
} finally {
|
||||
stageAcc.setSuppressRedraw(stage, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package ru.fokinatorr.sparkle.graphics;
|
||||
|
||||
import ru.fokinatorr.sparkle.graphics.image.Image;
|
||||
import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer;
|
||||
import ru.fokinatorr.sparkle.phys2d.Point2D;
|
||||
|
||||
/**
|
||||
* Allows reading pixel data from an image/framebuffer in ARGB format.
|
||||
* @see ARGB
|
||||
* @see Image#createPixelReader()
|
||||
* @see Framebuffer#createPixelReader()
|
||||
*/
|
||||
public interface PixelReader {
|
||||
/**
|
||||
* Returns the color of the given point in ARGB format.
|
||||
* @param x the X coordinate of the point
|
||||
* @param y the Y coordinate of the point
|
||||
* @return the color of the point
|
||||
*/
|
||||
int getARGB(int x, int y);
|
||||
|
||||
/**
|
||||
* Returns the width of underlying image data.
|
||||
* @return the width, always positive
|
||||
*/
|
||||
int getWidth();
|
||||
/**
|
||||
* Returns the height of underlying image data.
|
||||
* @return the height, always positive
|
||||
*/
|
||||
int getHeight();
|
||||
|
||||
/**
|
||||
* Returns a vector representing the dimensions of underlying image data.
|
||||
* @return the dimensions, both always positive
|
||||
*/
|
||||
default Point2D getDimensions() {
|
||||
return new Point2D(getWidth(), getHeight());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a horizontal line of pixels at the specified Y coordinate.
|
||||
* @param y the Y coordinate
|
||||
* @return all pixels at the given Y coordinate
|
||||
*/
|
||||
default int[] getRow(int y) {
|
||||
int[] row = new int[getWidth()];
|
||||
for (int x = 0; x < getWidth(); x++) {
|
||||
row[x] = getARGB(x, y);
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a vertical line of pixels at the specified X coordinate.
|
||||
* @param x the X coordinate
|
||||
* @return all pixels at the given X coordinate
|
||||
*/
|
||||
default int[] getColumn(int x) {
|
||||
int[] col = new int[getHeight()];
|
||||
for (int y = 0; y < getHeight(); y++) {
|
||||
col[y] = getARGB(x, y);
|
||||
}
|
||||
return col;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the entire image as a 2D array using row-major order.
|
||||
* @return the entire image data
|
||||
*/
|
||||
default int[][] getAll() {
|
||||
int[][] grid = new int[getHeight()][getWidth()];
|
||||
for (int y = 0; y < getHeight(); y++) {
|
||||
for (int x = 0; x < getWidth(); x++) {
|
||||
grid[y][x] = getARGB(x, y);
|
||||
}
|
||||
}
|
||||
return grid;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package ru.fokinatorr.sparkle.graphics;
|
||||
|
||||
import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
|
||||
/**
|
||||
* Allows modifying pixel data of an image/framebuffer in ARGB format.
|
||||
* @see ARGB
|
||||
* @see Framebuffer#createPixelWriter()
|
||||
*/
|
||||
public interface PixelWriter {
|
||||
/**
|
||||
* Sets a single pixel.
|
||||
* @param x the X coordinate
|
||||
* @param y the Y coordinate
|
||||
* @param argb the ARGB color
|
||||
* @throws IllegalArgumentException if x or y are out of bounds
|
||||
*/
|
||||
void setARGB(int x, int y, int argb);
|
||||
|
||||
/**
|
||||
* Fills a rectangular region with the given color.
|
||||
* @param x the X of top-left corner
|
||||
* @param y the Y of top-left corner
|
||||
* @param w rectangle width
|
||||
* @param h rectangle height
|
||||
* @param argb the ARGB color
|
||||
* @throws IllegalArgumentException if part of the region is out of bounds
|
||||
*/
|
||||
default void fillARGB(int x, int y, int w, int h, int argb) {
|
||||
for (int posX = x; posX < x + h; posX++) {
|
||||
for (int posY = y; posY < y + w; posY++) {
|
||||
setARGB(posX, posY, argb);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies pixel data from an array.
|
||||
* <p>A pixel at (x, y) is read from the given source array as:
|
||||
* <pre>{@code src[off + (y - startY) * scanSize + (x - startX)]}</pre>
|
||||
* (row-major order).
|
||||
* @param src the source array (ARGB)
|
||||
* @param off data offset in the source array
|
||||
* @param scanSize number of pixels per row
|
||||
* @param startX the starting X coordinate
|
||||
* @param startY the starting Y coordinate
|
||||
* @param w width of region to copy
|
||||
* @param h height of region to copy
|
||||
* @throws IllegalArgumentException if part of the region is out of bounds
|
||||
*/
|
||||
default void writePixels(int[] src, int off, int scanSize,
|
||||
int startX, int startY, int w, int h) {
|
||||
for (int x = startX; x < startX + h; x++) {
|
||||
for (int y = startY; y < startY + w; y++) {
|
||||
setARGB(x, y, src[off + (x - startX) * scanSize + (y - startY)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package ru.fokinatorr.sparkle.graphics.font;
|
||||
|
||||
import it.unimi.dsi.fastutil.Pair;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectReferenceImmutablePair;
|
||||
import lombok.NonNull;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.util.function.Predicate.not;
|
||||
import static lombok.AccessLevel.PRIVATE;
|
||||
|
||||
/**
|
||||
* A font provider that loads fonts from a base directory, using this format for locating TTF files:
|
||||
* <pre>{@code <base_dir>/<family>/<posture>/<weight>.ttf}</pre>
|
||||
* where:
|
||||
* <ul>
|
||||
* <li>
|
||||
* <tt><base_dir></tt> is the base directory path provided in the constructor;
|
||||
* </li>
|
||||
* <li>
|
||||
* <tt><family></tt> is the font family name as-is (without replacing spaces or changing case);
|
||||
* </li>
|
||||
* <li>
|
||||
* <tt><posture></tt> is the font's desired posture in lowercase;
|
||||
* </li>
|
||||
* <li>
|
||||
* <tt><weight></tt> is the font's desired weight in lowercase.
|
||||
* </li>
|
||||
* </ul>
|
||||
*/
|
||||
@Slf4j
|
||||
@FieldDefaults(level = PRIVATE)
|
||||
public class FilesystemFontProvider implements FontProvider {
|
||||
@NonNull
|
||||
final Path baseDir;
|
||||
@NonNull
|
||||
final String fallbackFamily;
|
||||
final Map<FontParams, Path> cache = new HashMap<>();
|
||||
|
||||
Set<String> availableFamilies;
|
||||
final Map<String, Set<FontPosture>> availablePostures = new HashMap<>();
|
||||
final Map<Pair<String, FontPosture>, Set<FontWeight>> availableWeights = new HashMap<>();
|
||||
|
||||
/**
|
||||
* Creates a new filesystem font provider.
|
||||
* @param baseDir the base directory to locate fonts in
|
||||
* @param fallbackFamily the fallback font family, if one cannot be found (must exist in available families)
|
||||
* @throws NullPointerException if any argument is {@code null}
|
||||
* @throws IllegalArgumentException if the base path does not exist or does not represent a directory
|
||||
*/
|
||||
public FilesystemFontProvider(@NonNull Path baseDir, @NonNull String fallbackFamily) {
|
||||
this.baseDir = Objects.requireNonNull(baseDir, "base directory");
|
||||
this.fallbackFamily = Objects.requireNonNull(fallbackFamily, "fallback family");
|
||||
if (!Files.exists(baseDir)) {
|
||||
throw new IllegalArgumentException("Path does not exist: " + baseDir);
|
||||
}
|
||||
if (!Files.isDirectory(baseDir)) {
|
||||
throw new IllegalArgumentException("Not a directory: " + baseDir);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Path getTTF(String family, FontWeight weight, FontPosture posture) {
|
||||
return cache.computeIfAbsent(new FontParams(family, weight, posture), params -> {
|
||||
Set<String> families = availableFamilies();
|
||||
if (families.isEmpty()) {
|
||||
throw new IllegalArgumentException("No font families found in " + baseDir);
|
||||
}
|
||||
|
||||
String actualFamily = family;
|
||||
if (!families.contains(actualFamily)) actualFamily = fallbackFamily;
|
||||
if (!families.contains(actualFamily)) {
|
||||
throw new IllegalArgumentException("Fallback family doesn't exist: '" + fallbackFamily + "' in " + baseDir);
|
||||
}
|
||||
|
||||
Set<FontPosture> postures = availablePostures(actualFamily);
|
||||
if (postures.isEmpty()) {
|
||||
throw new IllegalArgumentException("No font postures available for family: '" + actualFamily + "' in " + baseDir);
|
||||
}
|
||||
FontPosture actualPosture = posture;
|
||||
if (!postures.contains(actualPosture)) actualPosture = postures.iterator().next(); // If more postures appear later, choose a closer one
|
||||
|
||||
Set<FontWeight> weights = availableWeights(actualFamily, actualPosture);
|
||||
if (weights.isEmpty()) {
|
||||
throw new IllegalArgumentException("No font weights available for family: '" + actualFamily + "' in " + baseDir);
|
||||
}
|
||||
|
||||
FontWeight actualWeight = weight;
|
||||
if (!weights.contains(actualWeight)) actualWeight = actualWeight.closestOf(weights);
|
||||
|
||||
Path ttfPath = baseDir.resolve(actualFamily)
|
||||
.resolve(actualPosture.name().toLowerCase())
|
||||
.resolve(actualWeight.name().toLowerCase() + ".ttf");
|
||||
log.trace("Resolved font: {} -> {}", params, baseDir.relativize(ttfPath));
|
||||
return ttfPath.toAbsolutePath();
|
||||
});
|
||||
}
|
||||
|
||||
private Set<String> availableFamilies() {
|
||||
if (availableFamilies == null) {
|
||||
try (Stream<Path> list = Files.list(baseDir)) {
|
||||
availableFamilies = list.filter(Files::isDirectory)
|
||||
.map(Path::getFileName)
|
||||
.map(Path::toString)
|
||||
.collect(Collectors.toUnmodifiableSet());
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
return availableFamilies;
|
||||
}
|
||||
|
||||
private Set<FontPosture> availablePostures(String family) {
|
||||
return availablePostures.computeIfAbsent(family, _ -> {
|
||||
try (Stream<Path> list = Files.list(baseDir.resolve(family))) {
|
||||
return list.filter(Files::isDirectory)
|
||||
.map(Path::getFileName)
|
||||
.map(Path::toString)
|
||||
.map(String::toUpperCase)
|
||||
.map(name -> {
|
||||
try {
|
||||
return FontPosture.valueOf(name);
|
||||
} catch (IllegalArgumentException _) { // no such enum constant
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toUnmodifiableSet());
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Set<FontWeight> availableWeights(String family, FontPosture posture) {
|
||||
return availableWeights.computeIfAbsent(new ObjectReferenceImmutablePair<>(family, posture), _ -> {
|
||||
try (Stream<Path> list = Files.list(baseDir.resolve(family).resolve(posture.name().toLowerCase()))) {
|
||||
return list.filter(not(Files::isDirectory))
|
||||
.map(Path::getFileName)
|
||||
.map(Path::toString)
|
||||
.filter(fileName -> fileName.endsWith(".ttf"))
|
||||
.map(fileName -> fileName.substring(0, fileName.lastIndexOf(".")))
|
||||
.map(String::toUpperCase)
|
||||
.map(name -> {
|
||||
try {
|
||||
return FontWeight.valueOf(name);
|
||||
} catch (IllegalArgumentException _) { // no such enum constant
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toUnmodifiableSet());
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private record FontParams(
|
||||
@NonNull String family,
|
||||
@NonNull FontWeight weight,
|
||||
@NonNull FontPosture posture
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package ru.fokinatorr.sparkle.graphics.font;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.NonNull;
|
||||
import lombok.Value;
|
||||
import lombok.experimental.Tolerate;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Represents a font and its properties.
|
||||
* <p>This class has a builder, see {@link FontBuilder} and {@link #builder()}.
|
||||
* <p>Only standard fonts are supported by default; use {@link FontProvider} to associate custom
|
||||
* font families to font files on disk or other locations.
|
||||
* <p><i>Note for Scratchers: Default fonts are the ones used in Scratch! The fonts for Chinese, Japanese and Korean
|
||||
* are not present yet, since there are actually multiple font variations for these.</i>
|
||||
*
|
||||
* @see FontWeight
|
||||
* @see FontPosture
|
||||
* @see FontProvider
|
||||
*/
|
||||
@Builder(toBuilder = true)
|
||||
@Value
|
||||
public class Font {
|
||||
@NonNull
|
||||
String family;
|
||||
@Builder.Default
|
||||
double size = 20.0;
|
||||
@NonNull
|
||||
@Builder.Default
|
||||
FontWeight weight = FontWeight.NORMAL;
|
||||
@Builder.Default
|
||||
FontPosture posture = FontPosture.NORMAL;
|
||||
boolean underline;
|
||||
boolean strikethrough;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new font.
|
||||
* @param family the font's family
|
||||
* @param size the font's size, in points (1 pt = ~3/4 px)
|
||||
* @param weight the font's {@linkplain FontWeight weight}
|
||||
* @param posture the font's {@linkplain FontPosture posture}
|
||||
* @param underline whether to apply underlining to text
|
||||
* @param strikethrough whether to apply strikethrough to text
|
||||
* @throws NullPointerException if any argument is {@code null}
|
||||
* @throws IllegalArgumentException if size is non-positive, infinite or NaN
|
||||
*/
|
||||
public Font(@NonNull String family, double size,
|
||||
@NonNull FontWeight weight, @NonNull FontPosture posture,
|
||||
boolean underline, boolean strikethrough) {
|
||||
this.family = Objects.requireNonNull(family, "family");
|
||||
checkSize(size);
|
||||
this.size = size;
|
||||
this.weight = Objects.requireNonNull(weight, "weight");
|
||||
this.posture = Objects.requireNonNull(posture, "posture");
|
||||
this.underline = underline;
|
||||
this.strikethrough = strikethrough;
|
||||
}
|
||||
|
||||
// Standard Scratch fonts;
|
||||
// copying Scratch's font names to method names for Scratchers' convenience, but listing the actual font family in Javadoc
|
||||
|
||||
/**
|
||||
* Creates a font builder with "Noto Sans" family and the given size.
|
||||
*
|
||||
* @param size the font size
|
||||
* @return a new builder
|
||||
*/
|
||||
public static FontBuilder sansSerif(double size) {
|
||||
return new FontBuilder()
|
||||
.family("Noto Sans")
|
||||
.size(size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a font builder with the default family and the given size.
|
||||
*
|
||||
* @param size the font size
|
||||
* @return a new builder
|
||||
*/
|
||||
public static FontBuilder serif(double size) {
|
||||
return new FontBuilder()
|
||||
.family("")
|
||||
.size(size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a font builder with "Handlee" family and the given size.
|
||||
*
|
||||
* @param size the font size
|
||||
* @return a new builder
|
||||
*/
|
||||
public static FontBuilder handwriting(double size) {
|
||||
return new FontBuilder()
|
||||
.family("Handlee")
|
||||
.size(size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a font builder with "Knewave" family and the given size.
|
||||
*
|
||||
* @param size the font size
|
||||
* @return a new builder
|
||||
*/
|
||||
public static FontBuilder marker(double size) {
|
||||
return new FontBuilder()
|
||||
.family("Knewave")
|
||||
.size(size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a font builder with "Griffy" family and the given size.
|
||||
*
|
||||
* @param size the font size
|
||||
* @return a new builder
|
||||
*/
|
||||
public static FontBuilder curly(double size) {
|
||||
return new FontBuilder()
|
||||
.family("Griffy")
|
||||
.size(size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a font builder with "Grand9K Pixel" family and the given size.
|
||||
*
|
||||
* @param size the font size
|
||||
* @return a new builder
|
||||
*/
|
||||
public static FontBuilder pixel(double size) {
|
||||
return new FontBuilder()
|
||||
.family("Grand9K Pixel")
|
||||
.size(size);
|
||||
}
|
||||
|
||||
/**
|
||||
* A builder for conveniently creating {@link Font}s.
|
||||
*/
|
||||
public static class FontBuilder {
|
||||
|
||||
/**
|
||||
* Makes the font builder underlined.
|
||||
* <p>This is a shortcut for {@code .underline(true)}.
|
||||
*
|
||||
* @return this builder
|
||||
*/
|
||||
@Tolerate
|
||||
public FontBuilder underline() {
|
||||
this.underline = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes the font builder struck through.
|
||||
* <p>This is a shortcut for {@code .strikethrough(true)}.
|
||||
*
|
||||
* @return this builder
|
||||
*/
|
||||
@Tolerate
|
||||
public FontBuilder strikethrough() {
|
||||
this.strikethrough = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the desired size for the resulting font.
|
||||
*
|
||||
* @param size the size
|
||||
* @return this builder
|
||||
* @throws IllegalArgumentException if size is non-positive, infinite or NaN
|
||||
*/
|
||||
public FontBuilder size(double size) {
|
||||
checkSize(size);
|
||||
size$set = true;
|
||||
size$value = size;
|
||||
return this;
|
||||
}
|
||||
|
||||
// the rest generated by Lombok
|
||||
}
|
||||
|
||||
private static void checkSize(double size) {
|
||||
if (!(Double.isFinite(size) && size > 0)) {
|
||||
throw new IllegalArgumentException("Size must be finite and positive, found: " + size);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package ru.fokinatorr.sparkle.graphics.font;
|
||||
|
||||
/**
|
||||
* A font's postural style.
|
||||
*/
|
||||
public enum FontPosture {
|
||||
NORMAL,
|
||||
ITALIC
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package ru.fokinatorr.sparkle.graphics.font;
|
||||
|
||||
import ru.fokinatorr.sparkle.util.Constants;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* Provides TrueType fonts for family, weight and posture.
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FontProvider {
|
||||
|
||||
/**
|
||||
* Attempts to find a path to a TrueType font matching the given characteristics.
|
||||
* <p>Implementations are free to return a fallback font if no match is found (e.g. family doesn't exist,
|
||||
* no such weight or posture).
|
||||
* @param family the font's preferred family
|
||||
* @param weight the font's preferred weight
|
||||
* @param posture the font's preferred posture
|
||||
* @return the respective TTF file path
|
||||
* @throws NullPointerException if any argument is {@code null} (optional)
|
||||
*/
|
||||
Path getTTF(String family, FontWeight weight, FontPosture posture);
|
||||
|
||||
/**
|
||||
* Returns a {@code FontProvider} that loads default fonts from this framework's <tt>/assets/fonts</tt>
|
||||
* directory.
|
||||
* @return a new default font provider
|
||||
*/
|
||||
static FontProvider defaultProvider() {
|
||||
return new FilesystemFontProvider(
|
||||
Constants.ROOT.resolve("assets/fonts"),
|
||||
"Noto Sans"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package ru.fokinatorr.sparkle.graphics.font;
|
||||
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectMaps;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import static lombok.AccessLevel.PRIVATE;
|
||||
|
||||
/**
|
||||
* A font's weight (thickness).
|
||||
* <p>Note: most fonts don't support all weights; most widely supported weight values are {@link #NORMAL} and {@link #BOLD}.
|
||||
*/
|
||||
@FieldDefaults(makeFinal = true, level = PRIVATE)
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
public enum FontWeight {
|
||||
THIN(1),
|
||||
EXTRA_LIGHT(2),
|
||||
LIGHT(3),
|
||||
NORMAL(4),
|
||||
MEDIUM(5),
|
||||
SEMI_BOLD(6),
|
||||
BOLD(7),
|
||||
EXTRA_BOLD(8),
|
||||
BLACK(9);
|
||||
|
||||
/**
|
||||
* The lightest font weight.
|
||||
*/
|
||||
public static final FontWeight MIN_VALUE = THIN;
|
||||
/**
|
||||
* The boldest font weight.
|
||||
*/
|
||||
public static final FontWeight MAX_VALUE = BLACK;
|
||||
|
||||
/**
|
||||
* The weight's scalar value.
|
||||
* <p>This is used to choose the closest supported weight.
|
||||
*/
|
||||
int value;
|
||||
|
||||
/**
|
||||
* Returns a font weight that is bolder than this weight by one.
|
||||
* @return a bolder font weight
|
||||
*/
|
||||
public FontWeight bolder() {
|
||||
return this == MAX_VALUE ? this : ValueOfMapHolder.MAP.get(value + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a font weight that is lighter than this weight by one.
|
||||
* @return a lighter font weight
|
||||
*/
|
||||
public FontWeight lighter() {
|
||||
return this == MIN_VALUE ? this : ValueOfMapHolder.MAP.get(value - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the closest weight to this one from the specified collection.
|
||||
* <p>If two weights are found at the same distance from this one, the lighter one is returned.
|
||||
* @param weights the possible candidates
|
||||
* @return the closest of them to this one
|
||||
* @throws IllegalArgumentException if the collection is empty
|
||||
*/
|
||||
public FontWeight closestOf(Collection<? extends FontWeight> weights) {
|
||||
if (weights.contains(this)) {
|
||||
return this;
|
||||
}
|
||||
for (
|
||||
FontWeight lighter = this, bolder = this;
|
||||
!(lighter == MIN_VALUE || bolder == MAX_VALUE);
|
||||
lighter = lighter.lighter(), bolder = bolder.bolder()
|
||||
) {
|
||||
if (weights.contains(lighter)) return lighter;
|
||||
if (weights.contains(bolder)) return bolder;
|
||||
}
|
||||
throw new IllegalArgumentException("No available weights");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a font weight with the given scalar value.
|
||||
* @param value the weight value
|
||||
* @return the respective font weight
|
||||
* @throws IllegalArgumentException if no such font weight exists
|
||||
*/
|
||||
public static FontWeight valueOf(int value) {
|
||||
Int2ObjectMap<FontWeight> m = ValueOfMapHolder.MAP;
|
||||
if (!m.containsKey(value)) {
|
||||
throw new IllegalArgumentException("No weight with value " + value);
|
||||
}
|
||||
return m.get(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazy holder for the scalar value to instance map.
|
||||
*/
|
||||
private static class ValueOfMapHolder {
|
||||
static final Int2ObjectMap<FontWeight> MAP;
|
||||
|
||||
static {
|
||||
Int2ObjectMap<FontWeight> m = new Int2ObjectOpenHashMap<>();
|
||||
for (FontWeight wt : values()) {
|
||||
m.put(wt.value, wt);
|
||||
}
|
||||
MAP = Int2ObjectMaps.unmodifiable(m);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package ru.fokinatorr.sparkle.graphics.image;
|
||||
|
||||
import ru.fokinatorr.sparkle.graphics.PixelReader;
|
||||
import ru.fokinatorr.sparkle.graphics.render.RenderCanvas;
|
||||
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
|
||||
|
||||
/**
|
||||
* An image that can be rendered on a canvas.
|
||||
* <p>
|
||||
* This interface abstracts over various image formats (raster, vector, procedural)
|
||||
* and enables uniform handling across rendering pipelines. Implementations may represent:
|
||||
* <ul>
|
||||
* <li>Raster images (PNG, JPEG)</li>
|
||||
* <li>Vector graphics (SVG)</li>
|
||||
* <li>Dynamic/procedural textures</li>
|
||||
* <li>Animation frames</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h3>Resource Management</h3>
|
||||
* Images may hold native resources (e.g. GPU textures). Callers should ensure
|
||||
* {@link #prepare()} is called before drawing, and consider disposal
|
||||
* if the image supports it.
|
||||
* <p>To potentially release these resources, {@link #close()} must be called when the image
|
||||
* is no longer in use.
|
||||
*
|
||||
* <h3>Thread Safety</h3>
|
||||
* Implementations must be safe to pass between threads, but are not required to support
|
||||
* concurrent drawing from multiple canvases unless explicitly documented.
|
||||
*
|
||||
* @see RasterImage
|
||||
* @see SVGImage
|
||||
* @see AnimatedImage
|
||||
*/
|
||||
public interface Image extends NonThrowingAutoCloseable {
|
||||
|
||||
/**
|
||||
* Prepares the image for rendering.
|
||||
* <p>
|
||||
* This may involve:
|
||||
* <ul>
|
||||
* <li>Lazy decoding of compressed data</li>
|
||||
* <li>Rasterization of vector content</li>
|
||||
* <li>Creating internal rendering structures</li>
|
||||
* </ul>
|
||||
* <p>
|
||||
* Idempotent: calling multiple times has no additional effect.
|
||||
*
|
||||
* @throws NullPointerException if context is {@code null}
|
||||
*/
|
||||
void prepare();
|
||||
|
||||
/**
|
||||
* Checks whether this image is ready to be drawn.
|
||||
* <p>
|
||||
* Returns {@code false} only if:
|
||||
* <ul>
|
||||
* <li>The image is still loading asynchronously</li>
|
||||
* <li>Required resources failed to load</li>
|
||||
* <li>{@link #prepare()} hasn't been called yet</li>
|
||||
* </ul>
|
||||
*
|
||||
* @return true if safe to pass to {@link RenderCanvas#drawImage RenderCanvas.drawImage()}
|
||||
*/
|
||||
boolean isReady();
|
||||
|
||||
/**
|
||||
* Returns a pixel reader that can read this image's contents as pixels.
|
||||
* The image must be {@link #prepare() prepared} before calling this method.
|
||||
*
|
||||
* @return an object that reads this image by pixels
|
||||
* @see #isReady()
|
||||
* @see #prepare()
|
||||
*/
|
||||
PixelReader createPixelReader();
|
||||
|
||||
/**
|
||||
* Optional hint about the MIME type of this image.
|
||||
* <p>
|
||||
* Examples: {@code "image/png"}, {@code "image/svg+xml"}
|
||||
* <p>
|
||||
* May return {@code null} if unknown or irrelevant (e.g. procedural images).
|
||||
*
|
||||
* @return the MIME type, or null if unavailable
|
||||
*/
|
||||
default String getMimeType() {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* The image can not be used after calling this method.
|
||||
* Calling this method more than once does not have any effect.
|
||||
*/
|
||||
@Override
|
||||
void close();
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package ru.fokinatorr.sparkle.graphics.image;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NonNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import ru.fokinatorr.sparkle.graphics.ARGB;
|
||||
import ru.fokinatorr.sparkle.graphics.PixelReader;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
||||
/**
|
||||
* A raster image is an image consisting of pixels (e.g. PNG, JPEG). The pixels
|
||||
* are stored in ARGB format.
|
||||
* @see ARGB
|
||||
*/
|
||||
@FieldDefaults(level = AccessLevel.PRIVATE)
|
||||
@RequiredArgsConstructor
|
||||
public class RasterImage implements Image {
|
||||
/**
|
||||
* Location of the image data.
|
||||
*/
|
||||
@NonNull final URL resource;
|
||||
volatile BufferedImage decoded;
|
||||
|
||||
@Override
|
||||
public void prepare() {
|
||||
if (decoded == null) {
|
||||
try {
|
||||
decoded = ImageIO.read(resource);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to decode raster image", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isReady() {
|
||||
return decoded != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PixelReader createPixelReader() {
|
||||
prepare(); // ensure decoded in case caller forgot to prepare the image
|
||||
return new Reader(decoded);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMimeType() {
|
||||
String guessed = URLConnection.guessContentTypeFromName(resource.toString());
|
||||
return guessed == null ? "image/unknown" : guessed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
// technically this class CAN be used after calling this method since there are no resources to free
|
||||
// but for code architecture consistency it's not recommended
|
||||
decoded = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pixel accessor for a {@link BufferedImage}.
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
|
||||
public static class Reader implements PixelReader {
|
||||
/**
|
||||
* The image to read from.
|
||||
*/
|
||||
BufferedImage img;
|
||||
|
||||
@Override
|
||||
public int getARGB(int x, int y) {
|
||||
return img.getRGB(x, y);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getWidth() {
|
||||
return img.getWidth();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHeight() {
|
||||
return img.getHeight();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int[] getRow(int y) {
|
||||
return img.getRGB(0, y, img.getWidth(), 1, null, 0, img.getWidth());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int[] getColumn(int x) {
|
||||
return img.getRGB(x, 0, 1, img.getHeight(), null, 0, img.getWidth());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int[][] getAll() {
|
||||
int[][] result = new int[img.getHeight()][img.getWidth()];
|
||||
for (int y = 0; y < result.length; y++) {
|
||||
int[] row = result[y];
|
||||
img.getRGB(0, y, img.getWidth(), 1, row, 0, img.getWidth());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package ru.fokinatorr.sparkle.graphics.image;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NonNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import org.lwjgl.nanovg.NSVGImage;
|
||||
import ru.fokinatorr.sparkle.graphics.ARGB;
|
||||
import ru.fokinatorr.sparkle.graphics.PixelReader;
|
||||
import ru.fokinatorr.sparkle.graphics.impl.IntBufferPixelAccessor;
|
||||
import ru.fokinatorr.sparkle.graphics.vector.SVGVector;
|
||||
|
||||
import java.net.URL;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.IntBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.lwjgl.system.MemoryUtil.*;
|
||||
import static org.lwjgl.nanovg.NanoSVG.*;
|
||||
|
||||
/**
|
||||
* An SVG image is a vector-based format.
|
||||
*/
|
||||
@FieldDefaults(level = AccessLevel.PRIVATE)
|
||||
@RequiredArgsConstructor
|
||||
public class SVGImage implements Image {
|
||||
/**
|
||||
* Location of the image data.
|
||||
*/
|
||||
@NonNull
|
||||
final URL resource;
|
||||
volatile NSVGImage decoded;
|
||||
volatile IntBuffer rasterized;
|
||||
|
||||
@Override
|
||||
public void prepare() {
|
||||
if (decoded == null) {
|
||||
try {
|
||||
decoded = nsvgParseFromFile(resource.getPath(), "px", 96f);
|
||||
rasterize();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to decode SVG image from path: " + resource, e);
|
||||
}
|
||||
if (decoded == null) {
|
||||
throw new RuntimeException("Failed to decode SVG image from path: " + resource);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isReady() {
|
||||
return rasterized != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PixelReader createPixelReader() {
|
||||
prepare();
|
||||
return new IntBufferPixelAccessor((int) decoded.width(), (int) decoded.height(), rasterized, () -> {
|
||||
if (rasterized == null) {
|
||||
throw new IllegalStateException("Image has not been prepared yet");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMimeType() {
|
||||
return "image/svg+xml";
|
||||
}
|
||||
|
||||
public List<SVGVector> getVectors() {
|
||||
prepare();
|
||||
|
||||
List<SVGVector> vectors = new ArrayList<>();
|
||||
return vectors;//TODO
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
memFree(rasterized);
|
||||
rasterized = null;
|
||||
nsvgDelete(decoded);
|
||||
decoded = null;
|
||||
}
|
||||
|
||||
// Private implementation
|
||||
|
||||
private void rasterize() {
|
||||
long rasterizer /*pointer*/ = nsvgCreateRasterizer();
|
||||
ByteBuffer rasterizedBB = memAlloc((int) (decoded.width() * decoded.height() * Integer.BYTES));
|
||||
try {
|
||||
nsvgRasterize(
|
||||
rasterizer,
|
||||
decoded,
|
||||
0f, 0f,
|
||||
1f,
|
||||
rasterizedBB,
|
||||
(int) decoded.width(), (int) decoded.height(),
|
||||
(int) (decoded.width() * Integer.BYTES)
|
||||
);
|
||||
} catch (Exception e) {
|
||||
memFree(rasterizedBB);
|
||||
throw new RuntimeException("Failed to rasterise SVG image", e);
|
||||
} finally {
|
||||
nnsvgDeleteRasterizer(rasterizer);
|
||||
}
|
||||
rasterized = rasterizedBB.asIntBuffer();
|
||||
// convert from RGBA to ARGB
|
||||
for (int i = 0; i < rasterized.capacity(); i++) {
|
||||
int rgba = rasterized.get(i);
|
||||
int argb = ARGB.color(
|
||||
(byte) (rgba & 0xFF),
|
||||
(byte) (rgba >>> 24 & 0xFF),
|
||||
(byte) (rgba >>> 16 & 0xFF),
|
||||
(byte) (rgba >>> 8 & 0xFF)
|
||||
);
|
||||
rasterized.put(i, argb);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import ru.fokinatorr.sparkle.context.AppContext;
|
||||
import ru.fokinatorr.sparkle.graphics.GraphicsManager;
|
||||
import ru.fokinatorr.sparkle.graphics.GraphicsUtils;
|
||||
import ru.fokinatorr.sparkle.graphics.PixelReader;
|
||||
import ru.fokinatorr.sparkle.graphics.image.Image;
|
||||
import ru.fokinatorr.sparkle.graphics.render.RenderingContext;
|
||||
import ru.fokinatorr.sparkle.graphics.render.renderer.Renderer;
|
||||
import ru.fokinatorr.sparkle.graphics.render.renderer.RendererRegistry;
|
||||
import ru.fokinatorr.sparkle.graphics.render.surface.RenderingSurface;
|
||||
import ru.fokinatorr.sparkle.internal.access.SharedSecrets;
|
||||
import ru.fokinatorr.sparkle.internal.access.StageAccess;
|
||||
import ru.fokinatorr.sparkle.phys2d.Point2D;
|
||||
import ru.fokinatorr.sparkle.stage.RenderableID;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
|
||||
import static lombok.AccessLevel.PROTECTED;
|
||||
import static ru.fokinatorr.sparkle.graphics.render.RenderCanvas.ORIGINAL_SIZE;
|
||||
import static ru.fokinatorr.sparkle.util.Constants.NANOS_PER_SECOND;
|
||||
|
||||
/**
|
||||
* Base class for rendering context implementations.
|
||||
*/
|
||||
@FieldDefaults(level = PROTECTED)
|
||||
@RequiredArgsConstructor
|
||||
public abstract class AbstractRenderingContext implements RenderingContext {
|
||||
final AppContext context;
|
||||
@Getter final RenderingSurface surface;
|
||||
@Getter final Stage stage;
|
||||
@Getter final GraphicsManager parent;
|
||||
|
||||
boolean closed;
|
||||
@Getter double lastFPS;
|
||||
long totalRenderTimeNs;
|
||||
int frameCount;
|
||||
@Getter double avgFPS;
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!closed) {
|
||||
doClose();
|
||||
surface.close();
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void present() {
|
||||
ensureOpen();
|
||||
long startTimeNs = System.nanoTime();
|
||||
// actual rendering
|
||||
var fb = surface.acquireBuffer();
|
||||
RenderCanvasExt canvas = getCanvas();
|
||||
canvas.attachTarget(fb);
|
||||
canvas.clear();
|
||||
renderStage();
|
||||
canvas.flush();
|
||||
surface.present(fb);
|
||||
long renderTimeNs = System.nanoTime() - startTimeNs;
|
||||
|
||||
// statistics
|
||||
totalRenderTimeNs += renderTimeNs;
|
||||
frameCount++;
|
||||
double fps = (double) NANOS_PER_SECOND / renderTimeNs;
|
||||
if (Double.isFinite(fps)) { // ignore NaNs and infinities from division by zero etc.
|
||||
this.lastFPS = fps;
|
||||
}
|
||||
double avgFPS = 1d / totalRenderTimeNs * NANOS_PER_SECOND * frameCount;
|
||||
if (Double.isFinite(avgFPS)) {
|
||||
this.avgFPS = avgFPS;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public abstract RenderCanvasExt getCanvas();
|
||||
|
||||
protected abstract void doClose();
|
||||
|
||||
protected abstract boolean renderControlBar();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
protected void renderStage() {
|
||||
ensureOpen();
|
||||
RenderCanvasExt canvas = getCanvas();
|
||||
stage.drawBackdrop(canvas);
|
||||
|
||||
// render content
|
||||
RendererRegistry registry = context.get(RendererRegistry.class);
|
||||
for (RenderableID<?> id : stage.getLayers()) {
|
||||
Object renderable = id.getFrom(stage);
|
||||
Renderer<Object> renderer = registry.get((Class<Object>) renderable.getClass());
|
||||
if (renderer.isVisible(renderable)) {
|
||||
renderer.render(renderable, canvas);
|
||||
}
|
||||
}
|
||||
|
||||
// render control bar if needed
|
||||
if (renderControlBar()) {
|
||||
// TODO render stage's control bar
|
||||
}
|
||||
}
|
||||
|
||||
protected void ensureOpen() {
|
||||
if (closed) {
|
||||
throw new IllegalStateException("This context is closed");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.NonNull;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import ru.fokinatorr.sparkle.effect.graphics.GraphicEffectMap;
|
||||
import ru.fokinatorr.sparkle.graphics.BlendMode;
|
||||
import ru.fokinatorr.sparkle.graphics.render.RenderCanvas;
|
||||
import ru.fokinatorr.sparkle.phys2d.Point2D;
|
||||
import ru.fokinatorr.sparkle.util.Mth;
|
||||
|
||||
import java.awt.*;
|
||||
|
||||
import static lombok.AccessLevel.PRIVATE;
|
||||
|
||||
/**
|
||||
* Represents the current graphics state of a {@link RenderCanvas}.
|
||||
*
|
||||
* @see RenderCanvas
|
||||
* @see RenderCanvas#save()
|
||||
* @see RenderCanvas#restore()
|
||||
*/
|
||||
@FieldDefaults(level = PRIVATE)
|
||||
@Data
|
||||
public class GraphicsState {
|
||||
|
||||
double translateX;
|
||||
double translateY;
|
||||
double rotationDegrees;
|
||||
double scaleX = 1.0;
|
||||
double scaleY = 1.0;
|
||||
|
||||
int fillARGB = 0xFF_00_00_00; // Default black
|
||||
int strokeARGB = 0xFF_00_00_00; // Default black
|
||||
double lineWidth = 1.0;
|
||||
/**
|
||||
* Unsigned byte representing the opacity multiplier.
|
||||
* {@code 0} - fully transparent, {@code 255} ({@code -1}) - fully opaque.
|
||||
*/
|
||||
byte alpha = (byte) 255;
|
||||
|
||||
@NonNull
|
||||
BlendMode blendMode = BlendMode.ADD;
|
||||
@NonNull
|
||||
GraphicEffectMap effects = new GraphicEffectMap();
|
||||
|
||||
Shape clip;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a deep copy of this graphics state.
|
||||
*
|
||||
* @return a new {@code GraphicsState} with identical property values
|
||||
*/
|
||||
public GraphicsState copy() {
|
||||
GraphicsState copy = new GraphicsState();
|
||||
copy.translateX = this.translateX;
|
||||
copy.translateY = this.translateY;
|
||||
copy.rotationDegrees = this.rotationDegrees;
|
||||
copy.scaleX = this.scaleX;
|
||||
copy.scaleY = this.scaleY;
|
||||
copy.fillARGB = this.fillARGB;
|
||||
copy.strokeARGB = this.strokeARGB;
|
||||
copy.lineWidth = this.lineWidth;
|
||||
copy.alpha = this.alpha;
|
||||
copy.blendMode = this.blendMode;
|
||||
copy.effects = this.effects.copy();
|
||||
copy.clip = this.clip;
|
||||
return copy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the new X coordinate translation.
|
||||
* @param translateX the new translation
|
||||
* @throws IllegalArgumentException if translateX is infinite or NaN
|
||||
*/
|
||||
public void setTranslateX(double translateX) {
|
||||
if (Double.isInfinite(translateX) || Double.isNaN(translateX)) {
|
||||
throw new IllegalArgumentException("Translation must be finite, got: " + translateX);
|
||||
}
|
||||
this.translateX = translateX;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the new Y coordinate translation.
|
||||
* @param translateY the new translation
|
||||
* @throws IllegalArgumentException if translateY is infinite or NaN
|
||||
*/
|
||||
public void setTranslateY(double translateY) {
|
||||
if (Double.isInfinite(translateY) || Double.isNaN(translateY)) {
|
||||
throw new IllegalArgumentException("Translation must be finite, got: " + translateY);
|
||||
}
|
||||
this.translateY = translateY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates the state by the given deltas.
|
||||
* @param dx the X delta
|
||||
* @param dy the Y delta
|
||||
* @throws IllegalArgumentException if any argument is infinite or NaN
|
||||
*/
|
||||
public void translate(double dx, double dy) {
|
||||
setTranslateX(translateX + dx);
|
||||
setTranslateY(translateY + dy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the new rotation, in degrees.
|
||||
* @param rotationDegrees the new rotation
|
||||
* @throws IllegalArgumentException if rotationDegrees is infinite, or NaN
|
||||
*/
|
||||
public void setRotationDegrees(double rotationDegrees) {
|
||||
if (Double.isInfinite(rotationDegrees) || Double.isNaN(rotationDegrees)) {
|
||||
throw new IllegalArgumentException("Rotation must be positive and finite, got: " + rotationDegrees);
|
||||
}
|
||||
this.rotationDegrees = Mth.wrapClamp(rotationDegrees, -360d, 360d);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the given delta (in degrees) to the current rotation.
|
||||
* @param dr the rotation delta
|
||||
* @throws IllegalArgumentException if dr is infinite, or NaN
|
||||
*/
|
||||
public void rotate(double dr) {
|
||||
setRotationDegrees(rotationDegrees + dr);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the new X axis scale.
|
||||
* @param scaleX the new X axis scale
|
||||
* @throws IllegalArgumentException if scaleX is non-positive, infinite, or NaN
|
||||
*/
|
||||
public void setScaleX(double scaleX) {
|
||||
if (scaleX <= 0 || Double.isInfinite(scaleX) || Double.isNaN(scaleX)) {
|
||||
throw new IllegalArgumentException("Scale must be positive and finite, got: " + scaleX);
|
||||
}
|
||||
this.scaleX = scaleX;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the new Y axis scale.
|
||||
* @param scaleY the new Y axis scale
|
||||
* @throws IllegalArgumentException if scaleY is non-positive, infinite, or NaN
|
||||
*/
|
||||
public void setScaleY(double scaleY) {
|
||||
if (scaleY <= 0 || Double.isInfinite(scaleY) || Double.isNaN(scaleY)) {
|
||||
throw new IllegalArgumentException("Scale must be positive and finite, got: " + scaleY);
|
||||
}
|
||||
this.scaleY = scaleY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scales the state by the given deltas.
|
||||
* @param sx the X axis scale delta
|
||||
* @param sy the Y axis scale delta
|
||||
* @throws IllegalArgumentException if any argument is non-positive, infinite or NaN
|
||||
*/
|
||||
public void scale(double sx, double sy) {
|
||||
setScaleX(scaleX * sx);
|
||||
setScaleY(scaleY * sy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the new line width.
|
||||
* @param lineWidth the new line width
|
||||
* @throws IllegalArgumentException if lineWidth is non-positive, infinite, or NaN
|
||||
*/
|
||||
public void setLineWidth(double lineWidth) {
|
||||
if (lineWidth <= 0 || Double.isInfinite(lineWidth) || Double.isNaN(lineWidth)) {
|
||||
throw new IllegalArgumentException("Line width must be positive and finite, got: " + lineWidth);
|
||||
}
|
||||
this.lineWidth = lineWidth;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms the given point by this state's transformation matrix.
|
||||
* @param x the X coordinate
|
||||
* @param y the Y coordinate
|
||||
* @return a new {@link Point2D} with transformed coordinates
|
||||
*/
|
||||
public Point2D transformPoint(double x, double y) {
|
||||
// Apply scale
|
||||
double tx = x * scaleX;
|
||||
double ty = y * scaleY;
|
||||
|
||||
// Apply rotation (clockwise)
|
||||
double cos = Math.cos(Math.toRadians(rotationDegrees));
|
||||
double sin = Math.sin(Math.toRadians(rotationDegrees));
|
||||
double rx = tx * cos + ty * sin;
|
||||
double ry = -tx * sin + ty * cos;
|
||||
|
||||
// Apply translation
|
||||
return new Point2D(rx + translateX, ry + translateY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether this state has any non-identity transformations.
|
||||
* @return true if translation, rotation, or scaling is applied
|
||||
*/
|
||||
public boolean hasTransform() {
|
||||
return translateX != 0 || translateY != 0 ||
|
||||
rotationDegrees != 0 ||
|
||||
scaleX != 1.0 || scaleY != 1.0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import ru.fokinatorr.sparkle.graphics.PixelReader;
|
||||
import ru.fokinatorr.sparkle.graphics.PixelWriter;
|
||||
|
||||
import java.nio.IntBuffer;
|
||||
|
||||
import static lombok.AccessLevel.PRIVATE;
|
||||
|
||||
/**
|
||||
* IntBuffer as image accessor, row-major order.
|
||||
*/
|
||||
@FieldDefaults(makeFinal = true, level = PRIVATE)
|
||||
@RequiredArgsConstructor
|
||||
public class IntBufferPixelAccessor implements PixelReader, PixelWriter {
|
||||
|
||||
int width, height;
|
||||
IntBuffer img;
|
||||
Runnable ensureOpen;
|
||||
|
||||
// <editor-fold desc="-- PixelReader --">
|
||||
|
||||
@Override
|
||||
public int getWidth() {
|
||||
ensureOpen();
|
||||
return width;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHeight() {
|
||||
ensureOpen();
|
||||
return height;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getARGB(int x, int y) {
|
||||
ensureOpen();
|
||||
checkBounds(x, y);
|
||||
return img.get(y * width + x);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int[] getRow(int y) {
|
||||
ensureOpen();
|
||||
checkBoundsY(y);
|
||||
int[] row = new int[width];
|
||||
img.get(y * width, row);
|
||||
return row;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int[] getColumn(int x) {
|
||||
ensureOpen();
|
||||
checkBoundsX(x);
|
||||
int[] column = new int[height];
|
||||
for (int y = 0; y < height; y++) {
|
||||
column[y] = img.get(y * width + x);
|
||||
}
|
||||
return column;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int[][] getAll() {
|
||||
int[][] data = new int[height][width];
|
||||
for (int y = 0; y < height; y++) {
|
||||
img.get(y * width, data[y]);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
// </editor-fold>
|
||||
|
||||
// <editor-fold desc="-- PixelWriter --">
|
||||
|
||||
@Override
|
||||
public void setARGB(int x, int y, int argb) {
|
||||
ensureOpen();
|
||||
checkBounds(x, y);
|
||||
img.put(y * width + x, argb);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fillARGB(int startX, int startY, int w, int h, int argb) {
|
||||
ensureOpen();
|
||||
checkBounds(startX, startY);
|
||||
checkBounds(startX + w - 1, startY + h - 1);
|
||||
|
||||
for (int y = startY; y < startY + h; y++) {
|
||||
int base = y * width;
|
||||
for (int x = startX; x < startX + w; x++) {
|
||||
img.put(base + x, argb);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writePixels(int[] src, int off, int scanSize, int startX, int startY, int w, int h) {
|
||||
ensureOpen();
|
||||
checkBounds(startX, startY);
|
||||
checkBounds(startX + w - 1, startY + h - 1);
|
||||
|
||||
for (int y = startY; y < startY + w; y++) {
|
||||
img.put(y * width + startX, src, off + scanSize * (y - startX), h);
|
||||
}
|
||||
}
|
||||
|
||||
// </editor-fold>
|
||||
|
||||
private void ensureOpen() {
|
||||
ensureOpen.run();
|
||||
}
|
||||
|
||||
private void checkBoundsX(int x) {
|
||||
if (x >= width) {
|
||||
throw new IllegalArgumentException("X coordinate out of bounds for " + width + "x" + height + " image: " + x);
|
||||
}
|
||||
}
|
||||
|
||||
private void checkBoundsY(int y) {
|
||||
if (y >= height) {
|
||||
throw new IllegalArgumentException("Y coordinate out of bounds for " + width + "x" + height + " image: " + y);
|
||||
}
|
||||
}
|
||||
|
||||
private void checkBounds(int x, int y) {
|
||||
checkBoundsX(x);
|
||||
checkBoundsY(y);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl;
|
||||
|
||||
import it.unimi.dsi.fastutil.Pair;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.objects.ReferenceReferenceImmutablePair;
|
||||
import lombok.NonNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.lwjgl.glfw.GLFWErrorCallback;
|
||||
import ru.fokinatorr.sparkle.context.AppContext;
|
||||
import ru.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
|
||||
import ru.fokinatorr.sparkle.graphics.GraphicsManager;
|
||||
import ru.fokinatorr.sparkle.graphics.image.Image;
|
||||
import ru.fokinatorr.sparkle.graphics.image.RasterImage;
|
||||
import ru.fokinatorr.sparkle.graphics.image.SVGImage;
|
||||
import ru.fokinatorr.sparkle.graphics.impl.gl.OpenGLContext;
|
||||
import ru.fokinatorr.sparkle.graphics.impl.gl.surface.GL_GLFWWindowSurface;
|
||||
import ru.fokinatorr.sparkle.graphics.render.RenderingContext;
|
||||
import ru.fokinatorr.sparkle.graphics.render.surface.EmbeddedSurface;
|
||||
import ru.fokinatorr.sparkle.internal.access.SharedSecrets;
|
||||
import ru.fokinatorr.sparkle.internal.access.StageAccess;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
import ru.fokinatorr.sparkle.stage.StageCreator;
|
||||
|
||||
import java.net.MalformedURLException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
import static lombok.AccessLevel.PRIVATE;
|
||||
import static org.lwjgl.glfw.GLFW.*;
|
||||
|
||||
/**
|
||||
* A graphics manager using OpenGL + GLFW as a GPU-based backend.
|
||||
* <p><b>NOTE</b>: Make sure to call the constructor from the graphics loop thread!
|
||||
*/
|
||||
@Slf4j
|
||||
@FieldDefaults(level = PRIVATE)
|
||||
@RequiredArgsConstructor
|
||||
public class OpenGLGraphicsManager implements GraphicsManager {
|
||||
// NOTE: Using OpenGL for beta releases. If performance gets unbearably horrible, switch to Vulkan
|
||||
|
||||
private static final StageAccess stageAcc = SharedSecrets.getStageAccess();
|
||||
|
||||
@NonNull
|
||||
final AppContext context;
|
||||
final Queue<Runnable> workQ = new ConcurrentLinkedQueue<>();
|
||||
final Map<Stage, AbstractRenderingContext> renderContexts = new Reference2ReferenceOpenHashMap<>();
|
||||
final Thread graphicsThread = Thread.currentThread();
|
||||
final Map<Path, Image> images = new ConcurrentHashMap<>();
|
||||
final Set<Image> autoLoadImages = Collections.newSetFromMap(new ConcurrentHashMap<>());
|
||||
|
||||
boolean glInitialized;
|
||||
GLFWErrorCallback errorCallback;
|
||||
|
||||
boolean closed;
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!closed) {
|
||||
ensureOnCorrectThread();
|
||||
renderContexts.values().forEach(AbstractRenderingContext::close);
|
||||
renderContexts.clear();
|
||||
images.values().forEach(Image::close);
|
||||
images.clear();
|
||||
autoLoadImages.clear();
|
||||
if (glInitialized) {
|
||||
glfwTerminate();
|
||||
errorCallback.free();
|
||||
glInitialized = false;
|
||||
}
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Pair<Stage, RenderingContext> createWindowContext(String title, StageCreator stageCreator, boolean translucent, boolean fullscreen) {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
ensureGLInitialized();
|
||||
|
||||
|
||||
Stage stage = SharedSecrets.getStageAccess().newStage(stageCreator, context);
|
||||
// @formatter:off // for readability
|
||||
GL_GLFWWindowSurface window = fullscreen
|
||||
? GL_GLFWWindowSurface.createFullscreen(
|
||||
title, glfwGetPrimaryMonitor(), translucent,
|
||||
context.get(EventDispatcher.class), stage, graphicsThread
|
||||
)
|
||||
: GL_GLFWWindowSurface.create(
|
||||
title, translucent,
|
||||
context.get(EventDispatcher.class), stage, graphicsThread
|
||||
);
|
||||
// @formatter:on
|
||||
OpenGLContext glContext = new OpenGLContext(context, window, stage, autoLoadImages, this);
|
||||
renderContexts.put(stage, glContext);
|
||||
return new ReferenceReferenceImmutablePair<>(stage, glContext);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Pair<Stage, RenderingContext> createEmbeddedContext(EmbeddedSurface surface, StageCreator stageCreator) {
|
||||
ensureOpen();
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractRenderingContext getContext(Stage boundStage) {
|
||||
ensureOpen();
|
||||
return renderContexts.get(Objects.requireNonNull(boundStage, "bound stage"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasActiveContexts() {
|
||||
return !(closed || renderContexts.isEmpty());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Image loadImage(Path path, boolean autoLoad) {
|
||||
ensureOpen();
|
||||
|
||||
Image newImg;
|
||||
try {
|
||||
newImg = path.getFileName().toString().endsWith(".svg") // TODO more formats later
|
||||
? new SVGImage(path.toUri().toURL())
|
||||
: new RasterImage(path.toUri().toURL());
|
||||
} catch (MalformedURLException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
Image oldImg = images.put(path, newImg);
|
||||
if (oldImg != null) {
|
||||
autoLoadImages.remove(oldImg);
|
||||
oldImg.close();
|
||||
}
|
||||
|
||||
if (autoLoad) autoLoadImages.add(newImg);
|
||||
return newImg;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasLoadedImage(Path path) {
|
||||
return !closed && images.containsKey(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Image getLoadedImage(Path path) {
|
||||
ensureOpen();
|
||||
return images.get(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroyImage(Path path) {
|
||||
ensureOpen();
|
||||
if (images.containsKey(path)) {
|
||||
images.remove(path).close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void runLater(Runnable run) {
|
||||
ensureOpen();
|
||||
if (!workQ.offer(run)) {
|
||||
throw new IllegalStateException("Work queue overflow; cannot add more tasks");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick() {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
|
||||
runTasks();
|
||||
for (var renderCtx : renderContexts.values()) {
|
||||
renderCtx.pollEvents();
|
||||
if (!stageAcc.isSuppressRedraw(renderCtx.getStage())) {
|
||||
renderCtx.present();
|
||||
}
|
||||
if (renderCtx.shouldClose()) {
|
||||
renderCtx.getStage().stop().thenRun(() -> runLater(() -> {
|
||||
renderCtx.close();
|
||||
renderContexts.remove(renderCtx.getStage());
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureOpen() {
|
||||
if (closed) {
|
||||
throw new IllegalStateException("This manager is closed");
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureOnCorrectThread() {
|
||||
if (Thread.currentThread() != graphicsThread) {
|
||||
throw new IllegalCallerException("Called from incorrect thread; must call from " + graphicsThread);
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureGLInitialized() {
|
||||
if (!glInitialized) {
|
||||
// GLFW
|
||||
this.errorCallback = GLFWErrorCallback.createPrint(System.err).set();
|
||||
|
||||
if (glfwPlatformSupported(GLFW_PLATFORM_WAYLAND) || glfwPlatformSupported(GLFW_PLATFORM_X11)) {
|
||||
glfwInitHint(GLFW_PLATFORM, GLFW_PLATFORM_X11); // I don't think OpenGL works on Wayland
|
||||
}
|
||||
|
||||
if (!glfwInit()) {
|
||||
throw new IllegalStateException("Unable to initialize GLFW");
|
||||
}
|
||||
glfwDefaultWindowHints();
|
||||
glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_NATIVE_CONTEXT_API);
|
||||
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
|
||||
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
|
||||
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
|
||||
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
|
||||
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
|
||||
|
||||
// GL context not created here, so no GL calls yet
|
||||
}
|
||||
}
|
||||
|
||||
private void runTasks() {
|
||||
Runnable task;
|
||||
while ((task = workQ.poll()) != null) {
|
||||
try {
|
||||
task.run();
|
||||
} catch (Exception e) {
|
||||
log.error("Exception in task", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl;
|
||||
|
||||
import ru.fokinatorr.sparkle.graphics.image.Image;
|
||||
import ru.fokinatorr.sparkle.graphics.render.RenderCanvas;
|
||||
import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer;
|
||||
|
||||
/**
|
||||
* An extensions interface for {@link RenderCanvas} providing additional methods
|
||||
* for attaching framebuffers, flushing, etc.
|
||||
*/
|
||||
public interface RenderCanvasExt extends RenderCanvas {
|
||||
|
||||
/**
|
||||
* Attaches a new framebuffer for the canvas to draw on.
|
||||
* @param target the framebuffer
|
||||
*/
|
||||
void attachTarget(Framebuffer target);
|
||||
|
||||
/**
|
||||
* Clears the entire surface.
|
||||
*/
|
||||
void clear();
|
||||
|
||||
/**
|
||||
* Flushes all pending operations, if any.
|
||||
*/
|
||||
void flush();
|
||||
|
||||
/**
|
||||
* Uploads an Image object, making it ready for rendering.
|
||||
* @param image the image
|
||||
*/
|
||||
void uploadImage(Image image);
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl.gl;
|
||||
|
||||
import ru.fokinatorr.sparkle.graphics.ARGB;
|
||||
import ru.fokinatorr.sparkle.graphics.PixelReader;
|
||||
import ru.fokinatorr.sparkle.graphics.PixelWriter;
|
||||
import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
import static org.lwjgl.opengl.GL46.*;
|
||||
|
||||
/**
|
||||
* A wrapper for an OpenGL framebuffer.
|
||||
*/
|
||||
public record GLFramebuffer(int fboId, int width, int height) implements Framebuffer {
|
||||
|
||||
public GLFramebuffer {
|
||||
if (width <= 0 || height <= 0) {
|
||||
throw new IllegalArgumentException("Width and height must be positive");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new FBO with the given default dimensions.
|
||||
* @param width the initial width
|
||||
* @param height the initial height
|
||||
*/
|
||||
public GLFramebuffer(int width, int height) {
|
||||
this(glGenFramebuffers(), width, height);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PixelReader createPixelReader() {
|
||||
ensureOpen();
|
||||
if (fboId == 0) {
|
||||
return new Accessor();
|
||||
}
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return {@inheritDoc}
|
||||
* @deprecated By-pixel writing to a GL buffer is much slower than using GL operations
|
||||
* directly and may not work. Prefer GL operations instead of this method.
|
||||
*/
|
||||
@Override
|
||||
@Deprecated(since = "0.1-beta")
|
||||
public PixelWriter createPixelWriter() {
|
||||
ensureOpen();
|
||||
if (fboId == 0) {
|
||||
return new Accessor();
|
||||
}
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (fboId != 0) {
|
||||
glDeleteFramebuffers(fboId);
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureOpen() {
|
||||
if (!glIsFramebuffer(fboId)) {
|
||||
throw new IllegalStateException("The framebuffer is closed");
|
||||
}
|
||||
}
|
||||
|
||||
private void checkBoundsX(int x) {
|
||||
if (x >= width) {
|
||||
throw new IllegalArgumentException("X coordinate out of bounds for " + width + "x" + height + " image: " + x);
|
||||
}
|
||||
}
|
||||
|
||||
private void checkBoundsY(int y) {
|
||||
if (y >= height) {
|
||||
throw new IllegalArgumentException("Y coordinate out of bounds for " + width + "x" + height + " image: " + y);
|
||||
}
|
||||
}
|
||||
|
||||
private void checkBounds(int x, int y) {
|
||||
checkBoundsX(x);
|
||||
checkBoundsY(y);
|
||||
}
|
||||
|
||||
|
||||
// not thread-safe!
|
||||
private class Accessor implements PixelReader, PixelWriter {
|
||||
|
||||
private final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(Math.max(width, height) * Integer.BYTES);
|
||||
// can't use MemoryUtil.memAlloc since no chance to clean up (PixelReader/Writer are not closeable)
|
||||
|
||||
private static void rgbaToArgb(ByteBuffer src, int[] dest) {
|
||||
for (int i = 0; i < dest.length; i++) {
|
||||
byte
|
||||
r = src.get(),
|
||||
g = src.get(),
|
||||
b = src.get(),
|
||||
a = src.get();
|
||||
dest[i] = ARGB.color(a, r, g, b);
|
||||
}
|
||||
}
|
||||
|
||||
private static void argbToRgba(int argb, ByteBuffer dest) {
|
||||
dest
|
||||
.put(ARGB.red (argb))
|
||||
.put(ARGB.green(argb))
|
||||
.put(ARGB.blue (argb))
|
||||
.put(ARGB.alpha(argb))
|
||||
.flip();
|
||||
}
|
||||
|
||||
// <editor-fold desc="-- PixelReader --">
|
||||
|
||||
@Override
|
||||
public int getARGB(int x, int y) {
|
||||
ensureOpen();
|
||||
checkBounds(x, y);
|
||||
byteBuffer.limit(Integer.BYTES).rewind();
|
||||
glReadPixels(x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, byteBuffer);
|
||||
return ARGB.color(
|
||||
byteBuffer.get(3),
|
||||
byteBuffer.get(0),
|
||||
byteBuffer.get(1),
|
||||
byteBuffer.get(2)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int[] getRow(int y) {
|
||||
ensureOpen();
|
||||
checkBoundsY(y);
|
||||
int[] row = new int[width];
|
||||
byteBuffer.limit(width * Integer.BYTES).rewind();
|
||||
glReadPixels(0, y, width, 1, GL_RGBA, GL_UNSIGNED_BYTE, byteBuffer);
|
||||
rgbaToArgb(byteBuffer, row);
|
||||
return row;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int[] getColumn(int x) {
|
||||
ensureOpen();
|
||||
checkBoundsX(x);
|
||||
int[] column = new int[height];
|
||||
byteBuffer.limit(height * Integer.BYTES).rewind();
|
||||
glReadPixels(x, 0, 1, height, GL_RGBA, GL_UNSIGNED_BYTE, byteBuffer);
|
||||
rgbaToArgb(byteBuffer, column);
|
||||
return column;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int[][] getAll() {
|
||||
int[][] data = new int[height][width];
|
||||
byteBuffer.limit(width * Integer.BYTES).rewind();
|
||||
for (int y = 0; y < height; y++) {
|
||||
glReadPixels(0, y, width, 1, GL_RGBA, GL_UNSIGNED_BYTE, byteBuffer);
|
||||
rgbaToArgb(byteBuffer, data[y]);
|
||||
byteBuffer.rewind();
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
// </editor-fold>
|
||||
|
||||
// <editor-fold desc="-- PixelWriter (deprecated) --">
|
||||
|
||||
|
||||
@Override
|
||||
@Deprecated(since = "0.1-beta")
|
||||
public void setARGB(int x, int y, int argb) {
|
||||
ensureOpen();
|
||||
checkBounds(x, y);
|
||||
argbToRgba(argb, byteBuffer.rewind());
|
||||
glRasterPos2i(x, height - 1 - y);
|
||||
glDrawPixels(1, 1, GL_RGBA, GL_UNSIGNED_BYTE, byteBuffer);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Deprecated(since = "0.1-beta")
|
||||
public void fillARGB(int x, int y, int w, int h, int argb) {
|
||||
ensureOpen();
|
||||
checkBounds(x, y);
|
||||
checkBounds(x + w - 1, y + h - 1);
|
||||
argbToRgba(argb, byteBuffer.rewind());
|
||||
glRasterPos2i(x, height - 1 - y);
|
||||
glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, byteBuffer);
|
||||
}
|
||||
|
||||
// </editor-fold>
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,697 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl.gl;
|
||||
|
||||
import it.unimi.dsi.fastutil.floats.*;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import org.joml.Matrix4f;
|
||||
import org.lwjgl.opengl.GL46;
|
||||
import ru.fokinatorr.sparkle.effect.graphics.GraphicEffect;
|
||||
import ru.fokinatorr.sparkle.effect.graphics.GraphicEffectMap;
|
||||
import ru.fokinatorr.sparkle.graphics.ARGB;
|
||||
import ru.fokinatorr.sparkle.graphics.BlendMode;
|
||||
import ru.fokinatorr.sparkle.graphics.PixelReader;
|
||||
import ru.fokinatorr.sparkle.graphics.image.Image;
|
||||
import ru.fokinatorr.sparkle.graphics.impl.GraphicsState;
|
||||
import ru.fokinatorr.sparkle.graphics.impl.RenderCanvasExt;
|
||||
import ru.fokinatorr.sparkle.graphics.impl.gl.shader.GLShaderProgram;
|
||||
import ru.fokinatorr.sparkle.graphics.impl.gl.shader.ShaderType;
|
||||
import ru.fokinatorr.sparkle.graphics.render.RenderCanvas;
|
||||
import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.geom.Area;
|
||||
import java.awt.geom.PathIterator;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.FloatBuffer;
|
||||
import java.util.*;
|
||||
|
||||
import static lombok.AccessLevel.PROTECTED;
|
||||
import static org.lwjgl.opengl.GL46.*;
|
||||
import static org.lwjgl.system.MemoryUtil.*;
|
||||
import static ru.fokinatorr.sparkle.graphics.impl.gl.ShaderLoader.loadShader;
|
||||
|
||||
import ru.fokinatorr.sparkle.phys2d.Point2D;
|
||||
|
||||
/**
|
||||
* An OpenGL render canvas that accepts {@link GLFramebuffer}s.
|
||||
*/
|
||||
@FieldDefaults(level = PROTECTED)
|
||||
public class GLRenderCanvas implements RenderCanvasExt {
|
||||
|
||||
final OpenGLContext parent;
|
||||
final Set<Image> autoLoadImages;
|
||||
|
||||
final Deque<GraphicsState> stateStack = new LinkedList<>(); // Funny how Stack was effectively replaced with Deque
|
||||
GraphicsState currentState = new GraphicsState();
|
||||
|
||||
final GLShaderProgram strokeShader;
|
||||
final GLShaderProgram fillShader;
|
||||
final GLShaderProgram imageShader;
|
||||
|
||||
final Map<Image, Integer> textures = new WeakHashMap<>();
|
||||
GLFramebuffer fb;
|
||||
|
||||
boolean closed;
|
||||
|
||||
|
||||
public GLRenderCanvas(OpenGLContext parent, Set<Image> autoLoadImages) {
|
||||
this.parent = parent;
|
||||
this.autoLoadImages = autoLoadImages;
|
||||
|
||||
parent.makeCurrent();
|
||||
strokeShader = GLShaderProgram.compile(Map.of(
|
||||
ShaderType.VERTEX, loadShader("stroke.vert.glsl"),
|
||||
ShaderType.FRAGMENT, loadShader("stroke.frag.glsl")
|
||||
));
|
||||
fillShader = GLShaderProgram.compile(Map.of(
|
||||
ShaderType.VERTEX, loadShader("fill.vert.glsl"),
|
||||
ShaderType.FRAGMENT, loadShader("fill.frag.glsl")
|
||||
));
|
||||
imageShader = GLShaderProgram.compile(Map.of(
|
||||
ShaderType.VERTEX, loadShader("image.vert.glsl"),
|
||||
ShaderType.FRAGMENT, loadShader("image.frag.glsl")
|
||||
));
|
||||
}
|
||||
|
||||
// <editor-fold desc="RenderCanvasExt methods">
|
||||
|
||||
@Override
|
||||
public void attachTarget(Framebuffer target) {
|
||||
ensureOpen();
|
||||
if (!(target instanceof GLFramebuffer(int fboId, int width, int height))) {
|
||||
throw new IllegalArgumentException("Unsupported frame buffer type: " + target.getClass());
|
||||
}
|
||||
parent.makeCurrent();
|
||||
if (this.fb != null) this.fb.close();
|
||||
this.fb = (GLFramebuffer) target;
|
||||
|
||||
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId);
|
||||
glViewport(0, 0, width, height);
|
||||
glClearColor(1f, 1f, 1f, 0f); // transparent/white by default
|
||||
|
||||
for (Image img : autoLoadImages) uploadImage(img);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
ensureOpen();
|
||||
parent.makeCurrent();
|
||||
ensureCurrentBufferBound();
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() {
|
||||
ensureOpen();
|
||||
parent.makeCurrent();
|
||||
ensureCurrentBufferBound();
|
||||
glFlush();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void uploadImage(Image image) {
|
||||
ensureOpen();
|
||||
parent.makeCurrent();
|
||||
ensureCurrentBufferBound();
|
||||
if (!textures.containsKey(image)) {
|
||||
image.prepare();
|
||||
|
||||
PixelReader reader = image.createPixelReader();
|
||||
int width = reader.getWidth();
|
||||
int height = reader.getHeight();
|
||||
|
||||
int textureId = glGenTextures();
|
||||
textures.put(image, textureId);
|
||||
glBindTexture(GL_TEXTURE_2D, textureId);
|
||||
|
||||
ByteBuffer pixels = memAlloc(width * height * Integer.BYTES);
|
||||
int[][] data = reader.getAll();
|
||||
for (int y = 0; y < height; y++) {
|
||||
for (int x = 0; x < width; x++) {
|
||||
int argb = data[y][x];
|
||||
pixels
|
||||
.put(ARGB.red(argb))
|
||||
.put(ARGB.green(argb))
|
||||
.put(ARGB.blue(argb))
|
||||
.put(ARGB.alpha(argb));
|
||||
}
|
||||
}
|
||||
pixels.flip();
|
||||
|
||||
glTexImage2D(
|
||||
GL_TEXTURE_2D,
|
||||
0,
|
||||
GL_RGBA8,
|
||||
width, height,
|
||||
0,
|
||||
GL_RGBA, GL_UNSIGNED_BYTE,
|
||||
pixels
|
||||
);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// </editor-fold>
|
||||
|
||||
// <editor-fold desc="RenderCanvas methods">
|
||||
|
||||
// Drawing methods
|
||||
|
||||
@Override
|
||||
public void drawShape(Shape shape) {
|
||||
// Ensure openness and current context
|
||||
ensureOpen();
|
||||
parent.makeCurrent();
|
||||
ensureCurrentBufferBound();
|
||||
|
||||
// Convert Shape to VBO
|
||||
FloatList vertices = shapeToVertices(shape);
|
||||
|
||||
if (vertices.isEmpty()) return;
|
||||
int vbo = uploadAndBindVertices(vertices);
|
||||
|
||||
// Set up vertex attributes & shader uniforms
|
||||
strokeShader.use();
|
||||
glEnableVertexAttribArray(0);
|
||||
glVertexAttribPointer(0, 2, GL_FLOAT, false, 0, NULL);
|
||||
|
||||
Matrix4f modelViewProj = buildOrthoMatrix().mul(buildTransformMatrix());
|
||||
int strokeARGB = currentState.getStrokeARGB();
|
||||
float
|
||||
a = byteToFloat(ARGB.alpha(strokeARGB)) * byteToFloat(currentState.getAlpha()),
|
||||
r = byteToFloat(ARGB.red(strokeARGB)),
|
||||
g = byteToFloat(ARGB.green(strokeARGB)),
|
||||
b = byteToFloat(ARGB.blue(strokeARGB));
|
||||
|
||||
GraphicEffectMap effects = currentState.getEffects();
|
||||
|
||||
strokeShader
|
||||
.setUniform("u_ModelViewProj", modelViewProj)
|
||||
.setUniform("u_Color", r, g, b, a)
|
||||
.setUniform("u_HueShift", (float) effects.getDouble(GraphicEffect.HUE_SHIFT))
|
||||
.setUniform("u_Brightness", (float) effects.getDouble(GraphicEffect.BRIGHTNESS) / 100f)
|
||||
.setUniform("u_Opacity", (float) effects.getDouble(GraphicEffect.OPACITY) / 100f);
|
||||
|
||||
// Apply blend function & draw
|
||||
glEnable(GL_BLEND);
|
||||
applyBlendFunc();
|
||||
|
||||
glLineWidth((float) currentState.getLineWidth());
|
||||
glDrawArrays(GL_LINE_STRIP, 0, vertices.size() / 2);
|
||||
|
||||
// Cleanup
|
||||
glDisable(GL_BLEND);
|
||||
glDisableVertexAttribArray(0);
|
||||
glDeleteBuffers(vbo);
|
||||
strokeShader.unuse(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fillShape(Shape shape) {
|
||||
ensureOpen();
|
||||
parent.makeCurrent();
|
||||
ensureCurrentBufferBound();
|
||||
|
||||
// Init common objects
|
||||
glEnable(GL_BLEND);
|
||||
applyBlendFunc();
|
||||
Matrix4f modelViewProj = buildOrthoMatrix().mul(buildTransformMatrix());
|
||||
|
||||
// First fill...
|
||||
FloatList fillVertices = shapeToFillVertices(shape);
|
||||
if (!fillVertices.isEmpty()) {
|
||||
int vbo = uploadAndBindVertices(fillVertices);
|
||||
|
||||
// Set up vertex attributes & shader uniforms
|
||||
fillShader.use();
|
||||
glEnableVertexAttribArray(0);
|
||||
glVertexAttribPointer(0, 2, GL_FLOAT, false, 0, NULL);
|
||||
|
||||
int fillARGB = currentState.getFillARGB();
|
||||
float
|
||||
a = byteToFloat(ARGB.alpha(fillARGB)) * byteToFloat(currentState.getAlpha()),
|
||||
r = byteToFloat(ARGB.red(fillARGB)),
|
||||
g = byteToFloat(ARGB.green(fillARGB)),
|
||||
b = byteToFloat(ARGB.blue(fillARGB));
|
||||
|
||||
GraphicEffectMap effects = currentState.getEffects();
|
||||
|
||||
fillShader
|
||||
.setUniform("u_ModelViewProj", modelViewProj)
|
||||
.setUniform("u_Color", r, g, b, a)
|
||||
.setUniform("u_HueShift", (float) effects.getDouble(GraphicEffect.HUE_SHIFT))
|
||||
.setUniform("u_Brightness", (float) effects.getDouble(GraphicEffect.BRIGHTNESS) / 100f)
|
||||
.setUniform("u_Opacity", (float) effects.getDouble(GraphicEffect.OPACITY) / 100f);
|
||||
|
||||
// Draws as triangle fan (assumes convex or simple shape). TODO replace with tessellation
|
||||
glDrawArrays(GL_TRIANGLE_FAN, 0, fillVertices.size() / 2);
|
||||
|
||||
// Cleanup
|
||||
glDisableVertexAttribArray(0);
|
||||
glDeleteBuffers(vbo);
|
||||
fillShader.unuse(true);
|
||||
}
|
||||
|
||||
// ...then outline
|
||||
FloatList outlineVertices = shapeToVertices(shape);
|
||||
if (!outlineVertices.isEmpty()) {
|
||||
int vbo = uploadAndBindVertices(outlineVertices);
|
||||
|
||||
strokeShader.use();
|
||||
glEnableVertexAttribArray(0);
|
||||
glVertexAttribPointer(0, 2, GL_FLOAT, false, 0, NULL);
|
||||
|
||||
int strokeARGB = currentState.getStrokeARGB();
|
||||
float
|
||||
a = byteToFloat(ARGB.alpha(strokeARGB)) * byteToFloat(currentState.getAlpha()),
|
||||
r = byteToFloat(ARGB.red(strokeARGB)),
|
||||
g = byteToFloat(ARGB.green(strokeARGB)),
|
||||
b = byteToFloat(ARGB.blue(strokeARGB));
|
||||
|
||||
GraphicEffectMap effects = currentState.getEffects();
|
||||
|
||||
strokeShader
|
||||
.setUniform("u_ModelViewProj", modelViewProj)
|
||||
.setUniform("u_Color", r, g, b, a)
|
||||
.setUniform("u_HueShift", (float) effects.getDouble(GraphicEffect.HUE_SHIFT))
|
||||
.setUniform("u_Brightness", (float) effects.getDouble(GraphicEffect.BRIGHTNESS) / 100f)
|
||||
.setUniform("u_Opacity", (float) effects.getDouble(GraphicEffect.OPACITY) / 100f);
|
||||
|
||||
// Draw
|
||||
glLineWidth((float) currentState.getLineWidth());
|
||||
glDrawArrays(GL_LINE_STRIP, 0, outlineVertices.size() / 2);
|
||||
|
||||
// Cleanup
|
||||
glDisableVertexAttribArray(0);
|
||||
glDeleteBuffers(vbo);
|
||||
strokeShader.unuse(true);
|
||||
}
|
||||
|
||||
// Common cleanup
|
||||
glDisable(GL_BLEND);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawImage(Image image, double x, double y, double w, double h) {
|
||||
ensureOpen();
|
||||
|
||||
// sanity checks
|
||||
if (!Double.isFinite(x) || x < 0) {
|
||||
throw new IllegalArgumentException("X coordinate must be finite and non-negative, found: " + x);
|
||||
}
|
||||
if (!Double.isFinite(y) || y < 0) {
|
||||
throw new IllegalArgumentException("Y coordinate must be finite and non-negative, found: " + y);
|
||||
}
|
||||
if (w == ORIGINAL_SIZE || h == ORIGINAL_SIZE) {
|
||||
PixelReader reader = image.createPixelReader();
|
||||
if (w == ORIGINAL_SIZE) w = reader.getWidth();
|
||||
if (h == ORIGINAL_SIZE) h = reader.getHeight();
|
||||
}
|
||||
if (!Double.isFinite(w) || w <= 0) {
|
||||
throw new IllegalArgumentException("Width must be finite and positive, found: " + w);
|
||||
}
|
||||
if (!Double.isFinite(h) || h <= 0) {
|
||||
throw new IllegalArgumentException("Height must be finite and positive, found: " + h);
|
||||
}
|
||||
|
||||
parent.makeCurrent();
|
||||
ensureCurrentBufferBound();
|
||||
glEnable(GL_BLEND);
|
||||
|
||||
if (!textures.containsKey(image)) {
|
||||
uploadImage(image);
|
||||
}
|
||||
int textureId = textures.get(image);
|
||||
|
||||
// === 1. Upload Quad Geometry to GPU ===
|
||||
FloatBuffer quadVertices = memAllocFloat(16); // 4 vertices × 4 values (x,y,u,v)
|
||||
// Vertex format: x, y, u, v
|
||||
|
||||
quadVertices
|
||||
.put((float) x).put((float) y).put(0f).put(0f) // TL
|
||||
.put((float) x).put((float) (y + h)).put(0f).put(1f) // BL
|
||||
.put((float) (x + w)).put((float) (y + h)).put(1f).put(1f) // BR
|
||||
.put((float) (x + w)).put((float) y).put(1f).put(0f) // TR
|
||||
.flip();
|
||||
|
||||
int vbo = glGenBuffers();
|
||||
glBindBuffer(GL_ARRAY_BUFFER, vbo);
|
||||
glBufferData(GL_ARRAY_BUFFER, quadVertices, GL_DYNAMIC_DRAW);
|
||||
|
||||
// === 2. Bind Texture ===
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, textureId);
|
||||
|
||||
// === 3. Use Image Shader Program ===
|
||||
imageShader.use();
|
||||
|
||||
// === 4. Set Up Vertex Attributes ===
|
||||
glEnableVertexAttribArray(0); // Position (x,y)
|
||||
glEnableVertexAttribArray(1); // TexCoord (u,v)
|
||||
glVertexAttribPointer(0, 2, GL_FLOAT, false, 4 * Float.BYTES, 0);
|
||||
glVertexAttribPointer(1, 2, GL_FLOAT, false, 4 * Float.BYTES, 2 * Float.BYTES);
|
||||
|
||||
// === 5. Set Uniforms ===
|
||||
Matrix4f modelViewProj = buildOrthoMatrix().mul(buildTransformMatrix());
|
||||
imageShader
|
||||
.setUniform("u_ModelViewProj", modelViewProj)
|
||||
.setUniform("u_Texture", 0); // sampler2D bound to unit 0
|
||||
|
||||
// Apply alpha and blend mode
|
||||
float alphaMult = byteToFloat(currentState.getAlpha());
|
||||
imageShader.setUniform("u_Alpha", alphaMult);
|
||||
applyBlendFunc();
|
||||
|
||||
// Pass graphic effects
|
||||
GraphicEffectMap effects = currentState.getEffects();
|
||||
imageShader
|
||||
.setUniform("u_HueShift", (float) effects.getDouble(GraphicEffect.HUE_SHIFT))
|
||||
.setUniform("u_Bulge", (float) effects.getDouble(GraphicEffect.BULGE)) // bulge coefficient
|
||||
.setUniform("u_Whirl", (float) effects.getDouble(GraphicEffect.WHIRL)) // whirl coefficient: 0 - none, negative - whirl clockwise, positive - counter-clockwise
|
||||
.setUniform("u_SkewX", (float) effects.getDouble(GraphicEffect.SKEW_X)) // skew angle: 0 - none, negative - left, positive - right
|
||||
.setUniform("u_SkewY", (float) effects.getDouble(GraphicEffect.SKEW_Y)) // skew angle: 0 - none, negative - left, positive - right
|
||||
.setUniform("u_Mosaic", (float) effects.getDouble(GraphicEffect.MOSAIC))
|
||||
.setUniform("u_Brightness", (float) effects.getDouble(GraphicEffect.BRIGHTNESS) / 100f)
|
||||
.setUniform("u_Opacity", (float) effects.getDouble(GraphicEffect.OPACITY) / 100f)
|
||||
.setUniform("u_Pixelate", (float) effects.getDouble(GraphicEffect.PIXELATION));
|
||||
|
||||
// === 6. Draw Quad ===
|
||||
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
|
||||
|
||||
// === 7. Cleanup ===
|
||||
glDisable(GL_BLEND);
|
||||
glDisableVertexAttribArray(0);
|
||||
glDisableVertexAttribArray(1);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, 0);
|
||||
glDeleteBuffers(vbo);
|
||||
imageShader.unuse(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public RenderCanvas createSubCanvas(double width, double height) {
|
||||
Point2D dim = getDimensions();
|
||||
if (width > dim.x() || height > dim.y()) {
|
||||
throw new IllegalArgumentException("Width and height of a sub-canvas can't be greater than the original");
|
||||
}
|
||||
GLSubCanvas renderCanvas = new GLSubCanvas(parent, autoLoadImages);
|
||||
renderCanvas.attachTarget(new GLFramebuffer((int) width, (int) height));
|
||||
renderCanvas.clear();
|
||||
return renderCanvas;
|
||||
}
|
||||
|
||||
// Current state management
|
||||
|
||||
@Override
|
||||
public void translate(double dx, double dy) {
|
||||
currentState.translate(dx, dy);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void rotate(double degrees) {
|
||||
currentState.rotate(degrees);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void scale(double sx, double sy) {
|
||||
currentState.scale(sx, sy);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setFillARGB(int argb) {
|
||||
currentState.setFillARGB(argb);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setStrokeARGB(int argb) {
|
||||
currentState.setStrokeARGB(argb);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLineWidth(double width) {
|
||||
currentState.setLineWidth(width);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAlpha(byte alpha) {
|
||||
currentState.setAlpha(alpha);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBlendMode(BlendMode mode) {
|
||||
currentState.setBlendMode(mode);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setEffects(GraphicEffectMap effects) {
|
||||
currentState.setEffects(effects);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clip(Shape shape) {
|
||||
currentState.setClip(shape);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resetClip() {
|
||||
currentState.setClip(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save() {
|
||||
stateStack.push(currentState.copy());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void restore() {
|
||||
if (!stateStack.isEmpty()) {
|
||||
currentState = stateStack.pop();
|
||||
}
|
||||
}
|
||||
|
||||
private static final GraphicEffectMap EMPTY = new GraphicEffectMap();
|
||||
|
||||
@Override
|
||||
public void setIdentity() {
|
||||
currentState.setTranslateX(0);
|
||||
currentState.setTranslateY(0);
|
||||
currentState.setRotationDegrees(0);
|
||||
currentState.setScaleX(1);
|
||||
currentState.setScaleY(1);
|
||||
currentState.setFillARGB(0xFF_00_00_00);
|
||||
currentState.setStrokeARGB(0xFF_00_00_00);
|
||||
currentState.setLineWidth(1);
|
||||
currentState.setAlpha((byte) 255);
|
||||
currentState.setBlendMode(BlendMode.ADD);
|
||||
currentState.setEffects(EMPTY);
|
||||
currentState.setClip(null);
|
||||
}
|
||||
|
||||
// Other
|
||||
|
||||
@Override
|
||||
public Point2D getDimensions() {
|
||||
ensureOpen();
|
||||
if (fb == null) {
|
||||
throw new IllegalStateException("No buffer attached");
|
||||
}
|
||||
return fb.getDimensions();
|
||||
}
|
||||
|
||||
@Override
|
||||
public OpenGLContext getContext() {
|
||||
return parent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!closed) {
|
||||
textures.values().forEach(GL46::glDeleteTextures);
|
||||
textures.clear();
|
||||
strokeShader.close();
|
||||
fillShader.close();
|
||||
if (fb != null) {
|
||||
fb.close();
|
||||
fb = null;
|
||||
}
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
// </editor-fold>
|
||||
|
||||
// Private implementation
|
||||
|
||||
private void applyBlendFunc() {
|
||||
switch (currentState.getBlendMode()) {
|
||||
case ADD -> {
|
||||
// sum all components
|
||||
glBlendFunc(GL_ONE, GL_ONE);
|
||||
glBlendEquation(GL_FUNC_ADD);
|
||||
}
|
||||
case BLEND_SUBTRACT -> {
|
||||
// Subtract all components
|
||||
glBlendFunc(GL_ONE, GL_ONE);
|
||||
glBlendEquation(GL_FUNC_REVERSE_SUBTRACT); // reversed addition - subtraction
|
||||
}
|
||||
case RGB_SUBTRACT -> {
|
||||
// Subtract RGB components, sum alpha components
|
||||
glBlendFunc(GL_ONE, GL_ONE);
|
||||
glBlendEquationSeparate(GL_FUNC_REVERSE_SUBTRACT, GL_FUNC_ADD); // reverse only RGB components
|
||||
}
|
||||
case BLEND_MULTIPLY -> {
|
||||
// multiply all components
|
||||
glBlendFunc(GL_DST_COLOR, GL_ZERO);
|
||||
glBlendEquation(GL_FUNC_ADD);
|
||||
}
|
||||
case RGB_MULTIPLY -> {
|
||||
// multiply RGB components, sum alpha components
|
||||
glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_ONE, GL_ONE);
|
||||
glBlendEquation(GL_FUNC_ADD);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private FloatList shapeToVertices(Shape shape) {
|
||||
Area area = shape instanceof Area a ? a : new Area(shape);
|
||||
PathIterator itr = area.getPathIterator(null);
|
||||
double[] coords = new double[6];
|
||||
FloatList vertices = new FloatArrayList();
|
||||
|
||||
double startX = 0, startY = 0;
|
||||
boolean isMoveTo = true;
|
||||
|
||||
while (!itr.isDone()) {
|
||||
int type = itr.currentSegment(coords);
|
||||
switch (type) {
|
||||
case PathIterator.SEG_MOVETO:
|
||||
if (!isMoveTo) {
|
||||
// Close previous subpath by connecting to start point
|
||||
vertices.add((float) startX);
|
||||
vertices.add((float) startY);
|
||||
}
|
||||
startX = coords[0];
|
||||
startY = coords[1];
|
||||
isMoveTo = false;
|
||||
break;
|
||||
|
||||
case PathIterator.SEG_LINETO:
|
||||
if (isMoveTo) break; // Skip degenerate segments
|
||||
vertices.add((float) coords[0]);
|
||||
vertices.add((float) coords[1]);
|
||||
break;
|
||||
|
||||
case PathIterator.SEG_CLOSE:
|
||||
if (!isMoveTo) {
|
||||
vertices.add((float) startX);
|
||||
vertices.add((float) startY);
|
||||
}
|
||||
isMoveTo = true; // Triggers new MOVETO on next SEG_MOVETO
|
||||
break;
|
||||
}
|
||||
itr.next();
|
||||
}
|
||||
|
||||
return vertices;
|
||||
}
|
||||
|
||||
/**
|
||||
* Like {@link #shapeToVertices(Shape)}, but, at the end, closes the path if unclosed. This ensures
|
||||
* a closed fill area.
|
||||
*/
|
||||
private FloatList shapeToFillVertices(Shape shape) {
|
||||
Area area = shape instanceof Area a ? a : new Area(shape);
|
||||
PathIterator itr = area.getPathIterator(null, 0.2); // Flatness controls curve accuracy
|
||||
double[] coords = new double[6];
|
||||
FloatList vertices = new FloatArrayList();
|
||||
|
||||
double startX = 0, startY = 0;
|
||||
boolean isMoveTo = true;
|
||||
|
||||
while (!itr.isDone()) {
|
||||
int type = itr.currentSegment(coords);
|
||||
switch (type) {
|
||||
case PathIterator.SEG_MOVETO:
|
||||
if (!isMoveTo) {
|
||||
// Close previous contour
|
||||
vertices.add((float) startX);
|
||||
vertices.add((float) startY);
|
||||
}
|
||||
startX = coords[0];
|
||||
startY = coords[1];
|
||||
isMoveTo = false;
|
||||
break;
|
||||
|
||||
case PathIterator.SEG_LINETO:
|
||||
if (isMoveTo) break;
|
||||
vertices.add((float) coords[0]);
|
||||
vertices.add((float) coords[1]);
|
||||
break;
|
||||
|
||||
case PathIterator.SEG_CLOSE:
|
||||
if (!isMoveTo) {
|
||||
vertices.add((float) startX);
|
||||
vertices.add((float) startY);
|
||||
}
|
||||
isMoveTo = true;
|
||||
break;
|
||||
}
|
||||
itr.next();
|
||||
}
|
||||
|
||||
// Close final contour if open
|
||||
if (!isMoveTo) {
|
||||
vertices.add((float) startX);
|
||||
vertices.add((float) startY);
|
||||
}
|
||||
|
||||
return vertices;
|
||||
}
|
||||
|
||||
private int uploadAndBindVertices(FloatCollection vertices) {
|
||||
FloatBuffer vertexData = memAllocFloat(vertices.size());
|
||||
vertices.forEach(vertexData::put);
|
||||
vertexData.flip();
|
||||
|
||||
int vbo = glGenBuffers();
|
||||
glBindBuffer(GL_ARRAY_BUFFER, vbo);
|
||||
glBufferData(GL_ARRAY_BUFFER, vertexData, GL_DYNAMIC_DRAW);
|
||||
|
||||
return vbo;
|
||||
}
|
||||
|
||||
private Matrix4f buildOrthoMatrix() {
|
||||
int w = fb.width(), h = fb.height();
|
||||
return new Matrix4f().setOrtho(0, w, h, 0, -1, 1); // Y-down to match Java2D
|
||||
}
|
||||
|
||||
protected void ensureCurrentBufferBound() {
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, fb.fboId());
|
||||
}
|
||||
|
||||
// Helper: Build transform from GraphicsState
|
||||
private Matrix4f buildTransformMatrix() {
|
||||
Matrix4f translate = new Matrix4f().translation((float) currentState.getTranslateX(), (float) currentState.getTranslateY(), 0);
|
||||
Matrix4f rotate = new Matrix4f().rotationZ((float) Math.toRadians(-currentState.getRotationDegrees())); // Clockwise → negative angle
|
||||
Matrix4f scale = new Matrix4f().scaling((float) currentState.getScaleX(), (float) currentState.getScaleY(), 1);
|
||||
return new Matrix4f().mul(translate).mul(rotate).mul(scale);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a color component from unsigned byte (0 - 255) to float (0.0 - 1.0).
|
||||
*
|
||||
* @param b the color component
|
||||
*/
|
||||
private static float byteToFloat(byte b) {
|
||||
return Byte.toUnsignedInt(b) / 255f;
|
||||
}
|
||||
|
||||
protected void ensureOpen() {
|
||||
if (closed) {
|
||||
throw new IllegalStateException("This canvas is closed");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl.gl;
|
||||
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import ru.fokinatorr.sparkle.graphics.PixelReader;
|
||||
import ru.fokinatorr.sparkle.graphics.image.Image;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.IntBuffer;
|
||||
import java.util.Set;
|
||||
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
import ru.fokinatorr.sparkle.graphics.impl.IntBufferPixelAccessor;
|
||||
import ru.fokinatorr.sparkle.util.BufferUtils;
|
||||
|
||||
import static lombok.AccessLevel.PRIVATE;
|
||||
import static org.lwjgl.opengl.GL46.*;
|
||||
|
||||
/**
|
||||
* An OpenGL sub-canvas.
|
||||
*/
|
||||
@Slf4j
|
||||
public class GLSubCanvas extends GLRenderCanvas {
|
||||
public GLSubCanvas(OpenGLContext parent, Set<Image> autoLoadImages) {
|
||||
super(parent, autoLoadImages);
|
||||
}
|
||||
|
||||
private LoadedImage finalImage;
|
||||
|
||||
@Override
|
||||
public Image getFinalImage() {
|
||||
ensureOpen();
|
||||
if (finalImage == null) {
|
||||
flush();
|
||||
|
||||
int width = fb.width();
|
||||
int height = fb.height();
|
||||
|
||||
ByteBuffer pixels = MemoryUtil.memAlloc(width * height * Integer.BYTES);
|
||||
parent.makeCurrent();
|
||||
|
||||
glBindFramebuffer(GL_READ_FRAMEBUFFER, fb.fboId());
|
||||
glReadBuffer(GL_COLOR_ATTACHMENT0);
|
||||
|
||||
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
|
||||
pixels.rewind();
|
||||
|
||||
flipVertically(pixels, width, height);
|
||||
while (pixels.hasRemaining()) {
|
||||
int pos = pixels.position();
|
||||
byte
|
||||
r = pixels.get(),
|
||||
g = pixels.get(),
|
||||
b = pixels.get(),
|
||||
a = pixels.get();
|
||||
pixels.position(pos)
|
||||
.put(a)
|
||||
.put(r)
|
||||
.put(g)
|
||||
.put(b);
|
||||
}
|
||||
finalImage = new LoadedImage(pixels, width, height);
|
||||
}
|
||||
return finalImage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flips the image vertically, so that the origin is in the top-left corner for images
|
||||
* retrieved from GL.
|
||||
*
|
||||
* @param buffer the pixel data
|
||||
* @param width row width
|
||||
* @param height row count
|
||||
*/
|
||||
private static void flipVertically(ByteBuffer buffer, int width, int height) {
|
||||
int rowSize = width * Integer.BYTES;
|
||||
ByteBuffer tempRow = MemoryUtil.memAlloc(rowSize);
|
||||
|
||||
try (var _ = BufferUtils.freeing(tempRow)) {
|
||||
for (int y = 0; y < height / 2; y++) {
|
||||
int topRowStart = y * rowSize;
|
||||
int bottomRowStart = (height - y - 1) * rowSize;
|
||||
|
||||
buffer.position(topRowStart);
|
||||
tempRow.clear();
|
||||
tempRow.put(buffer.slice().limit(rowSize));
|
||||
|
||||
buffer.position(topRowStart);
|
||||
buffer.limit(bottomRowStart + rowSize);
|
||||
buffer.put(buffer.slice());
|
||||
|
||||
buffer.position(bottomRowStart);
|
||||
tempRow.flip();
|
||||
buffer.put(tempRow);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!closed) {
|
||||
finalImage.close();
|
||||
finalImage = null;
|
||||
super.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A loaded and always prepared image.
|
||||
*/
|
||||
@FieldDefaults(level = PRIVATE)
|
||||
static class LoadedImage implements Image {
|
||||
final ByteBuffer pixels;
|
||||
final IntBuffer img;
|
||||
final int width;
|
||||
final int height;
|
||||
boolean closed;
|
||||
|
||||
public LoadedImage(ByteBuffer pixels, int width, int height) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.pixels = pixels;
|
||||
img = MemoryUtil.memIntBuffer(MemoryUtil.memAddress(pixels.rewind()), pixels.capacity() / 4);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void prepare() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isReady() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PixelReader createPixelReader() {
|
||||
ensureOpen();
|
||||
return new IntBufferPixelAccessor(width, height, img, this::ensureOpen);
|
||||
}
|
||||
|
||||
private void ensureOpen() {
|
||||
if (closed) {
|
||||
throw new IllegalStateException("This image is closed");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!closed) {
|
||||
MemoryUtil.memFree(pixels);
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl.gl;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.lwjgl.opengl.GL;
|
||||
import ru.fokinatorr.sparkle.context.AppContext;
|
||||
import ru.fokinatorr.sparkle.graphics.GraphicsManager;
|
||||
import ru.fokinatorr.sparkle.graphics.image.Image;
|
||||
import ru.fokinatorr.sparkle.graphics.impl.AbstractRenderingContext;
|
||||
import ru.fokinatorr.sparkle.graphics.impl.gl.surface.GL_GLFWWindowSurface;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import static lombok.AccessLevel.PRIVATE;
|
||||
import static org.lwjgl.glfw.GLFW.*;
|
||||
import static org.lwjgl.opengl.GL11.*;
|
||||
|
||||
/**
|
||||
* An OpenGL rendering context bound to a GLFW window.
|
||||
* <p>
|
||||
* This context uses the GLFW window's OpenGL context for rendering.
|
||||
*/
|
||||
@Slf4j
|
||||
@FieldDefaults(makeFinal = true, level = PRIVATE)
|
||||
public class OpenGLContext extends AbstractRenderingContext {
|
||||
@Getter
|
||||
final long glfwWindow; // pointer
|
||||
@Getter
|
||||
final GLRenderCanvas canvas; // TODO implement & create!
|
||||
|
||||
public OpenGLContext(AppContext context, GL_GLFWWindowSurface surface, Stage stage, Set<Image> autoLoadImages, GraphicsManager parent) {
|
||||
super(context, surface, stage, parent);
|
||||
this.glfwWindow = surface.getGlfwWindow();
|
||||
makeCurrent();
|
||||
if (!GL.getCapabilities().OpenGL46) {
|
||||
throw new IllegalStateException("OpenGL 4.6 required but not supported");
|
||||
}
|
||||
log.info("Initialized OpenGL context version {}", glGetString(GL_VERSION));
|
||||
log.info("\tGL Renderer: {}", glGetString(GL_RENDERER));
|
||||
log.info("\tGL Vendor: {}", glGetString(GL_VENDOR));
|
||||
|
||||
this.canvas = new GLRenderCanvas(this, autoLoadImages);
|
||||
}
|
||||
|
||||
public void makeCurrent() {
|
||||
glfwMakeContextCurrent(glfwWindow);
|
||||
try {
|
||||
if (GL.getCapabilities() == null) {
|
||||
GL.createCapabilities();
|
||||
}
|
||||
} catch (IllegalStateException _) { // thrown when no capabilities were created yet
|
||||
GL.createCapabilities(); // sets automatically
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doClose() {
|
||||
canvas.close();
|
||||
// GL context destroyed by the surface
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean renderControlBar() {
|
||||
return !getSurface().isTranslucent();
|
||||
}
|
||||
|
||||
@Override
|
||||
public GL_GLFWWindowSurface getSurface() {
|
||||
return (GL_GLFWWindowSurface) super.getSurface();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl.gl;
|
||||
|
||||
import lombok.experimental.UtilityClass;
|
||||
import ru.fokinatorr.sparkle.util.Constants;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Loads shader files, replacing snippet placeholders with actual snippets.
|
||||
*/
|
||||
@UtilityClass
|
||||
public class ShaderLoader {
|
||||
|
||||
private static final Map<String, String> SNIPPETS;
|
||||
private static final Map<Path, String> SHADERS = new HashMap<>();
|
||||
|
||||
private static final Path SHADERS_DIR;
|
||||
private static final Path SNIPPETS_DIR;
|
||||
|
||||
/**
|
||||
* Loads a GLSL file at the given location.
|
||||
* @param loc the location of the shader file in <tt>/resources/shaders</tt>
|
||||
* @return the shader's code
|
||||
* @throws RuntimeException if loading fails
|
||||
*/
|
||||
public static String loadShader(String loc) {
|
||||
return SHADERS.computeIfAbsent(SHADERS_DIR.resolve(loc), shaderFile -> {
|
||||
try {
|
||||
String sourceCode = Files.readString(shaderFile);
|
||||
for (var entry : SNIPPETS.entrySet()) {
|
||||
sourceCode = sourceCode.replace(entry.getKey(), entry.getValue());
|
||||
}
|
||||
return sourceCode;
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to read shader '" + loc + "'", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static {
|
||||
SHADERS_DIR = Constants.ROOT.resolve("shaders");
|
||||
SNIPPETS_DIR = SHADERS_DIR.resolve("snippets");
|
||||
|
||||
Map<String, String> snippetMap = new HashMap<>();
|
||||
try (Stream<Path> snippets = Files.list(SNIPPETS_DIR)) {
|
||||
snippets.forEach(snippet -> {
|
||||
String name = snippet.getFileName().toString();
|
||||
int lastIndexOfDot = name.lastIndexOf(".");
|
||||
if (lastIndexOfDot >= 0) {
|
||||
name = name.substring(0, lastIndexOfDot);
|
||||
}
|
||||
snippetMap.put("{{" + name + "}}", loadSnippet(snippet));
|
||||
});
|
||||
} catch (IOException e) {
|
||||
throw new ExceptionInInitializerError(e);
|
||||
}
|
||||
|
||||
SNIPPETS = Collections.unmodifiableMap(snippetMap);
|
||||
}
|
||||
|
||||
private static String loadSnippet(Path path) {
|
||||
try {
|
||||
return Files.readString(path);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to read snippet '" + path.getFileName() + "'", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl.gl.shader;
|
||||
|
||||
import it.unimi.dsi.fastutil.ints.Int2IntMap;
|
||||
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
import lombok.Getter;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import org.joml.Matrix4f;
|
||||
import org.lwjgl.opengl.GL20;
|
||||
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
|
||||
|
||||
import java.nio.FloatBuffer;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
import static lombok.AccessLevel.PRIVATE;
|
||||
import static org.lwjgl.opengl.GL46.*;
|
||||
import static org.lwjgl.system.MemoryStack.stackPush;
|
||||
|
||||
/**
|
||||
* An OpenGL shader program wrapper. Not thread-safe.
|
||||
*/
|
||||
@SuppressWarnings("UnusedReturnValue")
|
||||
@FieldDefaults(level = PRIVATE)
|
||||
@Getter
|
||||
public class GLShaderProgram implements NonThrowingAutoCloseable {
|
||||
final int programId;
|
||||
final Int2IntMap uniformLocationsCache = new Int2IntOpenHashMap();
|
||||
|
||||
boolean closed;
|
||||
|
||||
// Factory methods
|
||||
|
||||
/**
|
||||
* Creates a {@code GLShaderProgram} from an initialized shader program.
|
||||
*
|
||||
* @param programId the program ID
|
||||
* @throws IllegalArgumentException if program ID is invalid
|
||||
*/
|
||||
public GLShaderProgram(int programId) {
|
||||
if (!glIsProgram(programId)) {
|
||||
throw new IllegalArgumentException("Invalid program ID: 0x" + Integer.toHexString(programId).toUpperCase());
|
||||
}
|
||||
this.programId = programId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiles the given GLSL sources into a new shader program.
|
||||
*
|
||||
* @param shadersGLSL the shader sources
|
||||
* @return a new {@code GLShaderProgram} of compiled shaders
|
||||
* @throws ShaderCompileException if compilation of any source fails
|
||||
* @throws ShaderProgramLinkException if program linkage fails
|
||||
* @throws NullPointerException if any key or value in map is {@code null}
|
||||
*/
|
||||
public static GLShaderProgram compile(Map<? extends ShaderType, ? extends CharSequence> shadersGLSL) {
|
||||
IntList shaders = new IntArrayList(shadersGLSL.size());
|
||||
for (var entry : shadersGLSL.entrySet()) {
|
||||
ShaderType type = Objects.requireNonNull(entry.getKey(), "One of keys in map is null");
|
||||
String code = Objects.requireNonNull(entry.getValue(), "One of values in map is null").toString();
|
||||
int shader = glCreateShader(type.getGlEnum());
|
||||
glShaderSource(shader, code);
|
||||
glCompileShader(shader);
|
||||
checkCompiled(shader, type.getName(), code);
|
||||
shaders.add(shader);
|
||||
}
|
||||
GLShaderProgram result = ofCompiled(shaders);
|
||||
shaders.forEach(GL20::glDeleteShader);
|
||||
shaders.clear();
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a shader program from already-compiled shaders.
|
||||
* <p><i>This method does not delete the shaders after linking; do so manually if they won't be used again.</i>
|
||||
*
|
||||
* @param shaderIDs the shader IDs
|
||||
* @throws IllegalArgumentException if any shader ID is invalid
|
||||
* @throws ShaderProgramLinkException if program linkage fails
|
||||
*/
|
||||
public static GLShaderProgram ofCompiled(IntList shaderIDs) {
|
||||
int program = glCreateProgram();
|
||||
shaderIDs.forEach((int shader) -> {
|
||||
if (!glIsShader(shader)) {
|
||||
glDeleteProgram(program);
|
||||
throw new IllegalArgumentException("Invalid shader ID: 0x" + Integer.toHexString(shader).toUpperCase());
|
||||
}
|
||||
glAttachShader(program, shader);
|
||||
});
|
||||
glLinkProgram(program);
|
||||
checkLinked(program);
|
||||
shaderIDs.forEach((int shader) -> glDetachShader(program, shader));
|
||||
|
||||
return new GLShaderProgram(program);
|
||||
}
|
||||
|
||||
// Public API
|
||||
|
||||
/**
|
||||
* Starts using this program in current context.
|
||||
*
|
||||
* @throws IllegalStateException if this program is closed
|
||||
*/
|
||||
public void use() {
|
||||
ensureOpen();
|
||||
glUseProgram(programId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops using this program in current context.
|
||||
*
|
||||
* @param onlyIfCurrent if {@code true}, will only stop usage when this program is currently active
|
||||
* @throws IllegalStateException if {@code onlyIfCurrent == true} and this program is closed
|
||||
*/
|
||||
public void unuse(boolean onlyIfCurrent) {
|
||||
if (onlyIfCurrent) {
|
||||
ensureOpen();
|
||||
int[] currentProgram = {0};
|
||||
glGetIntegerv(GL_CURRENT_PROGRAM, currentProgram);
|
||||
if (currentProgram[0] == programId) {
|
||||
glUseProgram(0);
|
||||
}
|
||||
} else {
|
||||
glUseProgram(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates uniform variable for this program with the specified integer value.
|
||||
* @param name the variable name
|
||||
* @param value the value
|
||||
* @return this program
|
||||
*/
|
||||
public GLShaderProgram setUniform(String name, int value) {
|
||||
int loc = getUniformLocation(name);
|
||||
if (loc != -1) glUniform1i(loc, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates uniform variable for this program with the specified floating-point value.
|
||||
* @param name the variable name
|
||||
* @param value the value
|
||||
* @return this program
|
||||
*/
|
||||
public GLShaderProgram setUniform(String name, float value) {
|
||||
int loc = getUniformLocation(name);
|
||||
if (loc != -1) glUniform1f(loc, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates uniform variable for this program with the specified floating-point 2D vector components.
|
||||
* @param name the variable name
|
||||
* @param x the first component
|
||||
* @param y the second component
|
||||
* @return this program
|
||||
*/
|
||||
public GLShaderProgram setUniform(String name, float x, float y) {
|
||||
int loc = getUniformLocation(name);
|
||||
if (loc != -1) glUniform2f(loc, x, y);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates uniform variable for this program with the specified floating-point 4D vector components.
|
||||
* @param name the variable name
|
||||
* @param x the first component
|
||||
* @param y the second component
|
||||
* @param z the third component
|
||||
* @param w the fourth component
|
||||
* @return this program
|
||||
*/
|
||||
public GLShaderProgram setUniform(String name, float x, float y, float z, float w) {
|
||||
int loc = getUniformLocation(name);
|
||||
if (loc != -1) glUniform4f(loc, x, y, z, w);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates uniform variable for this program with the specified 4x4 floating-point matrix.
|
||||
* @param name the variable name
|
||||
* @param matrix the matrix
|
||||
* @return this program
|
||||
*/
|
||||
public GLShaderProgram setUniform(String name, Matrix4f matrix) {
|
||||
int loc = getUniformLocation(name);
|
||||
if (loc != -1) {
|
||||
try (var stack = stackPush()) {
|
||||
FloatBuffer buf = stack.mallocFloat(16);
|
||||
matrix.get(buf);
|
||||
glUniformMatrix4fv(loc, false, buf);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc} After calling this method, the instance should no longer be used.
|
||||
* Idempotent: calling this method more than once has no effect.
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
if (!closed) {
|
||||
glDeleteProgram(programId);
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Private implementation
|
||||
|
||||
private void ensureOpen() {
|
||||
if (closed) {
|
||||
throw new IllegalStateException("This program is closed");
|
||||
}
|
||||
}
|
||||
|
||||
private int getUniformLocation(String name) {
|
||||
return uniformLocationsCache.computeIfAbsent(name.hashCode(), _ -> glGetUniformLocation(programId, name));
|
||||
}
|
||||
|
||||
private static void checkCompiled(int shader, String type, String code) {
|
||||
if (glGetShaderi(shader, GL_COMPILE_STATUS) == GL_FALSE) {
|
||||
throw new ShaderCompileException(
|
||||
type + " shader 0x" + Integer.toHexString(shader).toUpperCase() + " failed to compile",
|
||||
code,
|
||||
glGetShaderInfoLog(shader)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkLinked(int program) {
|
||||
if (glGetProgrami(program, GL_LINK_STATUS) == GL_FALSE) {
|
||||
int error = glGetError();
|
||||
if (error != GL_NO_ERROR) {
|
||||
throw new RuntimeException("OpenGL Error after link: 0x" + Integer.toHexString(error).toUpperCase());
|
||||
}
|
||||
|
||||
throw new ShaderProgramLinkException(
|
||||
"Program 0x" + Integer.toHexString(program).toUpperCase() + " failed to link",
|
||||
glGetProgramInfoLog(program)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl.gl.shader;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
|
||||
import static lombok.AccessLevel.PRIVATE;
|
||||
|
||||
/**
|
||||
* Thrown by {@link GLShaderProgram}'s factory methods when shader compilation fails.
|
||||
* <p>Includes the shader's code and error log.
|
||||
*/
|
||||
@FieldDefaults(makeFinal = true, level = PRIVATE)
|
||||
@Getter
|
||||
public class ShaderCompileException extends RuntimeException {
|
||||
String shaderCode;
|
||||
String errorLog;
|
||||
|
||||
/**
|
||||
* @param message the detail message
|
||||
* @param shaderCode the shader's source code, or {@code null} if unavailable
|
||||
* @param errorLog the compiler output, or {@code null} if unavailable
|
||||
*/
|
||||
public ShaderCompileException(String message, String shaderCode, String errorLog) {
|
||||
super(message);
|
||||
this.errorLog = errorLog;
|
||||
this.shaderCode = shaderCode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return super.getMessage()
|
||||
+ "\nError Log: " + (errorLog == null ? "<unavailable>" : "\n" + errorLog)
|
||||
+ "\nShader Code: " + (shaderCode == null ? "<unavailable>" : "\n" + shaderCode);
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl.gl.shader;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
|
||||
import static lombok.AccessLevel.PRIVATE;
|
||||
|
||||
/**
|
||||
* Thrown by {@link GLShaderProgram}'s factory methods when shader program linking fails.
|
||||
* <p>Includes the error log.
|
||||
*/
|
||||
@FieldDefaults(makeFinal = true, level = PRIVATE)
|
||||
@Getter
|
||||
public class ShaderProgramLinkException extends RuntimeException {
|
||||
String errorLog;
|
||||
|
||||
/**
|
||||
* @param message the detail message
|
||||
* @param errorLog the linker output, or {@code null} if unavailable
|
||||
*/
|
||||
public ShaderProgramLinkException(String message, String errorLog) {
|
||||
super(message);
|
||||
this.errorLog = errorLog;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return super.getMessage()
|
||||
+ "\nError Log: " + (errorLog == null ? "<unavailable>" : "\n" + errorLog);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl.gl.shader;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
|
||||
import static lombok.AccessLevel.PRIVATE;
|
||||
import static org.lwjgl.opengl.GL46.*;
|
||||
|
||||
/**
|
||||
* Represents a GL shader type.
|
||||
*/
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
@FieldDefaults(makeFinal = true, level = PRIVATE)
|
||||
public enum ShaderType {
|
||||
VERTEX(GL_VERTEX_SHADER, "Vertex"),
|
||||
FRAGMENT(GL_FRAGMENT_SHADER, "Fragment"),
|
||||
TESS_CTRL(GL_TESS_CONTROL_SHADER, "Tessellation control"),
|
||||
TESS_EVAL(GL_TESS_EVALUATION_SHADER, "Tessellation evaluation"),
|
||||
GEOMETRY(GL_GEOMETRY_SHADER, "Geometry"),
|
||||
COMPUTE(GL_COMPUTE_SHADER, "Compute");
|
||||
|
||||
/**
|
||||
* The OpenGL constant for this shader type.
|
||||
*/
|
||||
int glEnum;
|
||||
/**
|
||||
* User-friendly name of this shader type.
|
||||
*/
|
||||
String name;
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl.gl.surface;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import ru.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
|
||||
import ru.fokinatorr.sparkle.graphics.impl.gl.GLFramebuffer;
|
||||
import ru.fokinatorr.sparkle.graphics.impl.surface.AbstractGLFWWindowSurface;
|
||||
import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer;
|
||||
import ru.fokinatorr.sparkle.phys2d.Point2D;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
|
||||
import static org.lwjgl.glfw.GLFW.*;
|
||||
import static org.lwjgl.system.MemoryUtil.NULL;
|
||||
|
||||
/**
|
||||
* A GLFW window rendering surface, providing GL framebuffers.
|
||||
*/
|
||||
@Slf4j
|
||||
@FieldDefaults(level = AccessLevel.PRIVATE)
|
||||
public final class GL_GLFWWindowSurface extends AbstractGLFWWindowSurface {
|
||||
|
||||
/**
|
||||
* @throws NullPointerException if any argument is {@code null}
|
||||
*/
|
||||
GL_GLFWWindowSurface(long glfwWindow, EventDispatcher dispatcher, Stage stage, Thread graphicsThread) {
|
||||
super(glfwWindow, dispatcher, stage, graphicsThread);
|
||||
glfwMakeContextCurrent(glfwWindow);
|
||||
glfwSwapInterval(1);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new non-fullscreen window.
|
||||
*
|
||||
* @param title the window title
|
||||
* @param translucent whether the window must be translucent
|
||||
* @param dispatcher the event dispatcher to use for sending window events
|
||||
* @param stage the stage to use for sending window events
|
||||
* @param graphicsThread the thread on which all calls must be made
|
||||
* @return a new window surface
|
||||
*/
|
||||
public static GL_GLFWWindowSurface create(String title, boolean translucent,
|
||||
EventDispatcher dispatcher, Stage stage, Thread graphicsThread) {
|
||||
if (translucent) {
|
||||
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_TRUE);
|
||||
glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
|
||||
}
|
||||
GL_GLFWWindowSurface result = new GL_GLFWWindowSurface(
|
||||
glfwCreateWindow(stage.getWidth(), stage.getHeight(), title, NULL, NULL),
|
||||
dispatcher, stage, graphicsThread
|
||||
);
|
||||
if (translucent) {
|
||||
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_FALSE);
|
||||
glfwWindowHint(GLFW_DECORATED, GLFW_TRUE);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new fullscreen window.
|
||||
*
|
||||
* @param title the window title
|
||||
* @param translucent whether the window must be translucent
|
||||
* @param monitor the GLFW monitor on which the window should be fullscreen
|
||||
* @param dispatcher the event dispatcher to use for sending window events
|
||||
* @param stage the stage to use for sending window events
|
||||
* @param graphicsThread the thread on which all calls must be made
|
||||
* @return a new window surface
|
||||
*/
|
||||
public static GL_GLFWWindowSurface createFullscreen(String title, long monitor /*pointer*/, boolean translucent,
|
||||
EventDispatcher dispatcher, Stage stage, Thread graphicsThread) {
|
||||
if (translucent) {
|
||||
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_TRUE);
|
||||
glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
|
||||
}
|
||||
GL_GLFWWindowSurface result = new GL_GLFWWindowSurface(
|
||||
glfwCreateWindow(stage.getWidth(), stage.getHeight(), title, monitor, NULL),
|
||||
dispatcher, stage, graphicsThread
|
||||
);
|
||||
if (translucent) {
|
||||
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_FALSE);
|
||||
glfwWindowHint(GLFW_DECORATED, GLFW_TRUE);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Framebuffer acquireBuffer() {
|
||||
Point2D dim = getSize();
|
||||
return new GLFramebuffer(0, (int) dim.x(), (int) dim.y());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void present(Framebuffer frameBuffer) {
|
||||
if (!(frameBuffer instanceof GLFramebuffer fb)) {
|
||||
throw new IllegalArgumentException("Unsupported frame buffer type: " + frameBuffer.getClass());
|
||||
}
|
||||
if (fb.fboId() != 0) {
|
||||
throw new IllegalArgumentException("Can only render from the default framebuffer");
|
||||
}
|
||||
glfwSwapBuffers(glfwWindow);
|
||||
}
|
||||
}
|
||||
+377
@@ -0,0 +1,377 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl.surface;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.lwjgl.glfw.GLFWVidMode;
|
||||
import org.lwjgl.system.Callback;
|
||||
import ru.fokinatorr.sparkle.event.dispatcher.EventDispatcher;
|
||||
import ru.fokinatorr.sparkle.event.input.Key;
|
||||
import ru.fokinatorr.sparkle.event.input.KeyboardEvent;
|
||||
import ru.fokinatorr.sparkle.event.input.MouseButton;
|
||||
import ru.fokinatorr.sparkle.event.input.MouseEvent;
|
||||
import ru.fokinatorr.sparkle.graphics.render.surface.WindowSurface;
|
||||
import ru.fokinatorr.sparkle.phys2d.Point2D;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
import ru.fokinatorr.sparkle.util.concurrent.atomic.AtomicDouble;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import static org.lwjgl.glfw.GLFW.*;
|
||||
import static org.lwjgl.system.MemoryUtil.NULL;
|
||||
|
||||
/**
|
||||
* A GLFW window rendering surface, providing base GLFW functionality,
|
||||
* except framebuffer-related methods.
|
||||
*/
|
||||
@Slf4j
|
||||
@FieldDefaults(level = AccessLevel.PROTECTED)
|
||||
public abstract class AbstractGLFWWindowSurface implements WindowSurface {
|
||||
/**
|
||||
* The GLFW window pointer.
|
||||
*/
|
||||
@Getter
|
||||
final long glfwWindow; // pointer
|
||||
final List<ResizeListener> resizeCallback = new LinkedList<>();
|
||||
final List<Callback> callbacks = new LinkedList<>();
|
||||
final Thread graphicsThread;
|
||||
Callback resizeCB;
|
||||
int[] oldXYWH = null;
|
||||
boolean closed;
|
||||
|
||||
|
||||
/**
|
||||
* @throws NullPointerException if any argument is {@code null}
|
||||
*/
|
||||
protected AbstractGLFWWindowSurface(long glfwWindow, EventDispatcher dispatcher, Stage stage, Thread graphicsThread) {
|
||||
if (glfwWindow == NULL) {
|
||||
throw new NullPointerException("glfwWindow");
|
||||
}
|
||||
this.glfwWindow = glfwWindow;
|
||||
Objects.requireNonNull(dispatcher, "dispatcher");
|
||||
Objects.requireNonNull(stage, "stage");
|
||||
this.graphicsThread = Objects.requireNonNull(graphicsThread, "graphics thread");
|
||||
|
||||
// <editor-fold desc="-- Set callbacks --" defaultstate="collapsed">
|
||||
callbacks.add(glfwSetKeyCallback(glfwWindow, (_, keyCode, scancode, action, modifiers) -> {
|
||||
Key key = GLFWToPublicAPI.KEYS_MAP.get(keyCode);
|
||||
if (key != null) {
|
||||
switch (action) {
|
||||
case GLFW_PRESS -> {
|
||||
if (dispatcher.hasListenersFor(KeyboardEvent.KeyPressedEvent.class)) {
|
||||
dispatcher.fireEvent(new KeyboardEvent.KeyPressedEvent(stage, key, modifiers));
|
||||
}
|
||||
}
|
||||
case GLFW_RELEASE -> {
|
||||
if (dispatcher.hasListenersFor(KeyboardEvent.KeyReleasedEvent.class)) {
|
||||
dispatcher.fireEvent(new KeyboardEvent.KeyReleasedEvent(stage, key, modifiers));
|
||||
}
|
||||
}
|
||||
case GLFW_REPEAT -> {
|
||||
if (dispatcher.hasListenersFor(KeyboardEvent.KeyRepeatedEvent.class)) {
|
||||
dispatcher.fireEvent(new KeyboardEvent.KeyRepeatedEvent(stage, key, modifiers));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log.warn(
|
||||
"Unknown key with scancode {} {}",
|
||||
scancode,
|
||||
switch (action) {
|
||||
case GLFW_PRESS -> "pressed";
|
||||
case GLFW_RELEASE -> "released";
|
||||
case GLFW_REPEAT -> "repeated";
|
||||
default -> "<unknown action>";
|
||||
}
|
||||
);
|
||||
}
|
||||
}));
|
||||
|
||||
callbacks.add(glfwSetCharCallback(glfwWindow, (_, codePoint) -> {
|
||||
if (dispatcher.hasListenersFor(KeyboardEvent.CharInputEvent.class)) {
|
||||
dispatcher.fireEvent(new KeyboardEvent.CharInputEvent(stage, codePoint));
|
||||
}
|
||||
}));
|
||||
|
||||
AtomicLong lastMousePress = new AtomicLong(-1);
|
||||
callbacks.add(glfwSetMouseButtonCallback(glfwWindow, (_, buttonCode, action, _) -> {
|
||||
MouseButton button = GLFWToPublicAPI.MOUSE_BUTTONS_MAP.get(buttonCode);
|
||||
double[] realX = {0}, realY = {0};
|
||||
glfwGetCursorPos(glfwWindow, realX, realY);
|
||||
double x = realX[0] - stage.getWidth() / 2d;
|
||||
double y = realY[0] - stage.getHeight() / 2d;
|
||||
switch (action) {
|
||||
case GLFW_PRESS -> {
|
||||
lastMousePress.set(System.nanoTime());
|
||||
if (dispatcher.hasListenersFor(MouseEvent.MousePressedEvent.class)) {
|
||||
dispatcher.fireEvent(new MouseEvent.MousePressedEvent(button, stage, x, y));
|
||||
}
|
||||
}
|
||||
case GLFW_RELEASE -> {
|
||||
if (dispatcher.hasListenersFor(MouseEvent.MouseReleasedEvent.class)) {
|
||||
dispatcher.fireEvent(new MouseEvent.MouseReleasedEvent(button, stage, x, y));
|
||||
}
|
||||
if (lastMousePress.get() > 0) {
|
||||
long pressDurationNs = System.nanoTime() - lastMousePress.getAndSet(-1);
|
||||
if (dispatcher.hasListenersFor(MouseEvent.MouseClickedEvent.class)
|
||||
&& pressDurationNs <= 500_000_000L) { // TODO configurable?
|
||||
dispatcher.fireEvent(new MouseEvent.MouseClickedEvent(button, stage, x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
AtomicDouble lastMouseX = new AtomicDouble(-1);
|
||||
AtomicDouble lastMouseY = new AtomicDouble(-1);
|
||||
callbacks.add(glfwSetCursorPosCallback(glfwWindow, (_, newRealX, newRealY) -> {
|
||||
double oldRealX = lastMouseX.getAndSet(newRealX);
|
||||
double oldRealY = lastMouseY.getAndSet(newRealY);
|
||||
if (dispatcher.hasListenersFor(MouseEvent.MouseCursorMovedEvent.class) && oldRealX >= 0 && oldRealY >= 0) {
|
||||
double
|
||||
oldX = oldRealX - stage.getWidth() / 2d,
|
||||
oldY = oldRealY - stage.getWidth() / 2d,
|
||||
newX = newRealX - stage.getWidth() / 2d,
|
||||
newY = newRealY - stage.getWidth() / 2d;
|
||||
Set<MouseButton> pressedButtons = EnumSet.noneOf(MouseButton.class);
|
||||
for (int mb : GLFWToPublicAPI.MOUSE_BUTTONS_MAP.keySet()) {
|
||||
if (glfwGetMouseButton(glfwWindow, mb) == GLFW_PRESS) {
|
||||
pressedButtons.add(GLFWToPublicAPI.MOUSE_BUTTONS_MAP.get(mb));
|
||||
}
|
||||
}
|
||||
|
||||
dispatcher.fireEvent(new MouseEvent.MouseCursorMovedEvent(stage, oldX, oldY, newX, newY, pressedButtons));
|
||||
}
|
||||
}));
|
||||
|
||||
callbacks.add(glfwSetScrollCallback(glfwWindow, (_, dx, dy) -> {
|
||||
if (dispatcher.hasListenersFor(MouseEvent.MouseScrolledEvent.class)) {
|
||||
double[] realX = {0}, realY = {0};
|
||||
glfwGetCursorPos(glfwWindow, realX, realY);
|
||||
double x = realX[0] - stage.getWidth() / 2d;
|
||||
double y = realY[0] - stage.getHeight() / 2d;
|
||||
dispatcher.fireEvent(new MouseEvent.MouseScrolledEvent(stage, x, y, dx, dy));
|
||||
}
|
||||
}));
|
||||
// </editor-fold>
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getWidth() {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
int[] w = {0};
|
||||
glfwGetWindowSize(glfwWindow, w, null);
|
||||
return w[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHeight() {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
int[] h = {0};
|
||||
glfwGetWindowSize(glfwWindow, null, h);
|
||||
return h[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public Point2D getSize() {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
int[] w = {0}, h = {0};
|
||||
glfwGetWindowSize(glfwWindow, w, h);
|
||||
return new Point2D(w[0], h[0]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pollEvents() {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
glfwPollEvents();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldClose() {
|
||||
ensureOpen();
|
||||
// ensureOnCorrectThread();
|
||||
return glfwWindowShouldClose(glfwWindow);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResize(ResizeListener callback) {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
resizeCallback.add(callback);
|
||||
Callback newCB = glfwSetWindowSizeCallback(glfwWindow, (_, width, height) -> {
|
||||
for (var cb : resizeCallback) {
|
||||
cb.resized(this, width, height);
|
||||
}
|
||||
});
|
||||
if (resizeCB != null) resizeCB.free();
|
||||
resizeCB = newCB;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Feature> getFeatures() {
|
||||
return Collections.unmodifiableSet(EnumSet.of(
|
||||
Feature.RESIZABLE,
|
||||
Feature.MOVABLE,
|
||||
Feature.HIDEABLE,
|
||||
Feature.NAMEABLE,
|
||||
Feature.FULLSCREENABLE,
|
||||
Feature.TRANSLUCENT
|
||||
));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSize(int newWidth, int newHeight) {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
glfwSetWindowSize(glfwWindow, newWidth, newHeight);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getX() {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
int[] x = {0};
|
||||
glfwGetWindowPos(glfwWindow, x, null);
|
||||
return x[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getY() {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
int[] y = {0};
|
||||
glfwGetWindowPos(glfwWindow, null, y);
|
||||
return y[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public Point2D getPos() {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
int[] x = {0}, y = {0};
|
||||
glfwGetWindowPos(glfwWindow, x, y);
|
||||
return new Point2D(x[0], y[0]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPos(int newX, int newY) {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
glfwSetWindowPos(glfwWindow, newX, newY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHidden() {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
return glfwGetWindowAttrib(glfwWindow, GLFW_VISIBLE) == GLFW_TRUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void show() {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
glfwShowWindow(glfwWindow);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void hide() {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
glfwHideWindow(glfwWindow);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
return glfwGetWindowTitle(glfwWindow);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setName(String name) {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
glfwSetWindowTitle(glfwWindow, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isFullscreen() {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
return glfwGetWindowMonitor(glfwWindow) != NULL;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setFullscreen(boolean fullscreen) {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
GLFWVidMode vidMode = glfwGetVideoMode(glfwGetPrimaryMonitor());
|
||||
if (vidMode == null) {
|
||||
throw new IllegalStateException("GLFW error");
|
||||
}
|
||||
if (fullscreen) {
|
||||
Point2D pos = getPos(), dimensions = getSize();
|
||||
oldXYWH = new int[]{(int) pos.x(), (int) pos.y(), (int) dimensions.x(), (int) dimensions.y()};
|
||||
glfwSetWindowMonitor(
|
||||
glfwWindow,
|
||||
glfwGetPrimaryMonitor(),
|
||||
0, 0,
|
||||
vidMode.width(), vidMode.height(),
|
||||
vidMode.refreshRate()
|
||||
);
|
||||
} else {
|
||||
glfwSetWindowMonitor(
|
||||
glfwWindow,
|
||||
NULL,
|
||||
oldXYWH[0], oldXYWH[1],
|
||||
oldXYWH[2], oldXYWH[3],
|
||||
vidMode.refreshRate()
|
||||
);
|
||||
oldXYWH = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isTranslucent() {
|
||||
ensureOpen();
|
||||
ensureOnCorrectThread();
|
||||
return glfwGetWindowAttrib(glfwWindow, GLFW_TRANSPARENT_FRAMEBUFFER) == GLFW_TRUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!closed) {
|
||||
if (resizeCB != null) {
|
||||
resizeCB.free();
|
||||
resizeCB = null;
|
||||
}
|
||||
callbacks.forEach(callback -> {
|
||||
if (callback != null) {
|
||||
callback.free();
|
||||
}
|
||||
});
|
||||
callbacks.clear();
|
||||
glfwDestroyWindow(glfwWindow);
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
protected void ensureOpen() {
|
||||
if (closed) {
|
||||
throw new IllegalStateException("Window closed");
|
||||
}
|
||||
}
|
||||
|
||||
protected void ensureOnCorrectThread() {
|
||||
if (Thread.currentThread() != graphicsThread) {
|
||||
throw new IllegalCallerException("Called from incorrect thread; must call from " + graphicsThread);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package ru.fokinatorr.sparkle.graphics.impl.surface;
|
||||
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectMaps;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
|
||||
import lombok.experimental.UtilityClass;
|
||||
import ru.fokinatorr.sparkle.event.input.Key;
|
||||
import ru.fokinatorr.sparkle.event.input.MouseButton;
|
||||
|
||||
import static org.lwjgl.glfw.GLFW.*;
|
||||
|
||||
/**
|
||||
* Maps GLFW key & mouse button codes to public API enums.
|
||||
*
|
||||
* @see Key
|
||||
* @see MouseButton
|
||||
*/
|
||||
@UtilityClass
|
||||
public class GLFWToPublicAPI {
|
||||
|
||||
/**
|
||||
* GLFW key code -> {@link Key} instance
|
||||
*/
|
||||
public static final Int2ObjectMap<Key> KEYS_MAP;
|
||||
/**
|
||||
* GLFW mouse button code -> {@link MouseButton} instance
|
||||
*/
|
||||
public static final Int2ObjectMap<MouseButton> MOUSE_BUTTONS_MAP;
|
||||
|
||||
static {
|
||||
Int2ObjectMap<Key> k = new Int2ObjectOpenHashMap<>(Key.values().length);
|
||||
// Here goes hell. Wish there was a faster way of doing that...
|
||||
k.put(GLFW_KEY_SPACE, Key.SPACE); // %20 in URL
|
||||
k.put(GLFW_KEY_APOSTROPHE, Key.APOSTROPHE); // ' (" when shift down)
|
||||
k.put(GLFW_KEY_COMMA, Key.COMMA); // , (< with shift)
|
||||
k.put(GLFW_KEY_MINUS, Key.MINUS); // - (_ with shift)
|
||||
k.put(GLFW_KEY_PERIOD, Key.PERIOD); // . (>)
|
||||
k.put(GLFW_KEY_SLASH, Key.SLASH); // / (?)
|
||||
// digits
|
||||
k.put(GLFW_KEY_0, Key.KEY_0); // 0 or )
|
||||
k.put(GLFW_KEY_1, Key.KEY_1); // 1 or !
|
||||
k.put(GLFW_KEY_2, Key.KEY_2); // 2 or @
|
||||
k.put(GLFW_KEY_3, Key.KEY_3); // 3 or #
|
||||
k.put(GLFW_KEY_4, Key.KEY_4); // 4 or $
|
||||
k.put(GLFW_KEY_5, Key.KEY_5); // 5 or %
|
||||
k.put(GLFW_KEY_6, Key.KEY_6); // 6 or ^
|
||||
k.put(GLFW_KEY_7, Key.KEY_7); // 7 or &
|
||||
k.put(GLFW_KEY_8, Key.KEY_8); // 8 or *
|
||||
k.put(GLFW_KEY_9, Key.KEY_9); // 9 or (
|
||||
|
||||
k.put(GLFW_KEY_SEMICOLON, Key.SEMICOLON); // ; or :
|
||||
k.put(GLFW_KEY_EQUAL, Key.EQUALS); // = or +
|
||||
// alphabet lore
|
||||
k.put(GLFW_KEY_A, Key.A);
|
||||
k.put(GLFW_KEY_B, Key.B);
|
||||
k.put(GLFW_KEY_C, Key.C);
|
||||
k.put(GLFW_KEY_D, Key.D);
|
||||
k.put(GLFW_KEY_F, Key.F); // F, the villain, comes and kidnaps D
|
||||
k.put(GLFW_KEY_E, Key.E); // and also F kidnaps E
|
||||
k.put(GLFW_KEY_G, Key.G); // G is frustrated! He calls A, B and C to form a CAB and follow F
|
||||
k.put(GLFW_KEY_H, Key.H); // F hides behind H, G doesn't notice. F escapes
|
||||
k.put(GLFW_KEY_I, Key.I); // F stomps on I and uses it as a gun
|
||||
k.put(GLFW_KEY_J, Key.J); // "J" famous last words
|
||||
// G is looking for F... hears a sudden blast
|
||||
k.put(GLFW_KEY_K, Key.K); // K appears and laughs at J's sudden death. F uses K as wings
|
||||
// G arrives with his CAB. F points his gun at them. Who's going to save them?..
|
||||
// ...
|
||||
k.put(GLFW_KEY_L, Key.L); // L <transforms into a superhero character> He saved G and CAB from getting obliterated by F!
|
||||
k.put(GLFW_KEY_M, Key.M); // M also transforms and detaches K from F
|
||||
k.put(GLFW_KEY_N, Key.N); // N also transforms, tries to save I from F. F blows onto N's hair and N awkwardly runs away
|
||||
k.put(GLFW_KEY_O, Key.O); // Wheel! Oh no wait, it's O. He says "OOOOOOOOOOO" and transforms :P
|
||||
// F seems tired from these transformations
|
||||
k.put(GLFW_KEY_P, Key.P); // P transforms! L M N O P are all here! but wait F escaped :\
|
||||
k.put(GLFW_KEY_Q, Key.Q); // KYOOOOOOOOOOO
|
||||
// Hold up! Someone stole N's gem! He transforms back into his normal form. L and O look angrily at him
|
||||
// Meanwhile F, in his cave, where D, E, and I are chained to the walls, evilly smiles, looking at N's gem...
|
||||
k.put(GLFW_KEY_R, Key.R); // "A-a-ar?!" - says R before immediately getting kidnapped by F
|
||||
// L and O kick N because he lost his gem, then fly away. N lies on the ground, depressed. P cheers him up.
|
||||
// the CAB deforms back to letters; then M, A and P form a MAP. G takes it and sees F running towards S. They all
|
||||
// sit into the CAB and start chasing F. Meanwhile Q, being a slow snail, tries his best to catch-up...
|
||||
k.put(GLFW_KEY_S, Key.S); // "Essss-" says S before getting sucked by F like spaghetti ._.
|
||||
// L and O approach F faster than others, freeze F into place. But F uses N's gem to neutralize L and O by gluing them together >:)
|
||||
// For good measure F also steals L and O's gems...
|
||||
k.put(GLFW_KEY_T, Key.T); // <hammer shark noises> T appears and says "Tea!". F smashes T into the ground like a nail
|
||||
// G, P, N and M arrive on a CAB. M, A and P create a MAP again. G takes it, sees that F conjoined B and C with O's gem.
|
||||
// G was too late to realize F is right in front of him... then F froze G with L's gem...
|
||||
|
||||
// N, scared of F, hides behind G
|
||||
// M tried to defeat F using his powers... He transforms, jumps and... gets his gem unfairly stolen! F uses it to conjoin T, M and A.
|
||||
// P joins! She transforms and starts quickly knocking F onto the ground! But F uses M's gem to freeze her!
|
||||
// F starts looking for N. N is horrified. C notices that, starts crawling towards F. When he finally reaches him, he bites him.
|
||||
// F screams in pain, turns around and... literally rips C into pieces with his teeth. Everybody watches that in terror, unable to move,
|
||||
// everyone except N... who didn't move just because he was a coward...
|
||||
// ...
|
||||
// F finally flies away, leaving the letters with pain of C getting brutally murdered... G and N decided to take revenge.
|
||||
k.put(GLFW_KEY_U, Key.U); // They started looking for U to form a GUN and hunt F down.
|
||||
k.put(GLFW_KEY_V, Key.V); // V-v-v-vee! - says V. Suddenly, F appears; V starts shaking in fear...
|
||||
// G with a GUN notices F approaching V. He charges up the GUN and says "GG", then shoots F...
|
||||
// G, U and N come closer, then they notice that it wasn't F... it was P, bitten by F so that she looked like F...
|
||||
// G screams... "P, P, NO!!! DON'T LEAVE US! F, YOU WILL REGRET THIS!!" while F is watching them from above, evilly smiling,
|
||||
// then runs towards his cave...
|
||||
k.put(GLFW_KEY_W, Key.W); // N thinks how much of a coward he was... because of him, C and P were murdered by F, and he...
|
||||
// he was just hiding behind G the whole time, not even helping... coward... coward...
|
||||
// Suddenly, G wakes N up from his thoughts, pointing to F's cave. N decided to take revenge for P and C and drives towards the cave.
|
||||
k.put(GLFW_KEY_X, Key.X); // Meanwhile, F, running towards his cave, is stopped by X. X, with his power gem, starts replicating
|
||||
// and surrounded F with his clones. F, noticing that, drops all his stolen gems, knowing that X prefers fair fights. X also dropped
|
||||
// his gem, and the clones disappeared. X thought they're going to fight fairly, but F cheated... he bit X and stole his gem too...
|
||||
k.put(GLFW_KEY_Y, Key.Y); // Y sees X deceased, falls on her knees are screams "WHYYYYYYYYYY!!??"
|
||||
// Meanwhile, V, A, G, N, U and M entered F's cave, where his clones were everywhere, waiting for them to enter.
|
||||
// While everybody was walking, F's clones absorbed everyone except N. F only needed him now...
|
||||
// N noticed F dropped the gems and started picking them up. Then, he notices sawblades running towards him... he picks up
|
||||
// P's gem and started running away. Suddenly, the sawblades stopped. N couldn't go back anymore.
|
||||
// F used X's gem to point to some place. But N, blinded by a thirst for revenge, didn't understand F's sign... N used
|
||||
// all of his gems to create a powerful beam and shoot F with it. F, clearly shocked, was smashed against the wall, and died in agony...
|
||||
// N thought the villain is defeated, came to pick up X's gem, but then he noticed... Him, F and all the kidnapped letters formed
|
||||
// the word... FRIENDS. Something was clearly off, nobody understood what that meant... until Q finally came into the cave, very slowly.
|
||||
|
||||
// -- FLASHBACK... --
|
||||
// n, e, d, i, s, r and f, when they were children, were friends. once upon a time they peacefully played around. then o and l came,
|
||||
// clearly wanting to bully them. l used o to shoot into one of the letters... Everyone ran away except f and n, so l shoot o into n...
|
||||
// n fell onto the ground, while l and o were laughing. then f came to cheer n up. They used to be best friends...
|
||||
// f, wanting to avenge n, took a, r, and t to form a fart and make it look like l is farting. Everyone saw that and started laughing...
|
||||
// f and n were lying on the ground and laughing harder than anyone else. l and o became furious, they kicked f so hard he cried...
|
||||
// then l pushed f to other letters to form the word "frick"... o came and said "Look everybody, f is slurring!" Everybody's rage
|
||||
// turned against f. c bit him; j shot at his teeth and broke them; i, m, x, t, e and d also punched f, then f tripped against n
|
||||
// and fell over... n tried to help, but the letters stood behind him. n, seeing this, stood back and hid behind the letters...
|
||||
// f, seeing that even his best friend betrayed him, started intensely crying: "I hate every one of you!!!", running towards a cave,
|
||||
// planning to live there alone, isolated...
|
||||
// g and p weren't there. they never bullied f...
|
||||
// That's how F became a villain and L M N O P got superpowers. Villains are not born, they're made by people, by bullies...
|
||||
k.put(GLFW_KEY_Z, Key.Z); // And what about Z? Z always was with us. He is the planet. Watching everybody fight, unable to stop them...
|
||||
// end of alphabet lore...?
|
||||
// credits to Mike Salcedo (https://www.youtube.com/channel/UCZESvFbPmlmF9rnT4Ke1uKQ) for such an amazing and enlightening story.
|
||||
|
||||
k.put(GLFW_KEY_LEFT_BRACKET, Key.LEFT_SQUARE_BRACKET); // [ ({)
|
||||
k.put(GLFW_KEY_BACKSLASH, Key.BACKSLASH); // \ (|)
|
||||
k.put(GLFW_KEY_RIGHT_BRACKET, Key.RIGHT_SQUARE_BRACKET); // ] (})
|
||||
k.put(GLFW_KEY_GRAVE_ACCENT, Key.GRAVE_ACCENT); // ` (~)
|
||||
k.put(GLFW_KEY_ESCAPE, Key.ESCAPE);
|
||||
|
||||
// These two keys don't have a US keyboard mapping, and are rarely used
|
||||
k.put(GLFW_KEY_WORLD_1, Key.WORLD_1);
|
||||
k.put(GLFW_KEY_WORLD_2, Key.WORLD_2);
|
||||
|
||||
// purely functionality keys, no character representation
|
||||
k.put(GLFW_KEY_ENTER, Key.ENTER); // CR+LF on Windows/macOS, LF on Linux, CR on old macOS
|
||||
k.put(GLFW_KEY_TAB, Key.TAB); // exception: often inserts a tabulation character
|
||||
k.put(GLFW_KEY_BACKSPACE, Key.BACKSPACE); // erase left
|
||||
k.put(GLFW_KEY_INSERT, Key.INSERT); // switch between insert/overwrite character mode
|
||||
k.put(GLFW_KEY_DELETE, Key.DELETE); // erase right
|
||||
|
||||
// arrow keys
|
||||
k.put(GLFW_KEY_RIGHT, Key.RIGHT);
|
||||
k.put(GLFW_KEY_LEFT, Key.LEFT);
|
||||
k.put(GLFW_KEY_DOWN, Key.DOWN);
|
||||
k.put(GLFW_KEY_UP, Key.UP);
|
||||
|
||||
// navigation keys (similar to arrow keys, but go farther)
|
||||
k.put(GLFW_KEY_PAGE_UP, Key.PAGE_UP); // one segment up
|
||||
k.put(GLFW_KEY_PAGE_DOWN, Key.PAGE_DOWN); // one segment down
|
||||
k.put(GLFW_KEY_HOME, Key.HOME); // all the way left
|
||||
k.put(GLFW_KEY_END, Key.END); // all the way right
|
||||
|
||||
// lock keys
|
||||
k.put(GLFW_KEY_CAPS_LOCK, Key.CAPS_LOCK); // If enabled, capitalization of letters is reversed
|
||||
k.put(GLFW_KEY_SCROLL_LOCK, Key.SCROLL_LOCK); // Used to make arrow keys scroll the page instead of moving cursor; mostly not used nowadays
|
||||
k.put(GLFW_KEY_NUM_LOCK, Key.NUM_LOCK); // See numpad keys below
|
||||
|
||||
// miscellaneous
|
||||
k.put(GLFW_KEY_PRINT_SCREEN, Key.PRINT_SCREEN); // AKA SysRq when you hold Shift
|
||||
k.put(GLFW_KEY_PAUSE, Key.PAUSE); // AKA Break
|
||||
|
||||
// function keys ^u^
|
||||
k.put(GLFW_KEY_F1, Key.F1); // help
|
||||
k.put(GLFW_KEY_F2, Key.F2); // rename file
|
||||
k.put(GLFW_KEY_F3, Key.F3); // Opens up Minecraft cheat menu
|
||||
k.put(GLFW_KEY_F4, Key.F4); // This key is very important because Alt+F4
|
||||
k.put(GLFW_KEY_F5, Key.F5); // reload
|
||||
k.put(GLFW_KEY_F6, Key.F6);
|
||||
k.put(GLFW_KEY_F7, Key.F7);
|
||||
k.put(GLFW_KEY_F8, Key.F8);
|
||||
k.put(GLFW_KEY_F9, Key.F9);
|
||||
k.put(GLFW_KEY_F10, Key.F10);
|
||||
k.put(GLFW_KEY_F11, Key.F11); // fullscreen mode
|
||||
k.put(GLFW_KEY_F12, Key.F12); // the last one?...
|
||||
k.put(GLFW_KEY_F13, Key.F13); // ABSOLUTELY NOT!
|
||||
k.put(GLFW_KEY_F14, Key.F14); // nobody EVER uses this
|
||||
k.put(GLFW_KEY_F15, Key.F15); // because these keys
|
||||
k.put(GLFW_KEY_F16, Key.F16); // do not exist
|
||||
k.put(GLFW_KEY_F17, Key.F17); // on most modern keyboards
|
||||
k.put(GLFW_KEY_F18, Key.F18); // But GLFW is kind enough
|
||||
k.put(GLFW_KEY_F19, Key.F19); // to provide bindings
|
||||
k.put(GLFW_KEY_F20, Key.F20); // for every single
|
||||
k.put(GLFW_KEY_F21, Key.F21); // historically existed function key
|
||||
k.put(GLFW_KEY_F22, Key.F22);
|
||||
k.put(GLFW_KEY_F23, Key.F23);
|
||||
k.put(GLFW_KEY_F24, Key.F24);
|
||||
k.put(GLFW_KEY_F25, Key.F25); // the ACTUAL last function key
|
||||
|
||||
// Numpad keys! Without Num Lock, they're function keys; with Num Lock, they're printable keys :D
|
||||
k.put(GLFW_KEY_KP_0, Key.NUMPAD_0); // AKA Insert without Num Lock
|
||||
k.put(GLFW_KEY_KP_1, Key.NUMPAD_1); // AKA End without Num Lock
|
||||
k.put(GLFW_KEY_KP_2, Key.NUMPAD_2); // AKA Down arrow without Num Lock
|
||||
k.put(GLFW_KEY_KP_3, Key.NUMPAD_3); // Page down
|
||||
k.put(GLFW_KEY_KP_4, Key.NUMPAD_4); // Left arrow
|
||||
k.put(GLFW_KEY_KP_5, Key.NUMPAD_5); // Doesn't do anything without Num Lock... or, Does It?? <vsauce music starts playing>
|
||||
k.put(GLFW_KEY_KP_6, Key.NUMPAD_6); // Right Arrow
|
||||
k.put(GLFW_KEY_KP_7, Key.NUMPAD_7); // Home
|
||||
k.put(GLFW_KEY_KP_8, Key.NUMPAD_8); // Up Arrow
|
||||
k.put(GLFW_KEY_KP_9, Key.NUMPAD_9); // Page up
|
||||
k.put(GLFW_KEY_KP_DECIMAL, Key.NUMPAD_DECIMAL_POINT); // Delete key
|
||||
|
||||
// these are technically function keys, but they usually insert characters
|
||||
k.put(GLFW_KEY_KP_DIVIDE, Key.NUMPAD_DIVIDE);
|
||||
k.put(GLFW_KEY_KP_MULTIPLY, Key.NUMPAD_MULTIPLY);
|
||||
k.put(GLFW_KEY_KP_SUBTRACT, Key.NUMPAD_SUBTRACT);
|
||||
k.put(GLFW_KEY_KP_ADD, Key.NUMPAD_ADD);
|
||||
|
||||
k.put(GLFW_KEY_KP_ENTER, Key.NUMPAD_ENTER); // the tall guy
|
||||
k.put(GLFW_KEY_KP_EQUAL, Key.NUMPAD_EQUALS); // he is tall bc he ate this key
|
||||
// Modifier keys. The most controversial keys that have absolutely different meaning on different OSes.
|
||||
// the key's meaning becomes more and more blurry as we dive deeper...
|
||||
|
||||
// these guys are normal. they have the same name and overall do more or less the same in all OSes
|
||||
k.put(GLFW_KEY_LEFT_SHIFT, Key.LEFT_SHIFT);
|
||||
k.put(GLFW_KEY_RIGHT_SHIFT, Key.RIGHT_SHIFT);
|
||||
|
||||
// normal guys again. Apple just decided to stand out and named it "Option"...
|
||||
k.put(GLFW_KEY_LEFT_ALT, Key.LEFT_ALT);
|
||||
k.put(GLFW_KEY_RIGHT_ALT, Key.RIGHT_ALT);
|
||||
|
||||
// These would be NORMAL until Apple decided to stand out AGAIN and say "We're swapping the meaning of Control and Command" >:(
|
||||
k.put(GLFW_KEY_LEFT_CONTROL, Key.LEFT_CONTROL);
|
||||
k.put(GLFW_KEY_RIGHT_CONTROL, Key.RIGHT_CONTROL);
|
||||
|
||||
// This key has so many names we could barely decide on which one to use... anyway, we chose "Meta" cos it's the first ever name for this key.
|
||||
// Every single OS has its own interpretation of Meta.
|
||||
// macOS uses it for shortcuts and calls it "Command"
|
||||
// Microsoft was lazy and literally called it "Windows" key; there it's used for OS-level functions
|
||||
// Most Linux distros call it "Super"; some call it "Meta"
|
||||
// In conclusion... only ever use this key if the current platform is macOS. Otherwise, avoid using it altogether
|
||||
k.put(GLFW_KEY_LEFT_SUPER, Key.LEFT_META);
|
||||
k.put(GLFW_KEY_RIGHT_SUPER, Key.RIGHT_META);
|
||||
|
||||
// This key doesn't even exist on Macs! It exists only on Windows and Linux. There, it brings up the context menu
|
||||
// So it's basically an alternative to the right mouse button
|
||||
k.put(GLFW_KEY_MENU, Key.MENU);
|
||||
|
||||
|
||||
KEYS_MAP = Int2ObjectMaps.unmodifiable(k);
|
||||
|
||||
|
||||
Int2ObjectMap<MouseButton> mb = new Int2ObjectOpenHashMap<>(MouseButton.values().length);
|
||||
// standard buttons
|
||||
mb.put(GLFW_MOUSE_BUTTON_LEFT, MouseButton.LEFT);
|
||||
mb.put(GLFW_MOUSE_BUTTON_MIDDLE, MouseButton.MIDDLE); // usually the wheel
|
||||
mb.put(GLFW_MOUSE_BUTTON_RIGHT, MouseButton.RIGHT);
|
||||
// extra buttons; their name and purpose varies, and they don't appear on older mice
|
||||
mb.put(GLFW_MOUSE_BUTTON_4, MouseButton.BUTTON_4);
|
||||
mb.put(GLFW_MOUSE_BUTTON_5, MouseButton.BUTTON_5);
|
||||
mb.put(GLFW_MOUSE_BUTTON_6, MouseButton.BUTTON_6);
|
||||
mb.put(GLFW_MOUSE_BUTTON_7, MouseButton.BUTTON_7);
|
||||
mb.put(GLFW_MOUSE_BUTTON_8, MouseButton.BUTTON_8);
|
||||
MOUSE_BUTTONS_MAP = Int2ObjectMaps.unmodifiable(mb);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package ru.fokinatorr.sparkle.graphics.io;
|
||||
|
||||
public interface ImageDecoder {
|
||||
}
|
||||
@@ -0,0 +1,491 @@
|
||||
package ru.fokinatorr.sparkle.graphics.render;
|
||||
|
||||
import org.w3c.dom.Text;
|
||||
import ru.fokinatorr.sparkle.effect.graphics.GraphicEffect;
|
||||
import ru.fokinatorr.sparkle.effect.graphics.GraphicEffectMap;
|
||||
import ru.fokinatorr.sparkle.graphics.ARGB;
|
||||
import ru.fokinatorr.sparkle.graphics.BlendMode;
|
||||
import ru.fokinatorr.sparkle.graphics.image.Image;
|
||||
import ru.fokinatorr.sparkle.phys2d.Point2D;
|
||||
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
|
||||
|
||||
import java.awt.Shape;
|
||||
import java.awt.geom.Ellipse2D;
|
||||
import java.awt.geom.Line2D;
|
||||
import java.awt.geom.Rectangle2D;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* A canvas for 2D rendering operations.
|
||||
* <p>
|
||||
* This interface provides methods for drawing shapes and images, applying transformations,
|
||||
* setting styling properties, and managing clipping regions. It maintains a state
|
||||
* stack that can be saved and restored using {@link #save()} and {@link #restore()}.
|
||||
*
|
||||
* <h2>Coordinate System</h2>
|
||||
* The coordinate system uses floating-point coordinates where {@code (0, 0)} is typically the
|
||||
* top-left corner of the rendering surface. Positive X extends right and positive Y extends down.
|
||||
* <p><i><b>Note for Scratchers</b>: This is different from Scratch's coordinate system. In Scratch, {@code (0, 0)}
|
||||
* is the center of the stage, positive X values extend right and positive Y values extend up. To get
|
||||
* the center coordinates, use {@link #getDimensions()} to get the width & height of the canvas
|
||||
* and divide these values by 2. Vanilla renderers handle conversion between these systems automatically;
|
||||
* custom renderers must do this manually.</i>
|
||||
*
|
||||
* <h2>Graphics State</h2>
|
||||
* The render canvas maintains a state that includes:
|
||||
* <ul>
|
||||
* <li>Current transformation matrix ({@link #translate translation}, {@link #rotate rotation}, {@link #scale scaling})</li>
|
||||
* <li>Current {@link #setFillARGB fill} and {@link #setStrokeARGB stroke} colors</li>
|
||||
* <li>{@link #setLineWidth Line width}</li>
|
||||
* <li>{@link #setAlpha Alpha} (transparency) value</li>
|
||||
* <li>{@link #setBlendMode Blend mode}</li>
|
||||
* <li>{@link #setEffects Graphic effects}</li>
|
||||
* <li>Current {@link #clip clipping region}</li>
|
||||
* </ul>
|
||||
* This state can be pushed onto the stack with {@link #save()} and popped & restored with {@link #restore()}.
|
||||
*
|
||||
* <h2>Color Representation</h2>
|
||||
* Colors are represented as ARGB integers where:
|
||||
* <ul>
|
||||
* <li>Bits 0-7: <span style="background-color: #000000;" color="rgba(255, 255, 255, 0.5)">Alpha</span> (opacity)
|
||||
* component (0 = fully transparent, 255 = fully opaque)</li>
|
||||
* <li>Bits 8-15: <span color="#FF0000">Red</span> component</li>
|
||||
* <li>Bits 16-23: <span color="#00FF00">Green</span> component</li>
|
||||
* <li>Bits 24-31: <span color="#0000FF">Blue</span> component</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Blend Modes</h2>
|
||||
* Blend modes control how new pixels are combined with existing pixels in the framebuffer.
|
||||
* Available modes include:
|
||||
* <ul>
|
||||
* <li>{@link BlendMode#ADD}: Adds color components together</li>
|
||||
* <li>{@link BlendMode#BLEND_SUBTRACT}: Subtracts color components (true subtractive)</li>
|
||||
* <li>{@link BlendMode#RGB_SUBTRACT}: Subtracts RGB components, adds alpha (layered subtractive)</li>
|
||||
* <li>{@link BlendMode#BLEND_MULTIPLY}: Multiplies all components (true multiplicative)</li>
|
||||
* <li>{@link BlendMode#RGB_MULTIPLY}: Multiplies RGB components, adds alpha (layered multiplicative)</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h4>See {@link ARGB} for utility methods to work with ARGB colors, an explanation of layered/true blending types,
|
||||
* and more info about ARGB format.</h4>
|
||||
*
|
||||
* <h2>Resource Management</h2>
|
||||
* The render canvas may hold native resources that should be released by calling {@link #close()}.
|
||||
*
|
||||
* @see ARGB
|
||||
* @see BlendMode
|
||||
* @see NonThrowingAutoCloseable
|
||||
*/
|
||||
public interface RenderCanvas extends NonThrowingAutoCloseable {
|
||||
|
||||
/**
|
||||
* Pass this constant to width / height arguments of {@link #drawImage(Image, double, double, double, double)}
|
||||
* to prefer the original width / height of the image.
|
||||
*/
|
||||
double ORIGINAL_SIZE = -1;
|
||||
|
||||
// Drawing
|
||||
|
||||
/**
|
||||
* Draws an image at the specified position with the given size.
|
||||
*
|
||||
* @param image the image to draw
|
||||
* @param x the X coordinate of the top-left corner
|
||||
* @param y the Y coordinate of the top-left corner
|
||||
* @param w the preferred width of the image or {@link #ORIGINAL_SIZE}
|
||||
* @param h the preferred height of the image or {@link #ORIGINAL_SIZE}
|
||||
* @throws NullPointerException if image is {@code null}
|
||||
* @throws IllegalArgumentException if coordinates or dimensions are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
|
||||
* ({@link #ORIGINAL_SIZE} doesn't count since it's a special value)
|
||||
* @see #drawImage(Image, Point2D, Point2D)
|
||||
*/
|
||||
void drawImage(Image image, double x, double y, double w, double h);
|
||||
|
||||
/**
|
||||
* Draws an outline of the specified shape as specified in {@link #drawShape(Shape)} and fills it using the current
|
||||
* {@link #setFillARGB fill color} and {@link #setBlendMode blend mode}.
|
||||
*
|
||||
* @param shape the shape to fill
|
||||
* @throws NullPointerException if shape is {@code null}
|
||||
* @see #drawShape(Shape)
|
||||
* @see #setFillARGB(int)
|
||||
* @see #setBlendMode(BlendMode)
|
||||
*/
|
||||
void fillShape(Shape shape);
|
||||
|
||||
/**
|
||||
* Draws the outline of the specified shape using the current {@link #setStrokeARGB stroke color},
|
||||
* {@link #setLineWidth line width} and {@link #setBlendMode blend mode}.
|
||||
*
|
||||
* @param shape the shape to draw
|
||||
* @throws NullPointerException if shape is {@code null}
|
||||
* @see #setStrokeARGB(int)
|
||||
* @see #setLineWidth(double)
|
||||
* @see #setBlendMode(BlendMode)
|
||||
*/
|
||||
void drawShape(Shape shape);
|
||||
|
||||
// <editor-fold desc="-- convenience methods for drawing --" defaultstate="collapsed">
|
||||
|
||||
/**
|
||||
* Vector version of {@link #drawImage(Image, double, double, double, double)}.
|
||||
* @param image the image to draw
|
||||
* @param topLeft the top-left corner coordinates
|
||||
* @param deltaSize the preferred dimensions of the image
|
||||
* @throws NullPointerException if any argument is {@code null}
|
||||
*/
|
||||
default void drawImage(Image image, Point2D topLeft, Point2D deltaSize) {
|
||||
drawImage(image, topLeft.x(), topLeft.y(), deltaSize.x(), deltaSize.y());
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws an outline of a rectangle with the given position and dimensions as specified in {@link #drawShape(Shape)} and fills it
|
||||
* as specified in {@link #fillShape(Shape)}.
|
||||
* @param x the X coordinate of the top-left corner
|
||||
* @param y the Y coordinate of the top-left corner
|
||||
* @param w the width of the rectangle
|
||||
* @param h the height of the rectangle
|
||||
* @throws IllegalArgumentException if coordinates or dimensions are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
|
||||
* @see #drawShape(Shape)
|
||||
* @see #fillShape(Shape)
|
||||
*/
|
||||
default void fillRect(double x, double y, double w, double h) {
|
||||
fillShape(new Rectangle2D.Double(x, y, w, h));
|
||||
}
|
||||
/**
|
||||
* Vector version of {@link #fillRect(double, double, double, double)}.
|
||||
* @param topLeft the top-left corner coordinates
|
||||
* @param deltaSize the size dimensions of the rectangle
|
||||
* @throws NullPointerException if any argument is {@code null}
|
||||
* @throws IllegalArgumentException if coordinates or dimensions are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
|
||||
*/
|
||||
default void fillRect(Point2D topLeft, Point2D deltaSize) {
|
||||
fillRect(topLeft.x(), topLeft.y(), deltaSize.x(), deltaSize.y());
|
||||
}
|
||||
/**
|
||||
* Draws an outline of a rectangle with the given position and dimensions as specified in {@link #drawShape(Shape)}.
|
||||
* @param x the X coordinate of the top-left corner
|
||||
* @param y the Y coordinate of the top-left corner
|
||||
* @param w the width of the rectangle
|
||||
* @param h the height of the rectangle
|
||||
* @throws IllegalArgumentException if coordinates or dimensions are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
|
||||
* @see #drawShape(Shape)
|
||||
*/
|
||||
default void drawRect(double x, double y, double w, double h) {
|
||||
drawShape(new Rectangle2D.Double(x, y, w, h));
|
||||
}
|
||||
/**
|
||||
* Vector version of {@link #drawRect(double, double, double, double)}.
|
||||
* @param topLeft the top-left corner coordinates
|
||||
* @param deltaSize the size dimensions of the rectangle
|
||||
* @throws NullPointerException if any argument is {@code null}
|
||||
* @throws IllegalArgumentException if coordinates or dimensions are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
|
||||
*/
|
||||
default void drawRect(Point2D topLeft, Point2D deltaSize) {
|
||||
drawRect(topLeft.x(), topLeft.y(), deltaSize.x(), deltaSize.y());
|
||||
}
|
||||
/**
|
||||
* Draws a line from one position to another as specified in {@link #drawShape(Shape)}.
|
||||
* @param x1 the X coordinate of the first position
|
||||
* @param y1 the Y coordinate of the first position
|
||||
* @param x2 the X coordinate of the second position
|
||||
* @param y2 the Y coordinate of the second position
|
||||
* @throws IllegalArgumentException if any coordinates are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
|
||||
* @see #drawShape(Shape)
|
||||
*/
|
||||
default void drawLine(double x1, double y1, double x2, double y2) {
|
||||
drawShape(new Line2D.Double(x1, y1, x2, y2));
|
||||
}
|
||||
/**
|
||||
* Vector version of {@link #drawLine(double, double, double, double)}.
|
||||
* @param first the first position
|
||||
* @param second the second position
|
||||
* @throws NullPointerException if any argument is {@code null}
|
||||
* @throws IllegalArgumentException if any coordinates are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
|
||||
*/
|
||||
default void drawLine(Point2D first, Point2D second) {
|
||||
drawLine(first.x(), first.y(), second.x(), second.y());
|
||||
}
|
||||
/**
|
||||
* Draws an outline of an oval with the given position and dimensions as specified in {@link #drawShape(Shape)} and fills it
|
||||
* as specified in {@link #fillShape(Shape)}.
|
||||
* @param x the X coordinate of the top-left corner
|
||||
* @param y the Y coordinate of the top-left corner
|
||||
* @param w the width of the oval
|
||||
* @param h the height of the oval
|
||||
* @throws IllegalArgumentException if coordinates or dimensions are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
|
||||
* @see #drawShape(Shape)
|
||||
* @see #fillShape(Shape)
|
||||
*/
|
||||
default void fillOval(double x, double y, double w, double h) {
|
||||
fillShape(new Ellipse2D.Double(x, y, w, h));
|
||||
}
|
||||
/**
|
||||
* Vector version of {@link #fillOval(double, double, double, double)}.
|
||||
* @param topLeft the top-left corner coordinates
|
||||
* @param deltaSize the size dimensions of the oval
|
||||
* @throws NullPointerException if any argument is {@code null}
|
||||
* @throws IllegalArgumentException if coordinates or dimensions are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
|
||||
*/
|
||||
default void fillOval(Point2D topLeft, Point2D deltaSize) {
|
||||
fillOval(topLeft.x(), topLeft.y(), deltaSize.x(), deltaSize.y());
|
||||
}
|
||||
/**
|
||||
* Draws an outline of an oval with the given position and dimensions as specified in {@link #drawShape(Shape)}.
|
||||
* @param x the X coordinate of the top-left corner
|
||||
* @param y the Y coordinate of the top-left corner
|
||||
* @param w the width of the oval
|
||||
* @param h the height of the oval
|
||||
* @throws IllegalArgumentException if coordinates or dimensions are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
|
||||
* @see #drawShape(Shape)
|
||||
*/
|
||||
default void drawOval(double x, double y, double w, double h) {
|
||||
drawShape(new Ellipse2D.Double(x, y, w, h));
|
||||
}
|
||||
/**
|
||||
* Vector version of {@link #drawOval(double, double, double, double)}.
|
||||
* @param topLeft the top-left corner coordinates
|
||||
* @param deltaSize the size dimensions of the oval
|
||||
* @throws NullPointerException if any argument is {@code null}
|
||||
* @throws IllegalArgumentException if coordinates or dimensions are negative, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
|
||||
*/
|
||||
default void drawOval(Point2D topLeft, Point2D deltaSize) {
|
||||
drawOval(topLeft.x(), topLeft.y(), deltaSize.x(), deltaSize.y());
|
||||
}
|
||||
// </editor-fold>
|
||||
|
||||
// State management
|
||||
|
||||
/**
|
||||
* Saves the current graphics state (transformations, styling, clipping) onto a stack.
|
||||
* The state can be restored later using {@link #restore()}.
|
||||
*
|
||||
* @see #restore()
|
||||
* @see #translate(double, double)
|
||||
* @see #rotate(double)
|
||||
* @see #scale(double, double)
|
||||
*/
|
||||
void save();
|
||||
|
||||
/**
|
||||
* Restores the most recently saved graphics state from the stack.
|
||||
* This reverts all transformations, styling, and clipping to their values when
|
||||
* {@link #save()} was last called.
|
||||
*
|
||||
* @throws IllegalStateException if the state stack is empty
|
||||
* @see #save()
|
||||
*/
|
||||
void restore();
|
||||
|
||||
/**
|
||||
* Resets the current graphics state to default values. Useful for finer control over texture/primitive position,
|
||||
* rotation, scale, etc.
|
||||
*/
|
||||
void setIdentity();
|
||||
|
||||
/**
|
||||
* Translates the coordinate system by the specified amounts (subsequent drawing operations will be offset by {@code (dx, dy)}).
|
||||
* @param dx the distance to translate along X axis
|
||||
* @param dy the distance to translate along Y axis
|
||||
*/
|
||||
void translate(double dx, double dy);
|
||||
|
||||
/**
|
||||
* Translates the coordinate system by the specified delta vector.
|
||||
* @param delta the translation amount vector point
|
||||
* @throws NullPointerException if delta is {@code null}
|
||||
*/
|
||||
default void translate(Point2D delta) {
|
||||
Objects.requireNonNull(delta, "delta");
|
||||
translate(delta.x(), delta.y());
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotates the coordinate system around the origin by the specified angle (subsequent drawing operations will be rotated).
|
||||
* <p><i>Note for Scratchers: In Scratch, the rotation angle is relative to the upper part of the vertical axis (0 degrees is
|
||||
* facing up, 90 degrees is no rotation, etc.). In the context of graphics, for convenience’s sake (and because
|
||||
* there's usually no front face like with Scratch's built-in costumes), a different system is used:
|
||||
* 0 degrees means no rotation, positive values rotate clockwise and negative values - counterclockwise.
|
||||
* Conversion between these systems happens automatically in vanilla classes, but custom renderers need to do this manually.</i>
|
||||
* @param degrees the angle of rotation in degrees (0 or multiples of 360 mean no rotation)
|
||||
*/
|
||||
void rotate(double degrees);
|
||||
|
||||
/**
|
||||
* Scales the coordinate system by the specified factors.
|
||||
* Subsequent drawing operations will have their coordinates multiplied by (sx, sy).
|
||||
*
|
||||
* @param sx the scaling factor for the X axis
|
||||
* @param sy the scaling factor for the Y axis
|
||||
* @throws IllegalArgumentException if sx or sy is/are non-positive, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
|
||||
*/
|
||||
void scale(double sx, double sy);
|
||||
|
||||
/**
|
||||
* Sets the fill color for shape filling operations.
|
||||
* This color will be used by subsequent calls to {@link #fillShape(Shape)} and convenience methods.
|
||||
*
|
||||
* @param argb the ARGB color value (see {@link ARGB})
|
||||
* @see #fillShape(Shape)
|
||||
* @see #setBlendMode(BlendMode)
|
||||
* @see ARGB
|
||||
*/
|
||||
void setFillARGB(int argb);
|
||||
|
||||
/**
|
||||
* Sets the stroke color for shape outline drawing operations.
|
||||
* This color will be used by subsequent calls to {@link #drawShape(Shape)} and convenience methods.
|
||||
*
|
||||
* @param argb the ARGB color value (see {@link ARGB})
|
||||
* @see #drawShape(Shape)
|
||||
* @see #setBlendMode(BlendMode)
|
||||
* @see ARGB
|
||||
*/
|
||||
void setStrokeARGB(int argb);
|
||||
|
||||
/**
|
||||
* Sets the line width for stroke operations.
|
||||
* This width will be used by subsequent calls to {@link #drawShape(Shape)} and convenience methods.
|
||||
*
|
||||
* @param width the line width in coordinate units (must be positive)
|
||||
* @throws IllegalArgumentException if width is non-positive, {@link Double#isInfinite infinite} or {@link Double#NaN NaN}
|
||||
*/
|
||||
void setLineWidth(double width);
|
||||
|
||||
/**
|
||||
* Sets the alpha (transparency) value for all drawing operations.
|
||||
* This value is combined with the alpha components of fill/stroke colors.
|
||||
* A value of 0 means fully transparent, 255 (-1) means fully opaque.
|
||||
*
|
||||
* @param alpha the alpha value (0-255 unsigned)
|
||||
* @see #setFillARGB(int)
|
||||
* @see #setStrokeARGB(int)
|
||||
*/
|
||||
// ARGB.alpha(int) returns byte, so we respect that here
|
||||
void setAlpha(byte alpha);
|
||||
|
||||
/**
|
||||
* Sets the blend mode for combining source pixels with destination pixels.
|
||||
* The blend mode affects all drawing operations including shape filling/drawing and image drawing.
|
||||
*
|
||||
* @param mode the blend mode to use
|
||||
* @throws NullPointerException if mode is {@code null}
|
||||
* @see BlendMode
|
||||
* @see #drawImage(Image, double, double, double, double)
|
||||
* @see #fillShape(Shape)
|
||||
* @see #drawShape(Shape)
|
||||
*/
|
||||
void setBlendMode(BlendMode mode);
|
||||
|
||||
/**
|
||||
* Sets the graphic effects map to apply to subsequent drawing operations.
|
||||
* <p><i>Note: Spatial distortion effects can't be applied to vector content (shapes, text); effects
|
||||
* that can be applied to them are: {@link GraphicEffect#HUE_SHIFT HUE_SHIFT}, {@link GraphicEffect#BRIGHTNESS BRIGHTNESS}
|
||||
* and {@link GraphicEffect#OPACITY OPACITY}. Use {@link #createSubCanvas(double, double)} and {@link #getFinalImage()}
|
||||
* to apply spatial distortion to vector elements.</i>
|
||||
* @param effects the effect map
|
||||
*/
|
||||
void setEffects(GraphicEffectMap effects);
|
||||
|
||||
/**
|
||||
* Intersects the current clipping region with the specified shape.
|
||||
* All subsequent drawing operations will be clipped to the intersection of
|
||||
* the current clip and the specified shape. The clip is transformed by the
|
||||
* current transformation matrix.
|
||||
*
|
||||
* @param shape the shape to intersect with the current clip
|
||||
* @throws NullPointerException if shape is {@code null}
|
||||
* @see #resetClip()
|
||||
* @see #translate(double, double)
|
||||
* @see #rotate(double)
|
||||
* @see #scale(double, double)
|
||||
*/
|
||||
void clip(Shape shape);
|
||||
|
||||
/**
|
||||
* Resets the clipping region to the default (typically the entire rendering surface).
|
||||
* After calling this method, all drawing operations will not be clipped (except by
|
||||
* the bounds of the rendering surface itself).
|
||||
*
|
||||
* @see #clip(Shape)
|
||||
*/
|
||||
void resetClip();
|
||||
|
||||
// Sub-canvases
|
||||
|
||||
/**
|
||||
* Creates a new sub-canvas that renders into an offscreen buffer.
|
||||
* <p>
|
||||
* All drawing operations on the returned canvas are isolated and rasterized
|
||||
* into a procedural image when closed. The result can be retrieved via
|
||||
* {@link #getFinalImage()} and drawn like any other image.
|
||||
* <p>
|
||||
* This enables:
|
||||
* <ul>
|
||||
* <li>Coherent application of graphic effects</li>
|
||||
* <li>Layered rendering</li>
|
||||
* <li>Reusable render passes</li>
|
||||
* </ul>
|
||||
*
|
||||
* Example:
|
||||
* <pre>{@code
|
||||
* try (RenderCanvas layer = canvas.createSubCanvas(200, 200)) {
|
||||
* layer.setFillArgb(ARGB.RED);
|
||||
* layer.fillRect(10, 10, 50, 50);
|
||||
* layer.drawOval(30, 30, 40, 40);
|
||||
* try (Image img = layer.getFinalImage()) {
|
||||
* // If "canvas" has graphic effects, they'll be applied to the whole image, not to each component separately!
|
||||
* canvas.drawImage(img, 100, 100, 200, 200);
|
||||
* }
|
||||
* }
|
||||
* }</pre>
|
||||
*
|
||||
* @param width the width of the sub-canvas
|
||||
* @param height the height of the sub-canvas
|
||||
* @return a new render canvas targeting an offscreen buffer
|
||||
* @throws IllegalArgumentException if either dimension exceeds this canvas's respective dimension
|
||||
*/
|
||||
RenderCanvas createSubCanvas(double width, double height);
|
||||
|
||||
/**
|
||||
* Checks whether this canvas is a sub-canvas. If {@code true}, then {@link #getFinalImage()} can be safely called.
|
||||
*
|
||||
* @return {@code true} for sub-canvases, {@code false} for the main canvas
|
||||
*/
|
||||
default boolean isSubCanvas() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the final rendered image, if this canvas is a sub-canvas.
|
||||
* The image is not cached anywhere and becomes invalid once the canvas is closed.
|
||||
* @throws IllegalStateException if this canvas is not a sub-canvas
|
||||
* @see #isSubCanvas()
|
||||
*/
|
||||
default Image getFinalImage() {
|
||||
// TODO maybe allow calling on main canvas? For screenshots?
|
||||
throw new IllegalStateException("This canvas is not a sub-canvas");
|
||||
}
|
||||
|
||||
// Getters
|
||||
|
||||
/**
|
||||
* Returns a vector representing the width and height of the canvas area.
|
||||
* @return the dimensions of this canvas
|
||||
*/
|
||||
Point2D getDimensions();
|
||||
|
||||
/**
|
||||
* {@return the parent context of this canvas}
|
||||
*/
|
||||
RenderingContext getContext();
|
||||
|
||||
// Lifecycle
|
||||
|
||||
/**
|
||||
* Releases any resources associated with this render canvas.
|
||||
* After calling this method, the canvas should not be used.
|
||||
* Calling this method more than once does not have any effect.
|
||||
*/
|
||||
@Override
|
||||
void close();
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package ru.fokinatorr.sparkle.graphics.render;
|
||||
|
||||
import ru.fokinatorr.sparkle.assets.Assets;
|
||||
import ru.fokinatorr.sparkle.graphics.GraphicsManager;
|
||||
import ru.fokinatorr.sparkle.graphics.render.surface.RenderingSurface;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
import ru.fokinatorr.sparkle.stage.StageCreator;
|
||||
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
|
||||
|
||||
/**
|
||||
* Represents a graphics environment. Binds together:
|
||||
* <ul>
|
||||
* <li>
|
||||
* a {@link RenderingSurface} (where to draw)
|
||||
* </li>
|
||||
* <li>
|
||||
* a {@link Stage} (what to draw)
|
||||
* </li>
|
||||
* <li>
|
||||
* a {@link RenderCanvas} (how to draw)
|
||||
* </li>
|
||||
* </ul>
|
||||
* Multiple can coexist in one {@link GraphicsManager}.
|
||||
* <p>Note: do not manually close instances of this interface retrieved
|
||||
* from a {@link GraphicsManager}; it does so automatically when needed.
|
||||
* @see GraphicsManager#createWindowContext(String, StageCreator)
|
||||
*/
|
||||
public interface RenderingContext extends NonThrowingAutoCloseable {
|
||||
|
||||
/**
|
||||
* {@return the underlying rendering surface}
|
||||
* @throws IllegalStateException if this context is closed (optional)
|
||||
*/
|
||||
RenderingSurface getSurface();
|
||||
|
||||
/**
|
||||
* {@return the stage associated with this context}
|
||||
* @throws IllegalStateException if this context is closed (optional)
|
||||
*/
|
||||
Stage getStage();
|
||||
|
||||
/**
|
||||
* Returns the canvas used for drawing operations.
|
||||
* @return the canvas
|
||||
* @throws IllegalStateException if this context is closed (optional)
|
||||
*/
|
||||
RenderCanvas getCanvas();
|
||||
|
||||
/**
|
||||
* Polls input and system events (e.g., window close, resize, key press) and
|
||||
* fires them on the underlying stage's local event dispatcher.
|
||||
* <p>This method is called regularly from the graphics loop, no need
|
||||
* to call it manually.
|
||||
* @throws IllegalStateException if this context is closed
|
||||
*/
|
||||
default void pollEvents() {
|
||||
getSurface().pollEvents();
|
||||
}
|
||||
|
||||
/**
|
||||
* Presents the rendered frame.
|
||||
* <p>This method is called regularly from the graphics loop, no need
|
||||
* to call it manually.
|
||||
* @throws IllegalStateException if this context is closed
|
||||
*/
|
||||
void present();
|
||||
|
||||
/**
|
||||
* Checks if the surface should close.
|
||||
*
|
||||
* @return whether a close was requested
|
||||
*/
|
||||
default boolean shouldClose() {
|
||||
return getSurface().shouldClose();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a resize listener to the surface.
|
||||
*
|
||||
* @param callback the listener to call every time the surface gets resized
|
||||
*/
|
||||
default void onResize(RenderingSurface.ResizeListener callback) {
|
||||
getSurface().onResize(callback);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package ru.fokinatorr.sparkle.graphics.render.framebuffer;
|
||||
|
||||
import ru.fokinatorr.sparkle.graphics.ARGB;
|
||||
import ru.fokinatorr.sparkle.graphics.PixelReader;
|
||||
import ru.fokinatorr.sparkle.graphics.PixelWriter;
|
||||
import ru.fokinatorr.sparkle.phys2d.Point2D;
|
||||
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
|
||||
|
||||
/**
|
||||
* Represents a render target to present on a rendering surface.
|
||||
* <p>This is usually a handle to native platform framebuffer; do not use directly from your code
|
||||
* unless you're integrating with low-level rendering APIs.
|
||||
*/
|
||||
public interface Framebuffer extends NonThrowingAutoCloseable {
|
||||
|
||||
/**
|
||||
* Returns the width of underlying frame buffer.
|
||||
* @return the width, always positive
|
||||
*/
|
||||
int width();
|
||||
|
||||
/**
|
||||
* Returns the height of underlying frame buffer.
|
||||
* @return the height, always positive
|
||||
*/
|
||||
int height();
|
||||
|
||||
/**
|
||||
* Returns a vector representing the dimensions of underlying frame buffer's data.
|
||||
* @return the dimensions, both always positive
|
||||
*/
|
||||
default Point2D getDimensions() {
|
||||
return new Point2D(width(), height());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a pixel reader over this buffer, for reading its data as ARGB pixels.
|
||||
* @return a new {@link PixelReader}
|
||||
* @see ARGB
|
||||
*/
|
||||
PixelReader createPixelReader();
|
||||
|
||||
/**
|
||||
* Returns a pixel writer over this buffer, for writing ARGB pixels into it.
|
||||
* @return a new {@code PixelWriter}
|
||||
* @see ARGB
|
||||
*/
|
||||
PixelWriter createPixelWriter();
|
||||
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package ru.fokinatorr.sparkle.graphics.render.framebuffer;
|
||||
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import ru.fokinatorr.sparkle.graphics.PixelReader;
|
||||
import ru.fokinatorr.sparkle.graphics.PixelWriter;
|
||||
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
import ru.fokinatorr.sparkle.graphics.impl.IntBufferPixelAccessor;
|
||||
|
||||
import java.nio.IntBuffer;
|
||||
|
||||
import static lombok.AccessLevel.PRIVATE;
|
||||
|
||||
/**
|
||||
* An off-screen frame buffer (never displayed directly; use {@link #createPixelReader()} to use its content).
|
||||
* <p>When created, its contents are by default fully transparent (or black if transparency is disabled).
|
||||
*/
|
||||
@FieldDefaults(level = PRIVATE)
|
||||
public final class OffscreenFramebuffer implements Framebuffer {
|
||||
final IntBuffer img; // pixel[x][y] = pixel[y * width + x]
|
||||
final int width, height;
|
||||
boolean closed;
|
||||
|
||||
public OffscreenFramebuffer(int width, int height) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.img = MemoryUtil.memCallocInt(width * height);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int width() {
|
||||
ensureOpen();
|
||||
return width;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int height() {
|
||||
ensureOpen();
|
||||
return height;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized PixelReader createPixelReader() {
|
||||
ensureOpen();
|
||||
return new IntBufferPixelAccessor(width, height, img, this::ensureOpen);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized PixelWriter createPixelWriter() {
|
||||
ensureOpen();
|
||||
return new IntBufferPixelAccessor(width, height, img, this::ensureOpen);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!closed) {
|
||||
MemoryUtil.memFree(img);
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureOpen() {
|
||||
if (closed) {
|
||||
throw new IllegalStateException("The buffer is closed");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package ru.fokinatorr.sparkle.graphics.render.renderer;
|
||||
|
||||
import ru.fokinatorr.sparkle.effect.graphics.GraphicEffectMap;
|
||||
import ru.fokinatorr.sparkle.graphics.render.RenderCanvas;
|
||||
|
||||
/**
|
||||
* A renderable object is an object that knows how to draw itself.
|
||||
* <p>This base interface has these methods: {@link #render(RenderCanvas)} for drawing, {@link #isVisible()}
|
||||
* for checking visibility, and {@link #getGraphicEffects()} for getting and editing graphic effects.
|
||||
*/
|
||||
public interface Renderable {
|
||||
|
||||
/**
|
||||
* Render this object onto the given canvas.
|
||||
* @param canvas the canvas
|
||||
*/
|
||||
void render(RenderCanvas canvas);
|
||||
|
||||
/**
|
||||
* Checks if this object is visible. This method is used as a hint for skipping rendering of this object.
|
||||
* @return whether this object must be rendered
|
||||
*/
|
||||
boolean isVisible();
|
||||
|
||||
/**
|
||||
* Returns the graphic effect map to apply to this object's render. The map
|
||||
* is mutable and can be also used to edit graphic effects.
|
||||
* @return the graphic effect map of this object
|
||||
*/
|
||||
GraphicEffectMap getGraphicEffects();
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package ru.fokinatorr.sparkle.graphics.render.renderer;
|
||||
|
||||
import ru.fokinatorr.sparkle.phys2d.Hitbox2D;
|
||||
import ru.fokinatorr.sparkle.stage.sprite.Sprite;
|
||||
|
||||
/**
|
||||
* A 2-dimensional {@link Renderable renderable} object is a physical 2-dimensional object with a hitbox, position, direction, and size (X and Y axis stretches).
|
||||
*
|
||||
* @see Sprite Sprite - a general-purpose 2D renderable
|
||||
*/
|
||||
public interface Renderable2D extends Renderable {
|
||||
|
||||
/**
|
||||
* {@return the current X coordinate}
|
||||
*/
|
||||
double getX();
|
||||
|
||||
/**
|
||||
* {@return the current Y coordinate}
|
||||
*/
|
||||
double getY();
|
||||
|
||||
/**
|
||||
* {@return the current direction in angles} The direction is relative to the upper vertical axis: {@code 0}
|
||||
* means facing up, {@code 90} means no rotation. The minimal value is {@code -180} and the maximal value is
|
||||
* {@code 180} (both of these mean facing down).
|
||||
*/
|
||||
double getDirection();
|
||||
|
||||
/**
|
||||
* {@return the X axis stretch in percents} If you don't want to apply stretch, return {@code 100} (100% stretch - no change).
|
||||
*/
|
||||
double getStretchX();
|
||||
|
||||
/**
|
||||
* {@return the Y axis stretch in percents} If you don't want to apply stretch, return {@code 100} (100% stretch - no change).
|
||||
*/
|
||||
double getStretchY();
|
||||
|
||||
/**
|
||||
* Returns this object's collision box. This can be used to check what object was clicked, what objects intersect, etc.
|
||||
* The hitbox's center is relative to current coordinates.
|
||||
* @return the collision box
|
||||
*/
|
||||
Hitbox2D getHitbox();
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package ru.fokinatorr.sparkle.graphics.render.renderer;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import ru.fokinatorr.sparkle.graphics.image.Image;
|
||||
import ru.fokinatorr.sparkle.graphics.render.RenderCanvas;
|
||||
import ru.fokinatorr.sparkle.phys2d.Hitbox2D;
|
||||
import ru.fokinatorr.sparkle.phys2d.Point2D;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.WeakHashMap;
|
||||
|
||||
import static lombok.AccessLevel.PRIVATE;
|
||||
|
||||
/**
|
||||
* A renderer is an object that can render a specific type of objects. The objects don't have to
|
||||
* implement {@link Renderable}. This interface allows for dynamic rendering implementations.
|
||||
* @param <T> the type this renderer can draw
|
||||
* @see ForRenderable
|
||||
* @see ForRenderable2D
|
||||
* @see ForRenderable2DWithHitbox
|
||||
* @see Renderable
|
||||
*/
|
||||
public interface Renderer<T> {
|
||||
|
||||
/**
|
||||
* Render the given object onto the given canvas.
|
||||
* @param obj the object to render
|
||||
* @param canvas the canvas
|
||||
*/
|
||||
void render(T obj, RenderCanvas canvas);
|
||||
|
||||
/**
|
||||
* Checks if the given object is visible. This method is used as a hint for skipping rendering of the object.
|
||||
* @param obj the object to check
|
||||
* @return whether the object should be rendered
|
||||
*/
|
||||
boolean isVisible(T obj);
|
||||
|
||||
/**
|
||||
* Returns the boundaries of the given object on a 2D surface.
|
||||
* @param obj the object
|
||||
* @return the object's 2D bounds
|
||||
* @see ru.fokinatorr.sparkle.graphics.render.surface.RenderingSurface
|
||||
*/
|
||||
Hitbox2D getBounds(T obj);
|
||||
|
||||
/**
|
||||
* A simple implementation of {@link Renderer} which draws {@link Renderable} objects.
|
||||
* It is possible to extend this class and add custom functionality.
|
||||
* @param <T> the type this renderer can draw
|
||||
*/
|
||||
class ForRenderable<T extends Renderable> implements Renderer<T> {
|
||||
|
||||
/**
|
||||
* {@inheritDoc} The default implementation calls the object's {@link Renderable#render(RenderCanvas) render()} method.
|
||||
* @param obj {@inheritDoc}
|
||||
* @param canvas {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void render(T obj, RenderCanvas canvas) {
|
||||
canvas.save();
|
||||
canvas.setEffects(obj.getGraphicEffects());
|
||||
Point2D dim = canvas.getDimensions();
|
||||
try (RenderCanvas layer = canvas.createSubCanvas(dim.x(), dim.y())) {
|
||||
obj.render(layer);
|
||||
canvas.drawImage(layer.getFinalImage(), 0, 0, dim.x(), dim.y());
|
||||
}
|
||||
canvas.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc} The default implementation calls the object's {@link Renderable#isVisible() isVisible()} method.
|
||||
* @param obj {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isVisible(T obj) {
|
||||
return obj.isVisible();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc} The default implementation returns {@link Hitbox2D#never()}.
|
||||
* @param obj {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public Hitbox2D getBounds(T obj) {
|
||||
return Hitbox2D.never();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An implementation of {@link Renderer} which draws {@link Renderable2D} objects,
|
||||
* applying respective transformations.
|
||||
* It is possible to extend this class and add custom functionality.
|
||||
* @param <T> the type this renderer can draw
|
||||
*/
|
||||
class ForRenderable2D<T extends Renderable2D> extends ForRenderable<T> {
|
||||
|
||||
@Override
|
||||
public void render(T obj, RenderCanvas canvas) {
|
||||
canvas.save();
|
||||
canvas.translate(obj.getX(), obj.getY());
|
||||
canvas.rotate(obj.getDirection() - 90); // Convert from face direction to relative rotation
|
||||
canvas.scale(obj.getStretchX() / 100, obj.getStretchY() / 100); // Convert from percentage to coefficients
|
||||
super.render(obj, canvas);
|
||||
canvas.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc} The default implementation call the object's {@link Renderable2D#getHitbox() getHitbox()} method.
|
||||
* @param obj {@inheritDoc}
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public Hitbox2D getBounds(T obj) {
|
||||
return obj.getHitbox();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An implementation of {@link Renderer} which draws a {@link Renderable2D} and its hitbox on top.
|
||||
* It is possible to extend this class and add custom functionality.
|
||||
* @param <T> the type this renderer can draw
|
||||
*/
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
@FieldDefaults(makeFinal = true, level = PRIVATE)
|
||||
class ForRenderable2DWithHitbox<T extends Renderable2D> extends ForRenderable2D<T> {
|
||||
|
||||
/**
|
||||
* The outline color of the hitbox's area, in ARGB format.
|
||||
*/
|
||||
int outlineColor;
|
||||
/**
|
||||
* The fill color of the hitbox's area, in ARGB format.
|
||||
*/
|
||||
int fillColor;
|
||||
Map<Hitbox2D, Renderable2D> hitboxRenderers = new WeakHashMap<>(); // avoid constant recreation of hitbox renderers
|
||||
|
||||
|
||||
@Override
|
||||
public void render(T obj, RenderCanvas context) {
|
||||
super.render(obj, context);
|
||||
Renderable2D hitboxRenderer = hitboxRenderers.computeIfAbsent(obj.getHitbox(), hitbox -> hitbox.asRenderable(outlineColor, fillColor));
|
||||
hitboxRenderer.render(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package ru.fokinatorr.sparkle.graphics.render.renderer;
|
||||
|
||||
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
|
||||
import lombok.Getter;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
import lombok.experimental.NonFinal;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import ru.fokinatorr.sparkle.util.GUID;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Map;
|
||||
import java.util.Queue;
|
||||
import java.util.Set;
|
||||
|
||||
import static lombok.AccessLevel.PRIVATE;
|
||||
|
||||
/**
|
||||
* A registry that maps type -> renderer for that type or supertype.
|
||||
* <p>Also contains a separate class of renderers: debug renderers. They are disabled be default and can not be registered;
|
||||
* to enable them, use {@link #enableDebug()}.
|
||||
* <p>If both a regular and a debug renderer were found for the same type, the latter is used instead.
|
||||
*
|
||||
* @see Renderer
|
||||
*/
|
||||
@Slf4j
|
||||
@FieldDefaults(makeFinal = true, level = PRIVATE)
|
||||
public final class RendererRegistry {
|
||||
|
||||
/**
|
||||
* The ID of this registry. Useful for debugging purposes to differentiate between registries.
|
||||
*/
|
||||
@Getter
|
||||
String id = GUID.generate();
|
||||
Map<Class<?>, Renderer<?>> renderers = new Reference2ObjectOpenHashMap<>();
|
||||
Map<Class<?>, Renderer<?>> debugRenderers = new Reference2ObjectOpenHashMap<>();
|
||||
/**
|
||||
* Whether debug renderers are enabled and can be registered.
|
||||
*/
|
||||
@NonFinal
|
||||
@Getter
|
||||
volatile boolean debugEnabled;
|
||||
|
||||
|
||||
// Registration methods
|
||||
|
||||
/**
|
||||
* Registers a renderer for the given type.
|
||||
*
|
||||
* @param type the type
|
||||
* @param renderer the renderer for that type or its subtypes
|
||||
* @param <T> the type of the object
|
||||
* @return this registry, for chaining calls
|
||||
*/
|
||||
public <T> RendererRegistry register(Class<T> type, Renderer<? extends T> renderer) {
|
||||
if (renderers.containsKey(type)) {
|
||||
log.warn(
|
||||
"[RendererRegistry id={}] Replacing existing entry '{}' -> {} with {}",
|
||||
id, type.getSimpleName(), renderers.get(type), renderer
|
||||
);
|
||||
}
|
||||
renderers.put(type, renderer);
|
||||
log.debug("[RendererRegistry id={}] Registered a renderer '{}' -> {}", id, type.getSimpleName(), renderer);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a debug renderer for the given type.
|
||||
* <p>If debug renderers are disabled, calling this method does not have any effect.
|
||||
*
|
||||
* @param type the type
|
||||
* @param renderer the debug renderer for that type or its subtypes
|
||||
* @param <T> the type of the object
|
||||
* @return this registry, for chaining calls
|
||||
*/
|
||||
public <T> RendererRegistry registerDebug(Class<T> type, Renderer<? extends T> renderer) {
|
||||
if (debugRenderers.containsKey(type)) {
|
||||
log.warn(
|
||||
"[RendererRegistry id={}] Replacing existing debug entry '{}' -> {} with {}",
|
||||
id, type.getSimpleName(), renderers.get(type), renderer
|
||||
);
|
||||
}
|
||||
if (debugEnabled) {
|
||||
debugRenderers.put(type, renderer);
|
||||
log.debug("[RendererRegistry id={}] Registered a debug renderer '{}' -> {}", id, type.getSimpleName(), renderer);
|
||||
} else {
|
||||
log.warn(
|
||||
"[RendererRegistry id={}] Ignoring debug renderer registration '{}' -> {}; debug renderers are disabled",
|
||||
id, type.getSimpleName(), renderer
|
||||
);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables registering and using debug renderers in addition to regular ones. This can't be reversed.
|
||||
* @return this registry, for chaining calls
|
||||
*/
|
||||
public RendererRegistry enableDebug() {
|
||||
debugEnabled = true;
|
||||
log.debug("[RendererRegistry id={}] Debug renderers enabled", id);
|
||||
return this;
|
||||
}
|
||||
|
||||
// Retrieval methods
|
||||
|
||||
/**
|
||||
* Returns a renderer suitable for rendering instances of the given type or its supertype.
|
||||
* <p>If debug renderers are enabled and both a regular and a debug one were found for the given type, the latter is used instead.
|
||||
* @param type the type
|
||||
* @return the appropriate renderer, if any
|
||||
* @throws NullPointerException if no renderers were found for the given type
|
||||
* @param <T> the type of the object
|
||||
*/
|
||||
public <T> Renderer<T> get(Class<T> type) {
|
||||
Renderer<T> renderer = null;
|
||||
if (debugEnabled) {
|
||||
renderer = find(debugRenderers, type);
|
||||
}
|
||||
if (renderer == null) {
|
||||
renderer = find(renderers, type);
|
||||
}
|
||||
|
||||
if (renderer != null) {
|
||||
log.trace("[RendererRegistry id={}] Resolved '{}' -> {}", id, type.getSimpleName(), renderer);
|
||||
return renderer;
|
||||
} else {
|
||||
log.error(
|
||||
"[RendererRegistry id={}] No renderers found for type '{}'. Debug renderers are {}",
|
||||
id, type.getSimpleName(), debugEnabled ? "enabled" : "disabled"
|
||||
);
|
||||
throw new NullPointerException("No renderers found for type " + type);
|
||||
}
|
||||
}
|
||||
|
||||
// Factory methods
|
||||
|
||||
/**
|
||||
* Creates a renderer registry with default renderers pre-registered. This registry
|
||||
* has debug renderers disabled.
|
||||
* @return a new defaulted registry
|
||||
*/
|
||||
public static RendererRegistry withDefaults() {
|
||||
return new RendererRegistry()
|
||||
.register(Renderable.class, new Renderer.ForRenderable<>())
|
||||
.register(Renderable2D.class, new Renderer.ForRenderable2D<>());
|
||||
}
|
||||
|
||||
// Private implementation
|
||||
|
||||
/**
|
||||
* Finds the first renderer registered for any supertype or implemented interface of {@code type}.
|
||||
* Performs breadth-first search through the type hierarchy to ensure the closest matches win.
|
||||
*
|
||||
* @param m the map of type -> renderer
|
||||
* @param type the queried type
|
||||
* @param <T> the object type
|
||||
* @return the best matching renderer, or {@code null} if none found
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T> Renderer<T> find(Map<Class<?>, Renderer<?>> m, Class<T> type) {
|
||||
if (type == null) return null;
|
||||
|
||||
// Use a queue or stack to avoid deep recursion
|
||||
Queue<Class<?>> queue = new LinkedList<>();
|
||||
Set<Class<?>> visited = new HashSet<>();
|
||||
|
||||
visited.add(type);
|
||||
queue.offer(type);
|
||||
|
||||
while (!queue.isEmpty()) {
|
||||
Class<?> current = queue.poll();
|
||||
|
||||
// Check direct match
|
||||
Renderer<?> renderer = m.get(current);
|
||||
if (renderer != null) {
|
||||
return (Renderer<T>) renderer;
|
||||
}
|
||||
|
||||
// Add interfaces
|
||||
for (Class<?> iface : current.getInterfaces()) {
|
||||
if (visited.add(iface)) {
|
||||
queue.offer(iface);
|
||||
}
|
||||
}
|
||||
|
||||
// Add superclass
|
||||
Class<?> superClass = current.getSuperclass();
|
||||
if (superClass != null && visited.add(superClass)) {
|
||||
queue.offer(superClass);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package ru.fokinatorr.sparkle.graphics.render.surface;
|
||||
|
||||
import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer;
|
||||
import ru.fokinatorr.sparkle.graphics.render.framebuffer.OffscreenFramebuffer;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.EnumSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* An embedded surface (e.g. UI element). In general, more stationary than {@link WindowSurface}.
|
||||
*/
|
||||
public interface EmbeddedSurface extends RenderingSurface {
|
||||
|
||||
@Override
|
||||
default Set<Feature> getFeatures() {
|
||||
return Collections.unmodifiableSet(EnumSet.of(
|
||||
Feature.RESIZABLE,
|
||||
Feature.NAMEABLE // label or just for debugging
|
||||
));
|
||||
}
|
||||
|
||||
@Override
|
||||
void setSize(int newWidth, int newHeight);
|
||||
|
||||
@Override
|
||||
String getName();
|
||||
|
||||
@Override
|
||||
void setName(String name);
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* Embedded surfaces usually don't interact directly with rendering API, so they have to render to an off-screen buffer, then copy
|
||||
* it onto the actual surface.
|
||||
* @return {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
default Framebuffer acquireBuffer() {
|
||||
return new OffscreenFramebuffer(getWidth(), getHeight());
|
||||
}
|
||||
|
||||
/**
|
||||
* Presents the given frame buffer onto this surface and releases it.
|
||||
* <p><h4>Internal use only, do not call directly!</h4>
|
||||
* @param frameBuffer the frame buffer
|
||||
*/
|
||||
void present(OffscreenFramebuffer frameBuffer);
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* Embedded surfaces usually don't interact directly with rendering API, so they have to render to an off-screen buffer, then copy
|
||||
* it onto the actual surface.
|
||||
*/
|
||||
@Override
|
||||
default void present(Framebuffer frameBuffer) {
|
||||
if (!(frameBuffer instanceof OffscreenFramebuffer offscreen)) {
|
||||
throw new UnsupportedOperationException("Unsupported frame buffer type: " + frameBuffer.getClass());
|
||||
}
|
||||
present(offscreen);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package ru.fokinatorr.sparkle.graphics.render.surface;
|
||||
|
||||
import ru.fokinatorr.sparkle.graphics.render.framebuffer.Framebuffer;
|
||||
import ru.fokinatorr.sparkle.phys2d.Point2D;
|
||||
import ru.fokinatorr.sparkle.util.NonThrowingAutoCloseable;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Represents a surface where rendering occurs (e.g. window, embedded UI element).
|
||||
* <p>Different implementations provide different capabilities.
|
||||
*/
|
||||
public interface RenderingSurface extends NonThrowingAutoCloseable {
|
||||
|
||||
// Common features
|
||||
|
||||
/**
|
||||
* Returns the width of this surface, in pixels.
|
||||
* @return the width of this surface
|
||||
*/
|
||||
int getWidth();
|
||||
|
||||
/**
|
||||
* Returns the height of this surface, in pixels.
|
||||
* @return the height of this surface
|
||||
*/
|
||||
int getHeight();
|
||||
|
||||
/**
|
||||
* Returns a vector representing dimensions of this surface, in pixels.
|
||||
* @return dimensions of this surface
|
||||
*/
|
||||
default Point2D getSize() {
|
||||
return new Point2D(getWidth(), getHeight());
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether this surface is translucent (only the rendered content is visible).
|
||||
* This is, in general, determined at creation time and may not change later.
|
||||
* @return whether this surface is translucent
|
||||
* @implNote The default implementation returns {@code false}.
|
||||
*/
|
||||
default boolean isTranslucent() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Polls input and system events.
|
||||
*/
|
||||
void pollEvents();
|
||||
|
||||
/**
|
||||
* Acquires the next available framebuffer for rendering, if any.
|
||||
* <p><h4>Internal use only, do not call directly!</h4>
|
||||
* @return an available render target or {@code null} if not available
|
||||
*/
|
||||
Framebuffer acquireBuffer();
|
||||
|
||||
/**
|
||||
* Presents the given frame buffer onto this surface and releases it.
|
||||
* <p><h4>Internal use only, do not call directly!</h4>
|
||||
* @param frameBuffer the frame buffer
|
||||
*/
|
||||
void present(Framebuffer frameBuffer);
|
||||
|
||||
/**
|
||||
* Check if this surface should close.
|
||||
* @return whether a close was requested
|
||||
*/
|
||||
boolean shouldClose();
|
||||
|
||||
/**
|
||||
* Adds a resize listener to this surface.
|
||||
*
|
||||
* @param callback the listener to call every time this surface gets resized
|
||||
*/
|
||||
void onResize(ResizeListener callback);
|
||||
|
||||
|
||||
// Conditional features
|
||||
|
||||
/**
|
||||
* {@return supported features of this surface} This can be used to check
|
||||
* whether some method will throw {@link UnsupportedOperationException}.
|
||||
*/
|
||||
Set<Feature> getFeatures();
|
||||
|
||||
/**
|
||||
* Sets the new size for this surface, if {@link Feature#RESIZABLE}
|
||||
* is supported.
|
||||
* @param newWidth the new width
|
||||
* @param newHeight the new height
|
||||
* @throws UnsupportedOperationException if not resizable
|
||||
* @see #getFeatures()
|
||||
*/
|
||||
default void setSize(int newWidth, int newHeight) {
|
||||
throw new UnsupportedOperationException("Feature.RESIZABLE not supported");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns X coordinate of the top-left corner of this surface, if {@link Feature#MOVABLE}
|
||||
* is supported.
|
||||
* @return X coordinate of the top-left corner, if supported
|
||||
* @throws UnsupportedOperationException if not movable
|
||||
* @see #getFeatures()
|
||||
*/
|
||||
default int getX() {
|
||||
throw new UnsupportedOperationException("Feature.MOVABLE not supported"); // retrieving position doesn't usually make sense if not movable
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns Y coordinate of the top-left corner of this surface, if {@link Feature#MOVABLE}
|
||||
* is supported.
|
||||
* @return Y coordinate of the top-left corner, if supported
|
||||
* @throws UnsupportedOperationException if not movable
|
||||
* @see #getFeatures()
|
||||
*/
|
||||
default int getY() {
|
||||
throw new UnsupportedOperationException("Feature.MOVABLE not supported");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns position of the top-left corner of this surface, if {@link Feature#MOVABLE}
|
||||
* is supported.
|
||||
* @return position of the top-left corner, if supported
|
||||
* @throws UnsupportedOperationException if not movable
|
||||
* @see #getFeatures()
|
||||
*/
|
||||
default Point2D getPos() {
|
||||
return new Point2D(getX(), getY());
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the position of the top-left corner of this surface, if {@link Feature#MOVABLE}
|
||||
* is supported.
|
||||
* @param newX the X coordinate of the position
|
||||
* @param newY the Y coordinate of the position
|
||||
* @throws UnsupportedOperationException if not movable
|
||||
* @see #getFeatures()
|
||||
*/
|
||||
default void setPos(int newX, int newY) {
|
||||
throw new UnsupportedOperationException("Feature.MOVABLE not supported");
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether this surface is hidden, if {@link Feature#HIDEABLE}
|
||||
* is supported.
|
||||
* @return whether this surface is hidden, is supported
|
||||
* @throws UnsupportedOperationException if not hideable
|
||||
*/
|
||||
default boolean isHidden() {
|
||||
throw new UnsupportedOperationException("Feature.HIDEABLE not supported");
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows this surface, if {@link Feature#HIDEABLE} is supported.
|
||||
* @throws UnsupportedOperationException if not hideable
|
||||
*/
|
||||
default void show() {
|
||||
throw new UnsupportedOperationException("Feature.HIDEABLE not supported");
|
||||
}
|
||||
|
||||
/**
|
||||
* Hides this surface, if {@link Feature#HIDEABLE} is supported.
|
||||
* @throws UnsupportedOperationException if not hideable
|
||||
*/
|
||||
default void hide() {
|
||||
throw new UnsupportedOperationException("Feature.HIDEABLE not supported");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of this surface, if {@link Feature#NAMEABLE} is supported.
|
||||
* @return the name of this surface, if supported
|
||||
* @throws UnsupportedOperationException if not nameable
|
||||
*/
|
||||
default String getName() {
|
||||
throw new UnsupportedOperationException("Feature.NAMEABLE not supported");
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the name for this surface, if {@link Feature#NAMEABLE} is supported.
|
||||
* @param name the new name
|
||||
* @throws UnsupportedOperationException if not nameable
|
||||
*/
|
||||
default void setName(String name) {
|
||||
throw new UnsupportedOperationException("Feature.NAMEABLE not supported");
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether this surface is in fullscreen mode, if {@link Feature#FULLSCREENABLE} is supported.
|
||||
* @return whether this surface is fullscreen, if supported
|
||||
* @throws UnsupportedOperationException if not fullscreenable
|
||||
*/
|
||||
default boolean isFullscreen() {
|
||||
throw new UnsupportedOperationException("Feature.NAMEABLE not supported");
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the fullscreen state of this surface, if {@link Feature#FULLSCREENABLE} is supported.
|
||||
* @param fullscreen whether this surface must be in fullscreen mode
|
||||
* @throws UnsupportedOperationException if not fullscreenable
|
||||
*/
|
||||
default void setFullscreen(boolean fullscreen) {
|
||||
throw new UnsupportedOperationException("Feature.NAMEABLE not supported");
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc} After calling this method, the surface instance should not be used.
|
||||
* Calling this method more than once does not have any effect.
|
||||
*/
|
||||
@Override
|
||||
void close();
|
||||
|
||||
// Inner classes
|
||||
|
||||
/**
|
||||
* Feature flags describing capabilities of this surface.
|
||||
*/
|
||||
enum Feature {
|
||||
RESIZABLE,
|
||||
MOVABLE,
|
||||
HIDEABLE,
|
||||
NAMEABLE,
|
||||
FULLSCREENABLE,
|
||||
TRANSLUCENT
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a callback listening to resize events.
|
||||
*/
|
||||
@FunctionalInterface
|
||||
interface ResizeListener {
|
||||
/**
|
||||
* Executed when a surface was resized.
|
||||
* @param surface the surface
|
||||
* @param newWidth new width of the surface
|
||||
* @param newHeight new height of the surface
|
||||
*/
|
||||
void resized(RenderingSurface surface, int newWidth, int newHeight);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package ru.fokinatorr.sparkle.graphics.render.surface;
|
||||
|
||||
import ru.fokinatorr.sparkle.graphics.GraphicsManager;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.EnumSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* A window rendering surface.
|
||||
* <p>Custom implementations of ths interface are not supported by {@link GraphicsManager}; use its
|
||||
* {@link GraphicsManager#createWindowContext createWindowContext(...)} methods to create & obtain an instance of this interface.
|
||||
* If you want to insert a stage into a UI framework's window (JavaFX, Swing, etc.) - implement {@link EmbeddedSurface} instead.
|
||||
*/
|
||||
public interface WindowSurface extends RenderingSurface {
|
||||
|
||||
@Override
|
||||
default Set<Feature> getFeatures() {
|
||||
return Collections.unmodifiableSet(EnumSet.of(
|
||||
Feature.RESIZABLE,
|
||||
Feature.MOVABLE,
|
||||
Feature.HIDEABLE,
|
||||
Feature.NAMEABLE,
|
||||
Feature.FULLSCREENABLE
|
||||
));
|
||||
}
|
||||
|
||||
@Override
|
||||
void setSize(int newWidth, int newHeight);
|
||||
|
||||
@Override
|
||||
int getX();
|
||||
|
||||
@Override
|
||||
int getY();
|
||||
|
||||
@Override
|
||||
void setPos(int newX, int newY);
|
||||
|
||||
@Override
|
||||
boolean isHidden();
|
||||
|
||||
@Override
|
||||
void show();
|
||||
|
||||
@Override
|
||||
void hide();
|
||||
|
||||
@Override
|
||||
String getName();
|
||||
|
||||
@Override
|
||||
void setName(String name);
|
||||
|
||||
@Override
|
||||
boolean isFullscreen();
|
||||
|
||||
@Override
|
||||
void setFullscreen(boolean fullscreen);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package ru.fokinatorr.sparkle.graphics.vector;
|
||||
|
||||
import ru.fokinatorr.sparkle.graphics.ARGB;
|
||||
|
||||
import java.awt.Shape;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* A vector with SVG style properties.
|
||||
* @param vector the path
|
||||
* @param strokeARGB stroke color in {@link ARGB} format
|
||||
* @param fillARGB fill color in ARGB
|
||||
* @param lineWidth stroke line width; if {@code 0}, not outlined
|
||||
*/
|
||||
public record SVGVector(
|
||||
Shape vector,
|
||||
int strokeARGB,
|
||||
int fillARGB,
|
||||
double lineWidth
|
||||
) {
|
||||
|
||||
/**
|
||||
* @throws NullPointerException if any argument is {@code null}
|
||||
* @throws IllegalArgumentException if line width is negative
|
||||
*/
|
||||
public SVGVector {
|
||||
Objects.requireNonNull(vector, "vector");
|
||||
if (lineWidth < 0) {
|
||||
throw new IllegalArgumentException("Line width must be non-negative, found: " + lineWidth);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a filled-only version of this vector.
|
||||
* @param argb the fill color
|
||||
* @return a new instance with the given style
|
||||
*/
|
||||
public SVGVector filled(int argb) {
|
||||
return new SVGVector(vector, argb, 0, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a stroked-only version of this vector.
|
||||
* @param argb the stroke color
|
||||
* @param lineWidth the line width
|
||||
* @return a new instance with the given style
|
||||
*/
|
||||
public SVGVector stroked(int argb, double lineWidth) {
|
||||
return new SVGVector(vector, 0, argb, lineWidth);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a stroked and filled version of this vector.
|
||||
* @param strokeARGB the stroke color
|
||||
* @param fillARGB the fill color
|
||||
* @param lineWidth the line width
|
||||
* @return a new instance with the given style
|
||||
*/
|
||||
public SVGVector styled(int strokeARGB, int fillARGB, double lineWidth) {
|
||||
return new SVGVector(vector, strokeARGB, fillARGB, lineWidth);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package ru.fokinatorr.sparkle.internal.access;
|
||||
|
||||
import ru.fokinatorr.sparkle.event.AbstractCancellableEvent;
|
||||
import ru.fokinatorr.sparkle.event.lifecycle.StageStateChangeEvent;
|
||||
import ru.fokinatorr.sparkle.event.lifecycle.TickEvent;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
|
||||
public interface EventLifecycleAccess {
|
||||
|
||||
/// The class in which this interface is implemented.
|
||||
Class<?> INIT = TickEvent.class;
|
||||
|
||||
StageStateChangeEvent.StartEvent newStartEvent(Stage stage);
|
||||
|
||||
StageStateChangeEvent.StopEvent newStopEvent(Stage stage);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package ru.fokinatorr.sparkle.internal.access;
|
||||
|
||||
import lombok.SneakyThrows;
|
||||
import lombok.experimental.UtilityClass;
|
||||
|
||||
import java.lang.invoke.MethodHandles;
|
||||
|
||||
/**
|
||||
* Similarly to Java's {@code jdk.internal.access.SharedSecrets}, this class is a repository of "shared secrets"
|
||||
* used to avoid reflection when calling package-private methods in bounds of this module.
|
||||
*/
|
||||
@UtilityClass
|
||||
public class SharedSecrets {
|
||||
|
||||
private final MethodHandles.Lookup lookup = MethodHandles.lookup();
|
||||
|
||||
/**
|
||||
* Accesses package-private methods of {@link ru.fokinatorr.sparkle.stage.sprite} package.
|
||||
*/
|
||||
private SpriteAccess spriteAccess;
|
||||
/**
|
||||
* Accesses package-private methods of {@link ru.fokinatorr.sparkle.stage} package.
|
||||
*/
|
||||
private StageAccess stageAccess;
|
||||
/**
|
||||
* Accesses package-private methods of {@link ru.fokinatorr.sparkle.event.lifecycle} package.
|
||||
*/
|
||||
private EventLifecycleAccess eventLifecycleAccess;
|
||||
|
||||
|
||||
@SneakyThrows(IllegalAccessException.class)
|
||||
public SpriteAccess getSpriteAccess() {
|
||||
if (spriteAccess == null) {
|
||||
lookup.ensureInitialized(SpriteAccess.INIT);
|
||||
}
|
||||
return spriteAccess;
|
||||
}
|
||||
|
||||
public void setSpriteAccess(SpriteAccess spriteAccess) {
|
||||
if (SharedSecrets.spriteAccess != null) {
|
||||
throw new IllegalStateException("spriteAccess already initialized");
|
||||
}
|
||||
SharedSecrets.spriteAccess = spriteAccess;
|
||||
}
|
||||
|
||||
@SneakyThrows(IllegalAccessException.class)
|
||||
public StageAccess getStageAccess() {
|
||||
if (stageAccess == null) {
|
||||
lookup.ensureInitialized(StageAccess.INIT);
|
||||
}
|
||||
return stageAccess;
|
||||
}
|
||||
|
||||
public void setStageAccess(StageAccess stageAccess) {
|
||||
if (SharedSecrets.stageAccess != null) {
|
||||
throw new IllegalStateException("stageAccess already initialized");
|
||||
}
|
||||
SharedSecrets.stageAccess = stageAccess;
|
||||
}
|
||||
|
||||
@SneakyThrows(IllegalAccessException.class)
|
||||
public EventLifecycleAccess getEventLifecycleAccess() {
|
||||
if (eventLifecycleAccess == null) {
|
||||
lookup.ensureInitialized(EventLifecycleAccess.INIT);
|
||||
}
|
||||
return eventLifecycleAccess;
|
||||
}
|
||||
|
||||
public void setEventLifecycleAccess(EventLifecycleAccess eventLifecycleAccess) {
|
||||
if (SharedSecrets.eventLifecycleAccess != null) {
|
||||
throw new IllegalStateException("eventLifecycleAccess already initialized");
|
||||
}
|
||||
SharedSecrets.eventLifecycleAccess = eventLifecycleAccess;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package ru.fokinatorr.sparkle.internal.access;
|
||||
|
||||
import it.unimi.dsi.fastutil.Pair;
|
||||
import ru.fokinatorr.sparkle.assets.Assets;
|
||||
import ru.fokinatorr.sparkle.effect.graphics.GraphicEffectMap;
|
||||
import ru.fokinatorr.sparkle.effect.sounds.SoundEffectMap;
|
||||
import ru.fokinatorr.sparkle.stage.RenderableID;
|
||||
import ru.fokinatorr.sparkle.stage.Stage;
|
||||
import ru.fokinatorr.sparkle.stage.sprite.Sprite;
|
||||
|
||||
public interface SpriteAccess {
|
||||
|
||||
/// The class in which this interface is implemented.
|
||||
Class<?> INIT = Sprite.class;
|
||||
|
||||
Pair<Stage, RenderableID.SpriteID> getParent(Sprite sprite);
|
||||
|
||||
void attach(Sprite sprite, Stage toStage, String spriteId, int cloneId);
|
||||
|
||||
void detach(Sprite sprite);
|
||||
|
||||
Sprite newSprite(Assets assets, GraphicEffectMap graphicEffects, SoundEffectMap soundEffects);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user