diff --git a/build.gradle b/build.gradle index 60b6c4e6..32a9da9c 100644 --- a/build.gradle +++ b/build.gradle @@ -7,16 +7,15 @@ plugins { id 'jacoco' // For publishing to Maven Central, we'll want these. - id 'maven-publish' - id 'signing' + id "com.vanniktech.maven.publish" version "0.36.0" // To be able to use Spotless in the project, this will be needed. - id "com.diffplug.spotless" version "6.9.0" + id "com.diffplug.spotless" version "7.2.1" } -group('io.github.lucasstarsz.fastj') -version('1.7.0-SNAPSHOT-2') -description('An open source, Java-based 2D game engine.') +group = 'io.github.lucasstarsz.fastj' +version = '1.7.0-SNAPSHOT' +description = 'An open source, Java-based 2D game engine.' import org.gradle.api.internal.tasks.testing.results.DefaultTestResult @@ -25,14 +24,12 @@ import org.gradle.api.internal.tasks.testing.results.DefaultTestResult * ********************* */ -sourceCompatibility = 18 -targetCompatibility = 18 -java.withSourcesJar() -java.withJavadocJar() +java.sourceCompatibility = 21 +java.targetCompatibility = 21 -javadoc.source(sourceSets.main.allJava) -javadoc.failOnError(false) -javadoc.options.links = ['https://docs.oracle.com/en/java/javase/18/docs/api/', 'https://www.slf4j.org/apidocs/'] +javadoc.source = sourceSets.main.allJava +javadoc.failOnError = false +javadoc.options.links = ['https://docs.oracle.com/en/java/javase/21/docs/api/', 'https://www.slf4j.org/apidocs/'] javadoc.options.stylesheetFile = file("${projectDir}/src/fastjstyle.css") javadoc.doLast { copy { @@ -42,17 +39,12 @@ javadoc.doLast { } } -sourcesJar.from(sourceSets.main.allSource) -javadocJar.from(javadoc.destinationDir) -artifacts.archives(sourcesJar) -artifacts.archives(javadocJar) - // Java modules need this in order for the module path to be inferred based on module-info.java files. plugins.withType(JavaPlugin).configureEach { java.modularity.inferModulePath = true } -wrapper.gradleVersion = '7.5.1' +wrapper.gradleVersion = '8.14.3' wrapper.distributionType = Wrapper.DistributionType.ALL repositories.mavenCentral() @@ -73,28 +65,25 @@ dependencies.testRuntimeOnly("org.junit.platform:junit-platform-launcher") * ********************* */ -tasks.withType(Test) { +tasks.withType(Test).configureEach { useJUnitPlatform() - testLogging { - - def totalTestTime = 0 + def totalTestTime = 0 - afterTest { desc, DefaultTestResult result -> - totalTestTime += result.endTime - result.startTime - } + afterTest { desc, DefaultTestResult result -> + totalTestTime += result.endTime - result.startTime + } - afterSuite { desc, DefaultTestResult result -> - if (!desc.parent) { // will match the outermost suite - def passFailSkip = "$result.successfulTestCount passed, $result.failedTestCount failed, $result.skippedTestCount skipped" - def results = "Test Suite Results: $result.resultType ($result.testCount tests, $passFailSkip) in $totalTestTime ms." + afterSuite { desc, DefaultTestResult result -> + if (!desc.parent) { // will match the outermost suite + def passFailSkip = "$result.successfulTestCount passed, $result.failedTestCount failed, $result.skippedTestCount skipped" + def results = "Test Suite Results: $result.resultType ($result.testCount tests, $passFailSkip) in $totalTestTime ms." - def startItem = '| ' - def endItem = ' |' - def repeatLength = startItem.length() + results.length() + endItem.length() - def dashes = '-' * repeatLength + def startItem = '| ' + def endItem = ' |' + def repeatLength = startItem.length() + results.length() + endItem.length() + def dashes = '-' * repeatLength - logger.info(String.format('%n%n%s%n%s%s%s%n%s%n%n', dashes, startItem, results, endItem, dashes)) - } + logger.info(String.format('%n%n%s%n%s%s%s%n%s%n%n', dashes, startItem, results, endItem, dashes)) } } } @@ -134,7 +123,7 @@ jacocoTestReport { dependsOn(test) // tests are required to run before generating the report reports.xml.required.set(true) reports.csv.required.set(false) - reports.xml.destination(layout.buildDirectory.dir('build/reports/jacoco/test/jacocoTestReport.xml').get().asFile) + reports.xml.outputLocation = layout.buildDirectory.dir('build/reports/jacoco/test/jacocoTestReport.xml').get().asFile } @@ -142,56 +131,36 @@ jacocoTestReport { * Publishing * * ********************* */ - -def shouldPublish = System.getenv('ossrhUsername') != null && System.getenv('ossrhPassword') != null -publish.onlyIf { shouldPublish } - -if (shouldPublish) { - publishing.publications { - fastjPublish(MavenPublication) { - - groupId = project.group - version = project.version - artifactId = 'fastj-library' - - pom { - name = 'FastJ Game Library' - description = project.description - url = 'https://github.com/fastjengine/FastJ' - - scm { - connection = 'scm:git:https://github.com/fastjengine/FastJ.git' - developerConnection = 'scm:git:https://github.com/fastjengine/FastJ.git' - url = 'https://fastj.tech' - } - - licenses { - license { - name = 'MIT License' - url = 'https://github.com/fastjengine/FastJ/blob/main/LICENSE.txt' - } - } - - developers { - developer { - id = 'andrewd' - name = 'Andrew Dey' - email = 'andrewrcdey@gmail.com' - } - } +mavenPublishing { + publishToMavenCentral() + signAllPublications() + coordinates("io.github.lucasstarsz.fastj", "fastj-library", project.version as String) + + pom { + name = 'FastJ Game Library' + description = 'An open source, Java-based 2D game engine.' + inceptionYear = "2020" + url = 'https://github.com/fastjengine/FastJ' + + licenses { + license { + name = 'MIT License' + url = 'https://github.com/fastjengine/FastJ/blob/main/LICENSE.txt' + distribution = 'https://github.com/fastjengine/FastJ/blob/main/LICENSE.txt' } - - from(components.java) + } + developers { + developer { + id = 'andrewd' + name = 'Andrew Dey' + email = 'andrewrcdey@gmail.com' + url = 'https://github.com' + } + } + scm { + connection = 'scm:git:https://github.com/fastjengine/FastJ.git' + developerConnection = 'scm:git:https://github.com/fastjengine/FastJ.git' + url = 'https://fastj.tech' } } - - publishing.repositories.maven { - url = 'https://oss.sonatype.org/service/local/staging/deploy/maven2/' - credentials.username = System.getenv('ossrhUsername') - credentials.password = System.getenv('ossrhPassword') - } - - signing { - sign publishing.publications.fastjPublish - } -} \ No newline at end of file +} diff --git a/examples/build.gradle b/examples/build.gradle index 36499ac7..81ef0ee6 100644 --- a/examples/build.gradle +++ b/examples/build.gradle @@ -4,12 +4,12 @@ plugins { id 'java' } -group('io.github.lucasstarsz.fastj') -version('1.7.0-SNAPSHOT') -description('Example programs for the FastJ Game Engine.') +group = 'io.github.lucasstarsz.fastj' +version = '1.7.0-SNAPSHOT' +description = 'Example programs for the FastJ Game Engine.' -sourceCompatibility = 18 -targetCompatibility = 18 +java.sourceCompatibility = 21 +java.targetCompatibility = 21 repositories { mavenCentral() @@ -23,7 +23,7 @@ sourceSets { main.resources.srcDirs = ['resources'] } -task run(type: Exec) { +tasks.register('run', Exec) { doFirst { if (!project.hasProperty('toRun')) { throw new IllegalArgumentException( diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e708b1c0..249e5832 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 8fad3f5a..e69d0402 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-all.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 4f906e0c..a69d9cb6 100644 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,67 +17,101 @@ # ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` +APP_BASE_NAME=${0##*/} # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar @@ -87,9 +121,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" + JAVACMD=java which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the @@ -106,80 +140,101 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 107acd32..f127cfd4 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -14,7 +14,7 @@ @rem limitations under the License. @rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +25,7 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,7 +40,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -75,13 +75,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/src/main/java/tech/fastj/engine/FastJEngine.java b/src/main/java/tech/fastj/engine/FastJEngine.java index 5768270c..17338518 100644 --- a/src/main/java/tech/fastj/engine/FastJEngine.java +++ b/src/main/java/tech/fastj/engine/FastJEngine.java @@ -831,7 +831,7 @@ private static void initEngine() { GameLoop.setTargetFPS(targetFPS); GameLoop.setTargetUPS(targetUPS); - GameLoop.addEventObserver(RunLaterObserver, RunLaterEvent.class); + GameLoop.addEventObserver(RunLaterEvent.class, RunLaterObserver); AudioManager.init(); @@ -920,7 +920,7 @@ private static void exit() { isRunning = false; // Helpful? Debatable. Do I care? Not yet.... - System.gc(); +// System.gc(); } /** diff --git a/src/main/java/tech/fastj/gameloop/GameLoop.java b/src/main/java/tech/fastj/gameloop/GameLoop.java index 3ee7caa6..dd2bc58f 100644 --- a/src/main/java/tech/fastj/gameloop/GameLoop.java +++ b/src/main/java/tech/fastj/gameloop/GameLoop.java @@ -1,13 +1,18 @@ package tech.fastj.gameloop; import tech.fastj.gameloop.event.Event; +import tech.fastj.gameloop.event.EventBinding; import tech.fastj.gameloop.event.EventHandler; import tech.fastj.gameloop.event.EventObserver; +import tech.fastj.gameloop.event.EventObserverCombo; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Predicate; +import java.util.stream.Collectors; /** * Game loop made up of game states, such that you can create and configure your own custom game loop. @@ -97,8 +102,8 @@ public class GameLoop implements Runnable { ); private final Map> nextEvents; - private final Map, List>> gameEventObservers; - private final Map, EventHandler>> gameEventHandlers; + private final Map, List>> eventObservers; + private final Map, EventHandler>> eventHandlers; private final Map, Class> classAliases; private GameLoopState currentGameLoopState; @@ -122,11 +127,11 @@ public GameLoop(Predicate shouldRun, Predicate shouldSync) { this.syncCondition = Objects.requireNonNull(shouldSync); isRunning = false; - nextLoopStates = new ArrayDeque<>(); - nextEvents = new HashMap<>(); - gameEventObservers = new HashMap<>(); - gameEventHandlers = new HashMap<>(); - classAliases = new HashMap<>(); + nextLoopStates = new ConcurrentLinkedDeque<>(); + nextEvents = new ConcurrentHashMap<>(); + eventObservers = new ConcurrentHashMap<>(); + eventHandlers = new ConcurrentHashMap<>(); + classAliases = new ConcurrentHashMap<>(); currentGameLoopState = NoState; fixedUpdateInterval = new AtomicReference<>(); @@ -141,9 +146,7 @@ public GameLoop(Predicate shouldRun, Predicate shouldSync) { */ public void addGameLoopStates(GameLoopState... gameLoopStates) { if (isRunning) { - synchronized (nextLoopStates) { - nextLoopStates.addAll(Arrays.asList(gameLoopStates)); - } + nextLoopStates.addAll(Arrays.asList(gameLoopStates)); } else { for (GameLoopState gameLoopState : gameLoopStates) { this.gameLoopStates.get(gameLoopState.getCoreLoopState()).add(gameLoopState); @@ -158,9 +161,7 @@ public void addGameLoopStates(GameLoopState... gameLoopStates) { */ public void addGameLoopState(GameLoopState gameLoopState) { if (isRunning) { - synchronized (nextLoopStates) { - nextLoopStates.add(gameLoopState); - } + nextLoopStates.add(gameLoopState); } else { this.gameLoopStates.get(gameLoopState.getCoreLoopState()).add(gameLoopState); } @@ -169,47 +170,54 @@ public void addGameLoopState(GameLoopState gameLoopState) { /** * Adds the given event observer which observes the given class. * - * @param eventObserver The {@link EventObserver event observer} + * @param The type of {@link Event event} observed. * @param eventClass The class the event observer observes. + * @param eventObserver The {@link EventObserver event observer} + */ + public void addEventObserver(Class eventClass, EventObserver eventObserver) { + addEventObserver(eventClass, (event) -> true, eventObserver); + } + + /** + * Adds the given event observer which observes the given class. + * * @param The type of {@link Event event} observed. + * @param eventClass The class the event observer observes. + * @param eventObserver The {@link EventObserver event observer} */ - public void addEventObserver(EventObserver eventObserver, Class eventClass) { - synchronized (gameEventObservers) { - if (!gameEventObservers.containsKey(eventClass)) { - gameEventObservers.put(eventClass, new ArrayList<>()); - } - gameEventObservers.get(eventClass).add(eventObserver); + public void addEventObserver(Class eventClass, EventBinding eventBinding, EventObserver eventObserver) { + if (!eventObservers.containsKey(eventClass)) { + eventObservers.put(eventClass, new ArrayList<>()); } + + eventObservers.get(eventClass).add(new EventObserverCombo<>(eventObserver, eventBinding)); } /** * Removes the given event observer which observed the given class. * - * @param eventObserver The {@link EventObserver event observer} - * @param eventClass The class the event observer observed. * @param The type of {@link Event event} observed. + * @param eventClass The class the event observer observed. + * @param eventObserver The {@link EventObserver event observer} */ - public void removeEventObserver(EventObserver eventObserver, Class eventClass) { - if (!gameEventObservers.containsKey(eventClass)) { + public void removeEventObserver(Class eventClass, EventObserver eventObserver) { + if (!eventObservers.containsKey(eventClass)) { return; } - synchronized (gameEventObservers) { - gameEventObservers.get(eventClass).remove(eventObserver); - } + + eventObservers.get(eventClass).removeIf(combo -> combo.eventObserver().equals(eventObserver)); } /** * Adds the given event handler, to handle events received for the given event class. * - * @param gameEventHandler The {@link EventHandler event handler} to add. - * @param eventClass The class the event handler handles. * @param The type of {@link Event} handled. * @param The type of the event handler, based on the event type. + * @param eventClass The class the event handler handles. + * @param gameEventHandler The {@link EventHandler event handler} to add. */ - public >> void addEventHandler(V gameEventHandler, Class eventClass) { - synchronized (gameEventHandlers) { - gameEventHandlers.put(eventClass, gameEventHandler); - } + public >> void addEventHandler(Class eventClass, V gameEventHandler) { + eventHandlers.put(eventClass, gameEventHandler); } /** @@ -219,9 +227,7 @@ public >> void addEv * @param The type of {@link Event} handled. */ public void removeEventHandler(Class eventClass) { - synchronized (gameEventHandlers) { - gameEventHandlers.remove(eventClass); - } + eventHandlers.remove(eventClass); } /** @@ -338,8 +344,8 @@ public void setTargetUPS(int ups) { * @param eventClass The event class to get event observers for. * @param The type of {@link Event} */ - public List> getEventObservers(Class eventClass) { - return gameEventObservers.getOrDefault(eventClass, List.of()); + public List> getEventObservers(Class eventClass) { + return eventObservers.getOrDefault(eventClass, List.of()); } /** @@ -351,7 +357,7 @@ public List> getEventObservers( */ @SuppressWarnings("unchecked") public > EventHandler getEventHandler(Class eventClass) { - return (EventHandler) gameEventHandlers.get(eventClass); + return (EventHandler) eventHandlers.get(eventClass); } /** {@return all of the game loop's states} */ @@ -398,24 +404,33 @@ public void fireEvent(T event) { @SuppressWarnings("unchecked") private void tryFireEvent(T event, Class eventClass) { - var gameEventHandler = (EventHandler>) gameEventHandlers.get(eventClass); + var gameEventHandler = (EventHandler>) eventHandlers.get(eventClass); if (gameEventHandler != null) { - ((EventHandler) gameEventHandler).handleEvent(gameEventObservers.get(eventClass), event); + ((EventHandler) gameEventHandler).handleEvent( + eventObservers.getOrDefault(eventClass, List.of()) + .stream() + .map(EventObserverCombo::eventObserver) + .collect(Collectors.toList()), + event + ); + return; } - List> eventObservers = gameEventObservers.get(eventClass); + List> eventObservers = this.eventObservers.get(eventClass); if (eventObservers == null) { - gameEventObservers.put(eventClass, new ArrayList<>()); - eventObservers = gameEventObservers.get(eventClass); + this.eventObservers.put(eventClass, new ArrayList<>()); + eventObservers = this.eventObservers.get(eventClass); } - if (gameEventObservers.get(eventClass).isEmpty()) { + if (this.eventObservers.get(eventClass).isEmpty()) { return; } for (var gameEventObserver : eventObservers) { - ((EventObserver) gameEventObserver).eventReceived(event); + if (((EventBinding) gameEventObserver.eventBinding()).isRelevant(event)) { + ((EventObserver) gameEventObserver.eventObserver()).eventReceived(event); + } } } @@ -427,12 +442,11 @@ private void tryFireEvent(T event, Class eventClass) { * @param The class of the {@link Event event}. */ public void fireEvent(T event, GameLoopState whenToFire) { - synchronized (nextEvents) { - if (nextEvents.get(whenToFire) == null) { - nextEvents.put(whenToFire, new ArrayDeque<>()); - } - nextEvents.get(whenToFire).add(event); + if (nextEvents.get(whenToFire) == null) { + nextEvents.put(whenToFire, new ArrayDeque<>()); } + + nextEvents.get(whenToFire).add(event); } /** @@ -443,9 +457,7 @@ public void fireEvent(T event, GameLoopState whenToFire) { * @param The class of the {@link Event event}. */ public void fireEvent(T event, CoreLoopState whenToFire) { - synchronized (nextCoreEvents) { - nextCoreEvents.get(whenToFire).add(event); - } + nextCoreEvents.get(whenToFire).add(event); } /** Runs the game loop, setting {@link #isRunning()} to {@code true}. */ @@ -466,27 +478,26 @@ public synchronized void run() { accumulator += elapsedTime; if (!nextLoopStates.isEmpty()) { - synchronized (nextLoopStates) { - for (GameLoopState nextLoopState : nextLoopStates) { - gameLoopStates.get(nextLoopState.getCoreLoopState()).add(nextLoopState); - synchronized (nextEvents) { - nextEvents.computeIfAbsent(nextLoopState, gameLoopState -> new ArrayDeque<>()); - } - } - nextLoopStates.clear(); + for (GameLoopState nextLoopState : nextLoopStates) { + gameLoopStates.get(nextLoopState.getCoreLoopState()).add(nextLoopState); + nextEvents.computeIfAbsent(nextLoopState, gameLoopState -> new ArrayDeque<>()); } + + nextLoopStates.clear(); } runGameLoopStates(CoreLoopState.EarlyUpdate, elapsedTime); fireNextCoreEvents(CoreLoopState.EarlyUpdate); - while (accumulator >= fixedUpdateInterval.get()) { + int fixedUpdateRunCount = 0; + while (accumulator >= fixedUpdateInterval.get() && fixedUpdateRunCount < targetUPS) { elapsedFixedTime = fixedDeltaTimer.evalDeltaTime(); runGameLoopStates(CoreLoopState.FixedUpdate, elapsedFixedTime); fireNextCoreEvents(CoreLoopState.FixedUpdate); accumulator -= elapsedFixedTime; + fixedUpdateRunCount++; } runGameLoopStates(CoreLoopState.Update, elapsedTime); @@ -514,15 +525,11 @@ private void runGameLoopStates(CoreLoopState coreLoopState, float elapsedFixedTi } private void fireNextCoreEvents(CoreLoopState coreLoopState) { - synchronized (nextCoreEvents) { - fireNextEvents(nextCoreEvents.get(coreLoopState)); - } + fireNextEvents(nextCoreEvents.get(coreLoopState)); } private void fireNextEvents(GameLoopState gameLoopState) { - synchronized (nextEvents) { - fireNextEvents(nextEvents.get(gameLoopState)); - } + fireNextEvents(nextEvents.get(gameLoopState)); } private void fireNextEvents(Queue gameEvents) { @@ -569,7 +576,7 @@ public void reset() { /** Clears the game loop's events, observers, and handlers. */ public void clearEventSystem() { nextEvents.clear(); - gameEventObservers.clear(); - gameEventHandlers.clear(); + eventObservers.clear(); + eventHandlers.clear(); } } diff --git a/src/main/java/tech/fastj/gameloop/event/EventBinding.java b/src/main/java/tech/fastj/gameloop/event/EventBinding.java new file mode 100644 index 00000000..db9234a3 --- /dev/null +++ b/src/main/java/tech/fastj/gameloop/event/EventBinding.java @@ -0,0 +1,6 @@ +package tech.fastj.gameloop.event; + +@FunctionalInterface +public interface EventBinding { + boolean isRelevant(T event); +} diff --git a/src/main/java/tech/fastj/gameloop/event/EventHandler.java b/src/main/java/tech/fastj/gameloop/event/EventHandler.java index 7d7fcbd5..5a017b7d 100644 --- a/src/main/java/tech/fastj/gameloop/event/EventHandler.java +++ b/src/main/java/tech/fastj/gameloop/event/EventHandler.java @@ -8,7 +8,7 @@ /** * Handler of {@link Event events} and their {@link EventObserver observers} for the {@link GameLoop game loop}. *

- * Event handling is a callback feature -- once {@link GameLoop#addEventHandler(EventHandler, Class) added}, it allows you to + * Event handling is a callback feature -- once {@link GameLoop#addEventHandler(Class, EventHandler) added}, it allows you to * {@link #handleEvents(List, Queue) handle} events and observers of the registered types {@code T} and {@code V}. * * @param The type of {@link Event event} to handle. diff --git a/src/main/java/tech/fastj/gameloop/event/EventObserver.java b/src/main/java/tech/fastj/gameloop/event/EventObserver.java index 82057724..92b5760b 100644 --- a/src/main/java/tech/fastj/gameloop/event/EventObserver.java +++ b/src/main/java/tech/fastj/gameloop/event/EventObserver.java @@ -5,7 +5,7 @@ /** * Observer of {@link Event events} for the {@link GameLoop game loop}. *

- * Event observing is a callback feature -- once {@link GameLoop#addEventObserver(EventObserver, Class) added}, it allows you to + * Event observing is a callback feature -- once {@link GameLoop#addEventObserver(Class, EventObserver) added}, it allows you to * {@link #eventReceived(Event) receive} events of the registered type {@code T}. * * @param The type of {@link Event event} to observe. diff --git a/src/main/java/tech/fastj/gameloop/event/EventObserverCombo.java b/src/main/java/tech/fastj/gameloop/event/EventObserverCombo.java new file mode 100644 index 00000000..cb1d11b3 --- /dev/null +++ b/src/main/java/tech/fastj/gameloop/event/EventObserverCombo.java @@ -0,0 +1,3 @@ +package tech.fastj.gameloop.event; + +public record EventObserverCombo(EventObserver eventObserver, EventBinding eventBinding) {} diff --git a/src/main/java/tech/fastj/graphics/Drawable.java b/src/main/java/tech/fastj/graphics/Drawable.java index 6d4b105d..e6fb6406 100644 --- a/src/main/java/tech/fastj/graphics/Drawable.java +++ b/src/main/java/tech/fastj/graphics/Drawable.java @@ -106,7 +106,13 @@ public UUID getUUID() { * @return The {@code Pointf} array that contains the bounds of the {@code Drawable}. */ public Pointf[] getBounds() { - return DrawUtil.createBox((Rectangle2D.Float) transformedCollisionPath.getBounds2D()); + Rectangle2D transformedCollisionBounds = transformedCollisionPath.getBounds2D(); + return DrawUtil.createBox(new Rectangle2D.Float( + (float) transformedCollisionBounds.getX(), + (float) transformedCollisionBounds.getY(), + (float) transformedCollisionBounds.getWidth(), + (float) transformedCollisionBounds.getHeight() + )); } /** diff --git a/src/main/java/tech/fastj/graphics/display/SimpleDisplay.java b/src/main/java/tech/fastj/graphics/display/SimpleDisplay.java index 1ba00c2e..f7c3f1a2 100644 --- a/src/main/java/tech/fastj/graphics/display/SimpleDisplay.java +++ b/src/main/java/tech/fastj/graphics/display/SimpleDisplay.java @@ -1,7 +1,6 @@ package tech.fastj.graphics.display; import tech.fastj.engine.FastJEngine; -import tech.fastj.gameloop.CoreLoopState; import tech.fastj.math.Point; import java.awt.GraphicsEnvironment; @@ -10,7 +9,6 @@ import java.awt.event.ComponentEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; -import java.util.concurrent.TimeUnit; import javax.swing.JFrame; @@ -71,16 +69,7 @@ public void windowClosing(WindowEvent windowEvent) { DisplayEvent displayEvent = new DisplayEvent<>(DisplayEventType.Closing, windowEvent, display); FastJEngine.getGameLoop().fireEvent(displayEvent); - // TODO: find out why this only works as intended during FixedUpdate - while (FastJEngine.getGameLoop().getCurrentGameLoopState().getCoreLoopState() != CoreLoopState.FixedUpdate) { - try { - TimeUnit.MILLISECONDS.sleep(1L); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } - - FastJEngine.runLater(FastJEngine::closeGame); + close(); } @Override diff --git a/src/main/java/tech/fastj/graphics/ui/elements/Button.java b/src/main/java/tech/fastj/graphics/ui/elements/Button.java index 1033814f..dc66d457 100644 --- a/src/main/java/tech/fastj/graphics/ui/elements/Button.java +++ b/src/main/java/tech/fastj/graphics/ui/elements/Button.java @@ -244,7 +244,14 @@ private void setMetrics(Graphics2D g) { int textWidth = fm.stringWidth(text); int textHeight = fm.getHeight(); - Rectangle2D.Float renderPathBounds = (Rectangle2D.Float) collisionPath.getBounds2D(); + + Rectangle2D collisionPathBounds = collisionPath.getBounds2D(); + Rectangle2D.Float renderPathBounds = new Rectangle2D.Float( + (float) collisionPathBounds.getX(), + (float) collisionPathBounds.getY(), + (float) collisionPathBounds.getWidth(), + (float) collisionPathBounds.getHeight() + ); textBounds = new Rectangle2D.Float( (renderPathBounds.width - textWidth) / 2f, @@ -253,7 +260,14 @@ private void setMetrics(Graphics2D g) { textHeight ); - Rectangle2D.Float newPathBounds = (Rectangle2D.Float) super.collisionPath.getBounds2D(); + Rectangle2D parentCollisionPathBounds = super.collisionPath.getBounds2D(); + Rectangle2D.Float newPathBounds = new Rectangle2D.Float( + (float) parentCollisionPathBounds.getX(), + (float) parentCollisionPathBounds.getY(), + (float) parentCollisionPathBounds.getWidth(), + (float) parentCollisionPathBounds.getHeight() + ); + if (renderPathBounds.width < textBounds.width) { float diff = (textBounds.width - renderPathBounds.width) / 2f; newPathBounds.width = textBounds.width + diff; diff --git a/src/main/java/tech/fastj/input/InputManager.java b/src/main/java/tech/fastj/input/InputManager.java index af68654e..1375efb9 100644 --- a/src/main/java/tech/fastj/input/InputManager.java +++ b/src/main/java/tech/fastj/input/InputManager.java @@ -1,6 +1,7 @@ package tech.fastj.input; import tech.fastj.engine.FastJEngine; +import tech.fastj.gameloop.event.EventObserverCombo; import tech.fastj.graphics.display.FastJCanvas; import tech.fastj.input.keyboard.Keyboard; import tech.fastj.input.keyboard.KeyboardActionListener; @@ -12,6 +13,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.stream.Collectors; /** * Class to manage user input and input event processing. @@ -39,7 +41,10 @@ public InputManager() { */ @SuppressWarnings("unchecked") public List getKeyboardActionListeners() { - return (List) FastJEngine.getGameLoop().getEventObservers(KeyboardActionEvent.class); + return (List) FastJEngine.getGameLoop().getEventObservers(KeyboardActionEvent.class) + .stream() + .map(EventObserverCombo::eventObserver) + .collect(Collectors.toList()); } /** @@ -49,7 +54,10 @@ public List getKeyboardActionListeners() { */ @SuppressWarnings("unchecked") public List getMouseActionListeners() { - return (List) FastJEngine.getGameLoop().getEventObservers(MouseActionEvent.class); + return (List) FastJEngine.getGameLoop().getEventObservers(MouseActionEvent.class) + .stream() + .map(EventObserverCombo::eventObserver) + .collect(Collectors.toList()); } /* Key Action Listeners */ @@ -63,7 +71,7 @@ public List getMouseActionListeners() { */ public void addKeyboardActionListener(KeyboardActionListener listener) { keyboardActionListeners.add(listener); - FastJEngine.getGameLoop().addEventObserver(listener, KeyboardActionEvent.class); + FastJEngine.getGameLoop().addEventObserver(KeyboardActionEvent.class, listener); } /** @@ -73,7 +81,7 @@ public void addKeyboardActionListener(KeyboardActionListener listener) { */ public void removeKeyboardActionListener(KeyboardActionListener listener) { keyboardActionListeners.remove(listener); - FastJEngine.getGameLoop().removeEventObserver(listener, KeyboardActionEvent.class); + FastJEngine.getGameLoop().removeEventObserver(KeyboardActionEvent.class, listener); } /** Fires a {@code keys down} event to all listening {@link KeyboardActionListener keyboard action listeners}. */ @@ -96,7 +104,7 @@ public void fireKeysDown() { */ public void addMouseActionListener(MouseActionListener listener) { mouseActionListeners.add(listener); - FastJEngine.getGameLoop().addEventObserver(listener, MouseActionEvent.class); + FastJEngine.getGameLoop().addEventObserver(MouseActionEvent.class, listener); } /** @@ -106,7 +114,7 @@ public void addMouseActionListener(MouseActionListener listener) { */ public void removeMouseActionListener(MouseActionListener listener) { mouseActionListeners.remove(listener); - FastJEngine.getGameLoop().removeEventObserver(listener, MouseActionEvent.class); + FastJEngine.getGameLoop().removeEventObserver(MouseActionEvent.class, listener); } /** @@ -123,10 +131,10 @@ public void load() { } for (MouseActionListener mouseActionListener : mouseActionListeners) { - FastJEngine.getGameLoop().addEventObserver(mouseActionListener, MouseActionEvent.class); + FastJEngine.getGameLoop().addEventObserver(MouseActionEvent.class, mouseActionListener); } for (KeyboardActionListener keyboardActionListener : keyboardActionListeners) { - FastJEngine.getGameLoop().addEventObserver(keyboardActionListener, KeyboardActionEvent.class); + FastJEngine.getGameLoop().addEventObserver(KeyboardActionEvent.class, keyboardActionListener); } isLoaded = true; } @@ -143,10 +151,10 @@ public void unload() { return; } for (MouseActionListener mouseActionListener : mouseActionListeners) { - FastJEngine.getGameLoop().removeEventObserver(mouseActionListener, MouseActionEvent.class); + FastJEngine.getGameLoop().removeEventObserver(MouseActionEvent.class, mouseActionListener); } for (KeyboardActionListener keyboardActionListener : keyboardActionListeners) { - FastJEngine.getGameLoop().removeEventObserver(keyboardActionListener, KeyboardActionEvent.class); + FastJEngine.getGameLoop().removeEventObserver(KeyboardActionEvent.class, keyboardActionListener); } isLoaded = false; } diff --git a/src/main/java/tech/fastj/resources/files/FileUtil.java b/src/main/java/tech/fastj/resources/files/FileUtil.java index 2ce684e5..302603c1 100644 --- a/src/main/java/tech/fastj/resources/files/FileUtil.java +++ b/src/main/java/tech/fastj/resources/files/FileUtil.java @@ -31,8 +31,23 @@ private FileUtil() { * @return The {@code Path}'s file extension. */ public static String getFileExtension(Path filePath) { - if (filePath.toString().contains(".")) { - return filePath.toString().substring(filePath.toString().lastIndexOf(".") + 1); + return getFileExtension(filePath.toString()); + } + + /** + * Gets the file extension of the specified path. + *

+ * This method does not account for file extensions with more than one dot ({@code .}) -- in cases like those, only the last part + * of the extension will be returned. + *

+ * For paths which contain no file extension, an empty {@code String} will be returned. + * + * @param filePath The {@code Path} to get the file extension of. + * @return The {@code Path}'s file extension. + */ + public static String getFileExtension(String filePath) { + if (filePath.contains(".")) { + return filePath.substring(filePath.lastIndexOf(".") + 1); } return ""; } diff --git a/src/main/java/tech/fastj/resources/models/MtlUtil.java b/src/main/java/tech/fastj/resources/models/MtlUtil.java index b0780e1c..c2e45cac 100644 --- a/src/main/java/tech/fastj/resources/models/MtlUtil.java +++ b/src/main/java/tech/fastj/resources/models/MtlUtil.java @@ -78,7 +78,8 @@ public static void parse(Polygon2D polygon, Path materialPath, String materialNa case ParsingKeys.NewMaterial -> { return; } - case ParsingKeys.DiffuseColor, ParsingKeys.SpecularColor, ParsingKeys.SpecularExponent, ParsingKeys.Empty -> { + case ParsingKeys.DiffuseColor, ParsingKeys.SpecularColor, ParsingKeys.SpecularExponent, ParsingKeys.IlluminationMode, + ParsingKeys.Empty -> { } default -> Log.warn(ObjUtil.class, "Unused parsing key: \"{}\"", tokens[0]); } diff --git a/src/main/java/tech/fastj/resources/models/ObjUtil.java b/src/main/java/tech/fastj/resources/models/ObjUtil.java index 7cf263f1..ac8e3926 100644 --- a/src/main/java/tech/fastj/resources/models/ObjUtil.java +++ b/src/main/java/tech/fastj/resources/models/ObjUtil.java @@ -87,7 +87,8 @@ public static Polygon2D[] parse(Path modelPath, List lines) { // material names in .obj files cannot contain spaces, allowing us to use a // non-robust solution. case ParsingKeys.UseMaterial -> currentMaterial = tokens[1]; - case ParsingKeys.Empty -> { + // unused + case ParsingKeys.VertexTexture, ParsingKeys.ObjectName, ParsingKeys.Empty -> { } default -> Log.warn(ObjUtil.class, "Unrecognized parsing key: \"{}\"", tokens[0]); } diff --git a/src/main/java/tech/fastj/systems/audio/AudioEventListener.java b/src/main/java/tech/fastj/systems/audio/AudioEventListener.java index 67a7976c..9f636581 100644 --- a/src/main/java/tech/fastj/systems/audio/AudioEventListener.java +++ b/src/main/java/tech/fastj/systems/audio/AudioEventListener.java @@ -98,7 +98,7 @@ public class AudioEventListener implements EventObserver { */ AudioEventListener(Audio audio) { this.audio = Objects.requireNonNull(audio); - FastJEngine.getGameLoop().addEventObserver(this, AudioEvent.class); + FastJEngine.getGameLoop().addEventObserver(AudioEvent.class, this); } /** {@return the "audio open" event action} */ diff --git a/src/main/java/tech/fastj/systems/audio/AudioManager.java b/src/main/java/tech/fastj/systems/audio/AudioManager.java index a512d1fc..53a0f76f 100644 --- a/src/main/java/tech/fastj/systems/audio/AudioManager.java +++ b/src/main/java/tech/fastj/systems/audio/AudioManager.java @@ -86,7 +86,7 @@ public static void playSound(URL audioPath) { /** Initializes the audio manager to be ready to handle audio events. */ public void init() { - FastJEngine.getGameLoop().addEventHandler(this, AudioEvent.class); + FastJEngine.getGameLoop().addEventHandler(AudioEvent.class, this); } /** diff --git a/src/main/java/tech/fastj/systems/audio/StreamedAudio.java b/src/main/java/tech/fastj/systems/audio/StreamedAudio.java index d18622f5..89becb88 100644 --- a/src/main/java/tech/fastj/systems/audio/StreamedAudio.java +++ b/src/main/java/tech/fastj/systems/audio/StreamedAudio.java @@ -141,7 +141,7 @@ private void initializeStreamData(boolean resetInputStream) { transferStopAction = audioEventListener.getAudioStopAction(); transferPauseAction = audioEventListener.getAudioPauseAction(); transferResumeAction = audioEventListener.getAudioResumeAction(); - FastJEngine.getGameLoop().removeEventObserver(audioEventListener, AudioEvent.class); + FastJEngine.getGameLoop().removeEventObserver(AudioEvent.class, audioEventListener); } audioEventListener = new AudioEventListener(this); diff --git a/src/test/java/unittest/testcases/gameloop/GameLoopTests.java b/src/test/java/unittest/testcases/gameloop/GameLoopTests.java index 6a1a0a6d..9145a312 100644 --- a/src/test/java/unittest/testcases/gameloop/GameLoopTests.java +++ b/src/test/java/unittest/testcases/gameloop/GameLoopTests.java @@ -97,10 +97,10 @@ void checkGameLoopRemovesEventObservers_shouldNotFail() { GameLoop gameLoop = new GameLoop((gl) -> shouldRemainOpen.get(), (gl) -> false); EventObserver eventObserver = (event) -> firedEvent.set(true); - gameLoop.addEventObserver(eventObserver, MockEvent.class); - assertEquals(eventObserver, gameLoop.getEventObservers(MockEvent.class).get(0)); + gameLoop.addEventObserver(MockEvent.class, eventObserver); + assertEquals(eventObserver, gameLoop.getEventObservers(MockEvent.class).get(0).eventObserver()); assertEquals(1, gameLoop.getEventObservers(MockEvent.class).size()); - gameLoop.removeEventObserver(eventObserver, MockEvent.class); + gameLoop.removeEventObserver(MockEvent.class, eventObserver); gameLoop.addGameLoopState(new GameLoopState(CoreLoopState.Update, 1, (gl, deltaTime) -> gameLoop.fireEvent(new MockEvent()))); gameLoop.addGameLoopState(new GameLoopState(CoreLoopState.LateUpdate, 1, (gl, deltaTime) -> shouldRemainOpen.set(false))); @@ -116,7 +116,7 @@ void checkGameLoopRemovesEventHandlers_shouldNotFail() { GameLoop gameLoop = new GameLoop((gl) -> shouldRemainOpen.get(), (gl) -> false); EventHandler> eventHandler = (eventObservers, event) -> firedEvent.set(true); - gameLoop.addEventHandler(eventHandler, MockEvent.class); + gameLoop.addEventHandler(MockEvent.class, eventHandler); assertEquals(eventHandler, gameLoop.getEventHandler(MockEvent.class)); gameLoop.removeEventHandler(MockEvent.class); @@ -133,7 +133,7 @@ void checkGameLoopFiresEventsImmediately_shouldNotFail() { AtomicBoolean firedEvent = new AtomicBoolean(); GameLoop gameLoop = new GameLoop((gl) -> shouldRemainOpen.get(), (gl) -> false); - gameLoop.addEventObserver((event) -> firedEvent.set(true), MockEvent.class); + gameLoop.addEventObserver(MockEvent.class, (event) -> firedEvent.set(true)); gameLoop.addGameLoopStates( new GameLoopState(CoreLoopState.Update, 1, (gl, deltaTime) -> gameLoop.fireEvent(new MockEvent())), new GameLoopState(CoreLoopState.LateUpdate, 1, (gl, deltaTime) -> shouldRemainOpen.set(false)) @@ -149,7 +149,7 @@ void checkGameLoopFiresEventsOnCoreLoopState_shouldNotFail() { AtomicBoolean firedEvent = new AtomicBoolean(); GameLoop gameLoop = new GameLoop((gl) -> shouldRemainOpen.get(), (gl) -> false); - gameLoop.addEventObserver((event) -> firedEvent.set(true), MockEvent.class); + gameLoop.addEventObserver(MockEvent.class, (event) -> firedEvent.set(true)); gameLoop.addGameLoopStates( new GameLoopState(CoreLoopState.LateUpdate, 1, (gl, deltaTime) -> shouldRemainOpen.set(false)), new GameLoopState(CoreLoopState.Update, 1, (gl, deltaTime) -> gameLoop.fireEvent(new MockEvent(), CoreLoopState.LateUpdate)) @@ -165,7 +165,7 @@ void checkGameLoopFiresEventsOnGameLoopState_shouldNotFail() { AtomicBoolean firedEvent = new AtomicBoolean(); GameLoop gameLoop = new GameLoop((gl) -> shouldRemainOpen.get(), (gl) -> false); - gameLoop.addEventObserver((event) -> firedEvent.set(true), MockEvent.class); + gameLoop.addEventObserver(MockEvent.class, (event) -> firedEvent.set(true)); GameLoopState lateUpdateState = new GameLoopState(CoreLoopState.LateUpdate, 1, (gl, deltaTime) -> shouldRemainOpen.set(false)); GameLoopState updateState = new GameLoopState(CoreLoopState.Update, 1, (gl, deltaTime) -> gameLoop.fireEvent(new MockEvent(), lateUpdateState)); @@ -181,7 +181,7 @@ void checkGameLoopFiresEventsImmediately_onEventHandler_shouldNotFail() { AtomicBoolean firedEvent = new AtomicBoolean(); GameLoop gameLoop = new GameLoop((gl) -> shouldRemainOpen.get(), (gl) -> false); - gameLoop.addEventHandler((eventObservers, event) -> firedEvent.set(true), MockEvent.class); + gameLoop.addEventHandler(MockEvent.class, (eventObservers, event) -> firedEvent.set(true)); gameLoop.addGameLoopStates( new GameLoopState(CoreLoopState.Update, 1, (gl, deltaTime) -> gameLoop.fireEvent(new MockEvent())), new GameLoopState(CoreLoopState.LateUpdate, 1, (gl, deltaTime) -> shouldRemainOpen.set(false)) @@ -197,7 +197,7 @@ void checkGameLoopFiresEventsOnCoreLoopState_onEventHandler_shouldNotFail() { AtomicBoolean firedEvent = new AtomicBoolean(); GameLoop gameLoop = new GameLoop((gl) -> shouldRemainOpen.get(), (gl) -> false); - gameLoop.addEventHandler((eventObservers, event) -> firedEvent.set(true), MockEvent.class); + gameLoop.addEventHandler(MockEvent.class, (eventObservers, event) -> firedEvent.set(true)); gameLoop.addGameLoopStates( new GameLoopState(CoreLoopState.LateUpdate, 1, (gl, deltaTime) -> shouldRemainOpen.set(false)), new GameLoopState(CoreLoopState.Update, 1, (gl, deltaTime) -> gameLoop.fireEvent(new MockEvent(), CoreLoopState.LateUpdate)) @@ -213,7 +213,7 @@ void checkGameLoopFiresEventsOnGameLoopState_onEventHandler_shouldNotFail() { AtomicBoolean firedEvent = new AtomicBoolean(); GameLoop gameLoop = new GameLoop((gl) -> shouldRemainOpen.get(), (gl) -> false); - gameLoop.addEventHandler((eventObservers, event) -> firedEvent.set(true), MockEvent.class); + gameLoop.addEventHandler(MockEvent.class, (eventObservers, event) -> firedEvent.set(true)); GameLoopState lateUpdateState = new GameLoopState(CoreLoopState.LateUpdate, 1, (gl, deltaTime) -> shouldRemainOpen.set(false)); GameLoopState updateState = new GameLoopState(CoreLoopState.Update, 1, (gl, deltaTime) -> gameLoop.fireEvent(new MockEvent(), lateUpdateState)); @@ -250,8 +250,8 @@ void checkGameLoopResetsAllValues() { gameLoop.addGameLoopStates(lateUpdates); gameLoop.addGameLoopState(new GameLoopState(CoreLoopState.LateUpdate, Integer.MAX_VALUE, (gl, deltaTime) -> shouldRemainOpen.set(false))); - gameLoop.addEventHandler((eventObservers, event) -> {}, MockEvent.class); - gameLoop.addEventObserver(event -> {}, MockEvent.class); + gameLoop.addEventHandler(MockEvent.class, (eventObservers, event) -> {}); + gameLoop.addEventObserver(MockEvent.class, event -> {}); gameLoop.reset(); @@ -271,8 +271,8 @@ void checkGameLoopClearsAllValues() { AtomicBoolean shouldRemainOpen = new AtomicBoolean(true); GameLoop gameLoop = new GameLoop((gl) -> shouldRemainOpen.get(), (gl) -> false); - gameLoop.addEventHandler((eventObservers, event) -> {}, MockEvent.class); - gameLoop.addEventObserver(event -> {}, MockEvent.class); + gameLoop.addEventHandler(MockEvent.class, (eventObservers, event) -> {}); + gameLoop.addEventObserver(MockEvent.class, event -> {}); gameLoop.clearEventSystem();