diff --git a/.github/jobs/android_tests.yml b/.github/jobs/android_tests.yml new file mode 100644 index 000000000..a0ebef489 --- /dev/null +++ b/.github/jobs/android_tests.yml @@ -0,0 +1,58 @@ +parameters: + name: '' + vmImage: '' + JSEngine: '' + macOSCodename: '' + +jobs: + - job: ${{ parameters.name }} + timeoutInMinutes: 45 + pool: + vmImage: ${{ parameters.vmImage }} + + steps: + - script: | + git submodule update --init --recursive + displayName: 'Checkout dependencies' + - template: cmake.yml + parameters: + vmImage: ${{ parameters.vmImage }} + + - script: | + echo Install Android image + echo 'y' | $ANDROID_HOME/tools/bin/sdkmanager --install 'system-images;android-27;default;x86_64' + echo 'y' | $ANDROID_HOME/tools/bin/sdkmanager --licenses + echo Create AVD + $ANDROID_HOME/tools/bin/avdmanager create avd -n Pixel_API_27 -d pixel -k 'system-images;android-27;default;x86_64' + displayName: 'Install Android Emulator' + - script: | + echo Start emulator + nohup $ANDROID_HOME/emulator/emulator -avd Pixel_API_27 -gpu host -no-window 2>&1 & + echo Wait for emulator + $ANDROID_HOME/platform-tools/adb wait-for-device shell 'while [[ -z $(getprop sys.boot_completed) ]]; do echo '.'; sleep 1; done' + $ANDROID_HOME/platform-tools/adb devices + displayName: 'Start Android Emulator' + + - task: Gradle@3 + inputs: + gradleWrapperFile: 'Apps/UnitTests/Android/gradlew' + workingDirectory: 'Apps/UnitTests/Android' + options: '-PabiFilters=x86_64 -PjsEngine=${{parameters.jsEngine}}' + tasks: 'connectedAndroidTest' + jdkVersionOption: 1.11 + displayName: 'Run Connected Android Test' + + - script: | + export results=$(find ./app/build/outputs/androidTest-results -name "*.txt") + echo cat "$results" + cat "$results" + workingDirectory: 'Apps/UnitTests/Android' + condition: succeededOrFailed() + displayName: 'Dump logcat from Test Results' + + - task: PublishBuildArtifacts@1 + inputs: + pathToPublish: 'Apps/UnitTests/Android/app/build/outputs/androidTest-results/connected' + artifactName: 'AndroidTestResults_${{parameters.jsEngine}}' + condition: succeededOrFailed() + displayName: 'Publish Test Results' diff --git a/Apps/UnitTests/Android/.gitignore b/Apps/UnitTests/Android/.gitignore new file mode 100644 index 000000000..ca296116d --- /dev/null +++ b/Apps/UnitTests/Android/.gitignore @@ -0,0 +1,10 @@ +*.iml +.gradle/ +.idea/ +local.properties + +app/.cxx/ +app/build/ +app/src/main/assets + +build/ \ No newline at end of file diff --git a/Apps/UnitTests/Android/app/build.gradle b/Apps/UnitTests/Android/app/build.gradle new file mode 100644 index 000000000..96d8f04c5 --- /dev/null +++ b/Apps/UnitTests/Android/app/build.gradle @@ -0,0 +1,116 @@ +plugins { + id 'com.android.application' +} + +def jsEngine = "V8" +if (project.hasProperty("jsEngine")) { + jsEngine = project.property("jsEngine") +} + +configurations { natives } + +android { + namespace 'com.babylonnative.unittests' + compileSdk 33 + ndkVersion = "21.4.7075529" + + defaultConfig { + applicationId "com.babylonnative.unittests" + minSdk 21 + targetSdk 33 + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + + externalNativeBuild { + cmake { + arguments ( + "-DANDROID_STL=c++_shared", + "-DNAPI_JAVASCRIPT_ENGINE=${jsEngine}", + "-DJSRUNTIMEHOST_CORE_APPRUNTIME_V8_INSPECTOR=ON", + ) + } + } + + if (project.hasProperty("abiFilters")) { + ndk { + abiFilters project.getProperty("abiFilters") + } + } + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + externalNativeBuild { + cmake { + path file('src/main/cpp/CMakeLists.txt') + buildStagingDirectory '../../../../Build/Android' + version '3.22.1+' + } + } + buildFeatures { + viewBinding true + } +} + +dependencies { + implementation 'com.google.ar:core:1.16.0' + natives 'com.google.ar:core:1.16.0' + implementation 'androidx.appcompat:appcompat:1.6.0' + implementation 'com.google.android.material:material:1.7.0' + implementation 'androidx.constraintlayout:constraintlayout:2.1.3' + implementation group: 'org.java-websocket', name: 'Java-WebSocket', version: '1.5.3' + testImplementation 'junit:junit:4.13.2' + androidTestImplementation 'androidx.test.ext:junit:1.1.5' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' +} + +task copyScripts { + doLast { + // run copy at execution phase because npm command is not done at configuration phase + copy + { + from "../../../node_modules/chai" + include "chai.js" + into 'src/main/assets/Scripts' + } + copy + { + from "../../../node_modules/mocha" + include "mocha.js" + into 'src/main/assets/Scripts' + } + copy + { + from "../../../node_modules/babylonjs" + include "babylon.max.js" + into 'src/main/assets/Scripts' + } + copy + { + from "../../../node_modules/babylonjs-materials" + include "babylonjs.materials.js" + into 'src/main/assets/Scripts' + } + } +} + +// Run copyScripts task after CMake external build +// And make sure merging assets into output is performed after the scripts copy +tasks.whenTaskAdded { task -> + if (task.name == 'mergeDebugNativeLibs') { + task.finalizedBy(copyScripts) + } + if (task.name == 'mergeDebugAssets') { + task.dependsOn(copyScripts) + } +} diff --git a/Apps/UnitTests/Android/app/proguard-rules.pro b/Apps/UnitTests/Android/app/proguard-rules.pro new file mode 100644 index 000000000..481bb4348 --- /dev/null +++ b/Apps/UnitTests/Android/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/Apps/UnitTests/Android/app/src/androidTest/java/com/babylonnative/unittests/Main.java b/Apps/UnitTests/Android/app/src/androidTest/java/com/babylonnative/unittests/Main.java new file mode 100644 index 000000000..cff697434 --- /dev/null +++ b/Apps/UnitTests/Android/app/src/androidTest/java/com/babylonnative/unittests/Main.java @@ -0,0 +1,28 @@ +package com.babylonnative.unittests; + +import android.content.Context; + +import androidx.test.platform.app.InstrumentationRegistry; +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class Main { + @Test + public void javaScriptTests() { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); + assertEquals("com.babylonnative.unittests", appContext.getPackageName()); + + assertEquals(0, Native.javaScriptTests(appContext)); + } +} \ No newline at end of file diff --git a/Apps/UnitTests/Android/app/src/androidTest/java/com/babylonnative/unittests/Native.java b/Apps/UnitTests/Android/app/src/androidTest/java/com/babylonnative/unittests/Native.java new file mode 100644 index 000000000..882ecd5d5 --- /dev/null +++ b/Apps/UnitTests/Android/app/src/androidTest/java/com/babylonnative/unittests/Native.java @@ -0,0 +1,12 @@ +package com.babylonnative.unittests; + +import android.content.Context; + +public class Native { + // JNI interface + static { + System.loadLibrary("UnitTestsJNI"); + } + + public static native int javaScriptTests(Context context); +} diff --git a/Apps/UnitTests/Android/app/src/main/AndroidManifest.xml b/Apps/UnitTests/Android/app/src/main/AndroidManifest.xml new file mode 100644 index 000000000..c3537fae4 --- /dev/null +++ b/Apps/UnitTests/Android/app/src/main/AndroidManifest.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/Apps/UnitTests/Android/app/src/main/cpp/CMakeLists.txt b/Apps/UnitTests/Android/app/src/main/cpp/CMakeLists.txt new file mode 100644 index 000000000..a8ed60c00 --- /dev/null +++ b/Apps/UnitTests/Android/app/src/main/cpp/CMakeLists.txt @@ -0,0 +1,43 @@ +cmake_minimum_required(VERSION 3.18) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +project(UnitTestsJNI) + +get_filename_component(UNIT_TESTS_DIR "${CMAKE_CURRENT_LIST_DIR}/../../../../.." ABSOLUTE) +get_filename_component(REPO_ROOT_DIR "${UNIT_TESTS_DIR}/../.." ABSOLUTE) + +set(JSRUNTIMEHOST_TESTS OFF) # Turn off the tests folder for Android Studio path +add_subdirectory(${REPO_ROOT_DIR} "${CMAKE_CURRENT_BINARY_DIR}/BabylonNative") + +get_filename_component(APPS_DIR "${UNIT_TESTS_DIR}/.." ABSOLUTE) +npm(install "${APPS_DIR}" "Apps" "--silent") + +add_library(UnitTestsJNI SHARED + JNI.cpp + ${UNIT_TESTS_DIR}/Shared/Tests.h) +target_compile_definitions(UnitTestsJNI PRIVATE JSRUNTIMEHOST_PLATFORM="${JSRUNTIMEHOST_PLATFORM}") + +target_include_directories(UnitTestsJNI + PRIVATE ${UNIT_TESTS_DIR}) + +target_link_libraries(UnitTestsJNI + PRIVATE GLESv3 + PRIVATE android + PRIVATE EGL + PRIVATE log + PRIVATE -lz + PRIVATE AndroidExtensions + PRIVATE AppRuntime + PRIVATE Canvas + PRIVATE Console + PRIVATE GraphicsDevice + PRIVATE NativeCamera + PRIVATE NativeEngine + PRIVATE NativeInput + PRIVATE NativeOptimizations + PRIVATE ScriptLoader + PRIVATE XMLHttpRequest + PRIVATE gtest_main + PRIVATE Window) diff --git a/Apps/UnitTests/Android/app/src/main/cpp/JNI.cpp b/Apps/UnitTests/Android/app/src/main/cpp/JNI.cpp new file mode 100644 index 000000000..818fe6029 --- /dev/null +++ b/Apps/UnitTests/Android/app/src/main/cpp/JNI.cpp @@ -0,0 +1,72 @@ +#include "gtest/gtest.h" +#include +#include +#include +#include +#include +#include + +namespace +{ + int pfd[2]; + int fd_saved[2]; +} +void* thread_func(void*) +{ + ssize_t rdsz; + char buf[128]; + while ((rdsz = read(pfd[0], buf, sizeof buf - 1)) > 0) + { + if (buf[rdsz - 1] == '\n') --rdsz; + buf[rdsz] = 0; + __android_log_write(ANDROID_LOG_DEBUG, "UnitTests", buf); + } + __android_log_write(ANDROID_LOG_DEBUG, "UnitTests", "Logger shutdown"); + return 0; +} + +void start_logger() +{ + pthread_t thr; + + // make stdout line-buffered and stderr unbuffered + fd_saved[0] = setvbuf(stdout, 0, _IOLBF, 0); + fd_saved[1] = setvbuf(stderr, 0, _IONBF, 0); + + // create the pipe and redirect stdout and stderr + pipe(pfd); + dup2(pfd[1], 1); + dup2(pfd[1], 2); + + // spawn the logging thread + if (pthread_create(&thr, 0, thread_func, 0) == -1) + { + return; + } + pthread_detach(thr); +} + +void stop_logger() +{ + close(pfd[1]); + close(pfd[0]); + setvbuf(stdout, NULL, fd_saved[0], 0); + setvbuf(stderr, NULL, fd_saved[1], 0); +} + +extern "C" JNIEXPORT jint JNICALL +Java_com_babylonnative_unittests_Native_javaScriptTests(JNIEnv* env, jclass clazz, jobject context) { + JavaVM* javaVM{}; + if (env->GetJavaVM(&javaVM) != JNI_OK) + { + throw std::runtime_error{"Failed to get Java VM"}; + } + + start_logger(); + + android::global::Initialize(javaVM, context); + auto testResult = Run(); + + stop_logger(); + return testResult; +} diff --git a/Apps/UnitTests/Android/app/src/main/res/values/strings.xml b/Apps/UnitTests/Android/app/src/main/res/values/strings.xml new file mode 100644 index 000000000..b1ceb201f --- /dev/null +++ b/Apps/UnitTests/Android/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + BabylonNative UnitTests + \ No newline at end of file diff --git a/Apps/UnitTests/Android/build.gradle b/Apps/UnitTests/Android/build.gradle new file mode 100644 index 000000000..71b99f4ca --- /dev/null +++ b/Apps/UnitTests/Android/build.gradle @@ -0,0 +1,5 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +plugins { + id 'com.android.application' version '7.3.1' apply false + id 'com.android.library' version '7.3.1' apply false +} \ No newline at end of file diff --git a/Apps/UnitTests/Android/gradle.properties b/Apps/UnitTests/Android/gradle.properties new file mode 100644 index 000000000..3e927b11e --- /dev/null +++ b/Apps/UnitTests/Android/gradle.properties @@ -0,0 +1,21 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true +# Enables namespacing of each library's R class so that its R class includes only the +# resources declared in the library itself and none from the library's dependencies, +# thereby reducing the size of the R class for that library +android.nonTransitiveRClass=true \ No newline at end of file diff --git a/Apps/UnitTests/Android/gradle/wrapper/gradle-wrapper.jar b/Apps/UnitTests/Android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..e708b1c02 Binary files /dev/null and b/Apps/UnitTests/Android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/Apps/UnitTests/Android/gradle/wrapper/gradle-wrapper.properties b/Apps/UnitTests/Android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..806746cfe --- /dev/null +++ b/Apps/UnitTests/Android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri Jan 20 12:19:56 PST 2023 +distributionBase=GRADLE_USER_HOME +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip +distributionPath=wrapper/dists +zipStorePath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME diff --git a/Apps/UnitTests/Android/gradlew b/Apps/UnitTests/Android/gradlew new file mode 100644 index 000000000..4f906e0c8 --- /dev/null +++ b/Apps/UnitTests/Android/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/Apps/UnitTests/Android/gradlew.bat b/Apps/UnitTests/Android/gradlew.bat new file mode 100644 index 000000000..107acd32c --- /dev/null +++ b/Apps/UnitTests/Android/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/Apps/UnitTests/Android/settings.gradle b/Apps/UnitTests/Android/settings.gradle new file mode 100644 index 000000000..52ff7502b --- /dev/null +++ b/Apps/UnitTests/Android/settings.gradle @@ -0,0 +1,16 @@ +pluginManagement { + repositories { + gradlePluginPortal() + google() + mavenCentral() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} +rootProject.name = "UnitTests" +include ':app' diff --git a/Apps/UnitTests/Apple/App.mm b/Apps/UnitTests/Apple/App.mm index 5e6622c94..8cdce73a1 100644 --- a/Apps/UnitTests/Apple/App.mm +++ b/Apps/UnitTests/Apple/App.mm @@ -1,5 +1,5 @@ #include "../Shared/Tests.h" int main() { - return Run({{}}); + return Run(); } diff --git a/Apps/UnitTests/CMakeLists.txt b/Apps/UnitTests/CMakeLists.txt index 810579cc5..b4d9562de 100644 --- a/Apps/UnitTests/CMakeLists.txt +++ b/Apps/UnitTests/CMakeLists.txt @@ -40,6 +40,7 @@ target_link_libraries(UnitTests PRIVATE UrlLib PRIVATE Window PRIVATE XMLHttpRequest + PRIVATE gtest_main ${ADDITIONAL_LIBRARIES}) add_test(NAME UnitTests COMMAND UnitTests) diff --git a/Apps/UnitTests/Shared/Tests.h b/Apps/UnitTests/Shared/Tests.h index 9d48d963d..97a0a4a37 100644 --- a/Apps/UnitTests/Shared/Tests.h +++ b/Apps/UnitTests/Shared/Tests.h @@ -1,3 +1,4 @@ +#include "gtest/gtest.h" #include #include #include @@ -12,25 +13,17 @@ #include #include -std::promise exitCode; +Babylon::Graphics::Configuration deviceTestConfig{}; -static inline constexpr const char* JS_FUNCTION_NAME{ "SetExitCode" }; -void SetExitCode(const Napi::CallbackInfo& info) +TEST(JSTest, JavaScriptTests) { - Napi::Env env = info.Env(); - if (info.Length() < 1) - { - throw Napi::TypeError::New(env, "Must provide an exit code"); - } - exitCode.set_value(info[0].As().Int32Value()); -} + std::promise exitCode; + Babylon::Graphics::Device device{deviceTestConfig}; -int Run(Babylon::Graphics::Device device) -{ std::optional nativeCanvas; Babylon::AppRuntime runtime{}; - runtime.Dispatch([&device, &nativeCanvas](Napi::Env env) + runtime.Dispatch([&exitCode, &device, &nativeCanvas](Napi::Env env) { device.AddToJavaScript(env); @@ -44,7 +37,11 @@ int Run(Babylon::Graphics::Device device) nativeCanvas.emplace(Babylon::Polyfills::Canvas::Initialize(env)); Babylon::Plugins::NativeEngine::Initialize(env); - env.Global().Set(JS_FUNCTION_NAME, Napi::Function::New(env, SetExitCode, JS_FUNCTION_NAME)); + env.Global().Set("SetExitCode", Napi::Function::New(env, [&exitCode](const Napi::CallbackInfo& info) + { + Napi::Env env = info.Env(); + exitCode.set_value(info[0].As().Int32Value()); + }, "SetExitCode")); }); Babylon::ScriptLoader loader{runtime}; @@ -59,6 +56,50 @@ int Run(Babylon::Graphics::Device device) device.StartRenderingCurrentFrame(); device.FinishRenderingCurrentFrame(); + // Add CPP tests here + auto code{exitCode.get_future().get()}; - return code; + EXPECT_EQ(code, 0); +} + +/* +This test does a serie of initialization and shutdowns. +It needs the shutdown PR to be merged before running properly. +TEST(NativeAPI, LifeCycle) +{ + for (int cycle = 0; cycle < 20; cycle++) + { + Babylon::Graphics::Device device = deviceTestConfig; + std::optional nativeCanvas; + + Babylon::AppRuntime runtime{}; + runtime.Dispatch([&device, &nativeCanvas](Napi::Env env) { + device.AddToJavaScript(env); + + Babylon::Polyfills::XMLHttpRequest::Initialize(env); + Babylon::Polyfills::Console::Initialize(env, [](const char* message, auto) { + printf("%s", message); + fflush(stdout); + }); + Babylon::Polyfills::Window::Initialize(env); + nativeCanvas.emplace(Babylon::Polyfills::Canvas::Initialize(env)); + Babylon::Plugins::NativeEngine::Initialize(env); + }); + + Babylon::ScriptLoader loader{runtime}; + loader.LoadScript("app:///Scripts/babylon.max.js"); + loader.LoadScript("app:///Scripts/babylonjs.materials.js"); + + for (int frame = 0; frame < 10; frame++) + { + device.StartRenderingCurrentFrame(); + device.FinishRenderingCurrentFrame(); + } + } } +*/ +int Run() +{ + testing::InitGoogleTest(); + return RUN_ALL_TESTS(); +} \ No newline at end of file diff --git a/Apps/UnitTests/Win32/App.cpp b/Apps/UnitTests/Win32/App.cpp index 7006a831b..67aaa6259 100644 --- a/Apps/UnitTests/Win32/App.cpp +++ b/Apps/UnitTests/Win32/App.cpp @@ -13,9 +13,8 @@ int main() { ::RegisterClassEx(&wc); HWND hwnd = ::CreateWindow(wc.lpszClassName, "BabylonNative", WS_OVERLAPPEDWINDOW, -1, -1, -1, -1, NULL, NULL, wc.hInstance, NULL); - Babylon::Graphics::Configuration config{}; - config.Window = hwnd; - config.Width = 600; - config.Height = 400; - return Run({config}); + deviceTestConfig.Window = hwnd; + deviceTestConfig.Width = 600; + deviceTestConfig.Height = 400; + return Run(); } diff --git a/Apps/UnitTests/X11/App.cpp b/Apps/UnitTests/X11/App.cpp index f7467ae8e..4b26184ca 100644 --- a/Apps/UnitTests/X11/App.cpp +++ b/Apps/UnitTests/X11/App.cpp @@ -1,3 +1,5 @@ +// gtest.h included here and in Shared/Tests.h because of a preprocessor conflict +#include "gtest/gtest.h" #define XK_MISCELLANY #define XK_LATIN1 #include // will include X11 which #defines None... Don't mess with order of includes. @@ -42,9 +44,8 @@ int main() XMapWindow(display, window); XStoreName(display, window, applicationName); - Babylon::Graphics::Configuration graphicsConfig{}; - graphicsConfig.Window = window; - graphicsConfig.Width = static_cast(width); - graphicsConfig.Height = static_cast(height); - return Run({graphicsConfig}); + deviceTestConfig.Window = window; + deviceTestConfig.Width = static_cast(width); + deviceTestConfig.Height = static_cast(height); + return Run(); } \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index f5866afa7..c97a5bdf3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -13,10 +13,12 @@ FetchContent_Declare(ios-cmake GIT_TAG 04d91f6675dabb3c97df346a32f6184b0a7ef845) FetchContent_Declare(JsRuntimeHost GIT_REPOSITORY https://github.com/BabylonJS/JsRuntimeHost.git - GIT_TAG 85d8d91be3c157bf61857c1e1346444024794142) + GIT_TAG 4ef1c3eb3c557bb8120d2bc2b5c06cbcfb54238f) FetchContent_Declare(AndroidExtensions GIT_REPOSITORY https://github.com/BabylonJS/AndroidExtensions.git GIT_TAG 883c4a286116e51ee989e39ee8e216d632997329) +FetchContent_Declare(googletest + URL "https://github.com/google/googletest/archive/refs/tags/v1.13.0.tar.gz") set(JSRUNTIMEHOST_TESTS OFF) set(CONTENT_TO_FETCH cmake-extensions JsRuntimeHost) @@ -62,6 +64,18 @@ if(APPLE) set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) endif() + +if(NOT WINDOWS_STORE) + if(WIN32) + # For Windows: Prevent overriding the parent project's compiler/linker settings + # Default build type for my test projects are /MDd (MultiThreaded DLL) but GTests default to /MTd (MultiTreaded) + # see https://github.com/google/googletest/blob/main/googletest/README.md + # "Enabling this option will make gtest link the runtimes dynamically too, and match the project in which it is included." + set(gtest_force_shared_crt OFF CACHE BOOL "" FORCE) + endif() + set(CONTENT_TO_FETCH ${CONTENT_TO_FETCH} googletest) +endif() + # Setting Platform if(ANDROID) set(BABYLON_NATIVE_PLATFORM "Android") diff --git a/Core/Graphics/Source/DeviceImpl.cpp b/Core/Graphics/Source/DeviceImpl.cpp index 3dad574bb..656d155c1 100644 --- a/Core/Graphics/Source/DeviceImpl.cpp +++ b/Core/Graphics/Source/DeviceImpl.cpp @@ -52,6 +52,7 @@ namespace Babylon::Graphics std::scoped_lock lock{m_state.Mutex}; m_state.Bgfx.Dirty = true; ConfigureBgfxPlatformData(m_state.Bgfx.InitState.platformData, window); + ConfigureBgfxRenderType(m_state.Bgfx.InitState.platformData, m_state.Bgfx.InitState.type); m_state.Resolution.DevicePixelRatio = GetDevicePixelRatio(window); } diff --git a/Core/Graphics/Source/DeviceImpl.h b/Core/Graphics/Source/DeviceImpl.h index 7455a1575..22c61f30b 100644 --- a/Core/Graphics/Source/DeviceImpl.h +++ b/Core/Graphics/Source/DeviceImpl.h @@ -100,7 +100,8 @@ namespace Babylon::Graphics static const bool s_bgfxFlipAfterRender; static const bgfx::RendererType::Enum s_bgfxRenderType; - static void ConfigureBgfxPlatformData(bgfx::PlatformData& platformData, WindowT window); + static void ConfigureBgfxPlatformData(bgfx::PlatformData& pd, WindowT window); + static void ConfigureBgfxRenderType(bgfx::PlatformData& pd, bgfx::RendererType::Enum& renderType); static float GetDevicePixelRatio(WindowT window); void UpdateBgfxState(); diff --git a/Core/Graphics/Source/DeviceImpl_Android.cpp b/Core/Graphics/Source/DeviceImpl_Android.cpp index 9e5bf70be..2884ab23c 100644 --- a/Core/Graphics/Source/DeviceImpl_Android.cpp +++ b/Core/Graphics/Source/DeviceImpl_Android.cpp @@ -13,6 +13,15 @@ namespace Babylon::Graphics pd.nwh = window; } + void DeviceImpl::ConfigureBgfxRenderType(bgfx::PlatformData& pd, bgfx::RendererType::Enum& renderType) + { + // on Android, having no window or context set the renderer API to no op. + if (!pd.nwh && !pd.context) + { + renderType = bgfx::RendererType::Noop; + } + } + float DeviceImpl::GetDevicePixelRatio(WindowT) { // In Android, the baseline DPI is 160dpi. diff --git a/Core/Graphics/Source/DeviceImpl_Unix.cpp b/Core/Graphics/Source/DeviceImpl_Unix.cpp index c62aaae43..5f052aa19 100644 --- a/Core/Graphics/Source/DeviceImpl_Unix.cpp +++ b/Core/Graphics/Source/DeviceImpl_Unix.cpp @@ -10,6 +10,10 @@ namespace Babylon::Graphics pd.nwh = reinterpret_cast(window); } + void DeviceImpl::ConfigureBgfxRenderType(bgfx::PlatformData& /*pd*/, bgfx::RendererType::Enum& /*renderType*/) + { + } + float DeviceImpl::GetDevicePixelRatio(WindowT) { // TODO: We should persist a Display object instead of opening a new display. diff --git a/Core/Graphics/Source/DeviceImpl_Win32.cpp b/Core/Graphics/Source/DeviceImpl_Win32.cpp index d56d93a33..6c42345ba 100644 --- a/Core/Graphics/Source/DeviceImpl_Win32.cpp +++ b/Core/Graphics/Source/DeviceImpl_Win32.cpp @@ -11,6 +11,10 @@ namespace Babylon::Graphics pd.nwh = window; } + void DeviceImpl::ConfigureBgfxRenderType(bgfx::PlatformData& /*pd*/, bgfx::RendererType::Enum& /*renderType*/) + { + } + float DeviceImpl::GetDevicePixelRatio(WindowT window) { UINT dpi = GetDpiForWindow(window); diff --git a/Core/Graphics/Source/DeviceImpl_WinRT.cpp b/Core/Graphics/Source/DeviceImpl_WinRT.cpp index 78b156317..c0798ff6f 100644 --- a/Core/Graphics/Source/DeviceImpl_WinRT.cpp +++ b/Core/Graphics/Source/DeviceImpl_WinRT.cpp @@ -22,6 +22,10 @@ namespace Babylon::Graphics pd.nwh = winrt::get_abi(window); } + void DeviceImpl::ConfigureBgfxRenderType(bgfx::PlatformData& /*pd*/, bgfx::RendererType::Enum& /*renderType*/) + { + } + float DeviceImpl::GetDevicePixelRatio(WindowT window) { if (auto uiElement = window.try_as()) diff --git a/Core/Graphics/Source/DeviceImpl_iOS.mm b/Core/Graphics/Source/DeviceImpl_iOS.mm index 91808a8f5..b013c0c7f 100644 --- a/Core/Graphics/Source/DeviceImpl_iOS.mm +++ b/Core/Graphics/Source/DeviceImpl_iOS.mm @@ -10,6 +10,10 @@ pd.nwh = window; } + void DeviceImpl::ConfigureBgfxRenderType(bgfx::PlatformData& /*pd*/, bgfx::RendererType::Enum& /*renderType*/) + { + } + float DeviceImpl::GetDevicePixelRatio(WindowT window) { return window.contentScaleFactor; diff --git a/Core/Graphics/Source/DeviceImpl_macOS.mm b/Core/Graphics/Source/DeviceImpl_macOS.mm index 06486e3e9..07f972654 100644 --- a/Core/Graphics/Source/DeviceImpl_macOS.mm +++ b/Core/Graphics/Source/DeviceImpl_macOS.mm @@ -10,6 +10,10 @@ pd.nwh = window; } + void DeviceImpl::ConfigureBgfxRenderType(bgfx::PlatformData& /*pd*/, bgfx::RendererType::Enum& /*renderType*/) + { + } + float DeviceImpl::GetDevicePixelRatio(WindowT window) { return window.window.screen.backingScaleFactor; diff --git a/Install/Test/CMakeLists.txt b/Install/Test/CMakeLists.txt index 83bc3231d..ab6eaeece 100644 --- a/Install/Test/CMakeLists.txt +++ b/Install/Test/CMakeLists.txt @@ -9,7 +9,9 @@ project(TestInstall) FetchContent_Declare(cmake-extensions GIT_REPOSITORY https://github.com/BabylonJS/CMakeExtensions.git GIT_TAG 366dc4a84fb20f4060d97e89948c343e74c51fc3) -FetchContent_MakeAvailable(cmake-extensions) +FetchContent_Declare(googletest + URL "https://github.com/google/googletest/archive/refs/tags/v1.13.0.tar.gz") +FetchContent_MakeAvailable(cmake-extensions googletest) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -169,6 +171,7 @@ target_link_libraries(TestInstall d3d12 d3dcompiler Pathcch + gtest_main ${ADDITIONAL_LIBRARIES} ) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 1efead1b4..78f383fab 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -126,4 +126,17 @@ jobs: parameters: name: Android_MacOS_V8 vmImage: 'macOS-latest' - JSEngine: V8 \ No newline at end of file + JSEngine: V8 + +# These Android tests are unstable on the CI emulator. Disabled until a more reliable solution is found. +# - template: .github/jobs/android_tests.yml +# parameters: +# name: Android_Tests_MacOS_JSC +# vmImage: 'macOS-latest' +# JSEngine: JavaScriptCore +# +# - template: .github/jobs/android_tests.yml +# parameters: +# name: Android_Tests_MacOS_V8 +# vmImage: 'macOS-latest' +# JSEngine: V8