SDL3 Port for better keyboard&Wayland support - lwjgl3ify 3.0 (#202)

This commit is contained in:
Raven Szewczyk authored and GitHub committed 2025-11-27 18:18:54 +00:00
1 parent 19bdc08297
commit 0fda85575f
59 files changed
+2729 -4100

No files matched your search

+1
View File
@@ -30,3 +30,4 @@ whitelist.json
*.DS_Store
!gradlew.bat
layout.json
buildSrc/build
+8 -4
View File
@@ -5,7 +5,10 @@ Bundles [RetroFuturaBootstrap](https://github.com/GTNewHorizons/RetroFuturaBoots
# Usage
Lwjgl3ify depends on Unimixins (<https://github.com/LegacyModdingMC/UniMixins/>), use at least version 0.1.7 with the GTNHMixins module.
Lwjgl3ify depends on:
- Unimixins (<https://github.com/LegacyModdingMC/UniMixins/>), use at least version 0.1.7 with the GTNHMixins module.
- GTNHLib (<https://github.com/GTNewHorizons/GTNHLib/>), at least 0.6.2.
Hodgepodge (<https://github.com/GTNewHorizons/Hodgepodge>) is strongly recommended, it has many Java 17+ compatibility patches for ARR mods (Biomes'o'Plenty, Witchery, JourneyMap, and more) which we could not directly fix in the GTNH forks.
## Client
@@ -28,12 +31,13 @@ Change the instance java version to 17.0.6, 19.0.2, 20 or 21 (or newer), these a
### MultiMC setup (GTNH and non-GTNH)
> [!IMPORTANT]
> If you're using GTNH 2.8.1 or older, use the lwjgl3ify 2.x arguments from <https://github.com/GTNewHorizons/lwjgl3ify/blob/19bdc08297eca6975beaf0886ceca3bbc83cf368/README.MD#multimc-setup-gtnh-and-non-gtnh>.
> If you're using GTNH 2.5.1 or older, use the lwjgl3ify 1.x arguments from <https://github.com/GTNewHorizons/lwjgl3ify/blob/2229295b9fe5ed3304f62288f76f84bdb79ff5bb/README.MD#multimc-setup-gtnh-and-non-gtnh>.
> The following arguments are relevant to the 2.x version.
> The following arguments are relevant to the 3.x version.
For MultiMC, you need to manually put in extra java arguments, Prism Launcher can load them from the patches json files automatically:
```
-Dfile.encoding=UTF-8 -Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader --add-opens java.base/java.io=ALL-UNNAMED --add-opens java.base/java.lang.invoke=ALL-UNNAMED --add-opens java.base/java.lang.ref=ALL-UNNAMED --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.net.spi=ALL-UNNAMED --add-opens java.base/java.net=ALL-UNNAMED --add-opens java.base/java.nio.channels=ALL-UNNAMED --add-opens java.base/java.nio.charset=ALL-UNNAMED --add-opens java.base/java.nio.file=ALL-UNNAMED --add-opens java.base/java.nio=ALL-UNNAMED --add-opens java.base/java.text=ALL-UNNAMED --add-opens java.base/java.time.chrono=ALL-UNNAMED --add-opens java.base/java.time.format=ALL-UNNAMED --add-opens java.base/java.time.temporal=ALL-UNNAMED --add-opens java.base/java.time.zone=ALL-UNNAMED --add-opens java.base/java.time=ALL-UNNAMED --add-opens java.base/java.util.concurrent.atomic=ALL-UNNAMED --add-opens java.base/java.util.concurrent.locks=ALL-UNNAMED --add-opens java.base/java.util.jar=ALL-UNNAMED --add-opens java.base/java.util.zip=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/jdk.internal.loader=ALL-UNNAMED --add-opens java.base/jdk.internal.misc=ALL-UNNAMED --add-opens java.base/jdk.internal.ref=ALL-UNNAMED --add-opens java.base/jdk.internal.reflect=ALL-UNNAMED --add-opens java.base/sun.nio.ch=ALL-UNNAMED --add-opens java.desktop/com.sun.imageio.plugins.png=ALL-UNNAMED --add-opens java.desktop/sun.awt.image=ALL-UNNAMED --add-opens java.desktop/sun.awt=ALL-UNNAMED --add-opens java.sql.rowset/javax.sql.rowset.serial=ALL-UNNAMED --add-opens jdk.dynalink/jdk.dynalink.beans=ALL-UNNAMED --add-opens jdk.naming.dns/com.sun.jndi.dns=ALL-UNNAMED,java.naming
-Dfile.encoding=UTF-8 -Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader --enable-native-access ALL-UNNAMED --add-opens java.base/java.io=ALL-UNNAMED --add-opens java.base/java.lang.invoke=ALL-UNNAMED --add-opens java.base/java.lang.ref=ALL-UNNAMED --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.net.spi=ALL-UNNAMED --add-opens java.base/java.net=ALL-UNNAMED --add-opens java.base/java.nio.channels=ALL-UNNAMED --add-opens java.base/java.nio.charset=ALL-UNNAMED --add-opens java.base/java.nio.file=ALL-UNNAMED --add-opens java.base/java.nio=ALL-UNNAMED --add-opens java.base/java.text=ALL-UNNAMED --add-opens java.base/java.time.chrono=ALL-UNNAMED --add-opens java.base/java.time.format=ALL-UNNAMED --add-opens java.base/java.time.temporal=ALL-UNNAMED --add-opens java.base/java.time.zone=ALL-UNNAMED --add-opens java.base/java.time=ALL-UNNAMED --add-opens java.base/java.util.concurrent.atomic=ALL-UNNAMED --add-opens java.base/java.util.concurrent.locks=ALL-UNNAMED --add-opens java.base/java.util.jar=ALL-UNNAMED --add-opens java.base/java.util.zip=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/jdk.internal.loader=ALL-UNNAMED --add-opens java.base/jdk.internal.misc=ALL-UNNAMED --add-opens java.base/jdk.internal.ref=ALL-UNNAMED --add-opens java.base/jdk.internal.reflect=ALL-UNNAMED --add-opens java.base/sun.nio.ch=ALL-UNNAMED --add-opens java.desktop/com.sun.imageio.plugins.png=ALL-UNNAMED --add-opens java.desktop/sun.awt.image=ALL-UNNAMED --add-opens java.desktop/sun.awt=ALL-UNNAMED --add-opens java.desktop/sun.lwawt.macosx=ALL-UNNAMED --add-opens java.sql.rowset/javax.sql.rowset.serial=ALL-UNNAMED --add-opens jdk.dynalink/jdk.dynalink.beans=ALL-UNNAMED --add-opens jdk.naming.dns/com.sun.jndi.dns=ALL-UNNAMED,java.naming
```
### (Experimental) Relauncher installation
@@ -89,7 +93,7 @@ There are a few components to enabling modern java and lwjgl usage on old minecr
- FMLSecurityManager: fix some array index out of bounds exceptions, it is also deprecated in java 17 and will need to be replaced once a new API is available
- EnumHelper: replace all the enumhelper apis with new variants using the extensible enum transformer and unsafe hacks.
- Additional performance-enhancing mixins making use of LWJGL3 features:
- STB_image-based image loader, much faster than Image4J
- spng-based image loader, much faster than Image4J
- STB_rectpack-based texture sticher, it's nearly instant with tens of thousands of textures, compared to the vanilla code which takes many seconds to stitch that many textures into an atlas
## Fixing mods
+68 -33
View File
@@ -1,6 +1,9 @@
import com.gtnewhorizons.retrofuturagradle.minecraft.RunMinecraftTask
import com.gtnewhorizons.retrofuturagradle.shadow.org.apache.commons.lang3.SystemUtils
import com.gtnewhorizons.retrofuturagradle.util.Distribution
import com.gtnewhorizons.retrofuturagradle.util.ProviderToStringWrapper
import com.modrinth.minotaur.ModrinthExtension
import de.undercouch.gradle.tasks.download.Download
import org.apache.tools.ant.filters.ReplaceTokens
import java.nio.charset.StandardCharsets
import java.time.OffsetDateTime
@@ -10,6 +13,7 @@ import kotlin.streams.toList
plugins {
id("com.gtnewhorizons.gtnhconvention")
id("lwjgl3ify-helper")
}
val taskGroup = "lwjgl3ify"
@@ -50,6 +54,7 @@ val addOpens = listOf(
"java.desktop/com.sun.imageio.plugins.png=ALL-UNNAMED",
"java.desktop/sun.awt.image=ALL-UNNAMED",
"java.desktop/sun.awt=ALL-UNNAMED",
"java.desktop/sun.lwawt.macosx=ALL-UNNAMED",
"java.sql.rowset/javax.sql.rowset.serial=ALL-UNNAMED",
"jdk.dynalink/jdk.dynalink.beans=ALL-UNNAMED",
"jdk.naming.dns/com.sun.jndi.dns=ALL-UNNAMED,java.naming",
@@ -58,6 +63,8 @@ val addOpens = listOf(
val extraJavaArgs = mutableListOf(
"-Dfile.encoding=UTF-8",
"-Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader",
"--enable-native-access",
"ALL-UNNAMED"
)
for (openSpec in addOpens) {
extraJavaArgs += listOf("--add-opens", openSpec)
@@ -67,8 +74,9 @@ tasks.register("updateJava9ArgsTxt") {
group = taskGroup
description = "Updates java9args.txt with the current argument list"
outputs.file("java9args.txt")
val writtenText = extraJavaArgs.joinToString("\n") + "\n"
doLast {
file("java9args.txt").writeText(extraJavaArgs.joinToString("\n") + "\n", Charsets.UTF_8)
File("java9args.txt").writeText(writtenText, Charsets.UTF_8)
}
}
@@ -122,7 +130,7 @@ tasks.named<JavaCompile>(relauncherStubSet.compileJavaTaskName).configure {
tasks.createMcLauncherFiles {
// Override main class
replacementTokens.put("@@BOUNCERCLIENT@@", "com.gtnewhorizons.retrofuturabootstrap.Main")
replacementTokens.put("@@BOUNCERCLIENT@@", "com.gtnewhorizons.retrofuturabootstrap.MainStartOnFirstThread")
replacementTokens.put("@@BOUNCERSERVER@@", "com.gtnewhorizons.retrofuturabootstrap.Main")
}
@@ -187,27 +195,40 @@ val forgePatchesJar = tasks.register<Jar>("forgePatchesJar") {
}
}
val mmcInstanceFilesZip = tasks.register<Zip>("mmcInstanceFiles") {
abstract class MmcZip: Zip() {
@get:InputFile
abstract val lwjgl3Json: RegularFileProperty
}
val mmcInstanceFilesZip = tasks.register<MmcZip>("mmcInstanceFiles") {
group = taskGroup
description = "Packages the MultiMC patches"
dependsOn(forgePatchesJar)
dependsOn(forgePatchesJar, tasks.makeLwjgl3Json)
lwjgl3Json = tasks.makeLwjgl3Json.flatMap { it.outputFile }
archiveClassifier.set("multimc")
from(project.file("prism-libraries/"))
from(forgePatchesJar) {
into("libraries/")
}
exclude("META-INF", "META-INF/**")
val projVersion = project.version
val jvmArgs = extraJavaArgs.joinToString(", ") { '"' + it + '"' }
val lwjglVersion = libs.versions.lwjgl.get()
val lwjglDownloadsFile = lwjgl3Json.asFile.get().absolutePath
filesMatching(
listOf(
"mmc-pack.json",
"patches/me.eigenraven.lwjgl3ify.forgepatches.json",
"patches/me.eigenraven.lwjgl3ify.launchargs.json"
"patches/me.eigenraven.lwjgl3ify.launchargs.json",
"patches/org.lwjgl3.json"
)
) {
expand(
mapOf(
"version" to project.version,
"jvmArgs" to extraJavaArgs.map { '"' + it + '"' }.joinToString(", ")
"version" to projVersion,
"jvmArgs" to jvmArgs,
"lwjglVersion" to lwjglVersion,
"lwjglDownloadsFile" to lwjglDownloadsFile
)
)
}
@@ -215,22 +236,39 @@ val mmcInstanceFilesZip = tasks.register<Zip>("mmcInstanceFiles") {
val versionJsonPath = layout.buildDirectory.file("libs/version.json").get().asFile
val versionJsonFile = tasks.register("versionJson") {
abstract class VersionJsonTask : DefaultTask() {
@get:Inject
abstract val fs: FileSystemOperations
@get:InputFile
abstract val lwjgl3Json: RegularFileProperty
}
val versionJsonFile = tasks.register<VersionJsonTask>("versionJson") {
group = taskGroup
description = "Generates the vanilla launcher version.json file"
dependsOn(tasks.makeLwjgl3Json)
inputs.file("launcher-metadata/version.json")
inputs.property("version", project.version)
inputs.property("jvmArgs", extraJavaArgs)
outputs.file(versionJsonPath)
lwjgl3Json = tasks.makeLwjgl3Json.flatMap { it.outputFile }
val projVersion = project.version.toString()
val jvmArgs = extraJavaArgs.joinToString(", ") { '"' + it + '"' }
val versionJsonPathLocal = versionJsonPath
val lwjglVersion = libs.versions.lwjgl.get()
val lwjglDownloadsFile = lwjgl3Json.asFile.get()
doLast {
versionJsonPath.parentFile.mkdirs()
copy {
versionJsonPathLocal.parentFile.mkdirs()
val lwjglDownloads = lwjglDownloadsFile.readText(Charsets.UTF_8)
fs.copy {
from("launcher-metadata/version.json")
into(versionJsonPath.parentFile)
into(versionJsonPathLocal.parentFile)
filter(
ReplaceTokens::class, "tokens" to mapOf(
"version" to project.version,
"jvmArgs" to extraJavaArgs.map { '"' + it + '"' }.joinToString(", "),
"version" to projVersion,
"jvmArgs" to jvmArgs,
"lwjglVersion" to lwjglVersion,
"lwjglDownloads" to lwjglDownloads,
"time" to DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX")
.format(OffsetDateTime.now(ZoneOffset.UTC))
)
@@ -275,8 +313,9 @@ val runComparisonTool = tasks.register<JavaExec>("runComparisonTool") {
tasks.processResources {
inputs.property("version", project.version.toString())
val projVersion = project.version.toString()
filesMatching("META-INF/rfb-plugin/*") {
expand("version" to project.version.toString())
expand("version" to projVersion)
}
}
@@ -311,24 +350,27 @@ for (jarTask in listOf("jar", "shadowJar", "forgePatchesJar")) {
}
}
for (runTask in listOf(tasks.runClient, tasks.runServer)) {
for (runTask in listOf(tasks.runClient, tasks.runServer, tasks.runObfClient, tasks.runObfServer)) {
runTask.configure {
classpath = files(forgePatchesJar) + classpath
extraJvmArgs = extraJavaArgs
javaLauncher.set(newJavaLauncher)
}
}
for (runTask in listOf(tasks.runObfClient, tasks.runObfServer)) {
runTask.configure {
classpath = files(forgePatchesJar) + classpath
extraJvmArgs = extraJavaArgs
val jArgs = mutableListOf<String>()
jArgs.addAll(extraJavaArgs)
if (this.side == Distribution.CLIENT && SystemUtils.IS_OS_MAC) {
jArgs += "-XstartOnFirstThread"
}
extraJvmArgs = jArgs
javaLauncher.set(newJavaLauncher)
}
}
val originalLaunchWrapperPath = project.layout.buildDirectory.file("launchwrapper-1.12.jar").get().asFile
val dlOriginalLaunchwrapper = tasks.register<Download>("dlOriginalLaunchwrapper") {
src("https://libraries.minecraft.net/net/minecraft/launchwrapper/1.12/launchwrapper-1.12.jar")
dest(originalLaunchWrapperPath)
overwrite(false)
}
val runWithRelauncher = tasks.register<RunMinecraftTask>("runClientWithRelauncher", Distribution.CLIENT, gradle)
runWithRelauncher.configure {
setup(project)
@@ -339,6 +381,7 @@ runWithRelauncher.configure {
tasks.downloadVanillaAssets,
tasks.packagePatchedMc,
tasks.reobfJar,
dlOriginalLaunchwrapper,
"jar"
)
@@ -355,18 +398,10 @@ runWithRelauncher.configure {
classpath(tasks.reobfJar)
classpath(configurations.runtimeClasspath)
mainClass = "GradleStart"
doFirst {
download.run {
src("https://libraries.minecraft.net/net/minecraft/launchwrapper/1.12/launchwrapper-1.12.jar")
dest(originalLaunchWrapperPath)
overwrite(false)
}
}
}
tasks.runObfClient {
mainClass.set("com.gtnewhorizons.retrofuturabootstrap.Main")
mainClass.set("com.gtnewhorizons.retrofuturabootstrap.MainStartOnFirstThread")
}
tasks.runObfServer {
+22
View File
@@ -0,0 +1,22 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
plugins {
`kotlin-dsl`
kotlin("plugin.serialization") version "2.2.21"
}
repositories {
gradlePluginPortal()
}
tasks.compileKotlin.configure {
compilerOptions.jvmTarget = JvmTarget.JVM_24
}
tasks.compileJava.configure {
options.release = 24
}
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0")
}
@@ -0,0 +1,192 @@
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import org.gradle.api.DefaultTask
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.tasks.Classpath
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import java.io.File
import java.security.MessageDigest
import kotlin.text.split
val libs = project.extensions.getByType(VersionCatalogsExtension::class.java).named("libs")!!
val lwjglVersion: String = libs.findVersion("lwjgl").orElseThrow().toString()
abstract class LwjglPlatform {
abstract val name: Property<String>
abstract val launcherOs: ListProperty<String>
fun getJsonRules(): JsonArray {
return JsonArray(launcherOs.get().map { osName -> JsonObject(mapOf(
"action" to JsonPrimitive("allow"),
"os" to JsonObject(mapOf(
"name" to JsonPrimitive(osName)
))))}
)
}
}
fun makePlatform(name: String, launcherOs: List<String>): LwjglPlatform {
val platform = project.objects.newInstance<LwjglPlatform>()
platform.name = name
platform.launcherOs = launcherOs
return platform
}
data class LwjglBinding(val name: String, val hasNatives: Boolean = true) {
fun getGav(): String {
if (name.isEmpty()) {
return "org.lwjgl:lwjgl:${lwjglVersion}"
}
return "org.lwjgl:lwjgl-${this.name}:${lwjglVersion}"
}
fun getNativeGav(platform: LwjglPlatform): String {
return "${getGav()}:natives-${platform.name.get()}"
}
}
private val supportedNatives = listOf(
makePlatform("freebsd",listOf("freebsd")),
makePlatform("linux-arm32",listOf("linux-arm32")),
makePlatform("linux-arm64",listOf("linux-arm64")),
makePlatform("linux-ppc64le",listOf("linux-ppc64le")),
makePlatform("linux", listOf("linux")),
makePlatform("macos-arm64", listOf("osx", "osx-arm64")),
makePlatform("macos", listOf("osx")),
makePlatform("windows-arm64", listOf("windows", "windows-arm64")),
makePlatform("windows-x86", listOf("windows")),
makePlatform("windows", listOf("windows"))
);
private val nativesByName: Map<String, LwjglPlatform> = supportedNatives.associateBy { n -> n.name.get() }
private val hostNativeClassifier = (project.extensions.getByName("lwjgl3Natives")!! as String).removePrefix("natives-")
private val hostNativePlatform = nativesByName[hostNativeClassifier]!!;
private val lwjgl3Bindings = listOf(
LwjglBinding(""),
LwjglBinding("freetype"),
LwjglBinding("harfbuzz", false),
LwjglBinding("jemalloc"),
LwjglBinding("nuklear"),
LwjglBinding("openal"),
LwjglBinding("opengl"),
LwjglBinding("sdl"),
LwjglBinding("spng"),
LwjglBinding("stb"),
LwjglBinding("tinyfd"),
LwjglBinding("zstd")
);
val allOfLwjgl3: Configuration = project.configurations.create("allOfLwjgl3")
val lwjgl3Classpath = project.configurations.getByName("lwjgl3Classpath")
for (binding in lwjgl3Bindings) {
dependencies.add(lwjgl3Classpath.name, binding.getGav())
dependencies.add(allOfLwjgl3.name, binding.getGav())
if (binding.hasNatives) {
dependencies.add(lwjgl3Classpath.name, binding.getNativeGav(hostNativePlatform))
for (platform in supportedNatives) {
dependencies.add(allOfLwjgl3.name, binding.getNativeGav(platform))
}
}
}
abstract class Lwjgl3JsonMaker : DefaultTask() {
@get:Classpath
abstract val libraries: ConfigurableFileCollection
@get:OutputFile
abstract val outputFile: RegularFileProperty
@get:Input
abstract val lwjglVersionString: Property<String>
@get:Input
abstract val lwjglNativesTable: MapProperty<String, LwjglPlatform>
@TaskAction
fun makeJson() {
val sha1 = MessageDigest.getInstance("SHA-1")
val outArr = mutableListOf<JsonObject>()
val lwjglVersion = lwjglVersionString.get()
for (file in libraries.files) {
val fileName = file.name
val fileSize = file.length()
val fileSha1 = sha1.digest(file.readBytes()).joinToString("") { "%02x".format(it) }
// Reconstruct maven GAV coordinates and URL from the file name
val versionInterlude = "-${lwjglVersion}"
val versionIdx = fileName.indexOf(versionInterlude)
require(versionIdx > 0)
val artifact = fileName.substring(0, versionIdx)
val fileVersion = lwjglVersion
val versionDash = lwjglVersion.indexOf('-')
val urlVersion = if (versionDash >= 0) {lwjglVersion.substring(0, versionDash) + "-SNAPSHOT"} else {lwjglVersion}
val classifier = fileName.substring(versionIdx + versionInterlude.length).removePrefix("-").removeSuffix(".jar")
val dashClassifier = if (classifier.isEmpty()) {classifier} else { "-$classifier" }
val gav = "org.lwjgl:${artifact}${dashClassifier}:${fileVersion}"
/*
{
"downloads": {
"artifact": {
"sha1": "149070a5480900347071b7074779531f25a6e3dc",
"size": 1245129,
"url": "https://libraries.minecraft.net/org/lwjgl/lwjgl-freetype/3.3.3/lwjgl-freetype-3.3.3-natives-linux.jar"
}
},
"name": "org.lwjgl:lwjgl-freetype-natives-linux:3.3.3",
"rules": [
{
"action": "allow",
"os": {
"name": "linux"
}
}
]
},
*/
val downloadUrl = if (urlVersion.contains("-SNAPSHOT")) {
"https://nexus.gtnewhorizons.com/repository/central-sonatype-snapshots/org/lwjgl/${artifact}/${urlVersion}/${artifact}-${fileVersion}${dashClassifier}.jar"
} else {
"https://libraries.minecraft.net/org/lwjgl/${artifact}/${urlVersion}/${artifact}-${fileVersion}${dashClassifier}.jar"
}
val outObj = mutableMapOf(
"downloads" to JsonObject(
mapOf(
"artifact" to JsonObject(
mapOf(
"sha1" to JsonPrimitive(fileSha1),
"size" to JsonPrimitive(fileSize),
"url" to JsonPrimitive(downloadUrl)
)
)
)
),
"name" to JsonPrimitive(gav)
)
if (!classifier.isEmpty()) {
val native: LwjglPlatform = lwjglNativesTable.get()[classifier.removePrefix("natives-")]
?: throw IllegalStateException("Could not determine native for ${fileName}, classifier ${classifier}");
outObj["rules"] = native.getJsonRules()
}
outArr += JsonObject(
outObj
)
}
outArr.sortBy { j -> (j["name"] as JsonPrimitive).toString() }
outputFile.asFile.get().writeText(outArr.joinToString(",\n") { j -> j.toString() }, Charsets.UTF_8)
}
}
tasks.register<Lwjgl3JsonMaker>("makeLwjgl3Json") {
libraries = allOfLwjgl3
outputFile = project.layout.buildDirectory.file("lwjgl3-libs.json")
lwjglVersionString = lwjglVersion
lwjglNativesTable = nativesByName
}
+34 -30
View File
@@ -1,56 +1,61 @@
def lwjglVersion = libs.versions.lwjgl.get()
minecraft {
mainLwjglVersion = 3
lwjgl3Version = "3.3.3"
lwjgl3Version = lwjglVersion
}
def addGtForTesting = Boolean.parseBoolean(project.getProperties().getOrDefault("withGregtech", "false").toString())
def addReikaModsForTesting = Boolean.parseBoolean(project.getProperties().getOrDefault("withReikaMods", "false").toString())
def asmVersion = '9.8'
def rfbVersion = '1.0.11'
// 100% binary compatible, 1 minor source compatibility issue (removed a throws IOException clause)
def gsonVersion = '2.10.1'
configurations.configureEach {
resolutionStrategy.dependencySubstitution {
substitute module('net.minecraft:launchwrapper') using module("com.gtnewhorizons.retrofuturabootstrap:RetroFuturaBootstrap:${rfbVersion}") because("LW replacement")
substitute module('net.minecraft:launchwrapper') using module(libs.rfb.get().toString()) because("LW replacement")
}
}
dependencies {
// Resolve newer versions of LaunchWrapper to allow java 9+ compat
vanilla_minecraft("com.gtnewhorizons.retrofuturabootstrap:RetroFuturaBootstrap:${rfbVersion}") { transitive = false }
forgePatchesEmbedded("com.gtnewhorizons.retrofuturabootstrap:RetroFuturaBootstrap:${rfbVersion}") { transitive = false }
vanilla_minecraft("com.google.code.gson:gson:${gsonVersion}")
forgePatchesEmbedded("com.google.code.gson:gson:${gsonVersion}")
vanilla_minecraft(libs.rfb) { transitive = false }
forgePatchesEmbedded(libs.rfb) { transitive = false }
// 100% binary compatible, 1 minor source compatibility issue (removed a throws IOException clause)
vanilla_minecraft(libs.gson)
forgePatchesEmbedded(libs.gson)
utilImplementation("org.ow2.asm:asm:${asmVersion}")
utilImplementation("org.ow2.asm:asm-tree:${asmVersion}")
utilImplementation("org.apache.commons:commons-lang3:3.14.0")
utilImplementation("commons-io:commons-io:2.11.0")
api("com.github.GTNewHorizons:GTNHLib:0.6.2:dev")
patchedMinecraft("org.lwjgl:lwjgl-sdl:${lwjglVersion}")
patchedMinecraft("org.lwjgl:lwjgl-sdl:${lwjglVersion}:${lwjgl3Natives}")
patchedMinecraft("org.lwjgl:lwjgl-spng:${lwjglVersion}")
patchedMinecraft("org.lwjgl:lwjgl-spng:${lwjglVersion}:${lwjgl3Natives}")
utilImplementation(libs.asm)
utilImplementation(libs.asmTree)
utilImplementation("org.apache.commons:commons-lang3:3.17.0")
utilImplementation("commons-io:commons-io:2.18.0")
utilImplementation("commons-collections:commons-collections:3.2.2")
utilImplementation("com.google.guava:guava:31.1-jre")
utilImplementation("com.google.guava:guava:33.4.0-jre")
hotswapCompileOnly("org.hotswapagent:hotswap-agent-core:1.4.1")
hotswapCompileOnly("com.gtnewhorizons.retrofuturabootstrap:RetroFuturaBootstrap:${rfbVersion}")
hotswapCompileOnly(libs.rfb)
forgePatchesEmbedded("org.ow2.asm:asm:${asmVersion}")
forgePatchesEmbedded("org.ow2.asm:asm-commons:${asmVersion}")
forgePatchesEmbedded("org.ow2.asm:asm-tree:${asmVersion}")
forgePatchesEmbedded("org.ow2.asm:asm-analysis:${asmVersion}")
forgePatchesEmbedded("org.ow2.asm:asm-util:${asmVersion}")
forgePatchesEmbedded("org.apache.commons:commons-lang3:3.14.0")
forgePatchesEmbedded("org.apache.commons:commons-compress:1.26.2")
forgePatchesEmbedded("commons-io:commons-io:2.15.1")
forgePatchesEmbedded(libs.asm)
forgePatchesEmbedded(libs.asmCommons)
forgePatchesEmbedded(libs.asmTree)
forgePatchesEmbedded(libs.asmAnalysis)
forgePatchesEmbedded(libs.asmUtil)
forgePatchesEmbedded("org.apache.commons:commons-lang3:3.17.0")
forgePatchesEmbedded("org.apache.commons:commons-compress:1.27.1")
forgePatchesEmbedded("commons-io:commons-io:2.18.0")
// For Just Another Spawner
forgePatchesEmbedded("org.mvel:mvel2:2.5.2.Final")
compileOnly("org.jetbrains:annotations:24.1.0")
compileOnly("org.jetbrains:annotations:26.0.1")
// Allow using Unsafe with newer javac versions
compileOnly('me.eigenraven.java8unsupported:java-8-unsupported-shim:1.0.0')
api("com.google.code.gson:gson:${gsonVersion}")
api(libs.gson)
compileOnly("com.mumfrey:liteloader:1.7.10_04:mcpnames")
@@ -59,10 +64,9 @@ dependencies {
forgePatchesEmbedded("com.sun.xml.bind:jaxb-impl:3.0.2")
forgePatchesEmbedded("org.openjdk.nashorn:nashorn-core:15.4")
shadowImplementation("com.github.weisj:darklaf-core:3.0.2")
runtimeOnlyNonPublishable('com.github.GTNewHorizons:NotEnoughItems:2.8.35-GTNH:dev')
// runtimeOnlyNonPublishable('com.github.GTNewHorizons:inventory-tweaks:1.7.1:dev')
// runtimeOnlyNonPublishable('maven.modrinth:cursormod:1.2.2-1.7.10')
if (addGtForTesting) {
runtimeOnlyNonPublishable('com.github.GTNewHorizons:GT5-Unofficial:5.09.52.104:dev')
runtimeOnlyNonPublishable("com.github.GTNewHorizons:Applied-Energistics-2-Unofficial:rv3-beta-739-GTNH:dev")
@@ -74,7 +78,7 @@ dependencies {
runtimeOnlyNonPublishable("com.github.GTNewHorizons:MrTJPCore:1.3.4:dev")
runtimeOnlyNonPublishable("com.github.GTNewHorizons:ForgeMultipart:1.7.0:dev")
runtimeOnlyNonPublishable("com.github.GTNewHorizons:ForgeRelocation:0.3.4:dev")
reobfJarConfiguration group: 'curse.maven', name: 'cofh-core-69162', version: '2388750'
reobfJarConfiguration("curse.maven:cofh-core-69162:2388750")
runtimeOnlyNonPublishable("com.github.GTNewHorizons:AppleCore:3.3.7:dev")
runtimeOnlyNonPublishable("com.github.GTNewHorizons:Hodgepodge:2.7.11:dev")
}
+5 -2
View File
@@ -157,7 +157,7 @@ modrinthProjectId = eC4lt4Oy
# and the name is the Modrinth project or version slug/id of the other mod.
# Example: required-project:fplib;optional-project:gasstation;incompatible-project:gregtech
# Note: UniMixins is automatically set as a required dependency if usesMixins = true.
modrinthRelations =
modrinthRelations = required-project\:gtnhlib
# Publishing to CurseForge requires you to set the CURSEFORGE_TOKEN environment variable to one of your CurseForge API tokens.
#
@@ -171,7 +171,7 @@ curseForgeProjectId = 998880
# and the name is the CurseForge project slug of the other mod.
# Example: requiredDependency:railcraft;embeddedLibrary:cofhlib;incompatible:buildcraft
# Note: UniMixins is automatically set as a required dependency if usesMixins = true.
curseForgeRelations =
curseForgeRelations = requiredDependency\:gtnhlib
# Optional parameter to customize the produced artifacts. Use this to preserve artifact naming when migrating older
# projects. New projects should not use this parameter.
@@ -212,3 +212,6 @@ curseForgeRelations =
# This is meant to be set in $HOME/.gradle/gradle.properties.
# ideaCheckSpotlessOnBuild = true
# Non-GTNH properties
org.gradle.configuration-cache = true
org.gradle.parallel = true
+12
View File
@@ -0,0 +1,12 @@
#This file is generated by updateDaemonJvm
toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c5ee947fbfb70bc347d8d531e3a578c4/redirect
toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/5ee463876563a46fff651cce1bc53a4c/redirect
toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c5ee947fbfb70bc347d8d531e3a578c4/redirect
toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/5ee463876563a46fff651cce1bc53a4c/redirect
toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/e1118b4c7c2858d28154d086dbff010e/redirect
toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/59a9771cad43219260d9aac9a8ec4d6a/redirect
toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c5ee947fbfb70bc347d8d531e3a578c4/redirect
toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/5ee463876563a46fff651cce1bc53a4c/redirect
toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/832229f0f6f0be60ed817c5a5e5848eb/redirect
toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/b96cb7670c095245220e7d01d5927b58/redirect
toolchainVersion=25
+15
View File
@@ -0,0 +1,15 @@
[versions]
# https://asm.ow2.io/versions.html
asm = "9.9"
# https://central.sonatype.com/repository/maven-snapshots/org/lwjgl/lwjgl/3.4.0-SNAPSHOT/maven-metadata.xml
lwjgl = "3.4.0-20251111.002045-6"
[libraries]
asm = { module = "org.ow2.asm:asm", version.ref = "asm" }
asmCommons = { module = "org.ow2.asm:asm-commons", version.ref = "asm" }
asmTree = { module = "org.ow2.asm:asm-tree", version.ref = "asm" }
asmAnalysis = { module = "org.ow2.asm:asm-analysis", version.ref = "asm" }
asmUtil = { module = "org.ow2.asm:asm-util", version.ref = "asm" }
gson = { module = "com.google.code.gson:gson", version = "2.13.2" }
rfb = { module = "com.gtnewhorizons.retrofuturabootstrap:RetroFuturaBootstrap", version = "1.0.12" }
Binary file not shown.
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
Vendored
+2 -5
View File
@@ -1,7 +1,7 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
# Copyright © 2015 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.
@@ -114,7 +114,6 @@ case "$( uname )" in #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
@@ -172,7 +171,6 @@ fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
@@ -212,8 +210,7 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
Vendored
+1 -2
View File
@@ -70,11 +70,10 @@ goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
+4
View File
@@ -1,5 +1,7 @@
-Dfile.encoding=UTF-8
-Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader
--enable-native-access
ALL-UNNAMED
--add-opens
java.base/java.io=ALL-UNNAMED
--add-opens
@@ -61,6 +63,8 @@ java.desktop/sun.awt.image=ALL-UNNAMED
--add-opens
java.desktop/sun.awt=ALL-UNNAMED
--add-opens
java.desktop/sun.lwawt.macosx=ALL-UNNAMED
--add-opens
java.sql.rowset/javax.sql.rowset.serial=ALL-UNNAMED
--add-opens
jdk.dynalink/jdk.dynalink.beans=ALL-UNNAMED
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -2,17 +2,17 @@
"components": [
{
"cachedName": "LWJGL 3",
"cachedVersion": "3.3.3",
"cachedVersion": "${lwjglVersion}",
"cachedVolatile": true,
"dependencyOnly": true,
"uid": "org.lwjgl3",
"version": "3.3.3"
"version": "${lwjglVersion}"
},
{
"cachedName": "Minecraft with LWJGL3",
"cachedRequires": [
{
"suggests": "3.3.3",
"suggests": "${lwjglVersion}",
"uid": "org.lwjgl3"
}
],
@@ -4,5 +4,8 @@
"uid": "me.eigenraven.lwjgl3ify.launchargs",
"version": "${version}",
"order": 100,
"mainClass": "com.gtnewhorizons.retrofuturabootstrap.Main"
"mainClass": "com.gtnewhorizons.retrofuturabootstrap.MainStartOnFirstThread",
"+traits": [
"FirstThreadOnMacOS"
]
}
+3 -4
View File
@@ -9,9 +9,8 @@
"compatibleJavaMajors": [
17,
21,
23,
24,
25
25,
26
],
"formatVersion": 1,
"libraries": [
@@ -399,7 +398,7 @@
"releaseTime": "2014-05-14T17:29:23+00:00",
"requires": [
{
"suggests": "3.3.3",
"suggests": "${lwjglVersion}",
"uid": "org.lwjgl3"
}
],
File diff suppressed because it is too large. Load diff
+12 -2
View File
@@ -1,8 +1,8 @@
repositories {
ivy {
name "LiteLoader"
artifactPattern "https://dl.liteloader.com/versions/com/mumfrey/[module]/1.7.10/[module]-[revision](-[classifier]).[ext]"
name = "LiteLoader"
artifactPattern("https://dl.liteloader.com/versions/com/mumfrey/[module]/1.7.10/[module]-[revision](-[classifier]).[ext]")
metadataSources {
artifact()
}
@@ -10,4 +10,14 @@ repositories {
includeGroup("com.mumfrey")
}
}
maven {
name = "LWJGL snapshots"
// original upstream
//url = "https://central.sonatype.com/repository/maven-snapshots"
// gtnh proxy that won't remove artifacts for releases
url = "https://nexus.gtnewhorizons.com/repository/central-sonatype-snapshots/"
content {
includeGroup("org.lwjgl")
}
}
}
+3 -3
View File
@@ -3,8 +3,8 @@ pluginManagement {
repositories {
maven {
// RetroFuturaGradle
name "GTNH Maven"
url "https://nexus.gtnewhorizons.com/repository/public/"
name = "GTNH Maven"
url = uri("https://nexus.gtnewhorizons.com/repository/public/")
mavenContent {
includeGroup("com.gtnewhorizons")
includeGroupByRegex("com\\.gtnewhorizons\\..+")
@@ -17,7 +17,7 @@ pluginManagement {
}
plugins {
id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.48'
id("com.gtnewhorizons.gtnhsettingsconvention") version("2.0.3")
}
rootProject.name = "lwjgl3ify"
@@ -5,7 +5,7 @@ import java.util.HashMap;
public class CommonProxy {
public void registerF3Handler() {}
public void registerEventHandler() {}
@SuppressWarnings("unchecked")
public void runCompatHooks() {
@@ -57,7 +57,7 @@ public class Lwjgl3ify {
@Mod.EventHandler
public void postInit(FMLPostInitializationEvent event) {
PROXY.registerF3Handler();
PROXY.registerEventHandler();
final LaunchClassLoader loader = Launch.classLoader;
try {
final Field clExclusionsF = loader.getClass()
@@ -3,6 +3,11 @@ package me.eigenraven.lwjgl3ify.api;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import me.eigenraven.lwjgl3ify.client.TextFieldHandler;
/**
* Provides direct access to raw key press and text input events.
* The main benefit is the separation of key and char events, which allows proper dead key and unicode input handling.
@@ -20,33 +25,48 @@ public class InputEvents {
/** A key state change/repeat event. */
public static class KeyEvent {
/** The mapped LWJGL2 key code, e.g. {@link org.lwjglx.input.Keyboard#KEY_A} */
public final int lwjgl2KeyCode;
/** Raw codes from LWJGL3's GLFW */
public final int glfwKeyCode, glfwScanCode;
/**
* The mapped LWJGL2 key code, e.g. {@link org.lwjglx.input.Keyboard#KEY_A} - keyCode is the code based on the
* label, scanCode is based on the key position equivalent on a QWERTY keyboard.
*/
public final int lwjgl2KeyCode, lwjgl2ScanCode;
/**
* Raw codes from LWJGL3's SDL, e.g. {@link org.lwjgl.sdl.SDLKeycode#SDLK_A} and
* {@link org.lwjgl.sdl.SDLScancode#SDL_SCANCODE_A}
*/
public final int sdlKeyCode, sdlScanCode;
/**
* SDL key code decoded with SDL_GetKeyFromScancode(_, _, false), corresponding to a Unicode codepoint for the
* key if a single one exists
*/
public final int sdlRawKeyCode;
/** What happened to the key */
public final KeyAction action;
/** Modifiers held while the key action happened */
public final boolean controlPressed, shiftPressed, altPressed, superPressed;
/** Modifiers held while the key action happened, e.g. {@link org.lwjgl.sdl.SDLKeycode#SDL_KMOD_LCTRL} */
public final short sdlKeyModifiers;
/**
* Pointer to a UTF-8 string containing the name of the key. Can be decoded on-demand with
* {@link org.lwjgl.system.MemoryUtil#memUTF8(long)}
*/
public final long keyNamePointer;
/** Constructs a new KeyEvent with the given data. */
public KeyEvent(int lwjgl2KeyCode, int glfwKeyCode, int glfwScanCode, KeyAction action, boolean controlPressed,
boolean shiftPressed, boolean altPressed, boolean superPressed) {
public KeyEvent(int lwjgl2KeyCode, int lwjgl2ScanCode, int sdlKeyCode, int sdlScanCode, int sdlRawKeyCode,
KeyAction action, short sdlKeyModifiers, long keyNamePointer) {
this.lwjgl2KeyCode = lwjgl2KeyCode;
this.glfwKeyCode = glfwKeyCode;
this.glfwScanCode = glfwScanCode;
this.lwjgl2ScanCode = lwjgl2ScanCode;
this.sdlKeyCode = sdlKeyCode;
this.sdlScanCode = sdlScanCode;
this.sdlRawKeyCode = sdlRawKeyCode;
this.action = action;
this.controlPressed = controlPressed;
this.shiftPressed = shiftPressed;
this.altPressed = altPressed;
this.superPressed = superPressed;
this.sdlKeyModifiers = sdlKeyModifiers;
this.keyNamePointer = keyNamePointer;
}
}
/** A text input event, indicating some text was typed - either via a keypress or IME input */
public static class TextEvent {
// Currently GLFW only provides individual chars, but a future string-oriented API is planned
/** The text that was put in */
public final String text;
@@ -56,7 +76,10 @@ public class InputEvents {
}
}
/** Implement this interface and register it with this class to receive raw LWJGL3 input events. */
/**
* Implement this interface and register it with this class to receive raw LWJGL3 input events. You can also
* implement it on a Gui class to automatically receive events when the GUI is open.
*/
public interface KeyboardListener {
/** Handle a key press event */
@@ -100,6 +123,10 @@ public class InputEvents {
/** Sends a synthetic key event to all the handlers. */
public static void injectKeyEvent(final KeyEvent ev) {
final GuiScreen gui = Minecraft.getMinecraft().currentScreen;
if (gui instanceof KeyboardListener kl) {
kl.onKeyEvent(ev);
}
for (int i = 0; i < keyboardListeners.size(); i++) {
final KeyboardListener listener = keyboardListeners.get(i);
listener.onKeyEvent(ev);
@@ -119,6 +146,10 @@ public class InputEvents {
/** Sends a synthetic text event to all the handlers. */
public static void injectTextEvent(final TextEvent ev) {
final GuiScreen gui = Minecraft.getMinecraft().currentScreen;
if (gui instanceof KeyboardListener kl) {
kl.onTextEvent(ev);
}
for (int i = 0; i < keyboardListeners.size(); i++) {
final KeyboardListener listener = keyboardListeners.get(i);
listener.onTextEvent(ev);
@@ -135,4 +166,18 @@ public class InputEvents {
}
}
}
/**
* Turns on {@link TextEvent} generation.
*/
public static void beginTextInput() {
TextFieldHandler.beginTextInput();
}
/**
* Turns off {@link TextEvent} generation.
*/
public static void endTextInput() {
TextFieldHandler.endTextInput(null);
}
}
@@ -1,10 +1,13 @@
package me.eigenraven.lwjgl3ify.client;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.settings.KeyBinding;
import net.minecraftforge.client.event.GuiOpenEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.common.MinecraftForge;
import org.lwjgl.sdl.SDLVersion;
import org.lwjglx.input.Keyboard;
import org.lwjglx.opengl.Display;
@@ -18,7 +21,7 @@ import me.eigenraven.lwjgl3ify.core.Config;
public class ClientProxy extends CommonProxy {
static final String javaVersion;
static final String lwjglVersion = "LWJGL: " + org.lwjgl.Version.getVersion();
static final String lwjglVersion;
static {
String javaVersionRaw = "Java: " + System.getProperty("java.version");
@@ -26,6 +29,12 @@ public class ClientProxy extends CommonProxy {
javaVersionRaw = javaVersionRaw.substring(0, 29) + "...";
}
javaVersion = javaVersionRaw;
final int sdlVer = SDLVersion.SDL_GetVersion();
final int sdlMajor = SDLVersion.SDL_VERSIONNUM_MAJOR(sdlVer);
final int sdlMinor = SDLVersion.SDL_VERSIONNUM_MINOR(sdlVer);
final int sdlMicro = SDLVersion.SDL_VERSIONNUM_MICRO(sdlVer);
lwjglVersion = String
.format("LWJGL: %s SDL: %d.%d.%d", org.lwjgl.Version.getVersion(), sdlMajor, sdlMinor, sdlMicro);
}
@Override
@@ -60,6 +69,11 @@ public class ClientProxy extends CommonProxy {
}
}
}
@Override
public void onTextEvent(InputEvents.TextEvent event) {
TextFieldHandler.onTextInput(event);
}
}
private void registerKeybindHandler() {
@@ -67,7 +81,7 @@ public class ClientProxy extends CommonProxy {
}
@Override
public void registerF3Handler() {
public void registerEventHandler() {
MinecraftForge.EVENT_BUS.register(this);
}
@@ -95,4 +109,14 @@ public class ClientProxy extends CommonProxy {
Config.reloadConfigObject();
Display.lwjgl3ify$updateRawMouseMode(Config.INPUT_RAW_MOUSE);
}
@SubscribeEvent
@SuppressWarnings("unused")
public void onGuiChange(final GuiOpenEvent event) {
final GuiScreen oldScreen = Minecraft.getMinecraft().currentScreen;
final GuiScreen newScreen = event.gui;
if (oldScreen != newScreen) {
TextFieldHandler.resetTextInput();
}
}
}
@@ -0,0 +1,161 @@
package me.eigenraven.lwjgl3ify.client;
import static org.lwjgl.sdl.SDLError.*;
import static org.lwjgl.sdl.SDLInit.*;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BooleanSupplier;
import java.util.function.DoubleSupplier;
import java.util.function.IntSupplier;
import java.util.function.LongSupplier;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.system.Platform;
import com.google.common.base.Throwables;
import com.gtnewhorizons.retrofuturabootstrap.MainStartOnFirstThread;
/**
* Utilities for running code on the main thread for interacting with the SDL video/event subsystem.
*/
public class MainThreadExec {
public static final boolean IS_MACOS = Platform.get() == Platform.MACOSX;
private static final ExecutorService executor = MainStartOnFirstThread.instance();
private static final Thread mainThread;
static class CallableWithClassLoader<Ret> implements Callable<Ret> {
private final ClassLoader loader;
private final Callable<Ret> inner;
public CallableWithClassLoader(Callable<Ret> inner) {
this.loader = Thread.currentThread()
.getContextClassLoader();
this.inner = inner;
}
@Override
public Ret call() throws Exception {
final ClassLoader savedLoader = Thread.currentThread()
.getContextClassLoader();
Thread.currentThread()
.setContextClassLoader(loader);
try {
return inner.call();
} finally {
Thread.currentThread()
.setContextClassLoader(savedLoader);
}
}
}
static {
final AtomicReference<Thread> mainThreadStorage = new AtomicReference<>();
// Lambdas cause a deadlock on the class initializer monitor here
// noinspection Convert2Lambda
futureGet(executor.submit(new CallableWithClassLoader<>(new Callable<>() {
@Override
public Object call() {
mainThreadStorage.set(Thread.currentThread());
return null;
}
})));
mainThread = Objects.requireNonNull(mainThreadStorage.get());
}
public static void ensureInitialised() {}
/**
* @return If the current thread is the main thread that can run thread-specific SDL commands.
*/
public static boolean isMainThread() {
return Thread.currentThread() == mainThread;
}
private static <R> Callable<R> bindClassloader(Callable<R> callable) {
return new CallableWithClassLoader<>(callable);
}
private static <V> V futureGet(Future<V> future) {
while (true) {
try {
return future.get();
} catch (ExecutionException e) {
throw Throwables.propagate(e.getCause());
} catch (InterruptedException e) {
// continue
}
}
}
/**
* @param r The Runnable to run on the main thread - if the current thread is main, it gets run immediately.
*/
public static void runOnMainThread(Runnable r) {
Objects.requireNonNull(r);
if (isMainThread()) {
r.run();
} else {
futureGet(executor.submit(bindClassloader(Executors.callable(r))));
}
}
/**
* Requires SDL to already have been initialized on the correct thread.
*
* @param r The Supplier to run on the main thread - if the current thread is main, it gets run immediately.
* @return The value produced by the supplier.
*/
public static <ReturnType> @Nullable ReturnType runOnMainThread(Callable<@Nullable ReturnType> r) {
Objects.requireNonNull(r);
try {
if (isMainThread()) {
return r.call();
} else {
return futureGet(executor.submit(bindClassloader(r)));
}
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
public static boolean runOnMainThread(BooleanSupplier r) {
Objects.requireNonNull(r);
if (isMainThread()) {
return r.getAsBoolean();
}
return Objects.requireNonNull(runOnMainThread(() -> (Boolean) r.getAsBoolean()));
}
public static int runOnMainThread(IntSupplier r) {
Objects.requireNonNull(r);
if (isMainThread()) {
return r.getAsInt();
}
return Objects.requireNonNull(runOnMainThread(() -> (Integer) r.getAsInt()));
}
public static long runOnMainThread(LongSupplier r) {
Objects.requireNonNull(r);
if (isMainThread()) {
return r.getAsLong();
}
return Objects.requireNonNull(runOnMainThread(() -> (Long) r.getAsLong()));
}
public static double runOnMainThread(DoubleSupplier r) {
Objects.requireNonNull(r);
if (isMainThread()) {
return r.getAsDouble();
}
return Objects.requireNonNull(runOnMainThread(() -> (Double) r.getAsDouble()));
}
}
@@ -0,0 +1,104 @@
package me.eigenraven.lwjgl3ify.client;
import static org.lwjgl.sdl.SDLClipboard.*;
import static org.lwjgl.sdl.SDLKeyboard.*;
import static org.lwjgl.system.MemoryUtil.*;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.util.ChatAllowedCharacters;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.sdl.SDLClipboard;
import org.lwjglx.opengl.Display;
import me.eigenraven.lwjgl3ify.Lwjgl3ify;
import me.eigenraven.lwjgl3ify.api.InputEvents;
import me.eigenraven.lwjgl3ify.core.Config;
/** @see me.eigenraven.lwjgl3ify.mixins.early.game.MixinGuiTextField */
public final class TextFieldHandler {
private static int textInputDepth = 0;
private static final WeakReference<GuiTextField> NULL_TEXT_FIELD = new WeakReference<>(null);
private static WeakReference<GuiTextField> focusedTextInput = NULL_TEXT_FIELD;
public static void beginTextInput() {
if (textInputDepth == Integer.MAX_VALUE) {
return;
}
if (textInputDepth++ == 0) {
if (Config.DEBUG_PRINT_KEY_EVENTS) {
Lwjgl3ify.LOG.info("[DEBUG] Beginning text input");
}
MainThreadExec.runOnMainThread(() -> { SDL_StartTextInput(Display.getWindow()); });
}
}
public static void endTextInput(@Nullable GuiTextField textField) {
if (textInputDepth <= 0) {
return;
}
if (--textInputDepth == 0) {
if (Config.DEBUG_PRINT_KEY_EVENTS) {
Lwjgl3ify.LOG.info("[DEBUG] Stopping text input");
}
MainThreadExec.runOnMainThread(() -> { SDL_StopTextInput(Display.getWindow()); });
}
if (textField != null && textField == focusedTextInput.get()) {
focusedTextInput = NULL_TEXT_FIELD;
}
}
public static void resetTextInput() {
if (textInputDepth != 0) {
if (Config.DEBUG_PRINT_KEY_EVENTS) {
Lwjgl3ify.LOG.info("[DEBUG] Stopping text input (reset)");
}
MainThreadExec.runOnMainThread(() -> { SDL_StopTextInput(Display.getWindow()); });
textInputDepth = 0;
}
focusedTextInput = NULL_TEXT_FIELD;
}
public static void setFocusedTextField(GuiTextField textField) {
if (focusedTextInput.get() != textField) {
focusedTextInput = new WeakReference<>(textField);
}
}
public static void onTextInput(InputEvents.TextEvent event) {
final GuiTextField textField = focusedTextInput.get();
if (textInputDepth <= 0 || textField == null) {
return;
}
if (event.text.chars()
.allMatch(chr -> ChatAllowedCharacters.isAllowedCharacter((char) chr))) {
textField.writeText(event.text);
}
}
public static String getClipboardText() {
return MainThreadExec.runOnMainThread(SDLClipboard::SDL_GetClipboardText);
}
public static void setClipboardText(final String newText) {
if (newText == null || newText.isEmpty()) {
MainThreadExec.runOnMainThread(SDLClipboard::SDL_ClearClipboardData);
return;
}
final boolean putOnStack = newText.length() < 1024;
if (putOnStack) {
MainThreadExec.runOnMainThread(() -> SDL_SetClipboardText(newText));
return;
}
final ByteBuffer nativeText = memUTF8(newText, true);
try {
MainThreadExec.runOnMainThread(() -> SDL_SetClipboardText(nativeText));
} finally {
memFree(nativeText);
}
}
}
@@ -29,6 +29,7 @@ public class Config {
public static boolean WINDOW_DECORATED = true;
public static boolean WINDOW_BORDERLESS_REPLACES_FULLSCREEN = false;
public static boolean WINDOW_BORDERLESS_WINDOWS_COMPATIBILITY = true;
public static boolean WINDOW_HIDPI_RENDERING = true;
public static boolean OPENGL_DEBUG_CONTEXT = false;
public static boolean OPENGL_SRGB_CONTEXT = false;
public static boolean OPENGL_DOUBLEBUFFER = true;
@@ -43,9 +44,7 @@ public class Config {
public static boolean INPUT_ALTGR_ESCAPE_CODES = false;
public static boolean INPUT_RAW_MOUSE = false;
public static String X11_CLASS_NAME = "minecraft";
public static String COCOA_FRAME_NAME = "minecraft";
public static String WAYLAND_APP_ID = "minecraft";
public static String APP_ID = "com.gtnewhorizons.Lwjgl3ifyMinecraft";
public static String LWJGL3IFY_VERSION = Tags.VERSION;
@@ -84,7 +83,7 @@ public class Config {
"stbiTextureLoading",
CATEGORY_MIXIN,
MIXIN_STBI_TEXTURE_LOADING,
"Use the faster stb_image-based texture loader");
"Use the faster spng-based texture loader");
MIXIN_STBI_TEXTURE_STITCHING = config.getBoolean(
"stbiTextureStitching",
CATEGORY_MIXIN,
@@ -138,21 +137,16 @@ public class Config {
CATEGORY_WINDOW,
WINDOW_DECORATED,
"Should the window have decorations (titlebar, border, close button)");
X11_CLASS_NAME = config.getString(
"x11ClassName",
APP_ID = config.getString(
"appId",
CATEGORY_WINDOW,
X11_CLASS_NAME,
"Linux-only - change the X11 class name, which is used by your window manager to identify the running application");
COCOA_FRAME_NAME = config.getString(
"cocoaFrameName",
APP_ID,
"Changes the application ID used for categorizing windows in window managers, saving per-app settings etc.");
WINDOW_HIDPI_RENDERING = config.getBoolean(
"hidpiRendering",
CATEGORY_WINDOW,
COCOA_FRAME_NAME,
"OSX-only - identifier used to save and restore the window position and size");
WAYLAND_APP_ID = config.getString(
"waylandAppId",
CATEGORY_WINDOW,
WAYLAND_APP_ID,
"Linux-only - change the Wayland app id, which is used by your window manager to identify the running application");
WINDOW_HIDPI_RENDERING,
"Enables high DPI rendering in the window, make sure to increase your GUI scale in options if enabled");
INPUT_INVERT_WHEEL = config
.getBoolean("invertScrollWheel", CATEGORY_INPUT, INPUT_INVERT_WHEEL, "Invert scrolling direction");
@@ -1,9 +1,5 @@
package me.eigenraven.lwjgl3ify.core;
import java.awt.Toolkit;
import org.lwjgl.system.Configuration;
import org.lwjgl.system.Platform;
import org.lwjglx.Sys;
import cpw.mods.fml.relauncher.FMLLaunchHandler;
@@ -19,16 +15,7 @@ public class LateInit {
}
if (FMLLaunchHandler.side()
.isClient()) {
clientMacOsFix();
Sys.initialize();
}
}
private static void clientMacOsFix() {
if (Platform.get() == Platform.MACOSX) {
Configuration.GLFW_LIBRARY_NAME.set("glfw_async");
Configuration.GLFW_CHECK_THREAD0.set(false);
Toolkit.getDefaultToolkit(); // Initialize AWT before GLFW
}
}
}
@@ -23,13 +23,20 @@ public enum Mixins implements IMixins {
FIX_DEADKEY_KEYBINDING(
new MixinBuilder("Improved KeyBinding handling to handle dead keys")
.addClientMixins("game.MixinMinecraftKeyBinding")),
BORDERLESS_FULLSCREEN(
new MixinBuilder()
.addClientMixins("game.MixinBorderlessWindow")),
STB_TEXTURE_LOADING(
new MixinBuilder()
.addClientMixins("game.MixinTextureAtlasSprite", "game.MixinTextureMap")
.setApplyIf(() -> Config.MIXIN_STBI_TEXTURE_LOADING)),
TEXT_FIELD_SDL_INPUT(
new MixinBuilder()
.addClientMixins("game.MixinGuiTextField", "game.MixinGuiScreen")),
OPEN_URL_WITH_SDL(
new MixinBuilder()
.addClientMixins(
"game.openurl.MixinGuiChat",
"game.openurl.MixinGuiMainMenu",
"game.openurl.MixinGuiScreenDemoResourcePacks",
"game.openurl.MixinGuiStreamUnavailable")),
// apply the texture stitching mixin if
// - you don't have fastcraft
@@ -1,26 +0,0 @@
package me.eigenraven.lwjgl3ify.mixins.early.game;
import static org.lwjgl.glfw.GLFW.*;
import net.minecraft.client.Minecraft;
import org.lwjglx.opengl.Display;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import me.eigenraven.lwjgl3ify.core.Config;
@Mixin(Minecraft.class)
public class MixinBorderlessWindow {
@Inject(method = "Lnet/minecraft/client/Minecraft;toggleFullscreen()V", at = @At("HEAD"), cancellable = true)
public void toggleFullscreen(CallbackInfo ci) {
if (Config.WINDOW_BORDERLESS_REPLACES_FULLSCREEN) {
ci.cancel();
Display.toggleBorderless();
}
}
}
@@ -0,0 +1,31 @@
package me.eigenraven.lwjgl3ify.mixins.early.game;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiScreen;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import me.eigenraven.lwjgl3ify.client.TextFieldHandler;
@Mixin(GuiScreen.class)
public class MixinGuiScreen extends Gui {
/**
* @author eigenraven
* @reason Replace AWT reliance with SDL APIs.
*/
@Overwrite
public static String getClipboardString() {
return TextFieldHandler.getClipboardText();
}
/**
* @author eigenraven
* @reason Replace AWT reliance with SDL APIs.
*/
@Overwrite
public static void setClipboardString(final String newText) {
TextFieldHandler.setClipboardText(newText);
}
}
@@ -0,0 +1,43 @@
package me.eigenraven.lwjgl3ify.mixins.early.game;
import net.minecraft.client.gui.GuiTextField;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import me.eigenraven.lwjgl3ify.client.TextFieldHandler;
@Mixin(GuiTextField.class)
public class MixinGuiTextField {
@Shadow
private boolean isFocused;
@Inject(method = "setFocused", at = @At("HEAD"))
private void lwjgl3ify$onFocusChange(boolean nowFocused, CallbackInfo ci) {
final GuiTextField self = (GuiTextField) (Object) this;
final boolean wasFocused = isFocused;
if (nowFocused) {
TextFieldHandler.setFocusedTextField(self);
}
if (nowFocused == wasFocused) {
return;
}
if (nowFocused) {
TextFieldHandler.beginTextInput();
} else {
TextFieldHandler.endTextInput(self);
}
}
@Redirect(
method = "textboxKeyTyped",
at = @At(value = "INVOKE", target = "Lnet/minecraft/util/ChatAllowedCharacters;isAllowedCharacter(C)Z"))
private boolean lwjgl3ify$denyStandardTextInput(char character) {
return false;
}
}
@@ -0,0 +1,19 @@
package me.eigenraven.lwjgl3ify.mixins.early.game.openurl;
import net.minecraft.client.gui.GuiChat;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.Constant;
import org.spongepowered.asm.mixin.injection.ModifyConstant;
@Mixin({ GuiChat.class })
public class MixinGuiChat {
@ModifyConstant(
method = { "Lnet/minecraft/client/gui/GuiChat;func_146407_a(Ljava/net/URI;)V" },
constant = @Constant(stringValue = "java.awt.Desktop"),
require = 0)
private String lwjgl3ify$openUrlInSdl(String original) {
return "me.eigenraven.lwjgl3ify.redirects.Desktop";
}
}
@@ -0,0 +1,19 @@
package me.eigenraven.lwjgl3ify.mixins.early.game.openurl;
import net.minecraft.client.gui.GuiMainMenu;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.Constant;
import org.spongepowered.asm.mixin.injection.ModifyConstant;
@Mixin({ GuiMainMenu.class })
public class MixinGuiMainMenu {
@ModifyConstant(
method = { "Lnet/minecraft/client/gui/GuiMainMenu;confirmClicked(ZI)V" },
constant = @Constant(stringValue = "java.awt.Desktop"),
require = 0)
private String lwjgl3ify$openUrlInSdl(String original) {
return "me.eigenraven.lwjgl3ify.redirects.Desktop";
}
}
@@ -0,0 +1,20 @@
package me.eigenraven.lwjgl3ify.mixins.early.game.openurl;
import net.minecraft.client.gui.GuiScreenDemo;
import net.minecraft.client.gui.GuiScreenResourcePacks;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.Constant;
import org.spongepowered.asm.mixin.injection.ModifyConstant;
@Mixin({ GuiScreenDemo.class, GuiScreenResourcePacks.class })
public class MixinGuiScreenDemoResourcePacks {
@ModifyConstant(
method = { "actionPerformed(Lnet/minecraft/client/gui/GuiButton;)V", },
constant = @Constant(stringValue = "java.awt.Desktop"),
require = 0)
private String lwjgl3ify$openUrlInSdl(String original) {
return "me.eigenraven.lwjgl3ify.redirects.Desktop";
}
}
@@ -0,0 +1,19 @@
package me.eigenraven.lwjgl3ify.mixins.early.game.openurl;
import net.minecraft.client.gui.stream.GuiStreamUnavailable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.Constant;
import org.spongepowered.asm.mixin.injection.ModifyConstant;
@Mixin({ GuiStreamUnavailable.class })
public class MixinGuiStreamUnavailable {
@ModifyConstant(
method = { "Lnet/minecraft/client/gui/stream/GuiStreamUnavailable;func_152320_a(Ljava/lang/String;)V" },
constant = @Constant(stringValue = "java.awt.Desktop"),
require = 0)
private String lwjgl3ify$openUrlInSdl(String original) {
return "me.eigenraven.lwjgl3ify.redirects.Desktop";
}
}
@@ -0,0 +1,29 @@
package me.eigenraven.lwjgl3ify.redirects;
import java.net.URI;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.sdl.SDLMisc;
import me.eigenraven.lwjgl3ify.client.MainThreadExec;
/**
* Mixins redirect {@link java.awt.Desktop#browse(URI)} here.
*/
@SuppressWarnings("unused")
public final class Desktop {
public static final Desktop INSTANCE = new Desktop();
private static final Logger LOGGER = LogManager.getLogger("lwjgl3ify");
public static Desktop getDesktop() {
return INSTANCE;
}
public void browse(URI uri) {
final String uriString = uri.toString();
LOGGER.info("Opening URL via SDL: {}", uriString);
MainThreadExec.runOnMainThread(() -> { SDLMisc.SDL_OpenURL(uriString); });
}
}
@@ -61,14 +61,11 @@ public class Relauncher {
Path cacheDir;
try {
if (system.contains("win")) {
String temp = System.getenv("TEMP");
String localAppData = System.getenv("LOCALAPPDATA");
if (temp != null) {
cacheDir = Paths.get(temp, "lwjgl3ify");
} else if (localAppData != null) {
cacheDir = Paths.get(localAppData, "Temp", "lwjgl3ify");
if (localAppData != null) {
cacheDir = Paths.get(localAppData, "lwjgl3ify");
} else {
cacheDir = Paths.get(userHome, "AppData", "Local", "Temp", "lwjgl3ify");
cacheDir = Paths.get(userHome, "AppData", "Local", "lwjgl3ify");
}
} else if (system.contains("mac")) {
cacheDir = Paths.get(userHome, "Library", "Caches", "lwjgl3ify");
@@ -82,7 +79,7 @@ public class Relauncher {
}
} catch (InvalidPathException e) {
if (system.contains("win")) {
cacheDir = Paths.get(userHome, "AppData", "Local", "Temp", "lwjgl3ify");
cacheDir = Paths.get(userHome, "AppData", "Local", "lwjgl3ify");
} else {
cacheDir = Paths.get(userHome, ".cache", "lwjgl3ify");
}
@@ -193,6 +190,9 @@ public class Relauncher {
final List<String> cmd = new ArrayList<>();
cmd.addAll(Arrays.asList(RECOMMENDED_JAVA_ARGS));
if (SystemUtils.IS_OS_MAC) {
cmd.add("-XstartOnFirstThread");
}
cmd.addAll(RelauncherConfig.config.toJvmArgs());
cmd.add("-cp");
cmd.add(StringUtils.join(createClasspath(), File.pathSeparatorChar));
@@ -214,7 +214,7 @@ public class Relauncher {
cmd.add("-D" + key + "=" + value);
}
cmd.add("com.gtnewhorizons.retrofuturabootstrap.Main");
cmd.add("com.gtnewhorizons.retrofuturabootstrap.MainStartOnFirstThread");
cmd.addAll(
Arrays.asList(
@@ -10,6 +10,7 @@ import java.lang.reflect.InvocationTargetException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -23,15 +24,12 @@ import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;
import javax.swing.text.DefaultEditorKit;
import org.apache.commons.lang3.StringUtils;
import com.github.weisj.darklaf.LafManager;
import com.github.weisj.darklaf.theme.spec.ColorToneRule;
import com.github.weisj.darklaf.theme.spec.ContrastRule;
import com.github.weisj.darklaf.theme.spec.PreferredThemeStyle;
import com.google.common.base.Throwables;
/** Implements the UI components of the relauncher */
@@ -66,9 +64,15 @@ public class RelauncherUserInterface {
.setContextClassLoader(mcLoader);
try {
System.setProperty("awt.useSystemAAFontSettings", "on");
LafManager.installTheme(new PreferredThemeStyle(ContrastRule.STANDARD, ColorToneRule.DARK));
if (System.getProperty("os.name")
.toLowerCase(Locale.ROOT)
.contains("linux")) {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} else {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
} catch (Exception e) {
Relauncher.logger.warn("Could not initialize DarkLaf GUI theme", e);
Relauncher.logger.warn("Could not initialize GUI theme", e);
}
Thread.currentThread()
.setContextClassLoader(original);
@@ -5,14 +5,15 @@ import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import org.apache.commons.io.IOUtils;
import org.lwjgl.stb.STBImage;
import org.lwjgl.PointerBuffer;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.system.MemoryUtil;
import org.lwjgl.util.spng.SPNG;
import org.lwjgl.util.spng.spng_ihdr;
public class NativeBackedImage extends BufferedImage implements AutoCloseable {
@@ -83,7 +84,7 @@ public class NativeBackedImage extends BufferedImage implements AutoCloseable {
@Override
public void close() throws Exception {
if (this.pointer != 0) {
STBImage.nstbi_image_free(this.pointer);
MemoryUtil.nmemFree(this.pointer);
this.pointer = 0;
}
@@ -98,6 +99,15 @@ public class NativeBackedImage extends BufferedImage implements AutoCloseable {
// Parsing
static final int MAX_IMAGE_DIM = 32768;
private static final void spngCheck(int ec) throws IOException {
if (ec == 0) {
return;
}
throw new IOException("Error while decoding PNG data: " + SPNG.spng_strerror(ec));
}
public static NativeBackedImage make(InputStream stream) throws IOException {
ByteBuffer imgBuf = null;
@@ -106,17 +116,39 @@ public class NativeBackedImage extends BufferedImage implements AutoCloseable {
imgBuf.rewind();
try (MemoryStack memoryStack = MemoryStack.stackPush()) {
IntBuffer width = memoryStack.mallocInt(1);
IntBuffer height = memoryStack.mallocInt(1);
IntBuffer channels = memoryStack.mallocInt(1);
PointerBuffer outSize = memoryStack.mallocPointer(1);
spng_ihdr ihdr = spng_ihdr.calloc(memoryStack);
// 4 channels: RGBA
ByteBuffer buf = STBImage.stbi_load_from_memory(imgBuf, width, height, channels, 4);
if (buf == null) {
throw new IOException("Could not load image: " + STBImage.stbi_failure_reason());
long ctx = SPNG.spng_ctx_new(0);
final long imageBuffer;
try {
spngCheck(SPNG.spng_set_image_limits(ctx, 32768, 32768));
// 1 GB PNG file ought to be enough for anyone
spngCheck(SPNG.spng_set_chunk_limits(ctx, 1 << 30, 1 << 30));
spngCheck(SPNG.spng_set_png_buffer(ctx, imgBuf));
spngCheck(SPNG.spng_decoded_image_size(ctx, SPNG.SPNG_FMT_RGBA8, outSize));
if (outSize.get(0) > MAX_IMAGE_DIM * MAX_IMAGE_DIM) {
throw new IOException(
String.format(
"Could not load image: output buffer size %d larger than max supported %d x %d",
outSize.get(0),
MAX_IMAGE_DIM,
MAX_IMAGE_DIM));
}
final int outSizeI = Math.toIntExact(outSize.get(0));
spngCheck(SPNG.spng_get_ihdr(ctx, ihdr));
imageBuffer = MemoryUtil.nmemAlloc(outSizeI);
final int decodeEc = SPNG.nspng_decode_image(ctx, imageBuffer, outSizeI, SPNG.SPNG_FMT_RGBA8, 0);
if (decodeEc != 0) {
MemoryUtil.nmemFree(imageBuffer);
spngCheck(decodeEc);
}
} finally {
SPNG.spng_ctx_free(ctx);
}
return new NativeBackedImage(width.get(0), height.get(0), MemoryUtil.memAddress(buf));
return new NativeBackedImage(ihdr.width(), ihdr.height(), imageBuffer);
}
} finally {
@@ -0,0 +1,208 @@
package org.lwjglx;
import static org.lwjgl.sdl.SDLError.*;
import static org.lwjgl.sdl.SDLEvents.*;
import static org.lwjgl.sdl.SDLInit.*;
import static org.lwjgl.sdl.SDLKeyboard.*;
import static org.lwjgl.sdl.SDLKeycode.*;
import static org.lwjgl.sdl.SDLMouse.*;
import static org.lwjgl.sdl.SDLPixels.*;
import static org.lwjgl.sdl.SDLVideo.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*;
import org.lwjgl.sdl.SDL_Event;
import org.lwjgl.sdl.SDL_KeyboardEvent;
import org.lwjgl.sdl.SDL_MouseButtonEvent;
import org.lwjgl.sdl.SDL_MouseMotionEvent;
import org.lwjgl.sdl.SDL_MouseWheelEvent;
import org.lwjgl.sdl.SDL_TextInputEvent;
import org.lwjgl.sdl.SDL_WindowEvent;
import org.lwjglx.input.KeyCodes;
import org.lwjglx.input.Keyboard;
import org.lwjglx.input.Mouse;
import org.lwjglx.opengl.Display;
import me.eigenraven.lwjgl3ify.Lwjgl3ify;
import me.eigenraven.lwjgl3ify.api.InputEvents;
import me.eigenraven.lwjgl3ify.client.MainThreadExec;
import me.eigenraven.lwjgl3ify.core.Config;
/**
* Singleton (static) class for handling the SDL event loop on the correct main thread.
*/
public class Lwjgl3ifyEventLoop {
/**
* Call on the thread that called Java main() to process incoming SDL events.
*/
public static void pumpEvents() {
MainThreadExec.runOnMainThread(Lwjgl3ifyEventLoop::internalPumpEvents);
}
public static final SDL_Event event = SDL_Event.calloc();
public static final SDL_WindowEvent windowEvent = event.window();
public static final SDL_KeyboardEvent keyEvent = event.key();
public static final SDL_TextInputEvent textEvent = event.text();
public static final SDL_MouseMotionEvent mouseMotionEvent = event.motion();
public static final SDL_MouseButtonEvent mouseButtonEvent = event.button();
public static final SDL_MouseWheelEvent mouseWheelEvent = event.wheel();
private static void internalPumpEvents() {
if (!SDL_IsMainThread()) {
throw new IllegalStateException("SDL Event pump called from a non-main thread " + Thread.currentThread());
}
while (SDL_PollEvent(event)) {
if (Display.lwjgl3ify$handleSdlEvent()) {
continue;
}
switch (event.type()) {
case SDL_EVENT_MOUSE_MOTION -> {
if (Config.DEBUG_PRINT_MOUSE_EVENTS) {
Lwjgl3ify.LOG.info(
"[DEBUG-MOUSE] Motion ns:{} x:{} y:{} xrel:{} yrel:{}",
mouseMotionEvent.timestamp(),
mouseMotionEvent.x(),
mouseMotionEvent.y(),
mouseMotionEvent.xrel(),
mouseMotionEvent.yrel());
}
Mouse.addMoveEvent(mouseMotionEvent);
}
case SDL_EVENT_MOUSE_BUTTON_DOWN, SDL_EVENT_MOUSE_BUTTON_UP -> {
if (Config.DEBUG_PRINT_MOUSE_EVENTS) {
Lwjgl3ify.LOG.info(
"[DEBUG-MOUSE] Press ns:{} button:{} press:{} clicks:{} x:{} y:{}",
mouseButtonEvent.timestamp(),
mouseButtonEvent.button(),
mouseButtonEvent.down(),
mouseButtonEvent.clicks(),
mouseButtonEvent.x(),
mouseButtonEvent.y());
}
Mouse.addButtonEvent(
Mouse.sdlToLwjglMouseButton(mouseButtonEvent.button()),
event.type() == SDL_EVENT_MOUSE_BUTTON_DOWN);
}
case SDL_EVENT_MOUSE_WHEEL -> {
float xoffset = mouseWheelEvent.x();
float yoffset = mouseWheelEvent.y();
Mouse.addWheelEvent(yoffset == 0 ? (Config.INPUT_INVERT_X_WHEEL ? -xoffset : xoffset) : yoffset);
}
case SDL_EVENT_KEY_DOWN, SDL_EVENT_KEY_UP -> {
handleKeyEvent();
}
case SDL_EVENT_TEXT_INPUT -> {
handleTextEvent();
}
default -> {}
}
}
Mouse.sdlMouseButtonFlags = nSDL_GetMouseState(0, 0);
}
private static char rawKeyCodeToChar(int rawKeyCode) {
if (rawKeyCode < 0xFFFF) {
return (char) rawKeyCode;
} else {
return '\0';
}
}
// Assumes event type of SDL_EVENT_KEY_DOWN or SDL_EVENT_KEY_UP
private static void handleKeyEvent() {
final long ns = keyEvent.timestamp();
final boolean isDown = keyEvent.down();
final boolean isRepeat = keyEvent.repeat();
final short kmods = keyEvent.mod();
final int keyCode = keyEvent.key();
final int scanCode = keyEvent.scancode();
final long keyNamePtr = nSDL_GetKeyName(keyCode);
final int rawKeyCode = SDL_GetKeyFromScancode(scanCode, kmods, false);
final int lwjgl2KeyCode = KeyCodes.sdlKeycodeToLwjgl(keyCode);
final int lwjgl2ScanCode = KeyCodes.sdlScancodeToLwjgl(keyCode);
if (Config.DEBUG_PRINT_KEY_EVENTS) {
Lwjgl3ify.LOG.info(
"[DEBUG-KEY] key ns:{} key:{} ({}) rawKey:{} scancode:{} isDown:{} {} mods:{} naive-char:{}",
ns,
keyCode,
memUTF8Safe(keyNamePtr),
rawKeyCode,
scanCode,
isDown ? "PRESS" : "RELEASE",
isRepeat ? "REPEAT" : "",
kmods,
(rawKeyCode >= 32 && rawKeyCode < 0xFF_FFFF) ? ((char) rawKeyCode) : '?');
}
final InputEvents.KeyAction enumAction;
if (isDown) {
enumAction = isRepeat ? InputEvents.KeyAction.REPEATED : InputEvents.KeyAction.PRESSED;
} else {
enumAction = InputEvents.KeyAction.RELEASED;
}
InputEvents.injectKeyEvent(
new InputEvents.KeyEvent(
lwjgl2KeyCode,
lwjgl2ScanCode,
keyCode,
scanCode,
rawKeyCode,
enumAction,
kmods,
keyNamePtr));
if (rawKeyCode >= SDLK_SPACE && rawKeyCode <= SDLK_TILDE) {
/*
* AltGr and LAlt require special consideration.
* On Windows, AltGr and Ctrl+Alt send the same `mods` value of ALT|CTRL in this event.
* This means that to distinguish potential text input from special key combos we have to look at
* the last pressed Alt key side.
* Ctrl combos have to send a (key & 0x1f) ASCII Escape code to work correctly with a lot of older
* mods, but this obviously breaks text input.
* Therefore, we assume text input with AltGr, and control combination input with Left Alt, but both
* can be switched in the config if the player desires.
*/
final boolean isAlt = (kmods & SDL_KMOD_ALT) != 0;
final boolean isAltGr = (kmods & SDL_KMOD_RALT) != 0;
final boolean ctrlGraphicalMode;
if (isAlt) {
if (isAltGr) {
ctrlGraphicalMode = !Config.INPUT_ALTGR_ESCAPE_CODES;
} else {
// is left alt
ctrlGraphicalMode = Config.INPUT_CTRL_ALT_TEXT;
}
if (ctrlGraphicalMode) {
Keyboard.addSdlKeyEvent(keyCode, scanCode, enumAction, kmods, (char) (rawKeyCode & 0x1f), ns);
}
} else {
ctrlGraphicalMode = false;
}
if ((SDL_KMOD_GUI & kmods) != 0) {
Keyboard.addSdlKeyEvent(keyCode, scanCode, enumAction, kmods, rawKeyCodeToChar(rawKeyCode), ns);
} else if ((SDL_KMOD_CTRL & kmods) != 0 && !ctrlGraphicalMode) { // Handle ctrl + x/c/v.
if (Config.DEBUG_PRINT_KEY_EVENTS) {
Lwjgl3ify.LOG.info(
"[DEBUG-KEY] Handling key as escape code, skipping next char input. isAlt:{} isAltGr:{}",
isAlt,
isAltGr);
}
Keyboard.addSdlKeyEvent(keyCode, scanCode, enumAction, kmods, (char) (rawKeyCode & 0x1f), ns);
} else {
Keyboard.addSdlKeyEvent(keyCode, scanCode, enumAction, kmods, rawKeyCodeToChar(rawKeyCode), ns);
}
} else { // Other key with no char event associated
Keyboard.addSdlKeyEvent(keyCode, scanCode, enumAction, kmods, rawKeyCodeToChar(rawKeyCode), ns);
}
}
private static void handleTextEvent() {
final long ns = textEvent.timestamp();
final String text = textEvent.textString();
if (Config.DEBUG_PRINT_KEY_EVENTS) {
Lwjgl3ify.LOG.info("[DEBUG-KEY] ns:{} text:<{}>", ns, text);
}
InputEvents.injectTextEvent(new InputEvents.TextEvent(text));
}
}
@@ -0,0 +1,14 @@
package org.lwjglx;
import static org.lwjgl.sdl.SDLError.SDL_GetError;
public class SDLException extends RuntimeException {
public SDLException() {
super("SDL error: " + SDL_GetError());
}
public SDLException(String message) {
super(message + ", SDL error: " + SDL_GetError());
}
}
+100 -39
View File
@@ -1,31 +1,81 @@
package org.lwjglx;
import static org.lwjgl.glfw.GLFW.glfwInit;
import static org.lwjgl.sdl.SDLHints.*;
import static org.lwjgl.sdl.SDLInit.*;
import static org.lwjgl.sdl.SDLMessageBox.*;
import static org.lwjgl.sdl.SDLStdinc.*;
import static org.lwjgl.sdl.SDLTimer.*;
import static org.lwjgl.system.MemoryUtil.NULL;
import java.awt.Desktop;
import java.net.URI;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import java.awt.GraphicsEnvironment;
import java.util.concurrent.atomic.AtomicBoolean;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.Version;
import org.lwjgl.glfw.GLFW;
import org.lwjgl.sdl.SDLClipboard;
import org.lwjgl.sdl.SDLMisc;
import org.lwjgl.system.Configuration;
import org.lwjgl.system.MemoryUtil;
import org.lwjgl.system.Platform;
import org.lwjgl.system.Pointer;
import org.lwjglx.opengl.Display;
import me.eigenraven.lwjgl3ify.client.MainThreadExec;
import me.eigenraven.lwjgl3ify.core.Config;
public class Sys {
static {
try {
Class<?> debug = Class.forName("org.lwjglx.debug.org.lwjgl.glfw.GLFW");
debug.getMethod("glfwInit")
.invoke((Object) null);
} catch (Throwable ignored) {
if (!glfwInit()) throw new IllegalStateException("Unable to initialize glfw");
static private void firstTimeInit() {
Configuration.OPENGL_EXPLICIT_INIT.set(true);
Configuration.HARFBUZZ_LIBRARY_NAME.set("freetype");
if (Platform.get() == Platform.MACOSX) {
if (!GraphicsEnvironment.isHeadless()) {
throw new IllegalStateException(
"java.awt.headless must be set to true on macOS, this is normally set by RFB!");
}
}
MainThreadExec.ensureInitialised();
MainThreadExec.runOnMainThread(() -> {
SDL_SetMemoryFunctions(
MemoryUtil::nmemAllocChecked,
MemoryUtil::nmemCallocChecked,
MemoryUtil::nmemReallocChecked,
MemoryUtil::nmemFree);
checkSdl(SDL_SetAppMetadata("Lwjgl3ify Minecraft", "1.7.10", Config.APP_ID));
checkSdl(
SDL_SetAppMetadataProperty(
SDL_PROP_APP_METADATA_URL_STRING,
"https://github.com/GTNewHorizons/lwjgl3ify"));
checkSdl(SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_CREATOR_STRING, "Mojang, GTNH Team"));
checkSdl(
SDL_SetAppMetadataProperty(
SDL_PROP_APP_METADATA_COPYRIGHT_STRING,
"https://www.minecraft.net/en-us/eula"));
checkSdl(SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_TYPE_STRING, "game"));
if (!SDL_Init(
SDL_INIT_VIDEO | SDL_INIT_EVENTS
| SDL_INIT_JOYSTICK
| SDL_INIT_GAMEPAD
| SDL_INIT_HAPTIC
| SDL_INIT_SENSOR)) {
throw new SDLException("Could not initialize SDL.");
}
if (Platform.get() == Platform.MACOSX) {
SDL_SetHint(SDL_HINT_MAC_OPENGL_ASYNC_DISPATCH, "1");
}
});
}
public static void initialize() {}
private static final AtomicBoolean isFirstInit = new AtomicBoolean(true);
public static void initialize() {
if (!isFirstInit.compareAndSet(true, false)) {
return;
} else {
firstTimeInit();
}
}
/** Returns the LWJGL version. */
public static String getVersion() {
@@ -39,7 +89,7 @@ public class Sys {
* @return timer resolution in ticks per second or 0 if no timer is present.
*/
public static long getTimerResolution() {
return 1000;
return 1_000_000;
}
/**
@@ -51,43 +101,54 @@ public class Sys {
* @return the current hires time, in ticks (always >= 0)
*/
public static long getTime() {
return (long) (GLFW.glfwGetTime() * 1000);
return SDL_GetTicksNS() / 1_000;
}
public static long getNanoTime() {
return (long) (GLFW.glfwGetTime() * (1000L * 1000L * 1000L));
return SDL_GetTicksNS();
}
public static boolean openURL(String url) {
if (!Desktop.isDesktopSupported()) return false;
Desktop desktop = Desktop.getDesktop();
if (!desktop.isSupported(Desktop.Action.BROWSE)) return false;
try {
desktop.browse(new URI(url));
return true;
} catch (Exception ex) {
return false;
}
return MainThreadExec.runOnMainThread(() -> SDLMisc.SDL_OpenURL(url));
}
public static void alert(String title, String message) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
LWJGLUtil.log("Caught exception while setting LAF: " + e);
}
JOptionPane.showMessageDialog(null, message, title, JOptionPane.WARNING_MESSAGE);
MainThreadExec.runOnMainThread(
() -> { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING, title, message, Display.getWindow()); });
}
public static boolean is64Bit() {
return Platform.getArchitecture()
.toString()
.endsWith("64");
return Pointer.BITS64;
}
public static String getClipboard() {
return GLFW.glfwGetClipboardString(Display.getWindow());
return MainThreadExec.runOnMainThread(SDLClipboard::SDL_GetClipboardText);
}
public static void checkSdl(boolean result) {
if (!result) {
throw new SDLException();
}
}
public static <T> @NotNull T checkSdl(@Nullable T result) {
if (result == null) {
throw new SDLException();
}
return result;
}
public static int checkSdl(int result) {
if (result == NULL) {
throw new SDLException();
}
return result;
}
public static long checkSdl(long result) {
if (result == NULL) {
throw new SDLException();
}
return result;
}
}
+61 -81
View File
@@ -15,9 +15,18 @@
*/
package org.lwjglx.input;
import static org.lwjgl.sdl.SDLMouse.*;
import static org.lwjgl.sdl.SDLPixels.*;
import static org.lwjgl.sdl.SDLSurface.*;
import java.nio.IntBuffer;
import org.lwjglx.LWJGLException;
import org.joml.Math;
import org.lwjgl.sdl.SDL_Surface;
import org.lwjgl.system.MemoryStack;
import org.lwjglx.Sys;
import me.eigenraven.lwjgl3ify.client.MainThreadExec;
/**
*
@@ -38,13 +47,16 @@ public class Cursor {
public static final int CURSOR_ANIMATION = 4;
/** First element to display */
private final CursorElement[] cursors;
private final CursorElement[] cursors = null;
/** Index into list of cursors */
private int index;
private boolean destroyed;
private long sdlCursor;
private SDL_Surface sdlSurface;
/**
* Constructs a new Cursor, with the given parameters. Mouse must have been created before you can create Cursor
* objects. Cursor images are in ARGB format, but only one bit transparancy is guaranteed to be supported. So to
@@ -58,12 +70,32 @@ public class Cursor {
* @param numImages number of cursor images specified. Must be 1 if animations are not supported.
* @param images A buffer containing the images. The origin is at the lower left corner, like OpenGL.
* @param delays An int buffer of animation frame delays, if numImages is greater than 1, else null
* @throws LWJGLException if the cursor could not be created for any reason
*/
public Cursor(int width, int height, int xHotspot, int yHotspot, int numImages, IntBuffer images, IntBuffer delays)
throws LWJGLException {
// TODO
cursors = null;
public Cursor(int width, int height, int xHotspot, int yHotspot, int numImages, IntBuffer images,
IntBuffer delays) {
final int pixels = width * height;
if (numImages < 1) {
throw new IllegalArgumentException("There must be at least 1 cursor image");
}
if (images.remaining() < pixels) {
throw new IllegalArgumentException("Not enough pixels in the cursor image");
}
try (MemoryStack stack = MemoryStack.stackPush()) {
sdlSurface = Sys.checkSdl(SDL_CreateSurface(width, height, SDL_PIXELFORMAT_BGRA32));
Sys.checkSdl(SDL_LockSurface(sdlSurface));
final IntBuffer targetInts = sdlSurface.pixels()
.asIntBuffer();
for (int i = 0; i < pixels; i++) {
targetInts.put(i, images.get(i));
}
SDL_UnlockSurface(sdlSurface);
SDL_FlipSurface(sdlSurface, SDL_FLIP_VERTICAL);
sdlCursor = Sys.checkSdl(
SDL_CreateColorCursor(
sdlSurface,
Math.clamp(xHotspot, 0, width - 1),
Math.clamp(height - 1 - yHotspot, 0, height - 1)));
}
}
/**
@@ -73,8 +105,7 @@ public class Cursor {
* @return the maximum size of a native cursor
*/
public static int getMinCursorSize() {
// TODO
return 0;
return 8;
}
/**
@@ -84,8 +115,7 @@ public class Cursor {
* @return the maximum size of a native cursor
*/
public static int getMaxCursorSize() {
// TODO
return 0;
return 64;
}
/**
@@ -96,74 +126,7 @@ public class Cursor {
* @return A bit mask with native cursor capabilities.
*/
public static int getCapabilities() {
// TODO
return 0;
}
/**
* Creates the actual cursor, using a platform specific class
*/
private static CursorElement[] createCursors(int width, int height, int xHotspot, int yHotspot, int numImages,
IntBuffer images, IntBuffer delays) throws LWJGLException {
// TODO
return null;
}
/**
* Convert an IntBuffer image of ARGB format into ABGR
*
* @param imageBuffer image to convert
*/
private static void convertARGBtoABGR(IntBuffer imageBuffer) {
for (int i = 0; i < imageBuffer.limit(); i++) {
int argbColor = imageBuffer.get(i);
byte alpha = (byte) (argbColor >>> 24);
byte blue = (byte) (argbColor >>> 16);
byte green = (byte) (argbColor >>> 8);
byte red = (byte) argbColor;
int abgrColor = ((alpha & 0xff) << 24) + ((red & 0xff) << 16) + ((green & 0xff) << 8) + ((blue & 0xff));
imageBuffer.put(i, abgrColor);
}
}
/**
* Flips the images so they're oriented according to opengl
*
* @param width Width of image
* @param height Height of images
* @param numImages How many images to flip
* @param images Source images
* @param images_copy Destination images
*/
private static void flipImages(int width, int height, int numImages, IntBuffer images, IntBuffer images_copy) {
for (int i = 0; i < numImages; i++) {
int start_index = i * width * height;
flipImage(width, height, start_index, images, images_copy);
}
}
/**
* @param width Width of image
* @param height Height of images
* @param start_index index into source buffer to copy to
* @param images Source images
* @param images_copy Destination images
*/
private static void flipImage(int width, int height, int start_index, IntBuffer images, IntBuffer images_copy) {
for (int y = 0; y < height >> 1; y++) {
int index_y_1 = y * width + start_index;
int index_y_2 = (height - y - 1) * width + start_index;
for (int x = 0; x < width; x++) {
int index1 = index_y_1 + x;
int index2 = index_y_2 + x;
int temp_pixel = images.get(index1 + images.position());
images_copy.put(index1, images.get(index2 + images.position()));
images_copy.put(index2, temp_pixel);
}
}
return CURSOR_ONE_BIT_TRANSPARENCY | CURSOR_8_BIT_ALPHA;
}
/**
@@ -183,7 +146,17 @@ public class Cursor {
* cursor)
*/
public void destroy() {
// TODO
if (Mouse.getNativeCursor() == this) {
Mouse.setNativeCursor(null);
}
if (sdlCursor != 0) {
SDL_DestroyCursor(sdlCursor);
sdlCursor = 0;
}
if (sdlSurface != null) {
SDL_DestroySurface(sdlSurface);
sdlSurface = null;
}
}
/**
@@ -196,7 +169,7 @@ public class Cursor {
/**
* Determines whether this cursor has timed out
*
*
* @return true if the this cursor has timed out, false if not
*/
protected boolean hasTimedOut() {
@@ -232,4 +205,11 @@ public class Cursor {
this.timeout = timeout;
}
}
void sdlSet() {
if (sdlCursor == 0) {
return;
}
MainThreadExec.runOnMainThread(() -> SDL_SetCursor(sdlCursor));
}
}
+590 -281
View File
@@ -1,304 +1,613 @@
package org.lwjglx.input;
import static org.lwjgl.sdl.SDLKeycode.*;
import static org.lwjgl.sdl.SDLScancode.*;
import java.awt.event.KeyEvent;
import org.lwjgl.glfw.GLFW;
public class KeyCodes {
public static int glfwToLwjgl(int glfwKeyCode) {
if (glfwKeyCode > GLFW.GLFW_KEY_LAST) {
return glfwKeyCode;
}
return switch (glfwKeyCode) {
case GLFW.GLFW_KEY_UNKNOWN -> Keyboard.KEY_UNLABELED; // arbitrary mapping to fix text input here
case GLFW.GLFW_KEY_ESCAPE -> Keyboard.KEY_ESCAPE;
case GLFW.GLFW_KEY_BACKSPACE -> Keyboard.KEY_BACK;
case GLFW.GLFW_KEY_TAB -> Keyboard.KEY_TAB;
case GLFW.GLFW_KEY_ENTER -> Keyboard.KEY_RETURN;
case GLFW.GLFW_KEY_SPACE -> Keyboard.KEY_SPACE;
case GLFW.GLFW_KEY_LEFT_CONTROL -> Keyboard.KEY_LCONTROL;
case GLFW.GLFW_KEY_LEFT_SHIFT -> Keyboard.KEY_LSHIFT;
case GLFW.GLFW_KEY_LEFT_ALT -> Keyboard.KEY_LMENU;
case GLFW.GLFW_KEY_LEFT_SUPER -> Keyboard.KEY_LMETA;
case GLFW.GLFW_KEY_RIGHT_CONTROL -> Keyboard.KEY_RCONTROL;
case GLFW.GLFW_KEY_RIGHT_SHIFT -> Keyboard.KEY_RSHIFT;
case GLFW.GLFW_KEY_RIGHT_ALT -> Keyboard.KEY_RMENU;
case GLFW.GLFW_KEY_RIGHT_SUPER -> Keyboard.KEY_RMETA;
case GLFW.GLFW_KEY_1 -> Keyboard.KEY_1;
case GLFW.GLFW_KEY_2 -> Keyboard.KEY_2;
case GLFW.GLFW_KEY_3 -> Keyboard.KEY_3;
case GLFW.GLFW_KEY_4 -> Keyboard.KEY_4;
case GLFW.GLFW_KEY_5 -> Keyboard.KEY_5;
case GLFW.GLFW_KEY_6 -> Keyboard.KEY_6;
case GLFW.GLFW_KEY_7 -> Keyboard.KEY_7;
case GLFW.GLFW_KEY_8 -> Keyboard.KEY_8;
case GLFW.GLFW_KEY_9 -> Keyboard.KEY_9;
case GLFW.GLFW_KEY_0 -> Keyboard.KEY_0;
case GLFW.GLFW_KEY_A -> Keyboard.KEY_A;
case GLFW.GLFW_KEY_B -> Keyboard.KEY_B;
case GLFW.GLFW_KEY_C -> Keyboard.KEY_C;
case GLFW.GLFW_KEY_D -> Keyboard.KEY_D;
case GLFW.GLFW_KEY_E -> Keyboard.KEY_E;
case GLFW.GLFW_KEY_F -> Keyboard.KEY_F;
case GLFW.GLFW_KEY_G -> Keyboard.KEY_G;
case GLFW.GLFW_KEY_H -> Keyboard.KEY_H;
case GLFW.GLFW_KEY_I -> Keyboard.KEY_I;
case GLFW.GLFW_KEY_J -> Keyboard.KEY_J;
case GLFW.GLFW_KEY_K -> Keyboard.KEY_K;
case GLFW.GLFW_KEY_L -> Keyboard.KEY_L;
case GLFW.GLFW_KEY_M -> Keyboard.KEY_M;
case GLFW.GLFW_KEY_N -> Keyboard.KEY_N;
case GLFW.GLFW_KEY_O -> Keyboard.KEY_O;
case GLFW.GLFW_KEY_P -> Keyboard.KEY_P;
case GLFW.GLFW_KEY_Q -> Keyboard.KEY_Q;
case GLFW.GLFW_KEY_R -> Keyboard.KEY_R;
case GLFW.GLFW_KEY_S -> Keyboard.KEY_S;
case GLFW.GLFW_KEY_T -> Keyboard.KEY_T;
case GLFW.GLFW_KEY_U -> Keyboard.KEY_U;
case GLFW.GLFW_KEY_V -> Keyboard.KEY_V;
case GLFW.GLFW_KEY_W -> Keyboard.KEY_W;
case GLFW.GLFW_KEY_X -> Keyboard.KEY_X;
case GLFW.GLFW_KEY_Y -> Keyboard.KEY_Y;
case GLFW.GLFW_KEY_Z -> Keyboard.KEY_Z;
case GLFW.GLFW_KEY_UP -> Keyboard.KEY_UP;
case GLFW.GLFW_KEY_DOWN -> Keyboard.KEY_DOWN;
case GLFW.GLFW_KEY_LEFT -> Keyboard.KEY_LEFT;
case GLFW.GLFW_KEY_RIGHT -> Keyboard.KEY_RIGHT;
case GLFW.GLFW_KEY_INSERT -> Keyboard.KEY_INSERT;
case GLFW.GLFW_KEY_DELETE -> Keyboard.KEY_DELETE;
case GLFW.GLFW_KEY_HOME -> Keyboard.KEY_HOME;
case GLFW.GLFW_KEY_END -> Keyboard.KEY_END;
case GLFW.GLFW_KEY_PAGE_UP -> Keyboard.KEY_PRIOR;
case GLFW.GLFW_KEY_PAGE_DOWN -> Keyboard.KEY_NEXT;
case GLFW.GLFW_KEY_F1 -> Keyboard.KEY_F1;
case GLFW.GLFW_KEY_F2 -> Keyboard.KEY_F2;
case GLFW.GLFW_KEY_F3 -> Keyboard.KEY_F3;
case GLFW.GLFW_KEY_F4 -> Keyboard.KEY_F4;
case GLFW.GLFW_KEY_F5 -> Keyboard.KEY_F5;
case GLFW.GLFW_KEY_F6 -> Keyboard.KEY_F6;
case GLFW.GLFW_KEY_F7 -> Keyboard.KEY_F7;
case GLFW.GLFW_KEY_F8 -> Keyboard.KEY_F8;
case GLFW.GLFW_KEY_F9 -> Keyboard.KEY_F9;
case GLFW.GLFW_KEY_F10 -> Keyboard.KEY_F10;
case GLFW.GLFW_KEY_F11 -> Keyboard.KEY_F11;
case GLFW.GLFW_KEY_F12 -> Keyboard.KEY_F12;
case GLFW.GLFW_KEY_F13 -> Keyboard.KEY_F13;
case GLFW.GLFW_KEY_F14 -> Keyboard.KEY_F14;
case GLFW.GLFW_KEY_F15 -> Keyboard.KEY_F15;
case GLFW.GLFW_KEY_F16 -> Keyboard.KEY_F16;
case GLFW.GLFW_KEY_F17 -> Keyboard.KEY_F17;
case GLFW.GLFW_KEY_F18 -> Keyboard.KEY_F18;
case GLFW.GLFW_KEY_F19 -> Keyboard.KEY_F19;
case GLFW.GLFW_KEY_KP_1 -> Keyboard.KEY_NUMPAD1;
case GLFW.GLFW_KEY_KP_2 -> Keyboard.KEY_NUMPAD2;
case GLFW.GLFW_KEY_KP_3 -> Keyboard.KEY_NUMPAD3;
case GLFW.GLFW_KEY_KP_4 -> Keyboard.KEY_NUMPAD4;
case GLFW.GLFW_KEY_KP_5 -> Keyboard.KEY_NUMPAD5;
case GLFW.GLFW_KEY_KP_6 -> Keyboard.KEY_NUMPAD6;
case GLFW.GLFW_KEY_KP_7 -> Keyboard.KEY_NUMPAD7;
case GLFW.GLFW_KEY_KP_8 -> Keyboard.KEY_NUMPAD8;
case GLFW.GLFW_KEY_KP_9 -> Keyboard.KEY_NUMPAD9;
case GLFW.GLFW_KEY_KP_0 -> Keyboard.KEY_NUMPAD0;
case GLFW.GLFW_KEY_KP_ADD -> Keyboard.KEY_ADD;
case GLFW.GLFW_KEY_KP_SUBTRACT -> Keyboard.KEY_SUBTRACT;
case GLFW.GLFW_KEY_KP_MULTIPLY -> Keyboard.KEY_MULTIPLY;
case GLFW.GLFW_KEY_KP_DIVIDE -> Keyboard.KEY_DIVIDE;
case GLFW.GLFW_KEY_KP_DECIMAL -> Keyboard.KEY_DECIMAL;
case GLFW.GLFW_KEY_KP_EQUAL -> Keyboard.KEY_NUMPADEQUALS;
case GLFW.GLFW_KEY_KP_ENTER -> Keyboard.KEY_NUMPADENTER;
case GLFW.GLFW_KEY_NUM_LOCK -> Keyboard.KEY_NUMLOCK;
case GLFW.GLFW_KEY_SEMICOLON -> Keyboard.KEY_SEMICOLON;
case GLFW.GLFW_KEY_BACKSLASH -> Keyboard.KEY_BACKSLASH;
case GLFW.GLFW_KEY_COMMA -> Keyboard.KEY_COMMA;
case GLFW.GLFW_KEY_PERIOD -> Keyboard.KEY_PERIOD;
case GLFW.GLFW_KEY_SLASH -> Keyboard.KEY_SLASH;
case GLFW.GLFW_KEY_GRAVE_ACCENT -> Keyboard.KEY_GRAVE;
case GLFW.GLFW_KEY_CAPS_LOCK -> Keyboard.KEY_CAPITAL;
case GLFW.GLFW_KEY_SCROLL_LOCK -> Keyboard.KEY_SCROLL;
case GLFW.GLFW_KEY_WORLD_1 -> Keyboard.KEY_CIRCUMFLEX; // "World" keys could be anything depending on
// keyboard layout, pick something arbitrary
case GLFW.GLFW_KEY_WORLD_2 -> Keyboard.KEY_YEN;
case GLFW.GLFW_KEY_PAUSE -> Keyboard.KEY_PAUSE;
case GLFW.GLFW_KEY_MINUS -> Keyboard.KEY_MINUS;
case GLFW.GLFW_KEY_EQUAL -> Keyboard.KEY_EQUALS;
case GLFW.GLFW_KEY_LEFT_BRACKET -> Keyboard.KEY_LBRACKET;
case GLFW.GLFW_KEY_RIGHT_BRACKET -> Keyboard.KEY_RBRACKET;
case GLFW.GLFW_KEY_APOSTROPHE -> Keyboard.KEY_APOSTROPHE;
// public static final int KEY_AT = 0x91; /* (NEC PC98) */
// public static final int KEY_COLON = 0x92; /* (NEC PC98) */
// public static final int KEY_UNDERLINE = 0x93; /* (NEC PC98) */
/**
* This is the additional key that ISO
* keyboards have over ANSI ones,
* located between left shift and Y.
* Produces GRAVE ACCENT and TILDE in a
* US or UK Mac layout, REVERSE SOLIDUS
* (backslash) and VERTICAL LINE in a
* US or UK Windows layout, and
* LESS-THAN SIGN and GREATER-THAN SIGN
* in a Swiss German, German, or French
* layout.
*/
public static final int L3F_SDLK_NONUSBACKSLASH = SDL_SCANCODE_NONUSBACKSLASH | SDLK_SCANCODE_MASK;
// public static final int KEY_KANA = 0x70; /* (Japanese keyboard) */
// public static final int KEY_CONVERT = 0x79; /* (Japanese keyboard) */
// public static final int KEY_NOCONVERT = 0x7B; /* (Japanese keyboard) */
// public static final int KEY_YEN = 0x7D; /* (Japanese keyboard) */
// public static final int KEY_CIRCUMFLEX = 0x90; /* (Japanese keyboard) */
// public static final int KEY_KANJI = 0x94; /* (Japanese keyboard) */
// public static final int KEY_STOP = 0x95; /* (NEC PC98) */
// public static final int KEY_AX = 0x96; /* (Japan AX) */
// public static final int KEY_UNLABELED = 0x97; /* (J3100) */
// public static final int KEY_SECTION = 0xA7; /* Section symbol (Mac) */
// public static final int KEY_NUMPADCOMMA = 0xB3; /* , on numeric keypad (NEC PC98) */
// public static final int KEY_SYSRQ = 0xB7;
// public static final int KEY_FUNCTION = 0xC4; /* Function (Mac) */
// public static final int KEY_CLEAR = 0xDA; /* Clear key (Mac) */
public static final int L3F_SDLK_INTERNATIONAL2 = SDL_SCANCODE_INTERNATIONAL2 | SDLK_SCANCODE_MASK;
/** Yen */
public static final int L3F_SDLK_INTERNATIONAL3 = SDL_SCANCODE_INTERNATIONAL3 | SDLK_SCANCODE_MASK;
public static final int L3F_SDLK_INTERNATIONAL4 = SDL_SCANCODE_INTERNATIONAL4 | SDLK_SCANCODE_MASK;
public static final int L3F_SDLK_INTERNATIONAL5 = SDL_SCANCODE_INTERNATIONAL5 | SDLK_SCANCODE_MASK;
public static final int L3F_SDLK_INTERNATIONAL6 = SDL_SCANCODE_INTERNATIONAL6 | SDLK_SCANCODE_MASK;
public static final int L3F_SDLK_INTERNATIONAL7 = SDL_SCANCODE_INTERNATIONAL7 | SDLK_SCANCODE_MASK;
public static final int L3F_SDLK_INTERNATIONAL8 = SDL_SCANCODE_INTERNATIONAL8 | SDLK_SCANCODE_MASK;
public static final int L3F_SDLK_INTERNATIONAL9 = SDL_SCANCODE_INTERNATIONAL9 | SDLK_SCANCODE_MASK;
/** Hangul/English toggle */
public static final int L3F_SDLK_LANG1 = SDL_SCANCODE_LANG1 | SDLK_SCANCODE_MASK;
/** Hanja conversion */
public static final int L3F_SDLK_LANG2 = SDL_SCANCODE_LANG2 | SDLK_SCANCODE_MASK;
/** Katakana */
public static final int L3F_SDLK_LANG3 = SDL_SCANCODE_LANG3 | SDLK_SCANCODE_MASK;
/** Hiragana */
public static final int L3F_SDLK_LANG4 = SDL_SCANCODE_LANG4 | SDLK_SCANCODE_MASK;
/** Zenkaku/Hankaku */
public static final int L3F_SDLK_LANG5 = SDL_SCANCODE_LANG5 | SDLK_SCANCODE_MASK;
/** reserved */
public static final int L3F_SDLK_LANG6 = SDL_SCANCODE_LANG6 | SDLK_SCANCODE_MASK;
/** reserved */
public static final int L3F_SDLK_LANG7 = SDL_SCANCODE_LANG7 | SDLK_SCANCODE_MASK;
/** reserved */
public static final int L3F_SDLK_LANG8 = SDL_SCANCODE_LANG8 | SDLK_SCANCODE_MASK;
/** reserved */
public static final int L3F_SDLK_LANG9 = SDL_SCANCODE_LANG9 | SDLK_SCANCODE_MASK;
// public static final int KEY_APPS = 0xDD; /* AppMenu key */
// public static final int KEY_POWER = 0xDE;
// public static final int KEY_SLEEP = 0xDF;
public static int sdlKeycodeToLwjgl(int sdlKeycode) {
return switch (sdlKeycode) {
case -1 -> Keyboard.KEY_UNLABELED;
case SDLK_ESCAPE -> Keyboard.KEY_ESCAPE;
case SDLK_BACKSPACE -> Keyboard.KEY_BACK;
case SDLK_TAB -> Keyboard.KEY_TAB;
case SDLK_RETURN -> Keyboard.KEY_RETURN;
case SDLK_SPACE -> Keyboard.KEY_SPACE;
case SDLK_LCTRL -> Keyboard.KEY_LCONTROL;
case SDLK_LSHIFT -> Keyboard.KEY_LSHIFT;
case SDLK_MENU -> Keyboard.KEY_LMENU;
case SDLK_LGUI -> Keyboard.KEY_LMETA;
case SDLK_RCTRL -> Keyboard.KEY_RCONTROL;
case SDLK_RSHIFT -> Keyboard.KEY_RSHIFT;
case SDLK_1 -> Keyboard.KEY_1;
case SDLK_2 -> Keyboard.KEY_2;
case SDLK_3 -> Keyboard.KEY_3;
case SDLK_4 -> Keyboard.KEY_4;
case SDLK_5 -> Keyboard.KEY_5;
case SDLK_6 -> Keyboard.KEY_6;
case SDLK_7 -> Keyboard.KEY_7;
case SDLK_8 -> Keyboard.KEY_8;
case SDLK_9 -> Keyboard.KEY_9;
case SDLK_0 -> Keyboard.KEY_0;
case SDLK_A -> Keyboard.KEY_A;
case SDLK_B -> Keyboard.KEY_B;
case SDLK_C -> Keyboard.KEY_C;
case SDLK_D -> Keyboard.KEY_D;
case SDLK_E -> Keyboard.KEY_E;
case SDLK_F -> Keyboard.KEY_F;
case SDLK_G -> Keyboard.KEY_G;
case SDLK_H -> Keyboard.KEY_H;
case SDLK_I -> Keyboard.KEY_I;
case SDLK_J -> Keyboard.KEY_J;
case SDLK_K -> Keyboard.KEY_K;
case SDLK_L -> Keyboard.KEY_L;
case SDLK_M -> Keyboard.KEY_M;
case SDLK_N -> Keyboard.KEY_N;
case SDLK_O -> Keyboard.KEY_O;
case SDLK_P -> Keyboard.KEY_P;
case SDLK_Q -> Keyboard.KEY_Q;
case SDLK_R -> Keyboard.KEY_R;
case SDLK_S -> Keyboard.KEY_S;
case SDLK_T -> Keyboard.KEY_T;
case SDLK_U -> Keyboard.KEY_U;
case SDLK_V -> Keyboard.KEY_V;
case SDLK_W -> Keyboard.KEY_W;
case SDLK_X -> Keyboard.KEY_X;
case SDLK_Y -> Keyboard.KEY_Y;
case SDLK_Z -> Keyboard.KEY_Z;
case SDLK_UP -> Keyboard.KEY_UP;
case SDLK_DOWN -> Keyboard.KEY_DOWN;
case SDLK_LEFT -> Keyboard.KEY_LEFT;
case SDLK_RIGHT -> Keyboard.KEY_RIGHT;
case SDLK_INSERT -> Keyboard.KEY_INSERT;
case SDLK_DELETE -> Keyboard.KEY_DELETE;
case SDLK_HOME -> Keyboard.KEY_HOME;
case SDLK_END -> Keyboard.KEY_END;
case SDLK_PAGEUP -> Keyboard.KEY_PRIOR;
case SDLK_PAGEDOWN -> Keyboard.KEY_NEXT;
case SDLK_F1 -> Keyboard.KEY_F1;
case SDLK_F2 -> Keyboard.KEY_F2;
case SDLK_F3 -> Keyboard.KEY_F3;
case SDLK_F4 -> Keyboard.KEY_F4;
case SDLK_F5 -> Keyboard.KEY_F5;
case SDLK_F6 -> Keyboard.KEY_F6;
case SDLK_F7 -> Keyboard.KEY_F7;
case SDLK_F8 -> Keyboard.KEY_F8;
case SDLK_F9 -> Keyboard.KEY_F9;
case SDLK_F10 -> Keyboard.KEY_F10;
case SDLK_F11 -> Keyboard.KEY_F11;
case SDLK_F12 -> Keyboard.KEY_F12;
case SDLK_F13 -> Keyboard.KEY_F13;
case SDLK_F14 -> Keyboard.KEY_F14;
case SDLK_F15 -> Keyboard.KEY_F15;
case SDLK_F16 -> Keyboard.KEY_F16;
case SDLK_F17 -> Keyboard.KEY_F17;
case SDLK_F18 -> Keyboard.KEY_F18;
case SDLK_F19 -> Keyboard.KEY_F19;
case SDLK_KP_1 -> Keyboard.KEY_NUMPAD1;
case SDLK_KP_2 -> Keyboard.KEY_NUMPAD2;
case SDLK_KP_3 -> Keyboard.KEY_NUMPAD3;
case SDLK_KP_4 -> Keyboard.KEY_NUMPAD4;
case SDLK_KP_5 -> Keyboard.KEY_NUMPAD5;
case SDLK_KP_6 -> Keyboard.KEY_NUMPAD6;
case SDLK_KP_7 -> Keyboard.KEY_NUMPAD7;
case SDLK_KP_8 -> Keyboard.KEY_NUMPAD8;
case SDLK_KP_9 -> Keyboard.KEY_NUMPAD9;
case SDLK_KP_0 -> Keyboard.KEY_NUMPAD0;
case SDLK_KP_PLUS -> Keyboard.KEY_ADD;
case SDLK_KP_MINUS -> Keyboard.KEY_SUBTRACT;
case SDLK_KP_MULTIPLY -> Keyboard.KEY_MULTIPLY;
case SDLK_KP_DIVIDE -> Keyboard.KEY_DIVIDE;
case SDLK_KP_DECIMAL -> Keyboard.KEY_DECIMAL;
case SDLK_KP_EQUALS -> Keyboard.KEY_NUMPADEQUALS;
case SDLK_KP_ENTER -> Keyboard.KEY_NUMPADENTER;
case SDLK_NUMLOCKCLEAR -> Keyboard.KEY_NUMLOCK;
case SDLK_SEMICOLON -> Keyboard.KEY_SEMICOLON;
case SDLK_BACKSLASH -> Keyboard.KEY_BACKSLASH;
case SDLK_COMMA -> Keyboard.KEY_COMMA;
case SDLK_PERIOD -> Keyboard.KEY_PERIOD;
case SDLK_SLASH -> Keyboard.KEY_SLASH;
case SDLK_GRAVE -> Keyboard.KEY_GRAVE;
case SDLK_CAPSLOCK -> Keyboard.KEY_CAPITAL;
case SDLK_SCROLLLOCK -> Keyboard.KEY_SCROLL;
case SDLK_PAUSE -> Keyboard.KEY_PAUSE;
case SDLK_MINUS -> Keyboard.KEY_MINUS;
case SDLK_EQUALS -> Keyboard.KEY_EQUALS;
case SDLK_LEFTBRACKET -> Keyboard.KEY_LBRACKET;
case SDLK_RIGHTBRACKET -> Keyboard.KEY_RBRACKET;
case SDLK_APOSTROPHE -> Keyboard.KEY_APOSTROPHE;
case SDLK_AT -> Keyboard.KEY_AT; /* (NEC PC98) */
case SDLK_COLON -> Keyboard.KEY_COLON; /* (NEC PC98) */
// case SDLK_UNDERLINE -> Keyboard.KEY_UNDERLINE; /* (NEC PC98) */
case L3F_SDLK_LANG3 -> Keyboard.KEY_KANA; /* (Japanese keyboard) */
case L3F_SDLK_LANG2 -> Keyboard.KEY_CONVERT; /* (Japanese keyboard) */
case L3F_SDLK_LANG4 -> Keyboard.KEY_NOCONVERT; /* (Japanese keyboard) */
case L3F_SDLK_INTERNATIONAL3 -> Keyboard.KEY_YEN; /* (Japanese keyboard) */
case L3F_SDLK_LANG1 -> Keyboard.KEY_CIRCUMFLEX; /* (Japanese keyboard) */
case L3F_SDLK_LANG5 -> Keyboard.KEY_KANJI; /* (Japanese keyboard) */
case SDLK_STOP -> Keyboard.KEY_STOP; /* (NEC PC98) */
case L3F_SDLK_LANG6 -> Keyboard.KEY_AX; /* (Japan AX) */
case L3F_SDLK_LANG8 -> Keyboard.KEY_SECTION; /* Section symbol (Mac) */
case SDLK_KP_COMMA -> Keyboard.KEY_NUMPADCOMMA; /* , on numeric keypad (NEC PC98) */
case SDLK_SYSREQ -> Keyboard.KEY_SYSRQ;
// case SDLK_UNKNOWN -> Keyboard.KEY_FUNCTION; /* Function (Mac) */
case SDLK_CLEAR -> Keyboard.KEY_CLEAR; /* Clear key (Mac) */
case SDLK_APPLICATION -> Keyboard.KEY_APPS; /* AppMenu key */
case SDLK_POWER -> Keyboard.KEY_POWER;
case SDLK_SLEEP -> Keyboard.KEY_SLEEP;
default -> Keyboard.KEY_NONE;
};
}
public static int lwjglToGlfw(int lwjglKeyCode) {
if (lwjglKeyCode > GLFW.GLFW_KEY_LAST) {
return lwjglKeyCode;
}
public static int sdlScancodeToLwjgl(int sdlScancode) {
return switch (sdlScancode) {
case -1 -> Keyboard.KEY_UNLABELED;
case SDL_SCANCODE_ESCAPE -> Keyboard.KEY_ESCAPE;
case SDL_SCANCODE_BACKSPACE -> Keyboard.KEY_BACK;
case SDL_SCANCODE_TAB -> Keyboard.KEY_TAB;
case SDL_SCANCODE_RETURN -> Keyboard.KEY_RETURN;
case SDL_SCANCODE_SPACE -> Keyboard.KEY_SPACE;
case SDL_SCANCODE_LCTRL -> Keyboard.KEY_LCONTROL;
case SDL_SCANCODE_LSHIFT -> Keyboard.KEY_LSHIFT;
case SDL_SCANCODE_MENU -> Keyboard.KEY_LMENU;
case SDL_SCANCODE_LGUI -> Keyboard.KEY_LMETA;
case SDL_SCANCODE_RCTRL -> Keyboard.KEY_RCONTROL;
case SDL_SCANCODE_RSHIFT -> Keyboard.KEY_RSHIFT;
case SDL_SCANCODE_1 -> Keyboard.KEY_1;
case SDL_SCANCODE_2 -> Keyboard.KEY_2;
case SDL_SCANCODE_3 -> Keyboard.KEY_3;
case SDL_SCANCODE_4 -> Keyboard.KEY_4;
case SDL_SCANCODE_5 -> Keyboard.KEY_5;
case SDL_SCANCODE_6 -> Keyboard.KEY_6;
case SDL_SCANCODE_7 -> Keyboard.KEY_7;
case SDL_SCANCODE_8 -> Keyboard.KEY_8;
case SDL_SCANCODE_9 -> Keyboard.KEY_9;
case SDL_SCANCODE_0 -> Keyboard.KEY_0;
case SDL_SCANCODE_A -> Keyboard.KEY_A;
case SDL_SCANCODE_B -> Keyboard.KEY_B;
case SDL_SCANCODE_C -> Keyboard.KEY_C;
case SDL_SCANCODE_D -> Keyboard.KEY_D;
case SDL_SCANCODE_E -> Keyboard.KEY_E;
case SDL_SCANCODE_F -> Keyboard.KEY_F;
case SDL_SCANCODE_G -> Keyboard.KEY_G;
case SDL_SCANCODE_H -> Keyboard.KEY_H;
case SDL_SCANCODE_I -> Keyboard.KEY_I;
case SDL_SCANCODE_J -> Keyboard.KEY_J;
case SDL_SCANCODE_K -> Keyboard.KEY_K;
case SDL_SCANCODE_L -> Keyboard.KEY_L;
case SDL_SCANCODE_M -> Keyboard.KEY_M;
case SDL_SCANCODE_N -> Keyboard.KEY_N;
case SDL_SCANCODE_O -> Keyboard.KEY_O;
case SDL_SCANCODE_P -> Keyboard.KEY_P;
case SDL_SCANCODE_Q -> Keyboard.KEY_Q;
case SDL_SCANCODE_R -> Keyboard.KEY_R;
case SDL_SCANCODE_S -> Keyboard.KEY_S;
case SDL_SCANCODE_T -> Keyboard.KEY_T;
case SDL_SCANCODE_U -> Keyboard.KEY_U;
case SDL_SCANCODE_V -> Keyboard.KEY_V;
case SDL_SCANCODE_W -> Keyboard.KEY_W;
case SDL_SCANCODE_X -> Keyboard.KEY_X;
case SDL_SCANCODE_Y -> Keyboard.KEY_Y;
case SDL_SCANCODE_Z -> Keyboard.KEY_Z;
case SDL_SCANCODE_UP -> Keyboard.KEY_UP;
case SDL_SCANCODE_DOWN -> Keyboard.KEY_DOWN;
case SDL_SCANCODE_LEFT -> Keyboard.KEY_LEFT;
case SDL_SCANCODE_RIGHT -> Keyboard.KEY_RIGHT;
case SDL_SCANCODE_INSERT -> Keyboard.KEY_INSERT;
case SDL_SCANCODE_DELETE -> Keyboard.KEY_DELETE;
case SDL_SCANCODE_HOME -> Keyboard.KEY_HOME;
case SDL_SCANCODE_END -> Keyboard.KEY_END;
case SDL_SCANCODE_PAGEUP -> Keyboard.KEY_PRIOR;
case SDL_SCANCODE_PAGEDOWN -> Keyboard.KEY_NEXT;
case SDL_SCANCODE_F1 -> Keyboard.KEY_F1;
case SDL_SCANCODE_F2 -> Keyboard.KEY_F2;
case SDL_SCANCODE_F3 -> Keyboard.KEY_F3;
case SDL_SCANCODE_F4 -> Keyboard.KEY_F4;
case SDL_SCANCODE_F5 -> Keyboard.KEY_F5;
case SDL_SCANCODE_F6 -> Keyboard.KEY_F6;
case SDL_SCANCODE_F7 -> Keyboard.KEY_F7;
case SDL_SCANCODE_F8 -> Keyboard.KEY_F8;
case SDL_SCANCODE_F9 -> Keyboard.KEY_F9;
case SDL_SCANCODE_F10 -> Keyboard.KEY_F10;
case SDL_SCANCODE_F11 -> Keyboard.KEY_F11;
case SDL_SCANCODE_F12 -> Keyboard.KEY_F12;
case SDL_SCANCODE_F13 -> Keyboard.KEY_F13;
case SDL_SCANCODE_F14 -> Keyboard.KEY_F14;
case SDL_SCANCODE_F15 -> Keyboard.KEY_F15;
case SDL_SCANCODE_F16 -> Keyboard.KEY_F16;
case SDL_SCANCODE_F17 -> Keyboard.KEY_F17;
case SDL_SCANCODE_F18 -> Keyboard.KEY_F18;
case SDL_SCANCODE_F19 -> Keyboard.KEY_F19;
case SDL_SCANCODE_KP_1 -> Keyboard.KEY_NUMPAD1;
case SDL_SCANCODE_KP_2 -> Keyboard.KEY_NUMPAD2;
case SDL_SCANCODE_KP_3 -> Keyboard.KEY_NUMPAD3;
case SDL_SCANCODE_KP_4 -> Keyboard.KEY_NUMPAD4;
case SDL_SCANCODE_KP_5 -> Keyboard.KEY_NUMPAD5;
case SDL_SCANCODE_KP_6 -> Keyboard.KEY_NUMPAD6;
case SDL_SCANCODE_KP_7 -> Keyboard.KEY_NUMPAD7;
case SDL_SCANCODE_KP_8 -> Keyboard.KEY_NUMPAD8;
case SDL_SCANCODE_KP_9 -> Keyboard.KEY_NUMPAD9;
case SDL_SCANCODE_KP_0 -> Keyboard.KEY_NUMPAD0;
case SDL_SCANCODE_KP_PLUS -> Keyboard.KEY_ADD;
case SDL_SCANCODE_KP_MINUS -> Keyboard.KEY_SUBTRACT;
case SDL_SCANCODE_KP_MULTIPLY -> Keyboard.KEY_MULTIPLY;
case SDL_SCANCODE_KP_DIVIDE -> Keyboard.KEY_DIVIDE;
case SDL_SCANCODE_KP_DECIMAL -> Keyboard.KEY_DECIMAL;
case SDL_SCANCODE_KP_EQUALS -> Keyboard.KEY_NUMPADEQUALS;
case SDL_SCANCODE_KP_ENTER -> Keyboard.KEY_NUMPADENTER;
case SDL_SCANCODE_NUMLOCKCLEAR -> Keyboard.KEY_NUMLOCK;
case SDL_SCANCODE_SEMICOLON -> Keyboard.KEY_SEMICOLON;
case SDL_SCANCODE_BACKSLASH -> Keyboard.KEY_BACKSLASH;
case SDL_SCANCODE_COMMA -> Keyboard.KEY_COMMA;
case SDL_SCANCODE_PERIOD -> Keyboard.KEY_PERIOD;
case SDL_SCANCODE_SLASH -> Keyboard.KEY_SLASH;
case SDL_SCANCODE_GRAVE -> Keyboard.KEY_GRAVE;
case SDL_SCANCODE_CAPSLOCK -> Keyboard.KEY_CAPITAL;
case SDL_SCANCODE_SCROLLLOCK -> Keyboard.KEY_SCROLL;
case SDL_SCANCODE_PAUSE -> Keyboard.KEY_PAUSE;
case SDL_SCANCODE_MINUS -> Keyboard.KEY_MINUS;
case SDL_SCANCODE_EQUALS -> Keyboard.KEY_EQUALS;
case SDL_SCANCODE_LEFTBRACKET -> Keyboard.KEY_LBRACKET;
case SDL_SCANCODE_RIGHTBRACKET -> Keyboard.KEY_RBRACKET;
case SDL_SCANCODE_APOSTROPHE -> Keyboard.KEY_APOSTROPHE;
case SDL_SCANCODE_KP_AT -> Keyboard.KEY_AT; /* (NEC PC98) */
case SDL_SCANCODE_KP_COLON -> Keyboard.KEY_COLON; /* (NEC PC98) */
// case SDL_SCANCODE_UNDERLINE -> Keyboard.KEY_UNDERLINE; /* (NEC PC98) */
case SDL_SCANCODE_LANG3 -> Keyboard.KEY_KANA; /* (Japanese keyboard) */
case SDL_SCANCODE_LANG2 -> Keyboard.KEY_CONVERT; /* (Japanese keyboard) */
case SDL_SCANCODE_LANG4 -> Keyboard.KEY_NOCONVERT; /* (Japanese keyboard) */
case SDL_SCANCODE_INTERNATIONAL3 -> Keyboard.KEY_YEN; /* (Japanese keyboard) */
case SDL_SCANCODE_LANG1 -> Keyboard.KEY_CIRCUMFLEX; /* (Japanese keyboard) */
case SDL_SCANCODE_LANG5 -> Keyboard.KEY_KANJI; /* (Japanese keyboard) */
case SDL_SCANCODE_STOP -> Keyboard.KEY_STOP; /* (NEC PC98) */
case SDL_SCANCODE_LANG6 -> Keyboard.KEY_AX; /* (Japan AX) */
case SDL_SCANCODE_LANG8 -> Keyboard.KEY_SECTION; /* Section symbol (Mac) */
case SDL_SCANCODE_KP_COMMA -> Keyboard.KEY_NUMPADCOMMA; /* , on numeric keypad (NEC PC98) */
case SDL_SCANCODE_SYSREQ -> Keyboard.KEY_SYSRQ;
// case SDL_SCANCODE_UNKNOWN -> Keyboard.KEY_FUNCTION; /* Function (Mac) */
case SDL_SCANCODE_CLEAR -> Keyboard.KEY_CLEAR; /* Clear key (Mac) */
case SDL_SCANCODE_APPLICATION -> Keyboard.KEY_APPS; /* AppMenu key */
case SDL_SCANCODE_POWER -> Keyboard.KEY_POWER;
case SDL_SCANCODE_SLEEP -> Keyboard.KEY_SLEEP;
default -> Keyboard.KEY_NONE;
};
}
public static int lwjglToSdlKeycode(int lwjglKeyCode) {
return switch (lwjglKeyCode) {
case Keyboard.KEY_NONE -> 0;
case Keyboard.KEY_UNLABELED -> GLFW.GLFW_KEY_UNKNOWN; // arbitrary mapping to fix text input here
case Keyboard.KEY_ESCAPE -> GLFW.GLFW_KEY_ESCAPE;
case Keyboard.KEY_BACK -> GLFW.GLFW_KEY_BACKSPACE;
case Keyboard.KEY_TAB -> GLFW.GLFW_KEY_TAB;
case Keyboard.KEY_RETURN -> GLFW.GLFW_KEY_ENTER;
case Keyboard.KEY_SPACE -> GLFW.GLFW_KEY_SPACE;
case Keyboard.KEY_LCONTROL -> GLFW.GLFW_KEY_LEFT_CONTROL;
case Keyboard.KEY_LSHIFT -> GLFW.GLFW_KEY_LEFT_SHIFT;
case Keyboard.KEY_LMENU -> GLFW.GLFW_KEY_LEFT_ALT;
case Keyboard.KEY_LMETA -> GLFW.GLFW_KEY_LEFT_SUPER;
case Keyboard.KEY_RCONTROL -> GLFW.GLFW_KEY_RIGHT_CONTROL;
case Keyboard.KEY_RSHIFT -> GLFW.GLFW_KEY_RIGHT_SHIFT;
case Keyboard.KEY_RMENU -> GLFW.GLFW_KEY_RIGHT_ALT;
case Keyboard.KEY_RMETA -> GLFW.GLFW_KEY_RIGHT_SUPER;
case Keyboard.KEY_1 -> GLFW.GLFW_KEY_1;
case Keyboard.KEY_2 -> GLFW.GLFW_KEY_2;
case Keyboard.KEY_3 -> GLFW.GLFW_KEY_3;
case Keyboard.KEY_4 -> GLFW.GLFW_KEY_4;
case Keyboard.KEY_5 -> GLFW.GLFW_KEY_5;
case Keyboard.KEY_6 -> GLFW.GLFW_KEY_6;
case Keyboard.KEY_7 -> GLFW.GLFW_KEY_7;
case Keyboard.KEY_8 -> GLFW.GLFW_KEY_8;
case Keyboard.KEY_9 -> GLFW.GLFW_KEY_9;
case Keyboard.KEY_0 -> GLFW.GLFW_KEY_0;
case Keyboard.KEY_A -> GLFW.GLFW_KEY_A;
case Keyboard.KEY_B -> GLFW.GLFW_KEY_B;
case Keyboard.KEY_C -> GLFW.GLFW_KEY_C;
case Keyboard.KEY_D -> GLFW.GLFW_KEY_D;
case Keyboard.KEY_E -> GLFW.GLFW_KEY_E;
case Keyboard.KEY_F -> GLFW.GLFW_KEY_F;
case Keyboard.KEY_G -> GLFW.GLFW_KEY_G;
case Keyboard.KEY_H -> GLFW.GLFW_KEY_H;
case Keyboard.KEY_I -> GLFW.GLFW_KEY_I;
case Keyboard.KEY_J -> GLFW.GLFW_KEY_J;
case Keyboard.KEY_K -> GLFW.GLFW_KEY_K;
case Keyboard.KEY_L -> GLFW.GLFW_KEY_L;
case Keyboard.KEY_M -> GLFW.GLFW_KEY_M;
case Keyboard.KEY_N -> GLFW.GLFW_KEY_N;
case Keyboard.KEY_O -> GLFW.GLFW_KEY_O;
case Keyboard.KEY_P -> GLFW.GLFW_KEY_P;
case Keyboard.KEY_Q -> GLFW.GLFW_KEY_Q;
case Keyboard.KEY_R -> GLFW.GLFW_KEY_R;
case Keyboard.KEY_S -> GLFW.GLFW_KEY_S;
case Keyboard.KEY_T -> GLFW.GLFW_KEY_T;
case Keyboard.KEY_U -> GLFW.GLFW_KEY_U;
case Keyboard.KEY_V -> GLFW.GLFW_KEY_V;
case Keyboard.KEY_W -> GLFW.GLFW_KEY_W;
case Keyboard.KEY_X -> GLFW.GLFW_KEY_X;
case Keyboard.KEY_Y -> GLFW.GLFW_KEY_Y;
case Keyboard.KEY_Z -> GLFW.GLFW_KEY_Z;
case Keyboard.KEY_UP -> GLFW.GLFW_KEY_UP;
case Keyboard.KEY_DOWN -> GLFW.GLFW_KEY_DOWN;
case Keyboard.KEY_LEFT -> GLFW.GLFW_KEY_LEFT;
case Keyboard.KEY_RIGHT -> GLFW.GLFW_KEY_RIGHT;
case Keyboard.KEY_INSERT -> GLFW.GLFW_KEY_INSERT;
case Keyboard.KEY_DELETE -> GLFW.GLFW_KEY_DELETE;
case Keyboard.KEY_HOME -> GLFW.GLFW_KEY_HOME;
case Keyboard.KEY_END -> GLFW.GLFW_KEY_END;
case Keyboard.KEY_PRIOR -> GLFW.GLFW_KEY_PAGE_UP;
case Keyboard.KEY_NEXT -> GLFW.GLFW_KEY_PAGE_DOWN;
case Keyboard.KEY_F1 -> GLFW.GLFW_KEY_F1;
case Keyboard.KEY_F2 -> GLFW.GLFW_KEY_F2;
case Keyboard.KEY_F3 -> GLFW.GLFW_KEY_F3;
case Keyboard.KEY_F4 -> GLFW.GLFW_KEY_F4;
case Keyboard.KEY_F5 -> GLFW.GLFW_KEY_F5;
case Keyboard.KEY_F6 -> GLFW.GLFW_KEY_F6;
case Keyboard.KEY_F7 -> GLFW.GLFW_KEY_F7;
case Keyboard.KEY_F8 -> GLFW.GLFW_KEY_F8;
case Keyboard.KEY_F9 -> GLFW.GLFW_KEY_F9;
case Keyboard.KEY_F10 -> GLFW.GLFW_KEY_F10;
case Keyboard.KEY_F11 -> GLFW.GLFW_KEY_F11;
case Keyboard.KEY_F12 -> GLFW.GLFW_KEY_F12;
case Keyboard.KEY_F13 -> GLFW.GLFW_KEY_F13;
case Keyboard.KEY_F14 -> GLFW.GLFW_KEY_F14;
case Keyboard.KEY_F15 -> GLFW.GLFW_KEY_F15;
case Keyboard.KEY_F16 -> GLFW.GLFW_KEY_F16;
case Keyboard.KEY_F17 -> GLFW.GLFW_KEY_F17;
case Keyboard.KEY_F18 -> GLFW.GLFW_KEY_F18;
case Keyboard.KEY_F19 -> GLFW.GLFW_KEY_F19;
case Keyboard.KEY_NUMPAD1 -> GLFW.GLFW_KEY_KP_1;
case Keyboard.KEY_NUMPAD2 -> GLFW.GLFW_KEY_KP_2;
case Keyboard.KEY_NUMPAD3 -> GLFW.GLFW_KEY_KP_3;
case Keyboard.KEY_NUMPAD4 -> GLFW.GLFW_KEY_KP_4;
case Keyboard.KEY_NUMPAD5 -> GLFW.GLFW_KEY_KP_5;
case Keyboard.KEY_NUMPAD6 -> GLFW.GLFW_KEY_KP_6;
case Keyboard.KEY_NUMPAD7 -> GLFW.GLFW_KEY_KP_7;
case Keyboard.KEY_NUMPAD8 -> GLFW.GLFW_KEY_KP_8;
case Keyboard.KEY_NUMPAD9 -> GLFW.GLFW_KEY_KP_9;
case Keyboard.KEY_NUMPAD0 -> GLFW.GLFW_KEY_KP_0;
case Keyboard.KEY_ADD -> GLFW.GLFW_KEY_KP_ADD;
case Keyboard.KEY_SUBTRACT -> GLFW.GLFW_KEY_KP_SUBTRACT;
case Keyboard.KEY_MULTIPLY -> GLFW.GLFW_KEY_KP_MULTIPLY;
case Keyboard.KEY_DIVIDE -> GLFW.GLFW_KEY_KP_DIVIDE;
case Keyboard.KEY_DECIMAL -> GLFW.GLFW_KEY_KP_DECIMAL;
case Keyboard.KEY_NUMPADEQUALS -> GLFW.GLFW_KEY_KP_EQUAL;
case Keyboard.KEY_NUMPADENTER -> GLFW.GLFW_KEY_KP_ENTER;
case Keyboard.KEY_NUMLOCK -> GLFW.GLFW_KEY_NUM_LOCK;
case Keyboard.KEY_SEMICOLON -> GLFW.GLFW_KEY_SEMICOLON;
case Keyboard.KEY_BACKSLASH -> GLFW.GLFW_KEY_BACKSLASH;
case Keyboard.KEY_COMMA -> GLFW.GLFW_KEY_COMMA;
case Keyboard.KEY_PERIOD -> GLFW.GLFW_KEY_PERIOD;
case Keyboard.KEY_SLASH -> GLFW.GLFW_KEY_SLASH;
case Keyboard.KEY_GRAVE -> GLFW.GLFW_KEY_GRAVE_ACCENT;
case Keyboard.KEY_CAPITAL -> GLFW.GLFW_KEY_CAPS_LOCK;
case Keyboard.KEY_SCROLL -> GLFW.GLFW_KEY_SCROLL_LOCK;
case Keyboard.KEY_PAUSE -> GLFW.GLFW_KEY_PAUSE;
case Keyboard.KEY_CIRCUMFLEX -> GLFW.GLFW_KEY_WORLD_1; // "World" keys could be anything depending on
// keyboard layout, pick something arbitrary
case Keyboard.KEY_YEN -> GLFW.GLFW_KEY_WORLD_2;
case Keyboard.KEY_NONE -> -1;
case Keyboard.KEY_ESCAPE -> SDLK_ESCAPE;
case Keyboard.KEY_BACK -> SDLK_BACKSPACE;
case Keyboard.KEY_TAB -> SDLK_TAB;
case Keyboard.KEY_RETURN -> SDLK_RETURN;
case Keyboard.KEY_SPACE -> SDLK_SPACE;
case Keyboard.KEY_LCONTROL -> SDLK_LCTRL;
case Keyboard.KEY_LSHIFT -> SDLK_LSHIFT;
case Keyboard.KEY_LMENU -> SDLK_MENU;
case Keyboard.KEY_LMETA -> SDLK_LGUI;
case Keyboard.KEY_RCONTROL -> SDLK_RCTRL;
case Keyboard.KEY_RSHIFT -> SDLK_RSHIFT;
case Keyboard.KEY_RMENU -> SDLK_MENU;
case Keyboard.KEY_RMETA -> SDLK_RGUI;
case Keyboard.KEY_1 -> SDLK_1;
case Keyboard.KEY_2 -> SDLK_2;
case Keyboard.KEY_3 -> SDLK_3;
case Keyboard.KEY_4 -> SDLK_4;
case Keyboard.KEY_5 -> SDLK_5;
case Keyboard.KEY_6 -> SDLK_6;
case Keyboard.KEY_7 -> SDLK_7;
case Keyboard.KEY_8 -> SDLK_8;
case Keyboard.KEY_9 -> SDLK_9;
case Keyboard.KEY_0 -> SDLK_0;
case Keyboard.KEY_A -> SDLK_A;
case Keyboard.KEY_B -> SDLK_B;
case Keyboard.KEY_C -> SDLK_C;
case Keyboard.KEY_D -> SDLK_D;
case Keyboard.KEY_E -> SDLK_E;
case Keyboard.KEY_F -> SDLK_F;
case Keyboard.KEY_G -> SDLK_G;
case Keyboard.KEY_H -> SDLK_H;
case Keyboard.KEY_I -> SDLK_I;
case Keyboard.KEY_J -> SDLK_J;
case Keyboard.KEY_K -> SDLK_K;
case Keyboard.KEY_L -> SDLK_L;
case Keyboard.KEY_M -> SDLK_M;
case Keyboard.KEY_N -> SDLK_N;
case Keyboard.KEY_O -> SDLK_O;
case Keyboard.KEY_P -> SDLK_P;
case Keyboard.KEY_Q -> SDLK_Q;
case Keyboard.KEY_R -> SDLK_R;
case Keyboard.KEY_S -> SDLK_S;
case Keyboard.KEY_T -> SDLK_T;
case Keyboard.KEY_U -> SDLK_U;
case Keyboard.KEY_V -> SDLK_V;
case Keyboard.KEY_W -> SDLK_W;
case Keyboard.KEY_X -> SDLK_X;
case Keyboard.KEY_Y -> SDLK_Y;
case Keyboard.KEY_Z -> SDLK_Z;
case Keyboard.KEY_UP -> SDLK_UP;
case Keyboard.KEY_DOWN -> SDLK_DOWN;
case Keyboard.KEY_LEFT -> SDLK_LEFT;
case Keyboard.KEY_RIGHT -> SDLK_RIGHT;
case Keyboard.KEY_INSERT -> SDLK_INSERT;
case Keyboard.KEY_DELETE -> SDLK_DELETE;
case Keyboard.KEY_HOME -> SDLK_HOME;
case Keyboard.KEY_END -> SDLK_END;
case Keyboard.KEY_PRIOR -> SDLK_PAGEUP;
case Keyboard.KEY_NEXT -> SDLK_PAGEDOWN;
case Keyboard.KEY_F1 -> SDLK_F1;
case Keyboard.KEY_F2 -> SDLK_F2;
case Keyboard.KEY_F3 -> SDLK_F3;
case Keyboard.KEY_F4 -> SDLK_F4;
case Keyboard.KEY_F5 -> SDLK_F5;
case Keyboard.KEY_F6 -> SDLK_F6;
case Keyboard.KEY_F7 -> SDLK_F7;
case Keyboard.KEY_F8 -> SDLK_F8;
case Keyboard.KEY_F9 -> SDLK_F9;
case Keyboard.KEY_F10 -> SDLK_F10;
case Keyboard.KEY_F11 -> SDLK_F11;
case Keyboard.KEY_F12 -> SDLK_F12;
case Keyboard.KEY_F13 -> SDLK_F13;
case Keyboard.KEY_F14 -> SDLK_F14;
case Keyboard.KEY_F15 -> SDLK_F15;
case Keyboard.KEY_F16 -> SDLK_F16;
case Keyboard.KEY_F17 -> SDLK_F17;
case Keyboard.KEY_F18 -> SDLK_F18;
case Keyboard.KEY_F19 -> SDLK_F19;
case Keyboard.KEY_NUMPAD1 -> SDLK_KP_1;
case Keyboard.KEY_NUMPAD2 -> SDLK_KP_2;
case Keyboard.KEY_NUMPAD3 -> SDLK_KP_3;
case Keyboard.KEY_NUMPAD4 -> SDLK_KP_4;
case Keyboard.KEY_NUMPAD5 -> SDLK_KP_5;
case Keyboard.KEY_NUMPAD6 -> SDLK_KP_6;
case Keyboard.KEY_NUMPAD7 -> SDLK_KP_7;
case Keyboard.KEY_NUMPAD8 -> SDLK_KP_8;
case Keyboard.KEY_NUMPAD9 -> SDLK_KP_9;
case Keyboard.KEY_NUMPAD0 -> SDLK_KP_0;
case Keyboard.KEY_ADD -> SDLK_KP_PLUS;
case Keyboard.KEY_SUBTRACT -> SDLK_KP_MINUS;
case Keyboard.KEY_MULTIPLY -> SDLK_KP_MULTIPLY;
case Keyboard.KEY_DIVIDE -> SDLK_KP_DIVIDE;
case Keyboard.KEY_DECIMAL -> SDLK_KP_DECIMAL;
case Keyboard.KEY_NUMPADEQUALS -> SDLK_KP_EQUALS;
case Keyboard.KEY_NUMPADENTER -> SDLK_KP_ENTER;
case Keyboard.KEY_NUMLOCK -> SDLK_NUMLOCKCLEAR;
case Keyboard.KEY_SEMICOLON -> SDLK_SEMICOLON;
case Keyboard.KEY_BACKSLASH -> SDLK_BACKSLASH;
case Keyboard.KEY_COMMA -> SDLK_COMMA;
case Keyboard.KEY_PERIOD -> SDLK_PERIOD;
case Keyboard.KEY_SLASH -> SDLK_SLASH;
case Keyboard.KEY_GRAVE -> SDLK_GRAVE;
case Keyboard.KEY_CAPITAL -> SDLK_CAPSLOCK;
case Keyboard.KEY_SCROLL -> SDLK_SCROLLLOCK;
case Keyboard.KEY_PAUSE -> SDLK_PAUSE;
case Keyboard.KEY_MINUS -> GLFW.GLFW_KEY_MINUS;
case Keyboard.KEY_EQUALS -> GLFW.GLFW_KEY_EQUAL;
case Keyboard.KEY_LBRACKET -> GLFW.GLFW_KEY_LEFT_BRACKET;
case Keyboard.KEY_RBRACKET -> GLFW.GLFW_KEY_RIGHT_BRACKET;
case Keyboard.KEY_APOSTROPHE -> GLFW.GLFW_KEY_APOSTROPHE;
// public static final int KEY_AT = 0x91; /* (NEC PC98) */
// public static final int KEY_COLON = 0x92; /* (NEC PC98) */
// public static final int KEY_UNDERLINE = 0x93; /* (NEC PC98) */
case Keyboard.KEY_MINUS -> SDLK_MINUS;
case Keyboard.KEY_EQUALS -> SDLK_EQUALS;
case Keyboard.KEY_LBRACKET -> SDLK_LEFTBRACKET;
case Keyboard.KEY_RBRACKET -> SDLK_RIGHTBRACKET;
case Keyboard.KEY_APOSTROPHE -> SDLK_APOSTROPHE;
case Keyboard.KEY_AT -> SDLK_AT; /* (NEC PC98) */
case Keyboard.KEY_COLON -> SDLK_COLON; /* (NEC PC98) */
// case Keyboard.KEY_UNDERLINE -> SDLK_UNDERLINE; /* (NEC PC98) */
// public static final int KEY_KANA = 0x70; /* (Japanese keyboard) */
// public static final int KEY_CONVERT = 0x79; /* (Japanese keyboard) */
// public static final int KEY_NOCONVERT = 0x7B; /* (Japanese keyboard) */
// public static final int KEY_YEN = 0x7D; /* (Japanese keyboard) */
case Keyboard.KEY_KANA -> L3F_SDLK_LANG3; /* (Japanese keyboard) */
case Keyboard.KEY_CONVERT -> L3F_SDLK_LANG2; /* (Japanese keyboard) */
case Keyboard.KEY_NOCONVERT -> L3F_SDLK_LANG4; /* (Japanese keyboard) */
case Keyboard.KEY_YEN -> L3F_SDLK_INTERNATIONAL3; /* (Japanese keyboard) */
// public static final int KEY_CIRCUMFLEX = 0x90; /* (Japanese keyboard) */
// public static final int KEY_KANJI = 0x94; /* (Japanese keyboard) */
// public static final int KEY_STOP = 0x95; /* (NEC PC98) */
// public static final int KEY_AX = 0x96; /* (Japan AX) */
// public static final int KEY_UNLABELED = 0x97; /* (J3100) */
// public static final int KEY_SECTION = 0xA7; /* Section symbol (Mac) */
// public static final int KEY_NUMPADCOMMA = 0xB3; /* , on numeric keypad (NEC PC98) */
// public static final int KEY_SYSRQ = 0xB7;
// public static final int KEY_FUNCTION = 0xC4; /* Function (Mac) */
case Keyboard.KEY_CIRCUMFLEX -> L3F_SDLK_LANG1; /* (Japanese keyboard) */
case Keyboard.KEY_KANJI -> L3F_SDLK_LANG5; /* (Japanese keyboard) */
case Keyboard.KEY_STOP -> SDLK_STOP; /* (NEC PC98) */
case Keyboard.KEY_AX -> L3F_SDLK_LANG6; /* (Japan AX) */
case Keyboard.KEY_SECTION -> L3F_SDLK_LANG8; /* Section symbol (Mac) */
case Keyboard.KEY_NUMPADCOMMA -> SDLK_KP_COMMA; /* , on numeric keypad (NEC PC98) */
case Keyboard.KEY_SYSRQ -> SDLK_SYSREQ;
// case Keyboard.KEY_FUNCTION -> ; /* Function (Mac) */
// public static final int KEY_CLEAR = 0xDA; /* Clear key (Mac) */
case Keyboard.KEY_CLEAR -> SDLK_CLEAR; /* Clear key (Mac) */
// public static final int KEY_APPS = 0xDD; /* AppMenu key */
// public static final int KEY_POWER = 0xDE;
// public static final int KEY_SLEEP = 0xDF;
case Keyboard.KEY_APPS -> SDLK_APPLICATION; /* AppMenu key */
case Keyboard.KEY_POWER -> SDLK_POWER;
case Keyboard.KEY_SLEEP -> SDLK_SLEEP;
default -> GLFW.GLFW_KEY_UNKNOWN;
default -> SDLK_UNKNOWN;
};
}
public static int lwjglToSdlScancode(int lwjglCode) {
return switch (lwjglCode) {
case Keyboard.KEY_UNLABELED -> -1;
case Keyboard.KEY_ESCAPE -> SDL_SCANCODE_ESCAPE;
case Keyboard.KEY_BACK -> SDL_SCANCODE_BACKSPACE;
case Keyboard.KEY_TAB -> SDL_SCANCODE_TAB;
case Keyboard.KEY_RETURN -> SDL_SCANCODE_RETURN;
case Keyboard.KEY_SPACE -> SDL_SCANCODE_SPACE;
case Keyboard.KEY_LCONTROL -> SDL_SCANCODE_LCTRL;
case Keyboard.KEY_LSHIFT -> SDL_SCANCODE_LSHIFT;
case Keyboard.KEY_LMENU -> SDL_SCANCODE_MENU;
case Keyboard.KEY_LMETA -> SDL_SCANCODE_LGUI;
case Keyboard.KEY_RCONTROL -> SDL_SCANCODE_RCTRL;
case Keyboard.KEY_RSHIFT -> SDL_SCANCODE_RSHIFT;
case Keyboard.KEY_1 -> SDL_SCANCODE_1;
case Keyboard.KEY_2 -> SDL_SCANCODE_2;
case Keyboard.KEY_3 -> SDL_SCANCODE_3;
case Keyboard.KEY_4 -> SDL_SCANCODE_4;
case Keyboard.KEY_5 -> SDL_SCANCODE_5;
case Keyboard.KEY_6 -> SDL_SCANCODE_6;
case Keyboard.KEY_7 -> SDL_SCANCODE_7;
case Keyboard.KEY_8 -> SDL_SCANCODE_8;
case Keyboard.KEY_9 -> SDL_SCANCODE_9;
case Keyboard.KEY_0 -> SDL_SCANCODE_0;
case Keyboard.KEY_A -> SDL_SCANCODE_A;
case Keyboard.KEY_B -> SDL_SCANCODE_B;
case Keyboard.KEY_C -> SDL_SCANCODE_C;
case Keyboard.KEY_D -> SDL_SCANCODE_D;
case Keyboard.KEY_E -> SDL_SCANCODE_E;
case Keyboard.KEY_F -> SDL_SCANCODE_F;
case Keyboard.KEY_G -> SDL_SCANCODE_G;
case Keyboard.KEY_H -> SDL_SCANCODE_H;
case Keyboard.KEY_I -> SDL_SCANCODE_I;
case Keyboard.KEY_J -> SDL_SCANCODE_J;
case Keyboard.KEY_K -> SDL_SCANCODE_K;
case Keyboard.KEY_L -> SDL_SCANCODE_L;
case Keyboard.KEY_M -> SDL_SCANCODE_M;
case Keyboard.KEY_N -> SDL_SCANCODE_N;
case Keyboard.KEY_O -> SDL_SCANCODE_O;
case Keyboard.KEY_P -> SDL_SCANCODE_P;
case Keyboard.KEY_Q -> SDL_SCANCODE_Q;
case Keyboard.KEY_R -> SDL_SCANCODE_R;
case Keyboard.KEY_S -> SDL_SCANCODE_S;
case Keyboard.KEY_T -> SDL_SCANCODE_T;
case Keyboard.KEY_U -> SDL_SCANCODE_U;
case Keyboard.KEY_V -> SDL_SCANCODE_V;
case Keyboard.KEY_W -> SDL_SCANCODE_W;
case Keyboard.KEY_X -> SDL_SCANCODE_X;
case Keyboard.KEY_Y -> SDL_SCANCODE_Y;
case Keyboard.KEY_Z -> SDL_SCANCODE_Z;
case Keyboard.KEY_UP -> SDL_SCANCODE_UP;
case Keyboard.KEY_DOWN -> SDL_SCANCODE_DOWN;
case Keyboard.KEY_LEFT -> SDL_SCANCODE_LEFT;
case Keyboard.KEY_RIGHT -> SDL_SCANCODE_RIGHT;
case Keyboard.KEY_INSERT -> SDL_SCANCODE_INSERT;
case Keyboard.KEY_DELETE -> SDL_SCANCODE_DELETE;
case Keyboard.KEY_HOME -> SDL_SCANCODE_HOME;
case Keyboard.KEY_END -> SDL_SCANCODE_END;
case Keyboard.KEY_PRIOR -> SDL_SCANCODE_PAGEUP;
case Keyboard.KEY_NEXT -> SDL_SCANCODE_PAGEDOWN;
case Keyboard.KEY_F1 -> SDL_SCANCODE_F1;
case Keyboard.KEY_F2 -> SDL_SCANCODE_F2;
case Keyboard.KEY_F3 -> SDL_SCANCODE_F3;
case Keyboard.KEY_F4 -> SDL_SCANCODE_F4;
case Keyboard.KEY_F5 -> SDL_SCANCODE_F5;
case Keyboard.KEY_F6 -> SDL_SCANCODE_F6;
case Keyboard.KEY_F7 -> SDL_SCANCODE_F7;
case Keyboard.KEY_F8 -> SDL_SCANCODE_F8;
case Keyboard.KEY_F9 -> SDL_SCANCODE_F9;
case Keyboard.KEY_F10 -> SDL_SCANCODE_F10;
case Keyboard.KEY_F11 -> SDL_SCANCODE_F11;
case Keyboard.KEY_F12 -> SDL_SCANCODE_F12;
case Keyboard.KEY_F13 -> SDL_SCANCODE_F13;
case Keyboard.KEY_F14 -> SDL_SCANCODE_F14;
case Keyboard.KEY_F15 -> SDL_SCANCODE_F15;
case Keyboard.KEY_F16 -> SDL_SCANCODE_F16;
case Keyboard.KEY_F17 -> SDL_SCANCODE_F17;
case Keyboard.KEY_F18 -> SDL_SCANCODE_F18;
case Keyboard.KEY_F19 -> SDL_SCANCODE_F19;
case Keyboard.KEY_NUMPAD1 -> SDL_SCANCODE_KP_1;
case Keyboard.KEY_NUMPAD2 -> SDL_SCANCODE_KP_2;
case Keyboard.KEY_NUMPAD3 -> SDL_SCANCODE_KP_3;
case Keyboard.KEY_NUMPAD4 -> SDL_SCANCODE_KP_4;
case Keyboard.KEY_NUMPAD5 -> SDL_SCANCODE_KP_5;
case Keyboard.KEY_NUMPAD6 -> SDL_SCANCODE_KP_6;
case Keyboard.KEY_NUMPAD7 -> SDL_SCANCODE_KP_7;
case Keyboard.KEY_NUMPAD8 -> SDL_SCANCODE_KP_8;
case Keyboard.KEY_NUMPAD9 -> SDL_SCANCODE_KP_9;
case Keyboard.KEY_NUMPAD0 -> SDL_SCANCODE_KP_0;
case Keyboard.KEY_ADD -> SDL_SCANCODE_KP_PLUS;
case Keyboard.KEY_SUBTRACT -> SDL_SCANCODE_KP_MINUS;
case Keyboard.KEY_MULTIPLY -> SDL_SCANCODE_KP_MULTIPLY;
case Keyboard.KEY_DIVIDE -> SDL_SCANCODE_KP_DIVIDE;
case Keyboard.KEY_DECIMAL -> SDL_SCANCODE_KP_DECIMAL;
case Keyboard.KEY_NUMPADEQUALS -> SDL_SCANCODE_KP_EQUALS;
case Keyboard.KEY_NUMPADENTER -> SDL_SCANCODE_KP_ENTER;
case Keyboard.KEY_NUMLOCK -> SDL_SCANCODE_NUMLOCKCLEAR;
case Keyboard.KEY_SEMICOLON -> SDL_SCANCODE_SEMICOLON;
case Keyboard.KEY_BACKSLASH -> SDL_SCANCODE_BACKSLASH;
case Keyboard.KEY_COMMA -> SDL_SCANCODE_COMMA;
case Keyboard.KEY_PERIOD -> SDL_SCANCODE_PERIOD;
case Keyboard.KEY_SLASH -> SDL_SCANCODE_SLASH;
case Keyboard.KEY_GRAVE -> SDL_SCANCODE_GRAVE;
case Keyboard.KEY_CAPITAL -> SDL_SCANCODE_CAPSLOCK;
case Keyboard.KEY_SCROLL -> SDL_SCANCODE_SCROLLLOCK;
case Keyboard.KEY_PAUSE -> SDL_SCANCODE_PAUSE;
case Keyboard.KEY_MINUS -> SDL_SCANCODE_MINUS;
case Keyboard.KEY_EQUALS -> SDL_SCANCODE_EQUALS;
case Keyboard.KEY_LBRACKET -> SDL_SCANCODE_LEFTBRACKET;
case Keyboard.KEY_RBRACKET -> SDL_SCANCODE_RIGHTBRACKET;
case Keyboard.KEY_APOSTROPHE -> SDL_SCANCODE_APOSTROPHE;
case Keyboard.KEY_AT -> SDL_SCANCODE_KP_AT; /* (NEC PC98) */
case Keyboard.KEY_COLON -> SDL_SCANCODE_KP_COLON; /* (NEC PC98) */
// case Keyboard.KEY_UNDERLINE -> SDL_SCANCODE_UNDERLINE; /* (NEC PC98) */
case Keyboard.KEY_KANA -> SDL_SCANCODE_LANG3; /* (Japanese keyboard) */
case Keyboard.KEY_CONVERT -> SDL_SCANCODE_LANG2; /* (Japanese keyboard) */
case Keyboard.KEY_NOCONVERT -> SDL_SCANCODE_LANG4; /* (Japanese keyboard) */
case Keyboard.KEY_YEN -> SDL_SCANCODE_INTERNATIONAL3; /* (Japanese keyboard) */
case Keyboard.KEY_CIRCUMFLEX -> SDL_SCANCODE_LANG1; /* (Japanese keyboard) */
case Keyboard.KEY_KANJI -> SDL_SCANCODE_LANG5; /* (Japanese keyboard) */
case Keyboard.KEY_STOP -> SDL_SCANCODE_STOP; /* (NEC PC98) */
case Keyboard.KEY_AX -> SDL_SCANCODE_LANG6; /* (Japan AX) */
case Keyboard.KEY_SECTION -> SDL_SCANCODE_LANG8; /* Section symbol (Mac) */
case Keyboard.KEY_NUMPADCOMMA -> SDL_SCANCODE_KP_COMMA; /* , on numeric keypad (NEC PC98) */
case Keyboard.KEY_SYSRQ -> SDL_SCANCODE_SYSREQ;
// case Keyboard.KEY_FUNCTION -> SDL_SCANCODE_UNKNOWN; /* Function (Mac) */
case Keyboard.KEY_CLEAR -> SDL_SCANCODE_CLEAR; /* Clear key (Mac) */
case Keyboard.KEY_APPS -> SDL_SCANCODE_APPLICATION; /* AppMenu key */
case Keyboard.KEY_POWER -> SDL_SCANCODE_POWER;
case Keyboard.KEY_SLEEP -> SDL_SCANCODE_SLEEP;
default -> SDL_SCANCODE_UNKNOWN;
};
}
+43 -32
View File
@@ -1,21 +1,26 @@
package org.lwjglx.input;
import static org.lwjgl.glfw.GLFW.GLFW_KEY_UNKNOWN;
import static org.lwjgl.sdl.SDLKeyboard.*;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.nio.ByteBuffer;
import java.util.Locale;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.StringUtils;
import org.lwjgl.glfw.GLFW;
import org.lwjglx.LWJGLException;
import org.lwjgl.sdl.SDLKeycode;
import org.lwjglx.Sys;
import org.lwjglx.opengl.Display;
import com.google.common.base.Objects;
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
import it.unimi.dsi.fastutil.objects.Object2IntArrayMap;
import me.eigenraven.lwjgl3ify.Lwjgl3ify;
import me.eigenraven.lwjgl3ify.api.InputEvents;
import me.eigenraven.lwjgl3ify.client.MainThreadExec;
import me.eigenraven.lwjgl3ify.core.Config;
public class Keyboard {
@@ -165,7 +170,10 @@ public class Keyboard {
public static final int keyCount;
private static final Map<String, Integer> reverseKeyMap = new ConcurrentHashMap<>();
public static ByteBuffer sdlKeyPressedArray;
private static final Int2ObjectArrayMap<String> keyMap = new Int2ObjectArrayMap();
private static final Object2IntArrayMap<String> reverseKeyMap = new Object2IntArrayMap<>();
public enum KeyState {
@@ -236,7 +244,7 @@ public class Keyboard {
event.key,
event.state,
event.state,
java.awt.event.KeyEvent.getKeyText(KeyCodes.lwjglToAwt(KeyCodes.glfwToLwjgl(event.key))),
java.awt.event.KeyEvent.getKeyText(KeyCodes.lwjglToAwt(event.key)),
(event.key >= 32 && event.key < 127) ? (event.key) : '?');
}
try {
@@ -244,14 +252,14 @@ public class Keyboard {
} catch (IllegalStateException ignored) {}
}
public static void addGlfwKeyEvent(long window, int key, int scancode, int action, int mods, int c) {
public static void addSdlKeyEvent(int key, int scancode, InputEvents.KeyAction action, int mods, int c,
long nanoTime) {
final KeyState state = switch (action) {
case GLFW.GLFW_PRESS -> KeyState.PRESS;
case GLFW.GLFW_RELEASE -> KeyState.RELEASE;
case GLFW.GLFW_REPEAT -> KeyState.REPEAT;
default -> KeyState.RELEASE;
case PRESSED -> KeyState.PRESS;
case RELEASED -> KeyState.RELEASE;
case REPEATED -> KeyState.REPEAT;
};
addRawKeyEvent(new KeyEvent(KeyCodes.glfwToLwjgl(key), c, state, Sys.getNanoTime()));
addRawKeyEvent(new KeyEvent(KeyCodes.sdlScancodeToLwjgl(scancode), c, state, nanoTime));
}
public static void addCharEvent(int key, int c) {
@@ -263,14 +271,18 @@ public class Keyboard {
} catch (IllegalStateException ignored) {}
}
public static void create() throws LWJGLException {}
public static void create() {}
public static boolean isKeyDown(int key) {
if (key == KEY_NONE) {
final ByteBuffer array = sdlKeyPressedArray;
if (key == KEY_NONE || array == null) {
return false;
}
final int keyCode = KeyCodes.lwjglToGlfw(key);
return keyCode != GLFW_KEY_UNKNOWN && GLFW.glfwGetKey(Display.getWindow(), keyCode) == GLFW.GLFW_PRESS;
final int sdlScancode = KeyCodes.lwjglToSdlScancode(key);
if (sdlScancode <= 0 || sdlScancode >= array.limit()) {
return false;
}
return array.get(sdlScancode) != 0;
}
public static void poll() {
@@ -325,32 +337,31 @@ public class Keyboard {
return eventQueue.peek().nano;
}
public static String getKeyName(int key) {
public static synchronized String getKeyName(int key) {
if (key == KEY_NONE) {
return "NONE";
}
// GLFW caches this internally, and knows when keyboard layouts switch.
final String glfwName = StringUtils.toRootUpperCase(GLFW.glfwGetKeyName(KeyCodes.lwjglToGlfw(key), 0));
final String name;
if (glfwName == null) {
if (key >= 0 && key < unlocalizedKeyNameMiniLut.length) {
name = unlocalizedKeyNameMiniLut[key];
} else {
name = "Key " + key;
}
} else {
name = glfwName;
final String cached = keyMap.get(key);
if (cached != null) {
return cached;
}
int sdlKey = KeyCodes.lwjglToSdlKeycode(key);
if (sdlKey == -1 || sdlKey == SDLKeycode.SDLK_UNKNOWN) {
return "Key " + key;
}
String name = Objects.firstNonNull(MainThreadExec.runOnMainThread(() -> SDL_GetKeyName(sdlKey)), "UNKNOWN")
.toUpperCase(Locale.ROOT);
keyMap.put(key, name);
reverseKeyMap.put(name, key);
return name;
}
public static int getKeyIndex(String keyName) {
public static synchronized int getKeyIndex(String keyName) {
if (keyName.equals("NONE")) {
return KEY_NONE;
}
Integer ret = reverseKeyMap.get(keyName);
if (ret == null) {
int ret = reverseKeyMap.getOrDefault(keyName, -1);
if (ret == -1) {
if (keyName.matches("Key -?[0-9]+]")) {
return Integer.parseInt(StringUtils.removeStart(keyName, "Key "));
}
+79 -52
View File
@@ -1,15 +1,19 @@
package org.lwjglx.input;
import static org.lwjgl.sdl.SDLMouse.*;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import org.apache.commons.lang3.StringUtils;
import org.lwjgl.BufferUtils;
import org.lwjgl.glfw.GLFW;
import org.lwjglx.LWJGLException;
import org.lwjgl.sdl.SDLVideo;
import org.lwjgl.sdl.SDL_MouseMotionEvent;
import org.lwjgl.system.MemoryStack;
import org.lwjglx.Sys;
import org.lwjglx.opengl.Display;
import me.eigenraven.lwjgl3ify.client.MainThreadExec;
import me.eigenraven.lwjgl3ify.core.Config;
public class Mouse {
@@ -35,6 +39,8 @@ public class Mouse {
private static EventQueue queue = new EventQueue(128);
public static volatile int sdlMouseButtonFlags = 0;
private static int[] buttonEvents = new int[queue.getMaxEvents()];
private static boolean[] buttonEventStates = new boolean[queue.getMaxEvents()];
private static int[] xEvents = new int[queue.getMaxEvents()];
@@ -48,17 +54,39 @@ public class Mouse {
private static int ignoreNextDelta = 0;
private static int ignoreNextMove = 0;
public static void addMoveEvent(double mouseX, double mouseY) {
public static int sdlToLwjglMouseButton(byte sdlMouseButton) {
return switch (sdlMouseButton) {
case SDL_BUTTON_LEFT -> 0;
case SDL_BUTTON_RIGHT -> 1;
case SDL_BUTTON_MIDDLE -> 2;
case SDL_BUTTON_X1 -> 3;
case SDL_BUTTON_X2 -> 4;
default -> sdlMouseButton;
};
}
public static byte lwjglToSdlMouseButton(int lwjglMouseButton) {
return switch (lwjglMouseButton) {
case 0 -> SDL_BUTTON_LEFT;
case 1 -> SDL_BUTTON_RIGHT;
case 2 -> SDL_BUTTON_MIDDLE;
case 3 -> SDL_BUTTON_X1;
case 4 -> SDL_BUTTON_X2;
default -> (byte) lwjglMouseButton;
};
}
public static void addMoveEvent(SDL_MouseMotionEvent event) {
if (ignoreNextMove > 0) {
ignoreNextMove--;
return;
}
float scale = Display.getPixelScaleFactor();
final float mouseX = event.x() * scale;
final float mouseY = event.y() * scale;
// convert from screen-space coordinates to framebuffer coordinates
mouseX *= scale;
mouseY *= scale;
dx += (int) mouseX - latestX;
dy += Display.getHeight() - (int) mouseY - latestY;
dx += (int) (event.xrel() * scale);
dy -= (int) (event.yrel() * scale);
latestX = (int) mouseX;
latestY = Display.getHeight() - (int) mouseY;
if (ignoreNextDelta > 0) {
@@ -157,7 +185,11 @@ public class Mouse {
y = latestY;
}
public static void create() throws LWJGLException {}
public static void create() {
if (currentCursor != null) {
setNativeCursor(currentCursor);
}
}
public static boolean isCreated() {
return Display.isCreated();
@@ -167,38 +199,20 @@ public class Mouse {
if (grabbed == grab) {
return;
}
GLFW.glfwSetInputMode(
Display.getWindow(),
GLFW.GLFW_CURSOR,
grab ? GLFW.GLFW_CURSOR_DISABLED : GLFW.GLFW_CURSOR_NORMAL);
grabbed = grab;
if (!grab) {
// The old cursor position is sent instead of the new one in the events following mouse ungrab.
ignoreNextMove += 2;
setCursorPosition(Display.getWidth() / 2, Display.getHeight() / 2);
// Movement events are not properly sent when toggling mouse grab mode.
// Trick the game into getting the correct mouse position if no new events appear.
latestX = Display.getWidth() / 2;
latestY = Display.getHeight() / 2;
lastEventX = latestX;
lastEventY = latestY;
x = latestX;
y = latestY;
xEvents[queue.getNextPos()] = latestX;
yEvents[queue.getNextPos()] = latestY;
lastxEvents[queue.getNextPos()] = latestX;
lastyEvents[queue.getNextPos()] = latestY;
wheelEvents[queue.getNextPos()] = 0;
buttonEvents[queue.getNextPos()] = -1;
buttonEventStates[queue.getNextPos()] = false;
nanoTimeEvents[queue.getNextPos()] = Sys.getNanoTime();
queue.add();
} else {
ignoreNextDelta++; // Prevent camera rapidly rotating when closing GUIs.
MainThreadExec.runOnMainThread(() -> {
SDL_SetWindowRelativeMouseMode(Display.getWindow(), grab);
if (!grab) {
try (final MemoryStack ms = MemoryStack.stackPush()) {
final IntBuffer w = ms.ints(0);
final IntBuffer h = ms.ints(0);
SDLVideo.SDL_GetWindowSize(Display.getWindow(), w, h);
SDL_WarpMouseInWindow(Display.getWindow(), w.get(0) / 2.0f, h.get(0) / 2.0f);
}
}
dx = 0;
dy = 0;
}
});
grabbed = grab;
}
public static boolean isGrabbed() {
@@ -206,7 +220,7 @@ public class Mouse {
}
public static boolean isButtonDown(int button) {
return GLFW.glfwGetMouseButton(Display.getWindow(), button) == GLFW.GLFW_PRESS;
return (sdlMouseButtonFlags & (1 << (lwjglToSdlMouseButton(button) - 1))) != 0;
}
public static boolean next() {
@@ -285,17 +299,34 @@ public class Mouse {
}
// convert back from framebuffer coordinates to screen-space coordinates
float inv_scale = 1.0f / Display.getPixelScaleFactor();
new_x *= inv_scale;
new_y *= inv_scale;
GLFW.glfwSetCursorPos(Display.getWindow(), new_x, new_y);
// this might lose accuracy, since we just went from fb->screen and this will
// undo that change. Yay floating point numbers!
addMoveEvent(new_x, new_y);
MainThreadExec.runOnMainThread(
() -> { SDL_WarpMouseInWindow(Display.getWindow(), new_x * inv_scale, new_y * inv_scale); });
}
public static Cursor setNativeCursor(Cursor cursor) throws LWJGLException {
// no-op
return null;
private static Cursor currentCursor;
private static long systemCursor;
public static synchronized Cursor getNativeCursor() {
return currentCursor;
}
public static synchronized Cursor setNativeCursor(final Cursor cursor) {
final Cursor prevCursor = currentCursor;
currentCursor = cursor;
if (!Display.isCreated()) {
return prevCursor;
}
if (cursor == null) {
if (systemCursor == 0) {
systemCursor = Sys.checkSdl(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_DEFAULT));
}
MainThreadExec.runOnMainThread(() -> SDL_SetCursor(systemCursor));
} else {
cursor.sdlSet();
}
return prevCursor;
}
public static void destroy() {}
@@ -312,10 +343,6 @@ public class Mouse {
return "BUTTON" + button;
}
public static Cursor getNativeCursor() {
return null;
}
public static boolean hasWheel() {
return true;
}
+63 -40
View File
@@ -15,10 +15,13 @@
*/
package org.lwjglx.opengl;
import org.lwjgl.glfw.GLFW;
import static org.lwjgl.system.MemoryUtil.*;
import org.lwjgl.opengl.GL;
import org.lwjglx.LWJGLException;
import org.lwjgl.opengl.GLCapabilities;
import org.lwjgl.sdl.SDLVideo;
import org.lwjglx.PointerBuffer;
import org.lwjglx.Sys;
/**
* <p/>
@@ -32,50 +35,70 @@ import org.lwjglx.PointerBuffer;
*/
public final class ContextGL implements Context {
public long glfwWindow = Long.MIN_VALUE;
public long sdlWindow = 0, sdlContext = 0;
public final boolean shared;
GLCapabilities glCaps = null;
public ContextGL(long glfwWindow, boolean shared) {
this.glfwWindow = glfwWindow;
public ContextGL(long sdlWindow, long sdlContext, boolean shared) {
this.sdlWindow = sdlWindow;
this.sdlContext = sdlContext;
this.shared = shared;
}
public void releaseCurrent() throws LWJGLException {
GLFW.glfwMakeContextCurrent(0);
GL.setCapabilities(null);
}
public synchronized void releaseDrawable() throws LWJGLException {}
public synchronized void update() {}
public static void swapBuffers() throws LWJGLException {
GLFW.glfwSwapBuffers(Display.getWindow());
}
public synchronized void makeCurrent() throws LWJGLException {
GLFW.glfwMakeContextCurrent(glfwWindow);
GL.createCapabilities();
}
public synchronized boolean isCurrent() throws LWJGLException {
return GLFW.glfwGetCurrentContext() == glfwWindow;
}
public static void setSwapInterval(int value) {
GLFW.glfwSwapInterval(value);
}
public synchronized void forceDestroy() throws LWJGLException {
destroy();
}
public synchronized void destroy() throws LWJGLException {
if (shared && glfwWindow > 0) {
GLFW.glfwDestroyWindow(glfwWindow);
glfwWindow = -1;
public void releaseCurrent() {
Display.glContextMutex.lock();
try {
GL.setCapabilities(null);
SDLVideo.SDL_GL_MakeCurrent(sdlWindow, NULL);
} finally {
Display.glContextMutex.unlock();
}
}
public synchronized void setCLSharingProperties(final PointerBuffer properties) throws LWJGLException {}
public synchronized void releaseDrawable() {}
public synchronized void update() {}
public static void swapBuffers() {
Display.swapBuffers();
}
public synchronized void makeCurrent() {
Display.glContextMutex.lock();
try {
Sys.checkSdl(SDLVideo.SDL_GL_MakeCurrent(sdlWindow, sdlContext));
if (glCaps == null) {
glCaps = GL.createCapabilities();
} else {
GL.setCapabilities(glCaps);
}
} finally {
Display.glContextMutex.unlock();
}
}
public synchronized boolean isCurrent() {
return SDLVideo.SDL_GL_GetCurrentContext() == sdlContext;
}
public static void setSwapInterval(int value) {
Display.setSwapInterval(value);
}
public synchronized void forceDestroy() {
destroy();
}
public synchronized void destroy() {
if (shared && sdlWindow != NULL) {
if (sdlContext != NULL) {
SDLVideo.SDL_GL_DestroyContext(sdlContext);
sdlContext = NULL;
}
SDLVideo.SDL_DestroyWindow(sdlWindow);
sdlWindow = NULL;
}
}
public synchronized void setCLSharingProperties(final PointerBuffer properties) {}
}
File diff suppressed because it is too large. Load diff
@@ -56,7 +56,7 @@ public interface Drawable {
*/
void setCLSharingProperties(PointerBuffer properties) throws LWJGLException;
default long getGlfwWindowId() {
default long getSdlWindowId() {
return 0;
}
}
+41 -31
View File
@@ -15,17 +15,15 @@
*/
package org.lwjglx.opengl;
import static org.lwjgl.glfw.GLFW.GLFW_FALSE;
import static org.lwjgl.glfw.GLFW.GLFW_VISIBLE;
import static org.lwjgl.glfw.GLFW.glfwWindowHint;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.sdl.SDLVideo.*;
import org.lwjgl.glfw.GLFW;
import org.lwjglx.LWJGLException;
import org.lwjglx.LWJGLUtil;
import org.lwjglx.PointerBuffer;
import org.lwjglx.Sys;
import me.eigenraven.lwjgl3ify.client.MainThreadExec;
/** @author Spasi */
public class DrawableGL implements DrawableLWJGL {
/** The PixelFormat used to create the drawable. */
@@ -38,7 +36,15 @@ public class DrawableGL implements DrawableLWJGL {
protected ContextGL context;
protected DrawableGL() {
context = new ContextGL(Display.getWindow(), false);
this(Display.sdlWindow, Display.sdlMainGlContext, false);
}
protected DrawableGL(ContextGL gl) {
this.context = gl;
}
protected DrawableGL(long window, long context, boolean shared) {
this.context = new ContextGL(window, context, shared);
}
public void setPixelFormat(final PixelFormatLWJGL pf) throws LWJGLException {
@@ -60,14 +66,22 @@ public class DrawableGL implements DrawableLWJGL {
}
}
public ContextGL createSharedContext() throws LWJGLException {
public ContextGL createSharedContext() {
synchronized (GlobalLock.lock) {
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
long hiddenWindow = GLFW.glfwCreateWindow(16, 16, "MC - Shared Drawable", 0, this.context.glfwWindow);
if (hiddenWindow == 0) {
throw new LWJGLException("Couldn't create shared context hidden window");
}
return new ContextGL(hiddenWindow, true);
return MainThreadExec.runOnMainThread(() -> {
long prevCtx = SDL_GL_GetCurrentContext();
long prevWin = SDL_GL_GetCurrentWindow();
Sys.checkSdl(SDL_GL_MakeCurrent(Display.sdlHiddenWindow, Display.sdlCloneableGlContext));
long newWin = Sys.checkSdl(
SDL_CreateWindow(
"lwjgl3ify-sharedContext-" + Display.sdlMainGlContext,
1,
1,
SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN));
long newCtx = Sys.checkSdl(SDL_GL_CreateContext(newWin));
Sys.checkSdl(SDL_GL_MakeCurrent(prevWin, prevCtx));
return new ContextGL(newWin, newCtx, true);
});
}
}
@@ -79,7 +93,7 @@ public class DrawableGL implements DrawableLWJGL {
ContextGL.setSwapInterval(swap_interval);
}
public void swapBuffers() throws LWJGLException {
public void swapBuffers() {
ContextGL.swapBuffers();
}
@@ -90,21 +104,21 @@ public class DrawableGL implements DrawableLWJGL {
glClear(GL_COLOR_BUFFER_BIT);
}
public boolean isCurrent() throws LWJGLException {
public boolean isCurrent() {
synchronized (GlobalLock.lock) {
checkDestroyed();
return context.isCurrent();
}
}
public void makeCurrent() throws LWJGLException {
public void makeCurrent() {
synchronized (GlobalLock.lock) {
checkDestroyed();
context.makeCurrent();
}
}
public void releaseContext() throws LWJGLException {
public void releaseContext() {
synchronized (GlobalLock.lock) {
checkDestroyed();
if (context.isCurrent()) context.releaseCurrent();
@@ -115,23 +129,19 @@ public class DrawableGL implements DrawableLWJGL {
synchronized (GlobalLock.lock) {
if (context == null) return;
try {
releaseContext();
releaseContext();
context.forceDestroy();
context = null;
context.forceDestroy();
context = null;
if (peer_info != null) {
peer_info.destroy();
peer_info = null;
}
} catch (LWJGLException e) {
LWJGLUtil.log("Exception occurred while destroying Drawable: " + e);
if (peer_info != null) {
peer_info.destroy();
peer_info = null;
}
}
}
public void setCLSharingProperties(final PointerBuffer properties) throws LWJGLException {
public void setCLSharingProperties(final PointerBuffer properties) {
synchronized (GlobalLock.lock) {
checkDestroyed();
context.setCLSharingProperties(properties);
@@ -143,9 +153,9 @@ public class DrawableGL implements DrawableLWJGL {
}
@Override
public long getGlfwWindowId() {
public long getSdlWindowId() {
synchronized (GlobalLock.lock) {
return context.glfwWindow;
return context.sdlWindow;
}
}
}
@@ -33,7 +33,6 @@ public class GL20x {
}
public static String glGetActiveAttrib(int program, int index, int maxLength, IntBuffer sizeType) {
// TODO check if correct
String s;
try (MemoryStack stack = stackPush()) {
IntBuffer type = stack.mallocInt(1);
@@ -15,8 +15,6 @@
*/
package org.lwjglx.opengl;
import org.lwjglx.LWJGLException;
/**
* @author Spasi
*/
@@ -29,11 +27,14 @@ import org.lwjglx.LWJGLException;
*/
public final class SharedDrawable extends DrawableGL {
public SharedDrawable(final Drawable drawable) throws LWJGLException {
this.context = (ContextGL) ((DrawableLWJGL) drawable).createSharedContext();
final Drawable drawable;
public SharedDrawable(final Drawable drawable) {
super(((DrawableGL) drawable).createSharedContext());
this.drawable = drawable;
}
public ContextGL createSharedContext() {
throw new UnsupportedOperationException();
return ((DrawableGL) drawable).createSharedContext();
}
}
+15 -7
View File
@@ -16,6 +16,8 @@
package org.lwjglx.util.glu;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL12.GL_BGR;
import static org.lwjgl.opengl.GL12.GL_BGRA;
import static org.lwjgl.stb.STBImageResize.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjglx.util.glu.GLU.*;
@@ -175,10 +177,18 @@ public class MipMap extends Util {
int heightOut, int typeOut, ByteBuffer dataOut) {
final int components = compPerPix(format);
final int alphaIdx = formatAlphaIndex(format);
if (components == -1) return GLU_INVALID_ENUM;
final int strideIn = widthIn * components;
final int strideOut = widthOut * components;
final int pixelType = switch (format) {
case GL_COLOR_INDEX, GL_STENCIL_INDEX, GL_DEPTH_COMPONENT, GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA, GL_LUMINANCE -> STBIR_1CHANNEL;
case GL_LUMINANCE_ALPHA -> STBIR_AR;
case GL_RGB -> STBIR_RGB;
case GL_BGR -> STBIR_BGR;
case GL_RGBA -> STBIR_RGBA;
case GL_BGRA -> STBIR_BGRA;
default -> components;
};
if (typein != typeOut) {
// We don't care about float->int resizing unless proven otherwise
@@ -188,7 +198,7 @@ public class MipMap extends Util {
// Determine bytes per input type
switch (typein) {
case GL_UNSIGNED_BYTE -> {
if (!stbir_resize_uint8_srgb(
if (stbir_resize_uint8_srgb(
dataIn,
widthIn,
heightIn,
@@ -197,14 +207,12 @@ public class MipMap extends Util {
widthOut,
heightOut,
strideOut,
components,
alphaIdx,
0)) {
pixelType) == null) {
throw new RuntimeException("Couldn't resize image with stbir");
}
}
case GL_FLOAT -> {
if (!stbir_resize_float(
if (stbir_resize_float_linear(
dataIn.asFloatBuffer(),
widthIn,
heightIn,
@@ -213,7 +221,7 @@ public class MipMap extends Util {
widthOut,
heightOut,
strideOut * 4,
components)) {
pixelType) == null) {
throw new RuntimeException("Couldn't resize image with stbir");
}
}
@@ -23,7 +23,7 @@ import static org.lwjglx.util.glu.GLU.*;
*
*
* Created 23-dec-2003
*
*
* @author Erik Duijs
*/
public class Sphere extends Quadric {
@@ -47,8 +47,6 @@ public class Sphere extends Quadric {
* +y axis, to 0.25 at the +x axis, to 0.5 at the -y axis, to 0.75 at the -x axis, and back to 1.0 at the +y axis.
*/
public void draw(float radius, int slices, int stacks) {
// TODO
float rho, drho, theta, dtheta;
float x, y, z;
float s, t, ds, dt;
@@ -780,7 +780,7 @@ public class MappedObjectTransformer {
/*
* We need this map because we insert/remove instructions from the stream and we need a way
* to match each original instruction with the corresponding frame.
* TODO: Can we keep track of everything more efficiently without a map?
* Can we keep track of everything more efficiently without a map?
*/
final Map<AbstractInsnNode, Frame<BasicValue>> frameMap = new HashMap<AbstractInsnNode, Frame<BasicValue>>();
for (int i = 0; i < frames.length; i++) frameMap.put(instructions.get(i), frames[i]);
@@ -3,7 +3,7 @@ version=${version}
additionalVersions=
className=me.eigenraven.lwjgl3ify.rfb.Lwjgl3ifyRfbPlugin
transformerExclusions=me.eigenraven.lwjgl3ify
versionConstraints=
versionConstraints=gtnhlib@[0.6.2,)
loadBefore=
loadAfter=
loadRequires=
loadRequires=gtnhlib
@@ -9,6 +9,7 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -21,14 +22,10 @@ import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.text.BadLocationException;
import com.github.weisj.darklaf.LafManager;
import com.github.weisj.darklaf.theme.spec.ColorToneRule;
import com.github.weisj.darklaf.theme.spec.ContrastRule;
import com.github.weisj.darklaf.theme.spec.PreferredThemeStyle;
public class GraphicalConsole {
// Give up after 32MB of logs
@@ -103,7 +100,13 @@ public class GraphicalConsole {
this.process = process;
try {
System.setProperty("awt.useSystemAAFontSettings", "on");
LafManager.installTheme(new PreferredThemeStyle(ContrastRule.STANDARD, ColorToneRule.DARK));
if (System.getProperty("os.name")
.toLowerCase(Locale.ROOT)
.contains("linux")) {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} else {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
} catch (Exception e) {
consoleBuffer.add("Could not initialize DarkLaf GUI theme");
}