diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index db3a993d880..1d9f7248006 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -9,7 +9,7 @@ lwjgl3 = "3.4.3" angle = "2026-05-09" libjglios = "0.10" saferalloc = "0.0.11" -native-bootstrap = "0.1.4" +native-bootstrap = "0.1.5" nifty = "1.4.3" spotbugs = "4.9.8" jmeAndroidNatives = "3.10.0-xt16kb-alloc" diff --git a/jme3-android/src/main/java/com/jme3/input/android/AndroidJoyInput.java b/jme3-android/src/main/java/com/jme3/input/android/AndroidJoyInput.java index cfcda0c29da..e6f6ac14c2f 100644 --- a/jme3-android/src/main/java/com/jme3/input/android/AndroidJoyInput.java +++ b/jme3-android/src/main/java/com/jme3/input/android/AndroidJoyInput.java @@ -33,6 +33,7 @@ import android.opengl.GLSurfaceView; import android.view.MotionEvent; +import android.view.View; import com.jme3.input.InputManager; import com.jme3.input.JoyInput; import com.jme3.input.Joystick; @@ -238,10 +239,15 @@ public long getCapturedPointerMask() { public boolean onTouch(MotionEvent event) { VirtualJoystick joystick = virtualJoystick; - if (joystick == null || inputHandler.getView() == null) { + View view = inputHandler.getView(); + if (joystick == null || view == null) { return false; } + // Touch positions are view pixels; joystick hitboxes are in GUI camera units. + int width = view.getWidth(); + int height = view.getHeight(); + boolean hasSurface = width > 0 && height > 0; boolean consumed = false; int action = event.getAction() & MotionEvent.ACTION_MASK; int pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) @@ -251,21 +257,20 @@ public boolean onTouch(MotionEvent event) { switch (action) { case MotionEvent.ACTION_POINTER_DOWN: case MotionEvent.ACTION_DOWN: - consumed = joystick.onPointerDown(event.getPointerId(pointerIndex), - toJmeX(event.getX(pointerIndex)), toJmeY(event.getY(pointerIndex)), time); + consumed = hasSurface && joystick.onNormalizedPointerDown(event.getPointerId(pointerIndex), + event.getX(pointerIndex) / width, 1f - event.getY(pointerIndex) / height, time); break; case MotionEvent.ACTION_POINTER_UP: case MotionEvent.ACTION_UP: - consumed = joystick.onPointerUp(event.getPointerId(pointerIndex), - toJmeX(event.getX(pointerIndex)), toJmeY(event.getY(pointerIndex)), time); + consumed = joystick.onPointerUp(event.getPointerId(pointerIndex), time); break; case MotionEvent.ACTION_CANCEL: consumed = joystick.onPointerCancel(time); break; case MotionEvent.ACTION_MOVE: - for (int i = 0; i < event.getPointerCount(); i++) { - consumed = joystick.onPointerMove(event.getPointerId(i), - toJmeX(event.getX(i)), toJmeY(event.getY(i)), time) || consumed; + for (int i = 0; hasSurface && i < event.getPointerCount(); i++) { + consumed = joystick.onNormalizedPointerMove(event.getPointerId(i), + event.getX(i) / width, 1f - event.getY(i) / height, time) || consumed; } break; default: @@ -305,14 +310,6 @@ public void update() { } - private float toJmeX(float x) { - return inputHandler.touchInput.getJmeX(x); - } - - private float toJmeY(float y) { - return inputHandler.touchInput.invertY(inputHandler.touchInput.getJmeY(y)); - } - protected void setPhysicalJoystickAvailable(boolean available) { physicalJoystickAvailable = available; updateVirtualJoystickAutoVisibility(); diff --git a/jme3-android/src/main/java/com/jme3/renderer/android/AndroidGL.java b/jme3-android/src/main/java/com/jme3/renderer/android/AndroidGL.java index e5c7649f2ff..d0ff6cd3715 100644 --- a/jme3-android/src/main/java/com/jme3/renderer/android/AndroidGL.java +++ b/jme3-android/src/main/java/com/jme3/renderer/android/AndroidGL.java @@ -280,12 +280,12 @@ public void glCompileShader(int shader) { @Override public void glCompressedTexImage2D(int target, int level, int internalformat, int width, int height, int border, ByteBuffer data) { - GLES20.glCompressedTexImage2D(target, level, internalformat, width, height, 0, getLimitBytes(data), data); + GLES20.glCompressedTexImage2D(target, level, internalformat, width, height, 0, getRemainingBytes(data), data); } @Override public void glCompressedTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, ByteBuffer data) { - GLES20.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, getLimitBytes(data), data); + GLES20.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, getRemainingBytes(data), data); } @Override @@ -842,13 +842,13 @@ public void glReadBuffer(int mode) { @Override public void glCompressedTexImage3D(int target, int level, int internalFormat, int width, int height, int depth, int border, ByteBuffer data) { - GLES30.glCompressedTexImage3D(target, level, internalFormat, width, height, depth, border, getLimitBytes(data), data); + GLES30.glCompressedTexImage3D(target, level, internalFormat, width, height, depth, border, getRemainingBytes(data), data); } @Override public void glCompressedTexSubImage3D(int target, int level, int xoffset, int yoffset, int zoffset, int width, int height, int depth, int format, ByteBuffer data) { - GLES30.glCompressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, getLimitBytes(data), data); + GLES30.glCompressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, getRemainingBytes(data), data); } @Override diff --git a/jme3-core/src/main/java/com/jme3/input/virtual/VirtualJoystick.java b/jme3-core/src/main/java/com/jme3/input/virtual/VirtualJoystick.java index 3561979b0df..ec52fd8603f 100644 --- a/jme3-core/src/main/java/com/jme3/input/virtual/VirtualJoystick.java +++ b/jme3-core/src/main/java/com/jme3/input/virtual/VirtualJoystick.java @@ -207,6 +207,22 @@ public boolean onPointerDown(int pointerId, float x, float y, long time) { } } + /** + * Processes a pointer-down event in normalized surface coordinates. + * + * @param pointerId the pointer identifier + * @param x the horizontal position, relative to the left edge + * @param y the vertical position, relative to the bottom edge + * @param time the input event time + * @return true if the pointer was captured by a virtual control + */ + public boolean onNormalizedPointerDown(int pointerId, float x, float y, long time) { + synchronized (inputLock) { + return visualWidth > 0 && visualHeight > 0 + && onPointerDown(pointerId, x * visualWidth, y * visualHeight, time); + } + } + /** * Processes a pointer-move event. * @@ -225,12 +241,38 @@ public boolean onPointerMove(int pointerId, float x, float y, long time) { } } + /** + * Processes a pointer-move event in normalized surface coordinates. + * + * @param pointerId the pointer identifier + * @param x the horizontal position, relative to the left edge + * @param y the vertical position, relative to the bottom edge + * @param time the input event time + * @return true if the pointer is captured by a virtual control + */ + public boolean onNormalizedPointerMove(int pointerId, float x, float y, long time) { + synchronized (inputLock) { + return onPointerMove(pointerId, x * visualWidth, y * visualHeight, time); + } + } + /** * Processes a pointer-up event. * * @return true if the pointer was captured by a virtual control */ public boolean onPointerUp(int pointerId, float x, float y, long time) { + return onPointerUp(pointerId, time); + } + + /** + * Releases a captured pointer regardless of where it was released. + * + * @param pointerId the pointer identifier + * @param time the input event time + * @return true if the pointer was captured by a virtual control + */ + public boolean onPointerUp(int pointerId, long time) { synchronized (inputLock) { Capture capture = captures.remove(pointerId); if (capture == null) { diff --git a/jme3-desktop/src/main/java/com/jme3/system/NativeLibraryLoader.java b/jme3-desktop/src/main/java/com/jme3/system/NativeLibraryLoader.java index 0733e30646f..71118362d42 100644 --- a/jme3-desktop/src/main/java/com/jme3/system/NativeLibraryLoader.java +++ b/jme3-desktop/src/main/java/com/jme3/system/NativeLibraryLoader.java @@ -39,7 +39,7 @@ import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; -import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.HashMap; import java.util.HashSet; @@ -309,15 +309,9 @@ public static synchronized File getExtractionFolder() { private static List getExtractionCandidates() { configureNativeProperties(); - List candidates = new ArrayList<>( - NativeDirectories.candidates("jme3", NativeLibraryLoader::getOperatingSystem)); File custom = getCustomExtractionFolder(); - if (custom != null) { - Path customPath = custom.toPath(); - candidates.removeIf(candidate -> candidate.root().equals(customPath.toAbsolutePath().normalize())); - candidates.add(0, new DirectoryCandidate(customPath, "jme3", getOperatingSystem())); - } - return candidates; + List preferred = custom == null ? Collections.emptyList() : Collections.singletonList(custom.toPath()); + return NativeDirectories.candidates("jme3", preferred, NativeLibraryLoader::getOperatingSystem); } private static void configureNativeProperties() { diff --git a/jme3-desktop/src/test/java/com/jme3/system/NativeLibraryExtractionTest.java b/jme3-desktop/src/test/java/com/jme3/system/NativeLibraryExtractionTest.java index d9ece84c191..ec6e0c93636 100644 --- a/jme3-desktop/src/test/java/com/jme3/system/NativeLibraryExtractionTest.java +++ b/jme3-desktop/src/test/java/com/jme3/system/NativeLibraryExtractionTest.java @@ -36,7 +36,6 @@ import java.io.IOException; import java.io.UncheckedIOException; import java.net.URI; -import java.nio.file.DirectoryStream; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; @@ -46,7 +45,9 @@ import java.nio.file.attribute.AclFileAttributeView; import java.nio.file.attribute.PosixFilePermissions; import java.util.Collections; +import java.util.Comparator; import java.util.Locale; +import java.util.stream.Stream; import com.jme3.nativebootstrap.common.OperatingSystem; import com.jme3.nativebootstrap.directories.NativeDirectories; import static org.junit.jupiter.api.Assertions.*; @@ -83,10 +84,11 @@ void refusesSharedDirectoryWithoutStickyBit() throws Exception { () -> createDirectory(shared)); assertTrue(failure.getCause().getMessage().contains(shared.toRealPath().toString())); } finally { - try (DirectoryStream children = Files.newDirectoryStream(shared)) { - for (Path child : children) Files.deleteIfExists(child); + try (Stream paths = Files.walk(shared)) { + for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) { + Files.deleteIfExists(path); + } } - Files.deleteIfExists(shared); } } diff --git a/jme3-desktop/src/test/java/com/jme3/system/NativeLibraryLoaderExtractionTest.java b/jme3-desktop/src/test/java/com/jme3/system/NativeLibraryLoaderExtractionTest.java index d771ee688e5..69b6ee5d151 100644 --- a/jme3-desktop/src/test/java/com/jme3/system/NativeLibraryLoaderExtractionTest.java +++ b/jme3-desktop/src/test/java/com/jme3/system/NativeLibraryLoaderExtractionTest.java @@ -36,6 +36,9 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import com.jme3.nativebootstrap.common.OperatingSystem; +import com.jme3.nativebootstrap.directories.DirectoryCandidate; +import com.jme3.nativebootstrap.directories.NativeDirectories; import com.jme3.util.res.Resources; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -49,6 +52,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -69,13 +73,12 @@ class NativeLibraryLoaderExtractionTest { private final Map fields = new HashMap<>(); private Path tmp; private Path home; + private Path cache; @BeforeEach void isolateLoaderState() throws Exception { - NativeLibraryLoader.isExtractNativeLibraries(); // Initialize the global namespace before saving properties. - properties.put("natives.namespace", System.getProperty("natives.namespace")); for (String key : new String[]{"java.io.tmpdir", "user.home", - "natives.tempDir", "natives.userHome", "natives.cacheDir", + "natives.tempDir", "natives.userHome", "natives.cacheDir", "natives.namespace", NativeLibraryLoader.CUSTOM_EXTRACTION_FOLDER_PROPERTY, NativeLibraryLoader.EXTRACT_NATIVE_LIBRARIES_PROPERTY, NativeLibraryLoader.CACHE_FOLDER_PROPERTY}) { @@ -90,9 +93,10 @@ void isolateLoaderState() throws Exception { } tmp = Files.createDirectory(directory.resolve("tmp")); home = directory.resolve("home"); + cache = Files.createDirectory(directory.resolve("cache")); System.setProperty("java.io.tmpdir", tmp.toString()); System.setProperty("user.home", home.toString()); - System.setProperty(NativeLibraryLoader.CACHE_FOLDER_PROPERTY, home.resolve(".cache").toString()); + System.setProperty(NativeLibraryLoader.CACHE_FOLDER_PROPERTY, cache.toString()); } @AfterEach @@ -110,11 +114,8 @@ void restoreLoaderState() throws Exception { @Test void defaultNamespaceAlsoAppliesToOtherBootstrapLibraries() { assertNull(System.getProperty("natives.namespace")); - List candidates = - com.jme3.nativebootstrap.directories.NativeDirectories.candidates("other-library", - () -> com.jme3.nativebootstrap.common.OperatingSystem.LINUX); - assertEquals(home.resolve(".jme3/natives/other-library"), - candidates.get(candidates.size() - 1).root()); + List candidates = NativeDirectories.candidates("other-library", () -> OperatingSystem.LINUX); + assertEquals(tmp.resolve(".jme3/other-library"), candidates.get(0).root()); } @Test @@ -124,10 +125,11 @@ void customFolderDoesNotOverwriteBootstrapTempOverride() throws Exception { Path custom = Files.createDirectory(directory.resolve("custom")); NativeLibraryLoader.setCustomExtractionFolder(custom.toString()); assertEquals(nativeTemp.toString(), System.getProperty("natives.tempDir")); - assertEquals(custom.toRealPath(), NativeLibraryLoader.getExtractionFolder().toPath().getParent()); + assertEquals(extractionRoot(custom.toRealPath()), NativeLibraryLoader.getExtractionFolder().toPath().getParent()); NativeLibraryLoader.setCustomExtractionFolder(null); assertEquals(nativeTemp.toString(), System.getProperty("natives.tempDir")); - assertEquals(nativeTemp.toRealPath(), NativeLibraryLoader.getExtractionFolder().toPath().getParent()); + assertEquals(extractionRoot(nativeTemp.toRealPath()), + NativeLibraryLoader.getExtractionFolder().toPath().getParent()); } @Test @@ -149,7 +151,7 @@ void cachePropertyOnlyChangesWithJmeOverride() throws Exception { @Test void tempIsPrivateAndDoesNotCreateHome() throws Exception { Path selected = NativeLibraryLoader.getExtractionFolder().toPath(); - assertEquals(tmp.toRealPath(), selected.getParent()); + assertEquals(extractionRoot(tmp).toRealPath(), selected.getParent()); assertFalse(Files.exists(home)); if (Files.getFileStore(selected).supportsFileAttributeView("posix")) { assertEquals(PosixFilePermissions.fromString("rwx------"), Files.getPosixFilePermissions(selected)); @@ -166,7 +168,6 @@ void relativeHomeDoesNotBreakTemp() { @Test void relativeTempFallsBackToCache() throws Exception { - Files.createDirectories(home.resolve(".cache")); System.setProperty("java.io.tmpdir", "relative-temp"); Path selected = NativeLibraryLoader.getExtractionFolder().toPath(); assertEquals(cacheRoot().toRealPath(), selected.getParent()); @@ -197,13 +198,12 @@ void configuredCacheReplacesPlatformCacheAfterTemp() throws Exception { }), true); assertEquals(2, attempts.get()); assertEquals(cache.toString(), System.getProperty("natives.cacheDir")); - assertEquals(cache.resolve("jme3").toRealPath(), Paths.get(loaded).getParent().getParent()); + assertEquals(extractionRoot(cache).toRealPath(), Paths.get(loaded).getParent().getParent()); assertFalse(Files.exists(home)); } @Test void tempFileFallsBackToCacheDuringExtraction() throws Exception { - Files.createDirectories(home.resolve(".cache")); Path blockedTemp = Files.createFile(directory.resolve("temp-file")); System.setProperty("java.io.tmpdir", blockedTemp.toString()); @@ -215,11 +215,11 @@ void tempFileFallsBackToCacheDuringExtraction() throws Exception { @Test void unusableTempAndCacheFallBackToHome() throws Exception { System.setProperty("java.io.tmpdir", Files.createFile(directory.resolve("tmp-file")).toString()); - Path cache = cacheRoot(); - Files.createDirectories(cache.getParent()); - Files.createFile(cache); + Files.createDirectories(cacheRoot().getParent()); + Files.createFile(cacheRoot()); + Files.createDirectory(home); String loaded = NativeLibraryLoader.loadNativeLibrary(register("fixture.so", path -> {}), true); - assertTrue(Paths.get(loaded).startsWith(home.resolve(".jme3/natives/jme3").toRealPath())); + assertTrue(Paths.get(loaded).startsWith(extractionRoot(home).toRealPath())); assertTrue(Files.isRegularFile(Paths.get(loaded))); } @@ -228,7 +228,7 @@ void ignoresLegacyPredictableTempPath() throws Exception { Path legacy = Files.createDirectory(tmp.resolve("jme3")); Path poison = Files.write(legacy.resolve("poison"), new byte[]{1, 2, 3}); Path selected = NativeLibraryLoader.getExtractionFolder().toPath(); - assertEquals(tmp.toRealPath(), selected.getParent()); + assertEquals(extractionRoot(tmp).toRealPath(), selected.getParent()); assertArrayEquals(new byte[]{1, 2, 3}, Files.readAllBytes(poison)); } @@ -255,7 +255,6 @@ void rejectsSymlinkWithoutChangingTarget() throws Exception { @Test void failedLoadFallsBackAndRemovesFailedFile() throws Exception { - Files.createDirectories(home.resolve(".cache")); AtomicInteger calls = new AtomicInteger(); List attempted = new ArrayList<>(); String name = register("fixture.so", path -> { @@ -272,29 +271,29 @@ void failedLoadFallsBackAndRemovesFailedFile() throws Exception { @Test void errorsIncludeAllLoadAttemptsAndOptionalFailureReturnsNull() throws Exception { - Files.createDirectories(home.resolve(".cache")); + setExtractionRoots(tmp, cache, home); String name = register("fixture.so", path -> { throw new UnsatisfiedLinkError("mapping denied"); }); UnsatisfiedLinkError error = assertThrows(UnsatisfiedLinkError.class, () -> NativeLibraryLoader.loadNativeLibrary(name, true)); assertEquals(3, error.getSuppressed().length); + setExtractionRoots(tmp, cache, home); assertNull(NativeLibraryLoader.loadNativeLibrary(name, false)); } @Test void allUnusableRootsFailWithoutRetryingForever() throws Exception { Path notDirectory = Files.createFile(directory.resolve("not-a-directory")); - Path cache = Files.createDirectory(directory.resolve("cache")); - Files.createFile(cache.resolve("jme3")); - NativeLibraryLoader.setCustomExtractionFolder(notDirectory.toString()); - System.setProperty("java.io.tmpdir", notDirectory.toString()); - System.setProperty(NativeLibraryLoader.CACHE_FOLDER_PROPERTY, cache.toString()); - System.setProperty("user.home", Files.createFile(directory.resolve("home-file")).toString()); + Files.createDirectories(cacheRoot().getParent()); + Files.createFile(cacheRoot()); + Files.createFile(home); + setExtractionRoots(notDirectory, cache, home); String name = register("fixture.so", path -> fail("Must not load")); UnsatisfiedLinkError error = assertThrows(UnsatisfiedLinkError.class, () -> NativeLibraryLoader.loadNativeLibrary(name, true)); assertEquals(1, error.getSuppressed().length); assertEquals(3, error.getSuppressed()[0].getCause().getSuppressed().length); + setExtractionRoots(notDirectory, cache, home); assertNull(NativeLibraryLoader.loadNativeLibrary(name, false)); } @@ -302,6 +301,7 @@ void allUnusableRootsFailWithoutRetryingForever() throws Exception { void failedLoadRediscoversUpdatedCacheOverride() throws Exception { System.setProperty("java.io.tmpdir", Files.createFile(directory.resolve("tmp-file")).toString()); System.setProperty("user.home", Files.createFile(directory.resolve("home-file")).toString()); + setExtractionRoots(cache); AtomicBoolean denyLoad = new AtomicBoolean(true); String name = register("fixture.so", path -> { if (denyLoad.get()) throw new UnsatisfiedLinkError("mapping denied"); @@ -312,12 +312,13 @@ void failedLoadRediscoversUpdatedCacheOverride() throws Exception { System.setProperty(NativeLibraryLoader.CACHE_FOLDER_PROPERTY, newCache.toString()); denyLoad.set(false); String loaded = NativeLibraryLoader.loadNativeLibrary(name, true); - assertEquals(newCache.resolve("jme3").toRealPath(), Paths.get(loaded).getParent().getParent()); + assertEquals(extractionRoot(newCache).toRealPath(), Paths.get(loaded).getParent().getParent()); } @Test - void invalidLegacyCacheOverrideUsesBootstrapDefaults() throws Exception { + void invalidLegacyCacheOverridePreservesBootstrapCache() throws Exception { System.setProperty("java.io.tmpdir", Files.createFile(directory.resolve("tmp-file")).toString()); + System.setProperty("natives.cacheDir", cache.toString()); Path missingCache = directory.resolve("missing-cache"); Path cacheFile = Files.createFile(directory.resolve("cache-file")); for (String override : new String[]{"relative-cache", missingCache.toString(), cacheFile.toString()}) { @@ -325,7 +326,7 @@ void invalidLegacyCacheOverrideUsesBootstrapDefaults() throws Exception { NativeLibraryLoader.setCustomExtractionFolder(null); String loaded = NativeLibraryLoader.loadNativeLibrary(register("fixture.so", path -> {}), true); assertTrue(Files.isRegularFile(Paths.get(loaded))); - assertFalse(Paths.get(loaded).startsWith(missingCache)); + assertTrue(Paths.get(loaded).startsWith(cacheRoot().toRealPath())); } assertFalse(Files.exists(missingCache)); } @@ -333,12 +334,8 @@ void invalidLegacyCacheOverrideUsesBootstrapDefaults() throws Exception { @Test void explicitBootstrapNamespaceIsPreserved() throws Exception { System.setProperty("natives.namespace", ".custom-app"); - System.setProperty("java.io.tmpdir", Files.createFile(directory.resolve("tmp-file")).toString()); - Files.createDirectories(cacheRoot().getParent()); - Files.createFile(cacheRoot()); - String loaded = NativeLibraryLoader.loadNativeLibrary(register("fixture.so", path -> {}), true); - assertEquals(home.resolve(".custom-app/natives/jme3").toRealPath(), - Paths.get(loaded).getParent().getParent()); + Path selected = NativeLibraryLoader.getExtractionFolder().toPath(); + assertEquals(tmp.resolve(".custom-app/jme3").toRealPath(), selected.getParent()); assertEquals(".custom-app", System.getProperty("natives.namespace")); } @@ -362,7 +359,7 @@ void concurrentCallsShareOneDirectoryAndLoadOnce() throws Exception { String first = futures.get(0).get(10, TimeUnit.SECONDS); for (Future future : futures) assertEquals(first, future.get(10, TimeUnit.SECONDS)); assertEquals(1, loads.get()); - try (Stream children = Files.list(tmp)) { + try (Stream children = Files.list(extractionRoot(tmp))) { assertEquals(1, children.count()); } } finally { @@ -395,6 +392,21 @@ void customLoadFailureFallsBackToTemp() throws Exception { assertFalse(Files.exists(attempted.get(0))); } + @Test + void customDirectoryMatchingTempIsTriedOnlyOnce() throws Exception { + NativeLibraryLoader.setCustomExtractionFolder(tmp.toString()); + List attempted = new ArrayList<>(); + String name = register("fixture.so", path -> { + attempted.add(Paths.get(path)); + if (attempted.size() == 1) throw new UnsatisfiedLinkError("custom failure"); + }); + + String loaded = NativeLibraryLoader.loadNativeLibrary(name, true); + assertEquals(2, attempted.size()); + assertEquals(extractionRoot(tmp).toRealPath(), attempted.get(0).getParent().getParent()); + assertEquals(cacheRoot().toRealPath(), Paths.get(loaded).getParent().getParent()); + } + @Test void unusableCustomDirectoryFallsBackToTemp() throws Exception { Path custom = Files.createFile(directory.resolve("not-a-directory")); @@ -408,7 +420,7 @@ void customDirectoryIsCreatedWhenExtracting() throws Exception { Path custom = directory.resolve("new-custom"); NativeLibraryLoader.setCustomExtractionFolder(custom.toString()); Path selected = NativeLibraryLoader.getExtractionFolder().toPath(); - assertEquals(custom.toRealPath(), selected.getParent()); + assertEquals(extractionRoot(custom).toRealPath(), selected.getParent()); assertNull(System.getProperty("natives.tempDir")); assertTrue(Files.isDirectory(selected)); @@ -433,7 +445,7 @@ void settingCustomDirectoryAfterAutomaticSelectionTakesEffect() throws Exception Path custom = directory.resolve("late-custom"); NativeLibraryLoader.setCustomExtractionFolder(custom.toString()); Path selected = NativeLibraryLoader.getExtractionFolder().toPath(); - assertEquals(custom.toRealPath(), selected.getParent()); + assertEquals(extractionRoot(custom).toRealPath(), selected.getParent()); assertEquals(alreadyLoaded, NativeLibraryLoader.loadNativeLibrary(name, true)); assertEquals(1, loads.get()); assertEquals(selected.resolve("other.so").toString(), @@ -454,16 +466,15 @@ void customDirectoryDoesNotTrustExistingFile() throws Exception { @Test void noexecTempIsSkippedEvenForDelegatedLoaders() throws Exception { - Files.createDirectories(home.resolve(".cache")); Path noexec = createNoexecDirectory(); try { System.setProperty("java.io.tmpdir", noexec.toString()); String loaded = NativeLibraryLoader.loadNativeLibrary(register("fixture.so", path -> {}), true); assertTrue(Paths.get(loaded).startsWith(cacheRoot().toRealPath())); - try (Stream children = Files.list(noexec)) { - assertEquals(0, children.count()); - } } finally { + // A rejected extraction may still have created the stable namespace directories. + Files.deleteIfExists(extractionRoot(noexec)); + Files.deleteIfExists(noexec.resolve(".jme3")); Files.delete(noexec); } } @@ -475,7 +486,16 @@ private String register(String filename, Consumer loader) { } private Path cacheRoot() { - return home.resolve(".cache/jme3"); + return extractionRoot(cache); + } + + private static Path extractionRoot(Path base) { + return base.resolve(".jme3").resolve("jme3"); + } + + private static void setExtractionRoots(Path... bases) throws Exception { + OperatingSystem os = OperatingSystem.valueOf(JmeSystem.getPlatform().getOs().name().toUpperCase(Locale.ROOT)); + field("extractionCandidates").set(null, NativeDirectories.fromRoots("jme3", List.of(bases), () -> os)); } private static Path createNoexecDirectory() throws Exception { diff --git a/jme3-screenshot-tests/jme3-screenshot-tests-android/src/androidTest/java/org/jmonkeyengine/screenshottests/android/input/VirtualJoystickTouchTest.java b/jme3-screenshot-tests/jme3-screenshot-tests-android/src/androidTest/java/org/jmonkeyengine/screenshottests/android/input/VirtualJoystickTouchTest.java new file mode 100644 index 00000000000..90dc4584c33 --- /dev/null +++ b/jme3-screenshot-tests/jme3-screenshot-tests-android/src/androidTest/java/org/jmonkeyengine/screenshottests/android/input/VirtualJoystickTouchTest.java @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2026 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.jmonkeyengine.screenshottests.android.input; + +import android.opengl.GLSurfaceView; +import android.os.SystemClock; +import android.view.InputDevice; +import android.view.MotionEvent; +import androidx.test.annotation.UiThreadTest; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import com.jme3.asset.DesktopAssetManager; +import com.jme3.asset.plugins.ClasspathLocator; +import com.jme3.input.InputManager; +import com.jme3.input.JoystickAxis; +import com.jme3.input.RawInputListenerAdapter; +import com.jme3.input.android.AndroidInputHandler26; +import com.jme3.input.android.AndroidJoyInput; +import com.jme3.input.dummy.DummyKeyInput; +import com.jme3.input.event.JoyAxisEvent; +import com.jme3.input.virtual.VirtualJoystick; +import com.jme3.material.plugins.J3MLoader; +import com.jme3.math.Vector3f; +import com.jme3.scene.Node; +import com.jme3.scene.Spatial; +import com.jme3.system.AppSettings; +import com.jme3.texture.plugins.AndroidBufferImageLoader; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(AndroidJUnit4.class) +public class VirtualJoystickTouchTest { + private static final int LOGICAL_WIDTH = 450; + private static final int LOGICAL_HEIGHT = 300; + private static final String STICK_X = JoystickAxis.AXIS_XBOX_LEFT_THUMB_STICK_X; + private static final String STICK_Y = JoystickAxis.AXIS_XBOX_LEFT_THUMB_STICK_Y; + + @Test + @UiThreadTest + public void dragStickWithLogicalSizeGui() { + checkStickDrag(LOGICAL_WIDTH, LOGICAL_HEIGHT); + } + + @Test + @UiThreadTest + public void dragStickWithIndependentlySizedGui() { + checkStickDrag(1200, 800); + } + + private static void checkStickDrag(int guiWidth, int guiHeight) { + GLSurfaceView view = new GLSurfaceView(ApplicationProvider.getApplicationContext()); + view.layout(0, 0, 900, 600); + + AppSettings settings = new AppSettings(true); + settings.setResolution(LOGICAL_WIDTH, LOGICAL_HEIGHT); + settings.setUseJoysticks(true); + settings.setUseAndroidSensorJoystick(false); + settings.setVirtualJoystick(AppSettings.VIRTUAL_JOYSTICK_ENABLED); + settings.setVirtualJoystickDefaultLayout(AppSettings.VIRTUAL_JOYSTICK_LAYOUT_XBOX); + + AndroidInputHandler26 handler = new AndroidInputHandler26(); + handler.setView(view); + handler.loadSettings(settings); + AndroidJoyInput joyInput = (AndroidJoyInput) handler.getJoyInput(); + DummyKeyInput keys = new DummyKeyInput(); + keys.initialize(); + joyInput.initialize(); + handler.getTouchInput().initialize(); + handler.getMouseInput().initialize(); + try { + InputManager input = new InputManager(handler.getMouseInput(), keys, joyInput, handler.getTouchInput()); + VirtualJoystick joystick = (VirtualJoystick) input.getJoysticks()[0]; + Map axes = new HashMap<>(); + input.addRawInputListener(new RawInputListenerAdapter() { + @Override + public void onJoyAxisEvent(JoyAxisEvent event) { + if (event.getAxis().getJoystick() == joystick) { + axes.put(event.getAxis().getLogicalId(), event.getValue()); + } + } + }); + + DesktopAssetManager assets = new DesktopAssetManager(); + assets.registerLocator("/", ClasspathLocator.class); + assets.registerLoader(J3MLoader.class, "j3md"); + assets.registerLoader(AndroidBufferImageLoader.class, "png"); + joystick.getTheme().setFontPath(null); + Node gui = new Node("gui"); + joystick.updateVisuals(gui, assets, guiWidth, guiHeight, 0f); + + // Use the scene geometry as the reference for the stick's center and radius. + Node stick = (Node) gui.getChild("Virtual Joystick " + STICK_X); + assertNotNull("The left stick must be present in the GUI", stick); + Spatial pad = stick.getChild(STICK_X); + assertNotNull("The left stick must have a base picture", pad); + Vector3f center = stick.getLocalTranslation(); + float centerX = center.x * view.getWidth() / guiWidth; + float centerY = view.getHeight() - center.y * view.getHeight() / guiHeight; + float halfRadius = pad.getLocalScale().y / 4f; + + long downTime = SystemClock.uptimeMillis(); + dispatchTouch(view, downTime, MotionEvent.ACTION_DOWN, centerX, centerY); + assertEquals("A touch at the visual center must capture the stick", + 1L, joyInput.getCapturedPointerMask()); + + dispatchTouch(view, downTime, MotionEvent.ACTION_MOVE, + centerX + halfRadius * view.getWidth() / guiWidth, + centerY - halfRadius * view.getHeight() / guiHeight); + input.update(1f / 60f); + assertEquals("Dragging right must emit the corresponding X value", + 0.5f, axes.getOrDefault(STICK_X, Float.NaN), 0.001f); + assertEquals("Dragging up must emit the corresponding Y value", + -0.5f, axes.getOrDefault(STICK_Y, Float.NaN), 0.001f); + + axes.clear(); + dispatchTouch(view, downTime, MotionEvent.ACTION_UP, view.getWidth() / 2f, centerY); + input.update(1f / 60f); + assertEquals("Lifting the finger outside the stick must release it", + 0L, joyInput.getCapturedPointerMask()); + assertEquals(0f, axes.getOrDefault(STICK_X, Float.NaN), 0f); + assertEquals(0f, axes.getOrDefault(STICK_Y, Float.NaN), 0f); + } finally { + handler.setView(null); + joyInput.destroy(); + handler.getTouchInput().destroy(); + handler.getMouseInput().destroy(); + keys.destroy(); + } + } + + private static void dispatchTouch(GLSurfaceView view, long downTime, int action, float x, float y) { + MotionEvent event = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(), action, x, y, 0); + try { + event.setSource(InputDevice.SOURCE_TOUCHSCREEN); + view.dispatchTouchEvent(event); + } finally { + event.recycle(); + } + } +}