diff --git a/README.md b/README.md index ce500fa57..4d4741b0e 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,18 @@ - -# Simple DirectMedia Layer (SDL) Version 3.0 - -https://www.libsdl.org/ - -Simple DirectMedia Layer is a cross-platform development library designed -to provide low level access to audio, keyboard, mouse, joystick, and graphics -hardware via OpenGL and Direct3D. It is used by video playback software, -emulators, and popular games including Valve's award winning catalog -and many Humble Bundle games. - -More extensive documentation is available in the docs directory, starting -with [README.md](docs/README.md). If you are migrating to SDL 3.0 from SDL 2.0, -the changes are extensively documented in [README-migration.md](docs/README-migration.md). - -Enjoy! - -Sam Lantinga (slouken@libsdl.org) + +# Simple DirectMedia Layer (SDL) Version 3.0 + +https://www.libsdl.org/ + +Simple DirectMedia Layer is a cross-platform development library designed +to provide low level access to audio, keyboard, mouse, joystick, and graphics +hardware via OpenGL and Direct3D. It is used by video playback software, +emulators, and popular games including Valve's award winning catalog +and many Humble Bundle games. + +More extensive documentation is available in the docs directory, starting +with [README.md](docs/README.md). If you are migrating to SDL 3.0 from SDL 2.0, +the changes are extensively documented in [README-migration.md](docs/README-migration.md). + +Enjoy! + +Sam Lantinga (slouken@libsdl.org) diff --git a/docs/README-android.md b/docs/README-android.md index 2eaee31bd..588b43d0e 100644 --- a/docs/README-android.md +++ b/docs/README-android.md @@ -1,563 +1,563 @@ -Android -================================================================================ - -Matt Styles wrote a tutorial on building SDL for Android with Visual Studio: -http://trederia.blogspot.de/2017/03/building-sdl2-for-android-with-visual.html - -The rest of this README covers the Android gradle style build process. - - -Requirements -================================================================================ - -Android SDK (version 34 or later) -https://developer.android.com/sdk/index.html - -Android NDK r15c or later -https://developer.android.com/tools/sdk/ndk/index.html - -Minimum API level supported by SDL: 19 (Android 4.4) - - -How the port works -================================================================================ - -- Android applications are Java-based, optionally with parts written in C -- As SDL apps are C-based, we use a small Java shim that uses JNI to talk to - the SDL library -- This means that your application C code must be placed inside an Android - Java project, along with some C support code that communicates with Java -- This eventually produces a standard Android .apk package - -The Android Java code implements an "Activity" and can be found in: -android-project/app/src/main/java/org/libsdl/app/SDLActivity.java - -The Java code loads your game code, the SDL shared library, and -dispatches to native functions implemented in the SDL library: -src/core/android/SDL_android.c - - -Building an app -================================================================================ - -For simple projects you can use the script located at build-scripts/androidbuild.sh - -There's two ways of using it: - - androidbuild.sh com.yourcompany.yourapp < sources.list - androidbuild.sh com.yourcompany.yourapp source1.c source2.c ...sourceN.c - -sources.list should be a text file with a source file name in each line -Filenames should be specified relative to the current directory, for example if -you are in the build-scripts directory and want to create the testgles.c test, you'll -run: - - ./androidbuild.sh org.libsdl.testgles ../test/testgles.c - -One limitation of this script is that all sources provided will be aggregated into -a single directory, thus all your source files should have a unique name. - -Once the project is complete the script will tell you where the debug APK is located. -If you want to create a signed release APK, you can use the project created by this -utility to generate it. - -Finally, a word of caution: re running androidbuild.sh wipes any changes you may have -done in the build directory for the app! - - - -For more complex projects, follow these instructions: - -1. Get the source code for SDL and copy the 'android-project' directory located at SDL/android-project to a suitable location. Also make sure to rename it to your project name (In these examples: YOURPROJECT). - - (The 'android-project' directory can basically be seen as a sort of starting point for the android-port of your project. It contains the glue code between the Android Java 'frontend' and the SDL code 'backend'. It also contains some standard behaviour, like how events should be handled, which you will be able to change.) - -2. Move or [symlink](https://en.wikipedia.org/wiki/Symbolic_link) the SDL directory into the "YOURPROJECT/app/jni" directory - -(This is needed as the source of SDL has to be compiled by the Android compiler) - -3. Edit "YOURPROJECT/app/jni/src/Android.mk" to include your source files. - -(They should be separated by spaces after the "LOCAL_SRC_FILES := " declaration) - -4a. If you want to use Android Studio, simply open your 'YOURPROJECT' directory and start building. - -4b. If you want to build manually, run './gradlew installDebug' in the project directory. This compiles the .java, creates an .apk with the native code embedded, and installs it on any connected Android device - - -If you already have a project that uses CMake, the instructions change somewhat: - -1. Do points 1 and 2 from the instruction above. -2. Edit "YOURPROJECT/app/build.gradle" to comment out or remove sections containing ndk-build - and uncomment the cmake sections. Add arguments to the CMake invocation as needed. -3. Edit "YOURPROJECT/app/jni/CMakeLists.txt" to include your project (it defaults to - adding the "src" subdirectory). Note that you'll have SDL3 and SDL3-static - as targets in your project, so you should have "target_link_libraries(yourgame SDL3)" - in your CMakeLists.txt file. Also be aware that you should use add_library() instead of - add_executable() for the target containing your "main" function. - -If you wish to use Android Studio, you can skip the last step. - -4. Run './gradlew installDebug' or './gradlew installRelease' in the project directory. It will build and install your .apk on any - connected Android device - -Here's an explanation of the files in the Android project, so you can customize them: - - android-project/app - build.gradle - build info including the application version and SDK - src/main/AndroidManifest.xml - package manifest. Among others, it contains the class name of the main Activity and the package name of the application. - jni/ - directory holding native code - jni/Application.mk - Application JNI settings, including target platform and STL library - jni/Android.mk - Android makefile that can call recursively the Android.mk files in all subdirectories - jni/CMakeLists.txt - Top-level CMake project that adds SDL as a subproject - jni/SDL/ - (symlink to) directory holding the SDL library files - jni/SDL/Android.mk - Android makefile for creating the SDL shared library - jni/src/ - directory holding your C/C++ source - jni/src/Android.mk - Android makefile that you should customize to include your source code and any library references - jni/src/CMakeLists.txt - CMake file that you may customize to include your source code and any library references - src/main/assets/ - directory holding asset files for your application - src/main/res/ - directory holding resources for your application - src/main/res/mipmap-* - directories holding icons for different phone hardware - src/main/res/values/strings.xml - strings used in your application, including the application name - src/main/java/org/libsdl/app/SDLActivity.java - the Java class handling the initialization and binding to SDL. Be very careful changing this, as the SDL library relies on this implementation. You should instead subclass this for your application. - - -Customizing your application name -================================================================================ - -To customize your application name, edit AndroidManifest.xml and replace -"org.libsdl.app" with an identifier for your product package. - -Then create a Java class extending SDLActivity and place it in a directory -under src matching your package, e.g. - - src/com/gamemaker/game/MyGame.java - -Here's an example of a minimal class file: - - --- MyGame.java -------------------------- - package com.gamemaker.game; - - import org.libsdl.app.SDLActivity; - - /** - * A sample wrapper class that just calls SDLActivity - */ - - public class MyGame extends SDLActivity { } - - ------------------------------------------ - -Then replace "SDLActivity" in AndroidManifest.xml with the name of your -class, .e.g. "MyGame" - - -Customizing your application icon -================================================================================ - -Conceptually changing your icon is just replacing the "ic_launcher.png" files in -the drawable directories under the res directory. There are several directories -for different screen sizes. - - -Loading assets -================================================================================ - -Any files you put in the "app/src/main/assets" directory of your project -directory will get bundled into the application package and you can load -them using the standard functions in SDL_rwops.h. - -There are also a few Android specific functions that allow you to get other -useful paths for saving and loading data: -* SDL_AndroidGetInternalStoragePath() -* SDL_AndroidGetExternalStorageState() -* SDL_AndroidGetExternalStoragePath() - -See SDL_system.h for more details on these functions. - -The asset packaging system will, by default, compress certain file extensions. -SDL includes two asset file access mechanisms, the preferred one is the so -called "File Descriptor" method, which is faster and doesn't involve the Dalvik -GC, but given this method does not work on compressed assets, there is also the -"Input Stream" method, which is automatically used as a fall back by SDL. You -may want to keep this fact in mind when building your APK, specially when large -files are involved. -For more information on which extensions get compressed by default and how to -disable this behaviour, see for example: - -http://ponystyle.com/blog/2010/03/26/dealing-with-asset-compression-in-android-apps/ - - -Pause / Resume behaviour -================================================================================ - -If SDL_HINT_ANDROID_BLOCK_ON_PAUSE hint is set (the default), -the event loop will block itself when the app is paused (ie, when the user -returns to the main Android dashboard). Blocking is better in terms of battery -use, and it allows your app to spring back to life instantaneously after resume -(versus polling for a resume message). - -Upon resume, SDL will attempt to restore the GL context automatically. -In modern devices (Android 3.0 and up) this will most likely succeed and your -app can continue to operate as it was. - -However, there's a chance (on older hardware, or on systems under heavy load), -where the GL context can not be restored. In that case you have to listen for -a specific message (SDL_EVENT_RENDER_DEVICE_RESET) and restore your textures -manually or quit the app. - -You should not use the SDL renderer API while the app going in background: -- SDL_EVENT_WILL_ENTER_BACKGROUND: - after you read this message, GL context gets backed-up and you should not - use the SDL renderer API. - - When this event is received, you have to set the render target to NULL, if you're using it. - (eg call SDL_SetRenderTarget(renderer, NULL)) - -- SDL_EVENT_DID_ENTER_FOREGROUND: - GL context is restored, and the SDL renderer API is available (unless you - receive SDL_EVENT_RENDER_DEVICE_RESET). - -Activity lifecycle -================================================================================ - -You can control activity re-creation (eg. onCreate()) behaviour. This allows to keep -or re-initialize java and native static datas, see SDL_hints.h: -- SDL_HINT_ANDROID_ALLOW_RECREATE_ACTIVITY - -Mouse / Touch events -================================================================================ - -In some case, SDL generates synthetic mouse (resp. touch) events for touch -(resp. mouse) devices. -To enable/disable this behavior, see SDL_hints.h: -- SDL_HINT_TOUCH_MOUSE_EVENTS -- SDL_HINT_MOUSE_TOUCH_EVENTS - -Misc -================================================================================ - -For some device, it appears to works better setting explicitly GL attributes -before creating a window: - SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); - SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6); - SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); - -Threads and the Java VM -================================================================================ - -For a quick tour on how Linux native threads interoperate with the Java VM, take -a look here: https://developer.android.com/guide/practices/jni.html - -If you want to use threads in your SDL app, it's strongly recommended that you -do so by creating them using SDL functions. This way, the required attach/detach -handling is managed by SDL automagically. If you have threads created by other -means and they make calls to SDL functions, make sure that you call -Android_JNI_SetupThread() before doing anything else otherwise SDL will attach -your thread automatically anyway (when you make an SDL call), but it'll never -detach it. - - -If you ever want to use JNI in a native thread (created by "SDL_CreateThread()"), -it won't be able to find your java class and method because of the java class loader -which is different for native threads, than for java threads (eg your "main()"). - -the work-around is to find class/method, in you "main()" thread, and to use them -in your native thread. - -see: -https://developer.android.com/training/articles/perf-jni#faq:-why-didnt-findclass-find-my-class - -Using STL -================================================================================ - -You can use STL in your project by creating an Application.mk file in the jni -folder and adding the following line: - - APP_STL := c++_shared - -For more information go here: - https://developer.android.com/ndk/guides/cpp-support - - -Using the emulator -================================================================================ - -There are some good tips and tricks for getting the most out of the -emulator here: https://developer.android.com/tools/devices/emulator.html - -Especially useful is the info on setting up OpenGL ES 2.0 emulation. - -Notice that this software emulator is incredibly slow and needs a lot of disk space. -Using a real device works better. - - -Troubleshooting -================================================================================ - -You can see if adb can see any devices with the following command: - - adb devices - -You can see the output of log messages on the default device with: - - adb logcat - -You can push files to the device with: - - adb push local_file remote_path_and_file - -You can push files to the SD Card at /sdcard, for example: - - adb push moose.dat /sdcard/moose.dat - -You can see the files on the SD card with a shell command: - - adb shell ls /sdcard/ - -You can start a command shell on the default device with: - - adb shell - -You can remove the library files of your project (and not the SDL lib files) with: - - ndk-build clean - -You can do a build with the following command: - - ndk-build - -You can see the complete command line that ndk-build is using by passing V=1 on the command line: - - ndk-build V=1 - -If your application crashes in native code, you can use ndk-stack to get a symbolic stack trace: - https://developer.android.com/ndk/guides/ndk-stack - -If you want to go through the process manually, you can use addr2line to convert the -addresses in the stack trace to lines in your code. - -For example, if your crash looks like this: - - I/DEBUG ( 31): signal 11 (SIGSEGV), code 2 (SEGV_ACCERR), fault addr 400085d0 - I/DEBUG ( 31): r0 00000000 r1 00001000 r2 00000003 r3 400085d4 - I/DEBUG ( 31): r4 400085d0 r5 40008000 r6 afd41504 r7 436c6a7c - I/DEBUG ( 31): r8 436c6b30 r9 435c6fb0 10 435c6f9c fp 4168d82c - I/DEBUG ( 31): ip 8346aff0 sp 436c6a60 lr afd1c8ff pc afd1c902 cpsr 60000030 - I/DEBUG ( 31): #00 pc 0001c902 /system/lib/libc.so - I/DEBUG ( 31): #01 pc 0001ccf6 /system/lib/libc.so - I/DEBUG ( 31): #02 pc 000014bc /data/data/org.libsdl.app/lib/libmain.so - I/DEBUG ( 31): #03 pc 00001506 /data/data/org.libsdl.app/lib/libmain.so - -You can see that there's a crash in the C library being called from the main code. -I run addr2line with the debug version of my code: - - arm-eabi-addr2line -C -f -e obj/local/armeabi/libmain.so - -and then paste in the number after "pc" in the call stack, from the line that I care about: -000014bc - -I get output from addr2line showing that it's in the quit function, in testspriteminimal.c, on line 23. - -You can add logging to your code to help show what's happening: - - #include - - __android_log_print(ANDROID_LOG_INFO, "foo", "Something happened! x = %d", x); - -If you need to build without optimization turned on, you can create a file called -"Application.mk" in the jni directory, with the following line in it: - - APP_OPTIM := debug - - -Memory debugging -================================================================================ - -The best (and slowest) way to debug memory issues on Android is valgrind. -Valgrind has support for Android out of the box, just grab code using: - - svn co svn://svn.valgrind.org/valgrind/trunk valgrind - -... and follow the instructions in the file README.android to build it. - -One thing I needed to do on macOS was change the path to the toolchain, -and add ranlib to the environment variables: -export RANLIB=$NDKROOT/toolchains/arm-linux-androideabi-4.4.3/prebuilt/darwin-x86/bin/arm-linux-androideabi-ranlib - -Once valgrind is built, you can create a wrapper script to launch your -application with it, changing org.libsdl.app to your package identifier: - - --- start_valgrind_app ------------------- - #!/system/bin/sh - export TMPDIR=/data/data/org.libsdl.app - exec /data/local/Inst/bin/valgrind --log-file=/sdcard/valgrind.log --error-limit=no $* - ------------------------------------------ - -Then push it to the device: - - adb push start_valgrind_app /data/local - -and make it executable: - - adb shell chmod 755 /data/local/start_valgrind_app - -and tell Android to use the script to launch your application: - - adb shell setprop wrap.org.libsdl.app "logwrapper /data/local/start_valgrind_app" - -If the setprop command says "could not set property", it's likely that -your package name is too long and you should make it shorter by changing -AndroidManifest.xml and the path to your class file in android-project/src - -You can then launch your application normally and waaaaaaaiiittt for it. -You can monitor the startup process with the logcat command above, and -when it's done (or even while it's running) you can grab the valgrind -output file: - - adb pull /sdcard/valgrind.log - -When you're done instrumenting with valgrind, you can disable the wrapper: - - adb shell setprop wrap.org.libsdl.app "" - - -Graphics debugging -================================================================================ - -If you are developing on a compatible Tegra-based tablet, NVidia provides -Tegra Graphics Debugger at their website. Because SDL3 dynamically loads EGL -and GLES libraries, you must follow their instructions for installing the -interposer library on a rooted device. The non-rooted instructions are not -compatible with applications that use SDL3 for video. - -The Tegra Graphics Debugger is available from NVidia here: -https://developer.nvidia.com/tegra-graphics-debugger - - -Why is API level 19 the minimum required? -================================================================================ - -The latest NDK toolchain doesn't support targeting earlier than API level 19. -As of this writing, according to https://www.composables.com/tools/distribution-chart -about 99.7% of the Android devices accessing Google Play support API level 19 or -higher (August 2023). - - -A note regarding the use of the "dirty rectangles" rendering technique -================================================================================ - -If your app uses a variation of the "dirty rectangles" rendering technique, -where you only update a portion of the screen on each frame, you may notice a -variety of visual glitches on Android, that are not present on other platforms. -This is caused by SDL's use of EGL as the support system to handle OpenGL ES/ES2 -contexts, in particular the use of the eglSwapBuffers function. As stated in the -documentation for the function "The contents of ancillary buffers are always -undefined after calling eglSwapBuffers". -Setting the EGL_SWAP_BEHAVIOR attribute of the surface to EGL_BUFFER_PRESERVED -is not possible for SDL as it requires EGL 1.4, available only on the API level -17+, so the only workaround available on this platform is to redraw the entire -screen each frame. - -Reference: http://www.khronos.org/registry/egl/specs/EGLTechNote0001.html - - -Ending your application -================================================================================ - -Two legitimate ways: - -- return from your main() function. Java side will automatically terminate the -Activity by calling Activity.finish(). - -- Android OS can decide to terminate your application by calling onDestroy() -(see Activity life cycle). Your application will receive an SDL_EVENT_QUIT you -can handle to save things and quit. - -Don't call exit() as it stops the activity badly. - -NB: "Back button" can be handled as a SDL_EVENT_KEY_DOWN/UP events, with Keycode -SDLK_AC_BACK, for any purpose. - -Known issues -================================================================================ - -- The number of buttons reported for each joystick is hardcoded to be 36, which -is the current maximum number of buttons Android can report. - -Building the SDL tests -================================================================================ - -SDL's CMake build system can create APK's for the tests. -It can build all tests with a single command without a dependency on gradle or Android Studio. -The APK's are signed with a debug certificate. -The only caveat is that the APK's support a single architecture. - -### Requirements -- SDL source tree -- CMake -- ninja or make -- Android Platform SDK -- Android NDK -- Android Build tools -- Java JDK (version should be compatible with Android) -- keytool (usually provided with the Java JDK), used for generating a debug certificate -- zip - -### CMake configuration - -When configuring the CMake project, you need to use the Android NDK CMake toolchain, and pass the Android home path through `SDL_ANDROID_HOME`. -``` -cmake .. -DCMAKE_TOOLCHAIN_FILE= -DANDROID_ABI= -DSDL_ANDROID_HOME= -DANDROID_PLATFORM=23 -DSDL_TESTS=ON -``` - -Remarks: -- `android.toolchain.cmake` can usually be found at `$ANDROID_HOME/ndk/x.y.z/build/cmake/android.toolchain.cmake` -- `ANDROID_ABI` should be one of `arm64-v8a`, `armeabi-v7a`, `x86` or `x86_64`. -- When CMake is unable to find required paths, use `cmake-gui` to override required `SDL_ANDROID_` CMake cache variables. - -### Building the APK's - -For the `testsprite` executable, the `testsprite-apk` target will build the associated APK: -``` -cmake --build . --target testsprite-apk -``` - -APK's of all tests can be built with the `sdl-test-apks` target: -``` -cmake --build . --target sdl-test-apks -``` - -### Installation/removal of the tests - -`testsprite.apk` APK can be installed on your Android machine using the `install-testsprite` target: -``` -cmake --build . --target install-testsprite -``` - -APK's of all tests can be installed with the `install-sdl-test-apks` target: -``` -cmake --build . --target install-sdl-test-apks -``` - -All SDL tests can be uninstalled with the `uninstall-sdl-test-apks` target: -``` -cmake --build . --target uninstall-sdl-test-apks -``` - -### Starting the tests - -After installation, the tests can be started using the Android Launcher GUI. -Alternatively, they can also be started using CMake targets. - -This command will start the testsprite executable: -``` -cmake --build . --target start-testsprite -``` - -There is also a convenience target which will build, install and start a test: -``` -cmake --build . --target build-install-start-testsprite -``` - -Not all tests provide a GUI. For those, you can use `adb logcat` to read the output of stdout. +Android +================================================================================ + +Matt Styles wrote a tutorial on building SDL for Android with Visual Studio: +http://trederia.blogspot.de/2017/03/building-sdl2-for-android-with-visual.html + +The rest of this README covers the Android gradle style build process. + + +Requirements +================================================================================ + +Android SDK (version 34 or later) +https://developer.android.com/sdk/index.html + +Android NDK r15c or later +https://developer.android.com/tools/sdk/ndk/index.html + +Minimum API level supported by SDL: 19 (Android 4.4) + + +How the port works +================================================================================ + +- Android applications are Java-based, optionally with parts written in C +- As SDL apps are C-based, we use a small Java shim that uses JNI to talk to + the SDL library +- This means that your application C code must be placed inside an Android + Java project, along with some C support code that communicates with Java +- This eventually produces a standard Android .apk package + +The Android Java code implements an "Activity" and can be found in: +android-project/app/src/main/java/org/libsdl/app/SDLActivity.java + +The Java code loads your game code, the SDL shared library, and +dispatches to native functions implemented in the SDL library: +src/core/android/SDL_android.c + + +Building an app +================================================================================ + +For simple projects you can use the script located at build-scripts/androidbuild.sh + +There's two ways of using it: + + androidbuild.sh com.yourcompany.yourapp < sources.list + androidbuild.sh com.yourcompany.yourapp source1.c source2.c ...sourceN.c + +sources.list should be a text file with a source file name in each line +Filenames should be specified relative to the current directory, for example if +you are in the build-scripts directory and want to create the testgles.c test, you'll +run: + + ./androidbuild.sh org.libsdl.testgles ../test/testgles.c + +One limitation of this script is that all sources provided will be aggregated into +a single directory, thus all your source files should have a unique name. + +Once the project is complete the script will tell you where the debug APK is located. +If you want to create a signed release APK, you can use the project created by this +utility to generate it. + +Finally, a word of caution: re running androidbuild.sh wipes any changes you may have +done in the build directory for the app! + + + +For more complex projects, follow these instructions: + +1. Get the source code for SDL and copy the 'android-project' directory located at SDL/android-project to a suitable location. Also make sure to rename it to your project name (In these examples: YOURPROJECT). + + (The 'android-project' directory can basically be seen as a sort of starting point for the android-port of your project. It contains the glue code between the Android Java 'frontend' and the SDL code 'backend'. It also contains some standard behaviour, like how events should be handled, which you will be able to change.) + +2. Move or [symlink](https://en.wikipedia.org/wiki/Symbolic_link) the SDL directory into the "YOURPROJECT/app/jni" directory + +(This is needed as the source of SDL has to be compiled by the Android compiler) + +3. Edit "YOURPROJECT/app/jni/src/Android.mk" to include your source files. + +(They should be separated by spaces after the "LOCAL_SRC_FILES := " declaration) + +4a. If you want to use Android Studio, simply open your 'YOURPROJECT' directory and start building. + +4b. If you want to build manually, run './gradlew installDebug' in the project directory. This compiles the .java, creates an .apk with the native code embedded, and installs it on any connected Android device + + +If you already have a project that uses CMake, the instructions change somewhat: + +1. Do points 1 and 2 from the instruction above. +2. Edit "YOURPROJECT/app/build.gradle" to comment out or remove sections containing ndk-build + and uncomment the cmake sections. Add arguments to the CMake invocation as needed. +3. Edit "YOURPROJECT/app/jni/CMakeLists.txt" to include your project (it defaults to + adding the "src" subdirectory). Note that you'll have SDL3 and SDL3-static + as targets in your project, so you should have "target_link_libraries(yourgame SDL3)" + in your CMakeLists.txt file. Also be aware that you should use add_library() instead of + add_executable() for the target containing your "main" function. + +If you wish to use Android Studio, you can skip the last step. + +4. Run './gradlew installDebug' or './gradlew installRelease' in the project directory. It will build and install your .apk on any + connected Android device + +Here's an explanation of the files in the Android project, so you can customize them: + + android-project/app + build.gradle - build info including the application version and SDK + src/main/AndroidManifest.xml - package manifest. Among others, it contains the class name of the main Activity and the package name of the application. + jni/ - directory holding native code + jni/Application.mk - Application JNI settings, including target platform and STL library + jni/Android.mk - Android makefile that can call recursively the Android.mk files in all subdirectories + jni/CMakeLists.txt - Top-level CMake project that adds SDL as a subproject + jni/SDL/ - (symlink to) directory holding the SDL library files + jni/SDL/Android.mk - Android makefile for creating the SDL shared library + jni/src/ - directory holding your C/C++ source + jni/src/Android.mk - Android makefile that you should customize to include your source code and any library references + jni/src/CMakeLists.txt - CMake file that you may customize to include your source code and any library references + src/main/assets/ - directory holding asset files for your application + src/main/res/ - directory holding resources for your application + src/main/res/mipmap-* - directories holding icons for different phone hardware + src/main/res/values/strings.xml - strings used in your application, including the application name + src/main/java/org/libsdl/app/SDLActivity.java - the Java class handling the initialization and binding to SDL. Be very careful changing this, as the SDL library relies on this implementation. You should instead subclass this for your application. + + +Customizing your application name +================================================================================ + +To customize your application name, edit AndroidManifest.xml and replace +"org.libsdl.app" with an identifier for your product package. + +Then create a Java class extending SDLActivity and place it in a directory +under src matching your package, e.g. + + src/com/gamemaker/game/MyGame.java + +Here's an example of a minimal class file: + + --- MyGame.java -------------------------- + package com.gamemaker.game; + + import org.libsdl.app.SDLActivity; + + /** + * A sample wrapper class that just calls SDLActivity + */ + + public class MyGame extends SDLActivity { } + + ------------------------------------------ + +Then replace "SDLActivity" in AndroidManifest.xml with the name of your +class, .e.g. "MyGame" + + +Customizing your application icon +================================================================================ + +Conceptually changing your icon is just replacing the "ic_launcher.png" files in +the drawable directories under the res directory. There are several directories +for different screen sizes. + + +Loading assets +================================================================================ + +Any files you put in the "app/src/main/assets" directory of your project +directory will get bundled into the application package and you can load +them using the standard functions in SDL_rwops.h. + +There are also a few Android specific functions that allow you to get other +useful paths for saving and loading data: +* SDL_AndroidGetInternalStoragePath() +* SDL_AndroidGetExternalStorageState() +* SDL_AndroidGetExternalStoragePath() + +See SDL_system.h for more details on these functions. + +The asset packaging system will, by default, compress certain file extensions. +SDL includes two asset file access mechanisms, the preferred one is the so +called "File Descriptor" method, which is faster and doesn't involve the Dalvik +GC, but given this method does not work on compressed assets, there is also the +"Input Stream" method, which is automatically used as a fall back by SDL. You +may want to keep this fact in mind when building your APK, specially when large +files are involved. +For more information on which extensions get compressed by default and how to +disable this behaviour, see for example: + +http://ponystyle.com/blog/2010/03/26/dealing-with-asset-compression-in-android-apps/ + + +Pause / Resume behaviour +================================================================================ + +If SDL_HINT_ANDROID_BLOCK_ON_PAUSE hint is set (the default), +the event loop will block itself when the app is paused (ie, when the user +returns to the main Android dashboard). Blocking is better in terms of battery +use, and it allows your app to spring back to life instantaneously after resume +(versus polling for a resume message). + +Upon resume, SDL will attempt to restore the GL context automatically. +In modern devices (Android 3.0 and up) this will most likely succeed and your +app can continue to operate as it was. + +However, there's a chance (on older hardware, or on systems under heavy load), +where the GL context can not be restored. In that case you have to listen for +a specific message (SDL_EVENT_RENDER_DEVICE_RESET) and restore your textures +manually or quit the app. + +You should not use the SDL renderer API while the app going in background: +- SDL_EVENT_WILL_ENTER_BACKGROUND: + after you read this message, GL context gets backed-up and you should not + use the SDL renderer API. + + When this event is received, you have to set the render target to NULL, if you're using it. + (eg call SDL_SetRenderTarget(renderer, NULL)) + +- SDL_EVENT_DID_ENTER_FOREGROUND: + GL context is restored, and the SDL renderer API is available (unless you + receive SDL_EVENT_RENDER_DEVICE_RESET). + +Activity lifecycle +================================================================================ + +You can control activity re-creation (eg. onCreate()) behaviour. This allows to keep +or re-initialize java and native static datas, see SDL_hints.h: +- SDL_HINT_ANDROID_ALLOW_RECREATE_ACTIVITY + +Mouse / Touch events +================================================================================ + +In some case, SDL generates synthetic mouse (resp. touch) events for touch +(resp. mouse) devices. +To enable/disable this behavior, see SDL_hints.h: +- SDL_HINT_TOUCH_MOUSE_EVENTS +- SDL_HINT_MOUSE_TOUCH_EVENTS + +Misc +================================================================================ + +For some device, it appears to works better setting explicitly GL attributes +before creating a window: + SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); + SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6); + SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); + +Threads and the Java VM +================================================================================ + +For a quick tour on how Linux native threads interoperate with the Java VM, take +a look here: https://developer.android.com/guide/practices/jni.html + +If you want to use threads in your SDL app, it's strongly recommended that you +do so by creating them using SDL functions. This way, the required attach/detach +handling is managed by SDL automagically. If you have threads created by other +means and they make calls to SDL functions, make sure that you call +Android_JNI_SetupThread() before doing anything else otherwise SDL will attach +your thread automatically anyway (when you make an SDL call), but it'll never +detach it. + + +If you ever want to use JNI in a native thread (created by "SDL_CreateThread()"), +it won't be able to find your java class and method because of the java class loader +which is different for native threads, than for java threads (eg your "main()"). + +the work-around is to find class/method, in you "main()" thread, and to use them +in your native thread. + +see: +https://developer.android.com/training/articles/perf-jni#faq:-why-didnt-findclass-find-my-class + +Using STL +================================================================================ + +You can use STL in your project by creating an Application.mk file in the jni +folder and adding the following line: + + APP_STL := c++_shared + +For more information go here: + https://developer.android.com/ndk/guides/cpp-support + + +Using the emulator +================================================================================ + +There are some good tips and tricks for getting the most out of the +emulator here: https://developer.android.com/tools/devices/emulator.html + +Especially useful is the info on setting up OpenGL ES 2.0 emulation. + +Notice that this software emulator is incredibly slow and needs a lot of disk space. +Using a real device works better. + + +Troubleshooting +================================================================================ + +You can see if adb can see any devices with the following command: + + adb devices + +You can see the output of log messages on the default device with: + + adb logcat + +You can push files to the device with: + + adb push local_file remote_path_and_file + +You can push files to the SD Card at /sdcard, for example: + + adb push moose.dat /sdcard/moose.dat + +You can see the files on the SD card with a shell command: + + adb shell ls /sdcard/ + +You can start a command shell on the default device with: + + adb shell + +You can remove the library files of your project (and not the SDL lib files) with: + + ndk-build clean + +You can do a build with the following command: + + ndk-build + +You can see the complete command line that ndk-build is using by passing V=1 on the command line: + + ndk-build V=1 + +If your application crashes in native code, you can use ndk-stack to get a symbolic stack trace: + https://developer.android.com/ndk/guides/ndk-stack + +If you want to go through the process manually, you can use addr2line to convert the +addresses in the stack trace to lines in your code. + +For example, if your crash looks like this: + + I/DEBUG ( 31): signal 11 (SIGSEGV), code 2 (SEGV_ACCERR), fault addr 400085d0 + I/DEBUG ( 31): r0 00000000 r1 00001000 r2 00000003 r3 400085d4 + I/DEBUG ( 31): r4 400085d0 r5 40008000 r6 afd41504 r7 436c6a7c + I/DEBUG ( 31): r8 436c6b30 r9 435c6fb0 10 435c6f9c fp 4168d82c + I/DEBUG ( 31): ip 8346aff0 sp 436c6a60 lr afd1c8ff pc afd1c902 cpsr 60000030 + I/DEBUG ( 31): #00 pc 0001c902 /system/lib/libc.so + I/DEBUG ( 31): #01 pc 0001ccf6 /system/lib/libc.so + I/DEBUG ( 31): #02 pc 000014bc /data/data/org.libsdl.app/lib/libmain.so + I/DEBUG ( 31): #03 pc 00001506 /data/data/org.libsdl.app/lib/libmain.so + +You can see that there's a crash in the C library being called from the main code. +I run addr2line with the debug version of my code: + + arm-eabi-addr2line -C -f -e obj/local/armeabi/libmain.so + +and then paste in the number after "pc" in the call stack, from the line that I care about: +000014bc + +I get output from addr2line showing that it's in the quit function, in testspriteminimal.c, on line 23. + +You can add logging to your code to help show what's happening: + + #include + + __android_log_print(ANDROID_LOG_INFO, "foo", "Something happened! x = %d", x); + +If you need to build without optimization turned on, you can create a file called +"Application.mk" in the jni directory, with the following line in it: + + APP_OPTIM := debug + + +Memory debugging +================================================================================ + +The best (and slowest) way to debug memory issues on Android is valgrind. +Valgrind has support for Android out of the box, just grab code using: + + svn co svn://svn.valgrind.org/valgrind/trunk valgrind + +... and follow the instructions in the file README.android to build it. + +One thing I needed to do on macOS was change the path to the toolchain, +and add ranlib to the environment variables: +export RANLIB=$NDKROOT/toolchains/arm-linux-androideabi-4.4.3/prebuilt/darwin-x86/bin/arm-linux-androideabi-ranlib + +Once valgrind is built, you can create a wrapper script to launch your +application with it, changing org.libsdl.app to your package identifier: + + --- start_valgrind_app ------------------- + #!/system/bin/sh + export TMPDIR=/data/data/org.libsdl.app + exec /data/local/Inst/bin/valgrind --log-file=/sdcard/valgrind.log --error-limit=no $* + ------------------------------------------ + +Then push it to the device: + + adb push start_valgrind_app /data/local + +and make it executable: + + adb shell chmod 755 /data/local/start_valgrind_app + +and tell Android to use the script to launch your application: + + adb shell setprop wrap.org.libsdl.app "logwrapper /data/local/start_valgrind_app" + +If the setprop command says "could not set property", it's likely that +your package name is too long and you should make it shorter by changing +AndroidManifest.xml and the path to your class file in android-project/src + +You can then launch your application normally and waaaaaaaiiittt for it. +You can monitor the startup process with the logcat command above, and +when it's done (or even while it's running) you can grab the valgrind +output file: + + adb pull /sdcard/valgrind.log + +When you're done instrumenting with valgrind, you can disable the wrapper: + + adb shell setprop wrap.org.libsdl.app "" + + +Graphics debugging +================================================================================ + +If you are developing on a compatible Tegra-based tablet, NVidia provides +Tegra Graphics Debugger at their website. Because SDL3 dynamically loads EGL +and GLES libraries, you must follow their instructions for installing the +interposer library on a rooted device. The non-rooted instructions are not +compatible with applications that use SDL3 for video. + +The Tegra Graphics Debugger is available from NVidia here: +https://developer.nvidia.com/tegra-graphics-debugger + + +Why is API level 19 the minimum required? +================================================================================ + +The latest NDK toolchain doesn't support targeting earlier than API level 19. +As of this writing, according to https://www.composables.com/tools/distribution-chart +about 99.7% of the Android devices accessing Google Play support API level 19 or +higher (August 2023). + + +A note regarding the use of the "dirty rectangles" rendering technique +================================================================================ + +If your app uses a variation of the "dirty rectangles" rendering technique, +where you only update a portion of the screen on each frame, you may notice a +variety of visual glitches on Android, that are not present on other platforms. +This is caused by SDL's use of EGL as the support system to handle OpenGL ES/ES2 +contexts, in particular the use of the eglSwapBuffers function. As stated in the +documentation for the function "The contents of ancillary buffers are always +undefined after calling eglSwapBuffers". +Setting the EGL_SWAP_BEHAVIOR attribute of the surface to EGL_BUFFER_PRESERVED +is not possible for SDL as it requires EGL 1.4, available only on the API level +17+, so the only workaround available on this platform is to redraw the entire +screen each frame. + +Reference: http://www.khronos.org/registry/egl/specs/EGLTechNote0001.html + + +Ending your application +================================================================================ + +Two legitimate ways: + +- return from your main() function. Java side will automatically terminate the +Activity by calling Activity.finish(). + +- Android OS can decide to terminate your application by calling onDestroy() +(see Activity life cycle). Your application will receive an SDL_EVENT_QUIT you +can handle to save things and quit. + +Don't call exit() as it stops the activity badly. + +NB: "Back button" can be handled as a SDL_EVENT_KEY_DOWN/UP events, with Keycode +SDLK_AC_BACK, for any purpose. + +Known issues +================================================================================ + +- The number of buttons reported for each joystick is hardcoded to be 36, which +is the current maximum number of buttons Android can report. + +Building the SDL tests +================================================================================ + +SDL's CMake build system can create APK's for the tests. +It can build all tests with a single command without a dependency on gradle or Android Studio. +The APK's are signed with a debug certificate. +The only caveat is that the APK's support a single architecture. + +### Requirements +- SDL source tree +- CMake +- ninja or make +- Android Platform SDK +- Android NDK +- Android Build tools +- Java JDK (version should be compatible with Android) +- keytool (usually provided with the Java JDK), used for generating a debug certificate +- zip + +### CMake configuration + +When configuring the CMake project, you need to use the Android NDK CMake toolchain, and pass the Android home path through `SDL_ANDROID_HOME`. +``` +cmake .. -DCMAKE_TOOLCHAIN_FILE= -DANDROID_ABI= -DSDL_ANDROID_HOME= -DANDROID_PLATFORM=23 -DSDL_TESTS=ON +``` + +Remarks: +- `android.toolchain.cmake` can usually be found at `$ANDROID_HOME/ndk/x.y.z/build/cmake/android.toolchain.cmake` +- `ANDROID_ABI` should be one of `arm64-v8a`, `armeabi-v7a`, `x86` or `x86_64`. +- When CMake is unable to find required paths, use `cmake-gui` to override required `SDL_ANDROID_` CMake cache variables. + +### Building the APK's + +For the `testsprite` executable, the `testsprite-apk` target will build the associated APK: +``` +cmake --build . --target testsprite-apk +``` + +APK's of all tests can be built with the `sdl-test-apks` target: +``` +cmake --build . --target sdl-test-apks +``` + +### Installation/removal of the tests + +`testsprite.apk` APK can be installed on your Android machine using the `install-testsprite` target: +``` +cmake --build . --target install-testsprite +``` + +APK's of all tests can be installed with the `install-sdl-test-apks` target: +``` +cmake --build . --target install-sdl-test-apks +``` + +All SDL tests can be uninstalled with the `uninstall-sdl-test-apks` target: +``` +cmake --build . --target uninstall-sdl-test-apks +``` + +### Starting the tests + +After installation, the tests can be started using the Android Launcher GUI. +Alternatively, they can also be started using CMake targets. + +This command will start the testsprite executable: +``` +cmake --build . --target start-testsprite +``` + +There is also a convenience target which will build, install and start a test: +``` +cmake --build . --target build-install-start-testsprite +``` + +Not all tests provide a GUI. For those, you can use `adb logcat` to read the output of stdout. diff --git a/docs/README-cmake.md b/docs/README-cmake.md index 4accbcf58..337a41ab0 100644 --- a/docs/README-cmake.md +++ b/docs/README-cmake.md @@ -1,328 +1,328 @@ -# CMake - -[www.cmake.org](https://www.cmake.org/) - -The CMake build system is supported on the following platforms: - -* FreeBSD -* Linux -* Microsoft Visual C -* MinGW and Msys -* macOS, iOS, and tvOS, with support for XCode -* Android -* Emscripten -* FreeBSD -* Haiku -* Nintendo 3DS -* Playstation 2 -* Playstation Vita -* QNX 7.x/8.x -* RiscOS - -## Building SDL - -Assuming the source tree of SDL is located at `~/sdl`, -this will configure and build SDL in the `~/build` directory: -```sh -cmake -S ~/sdl -B ~/build -cmake --build ~/build -``` - -Installation can be done using: -```sh -cmake --install ~/build --prefix /usr/local # '--install' requires CMake 3.15, or newer -``` - -This will install SDL to /usr/local. - -### Building SDL tests - -You can build the SDL test programs by adding `-DSDL_TESTS=ON` to the first cmake command above: -```sh -cmake -S ~/sdl -B ~/build -DSDL_TEST_LIBRARY=ON -DSDL_TESTS=ON -``` -and then building normally. In this example, the test programs will be built and can be run from `~/build/tests/`. - -## Including SDL in your project - -SDL can be included in your project in 2 major ways: -- using a system SDL library, provided by your (*nix) distribution or a package manager -- using a vendored SDL library: this is SDL copied or symlinked in a subfolder. - -The following CMake script supports both, depending on the value of `MYGAME_VENDORED`. - -```cmake -cmake_minimum_required(VERSION 3.5) -project(mygame) - -# Create an option to switch between a system sdl library and a vendored SDL library -option(MYGAME_VENDORED "Use vendored libraries" OFF) - -if(MYGAME_VENDORED) - # This assumes you have added SDL as a submodule in vendored/SDL - add_subdirectory(vendored/SDL EXCLUDE_FROM_ALL) -else() - # 1. Look for a SDL3 package, - # 2. look for the SDL3-shared component, and - # 3. fail if the shared component cannot be found. - find_package(SDL3 REQUIRED CONFIG REQUIRED COMPONENTS SDL3-shared) -endif() - -# Create your game executable target as usual -add_executable(mygame WIN32 mygame.c) - -# Link to the actual SDL3 library. -target_link_libraries(mygame PRIVATE SDL3::SDL3) -``` - -### A system SDL library - -For CMake to find SDL, it must be installed in [a default location CMake is looking for](https://cmake.org/cmake/help/latest/command/find_package.html#config-mode-search-procedure). - -The following components are available, to be used as an argument of `find_package`. - -| Component name | Description | -|----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| SDL3-shared | The SDL3 shared library, available through the `SDL3::SDL3-shared` target | -| SDL3-static | The SDL3 static library, available through the `SDL3::SDL3-static` target | -| SDL3_test | The SDL3_test static library, available through the `SDL3::SDL3_test` target | -| SDL3 | The SDL3 library, available through the `SDL3::SDL3` target. This is an alias of `SDL3::SDL3-shared` or `SDL3::SDL3-static`. This component is always available. | -| Headers | The SDL3 headers, available through the `SDL3::Headers` target. This component is always available. | - - -### Using a vendored SDL - -This only requires a copy of SDL in a subdirectory + `add_subdirectory`. -Alternatively, use [FetchContent](https://cmake.org/cmake/help/latest/module/FetchContent.html). -Depending on the configuration, the same targets as a system SDL package are available. - -## CMake configuration options - -### Build optimized library - -By default, CMake provides 4 build types: `Debug`, `Release`, `RelWithDebInfo` and `MinSizeRel`. -The main difference(s) between these are the optimization options and the generation of debug info. -To configure SDL as an optimized `Release` library, configure SDL with: -```sh -cmake ~/SDL -DCMAKE_BUILD_TYPE=Release -``` -To build it, run: -```sh -cmake --build . --config Release -``` - -### Shared or static - -By default, only a shared SDL library is built and installed. -The options `-DSDL_SHARED=` and `-DSDL_STATIC=` accept boolean values to change this. - -### Pass custom compile options to the compiler - -- Use [`CMAKE__FLAGS`](https://cmake.org/cmake/help/latest/variable/CMAKE_LANG_FLAGS.html) to pass extra -flags to the compiler. -- Use [`CMAKE_EXE_LINKER_FLAGS`](https://cmake.org/cmake/help/latest/variable/CMAKE_EXE_LINKER_FLAGS.html) to pass extra option to the linker for executables. -- Use [`CMAKE_SHARED_LINKER_FLAGS`](https://cmake.org/cmake/help/latest/variable/CMAKE_SHARED_LINKER_FLAGS.html) to pass extra options to the linker for shared libraries. - -#### Examples - -- build a SDL library optimized for (more) modern x64 microprocessor architectures. - - With gcc or clang: - ```sh - cmake ~/sdl -DCMAKE_C_FLAGS="-march=x86-64-v3" -DCMAKE_CXX_FLAGS="-march=x86-64-v3" - ``` - With Visual C: - ```sh - cmake .. -DCMAKE_C_FLAGS="/ARCH:AVX2" -DCMAKE_CXX_FLAGS="/ARCH:AVX2" - ``` - -### iOS/tvOS - -CMake 3.14+ natively includes support for iOS and tvOS. SDL binaries may be built -using Xcode or Make, possibly among other build-systems. - -When using a recent version of CMake (3.14+), it should be possible to: - -- build SDL for iOS, both static and dynamic -- build SDL test apps (as iOS/tvOS .app bundles) -- generate a working SDL_build_config.h for iOS (using SDL_build_config.h.cmake as a basis) - -To use, set the following CMake variables when running CMake's configuration stage: - -- `CMAKE_SYSTEM_NAME=` (either `iOS` or `tvOS`) -- `CMAKE_OSX_SYSROOT=` (examples: `iphoneos`, `iphonesimulator`, `iphoneos12.4`, `/full/path/to/iPhoneOS.sdk`, - `appletvos`, `appletvsimulator`, `appletvos12.4`, `/full/path/to/AppleTVOS.sdk`, etc.) -- `CMAKE_OSX_ARCHITECTURES=` (example: "arm64;armv7s;x86_64") - - -#### Examples - -- for iOS-Simulator, using the latest, installed SDK: - - ```bash - cmake ~/sdl -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_SYSROOT=iphonesimulator -DCMAKE_OSX_ARCHITECTURES=x86_64 - ``` - -- for iOS-Device, using the latest, installed SDK, 64-bit only - - ```bash - cmake ~/sdl -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_SYSROOT=iphoneos -DCMAKE_OSX_ARCHITECTURES=arm64 - ``` - -- for iOS-Device, using the latest, installed SDK, mixed 32/64 bit - - ```cmake - cmake ~/sdl -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_SYSROOT=iphoneos -DCMAKE_OSX_ARCHITECTURES="arm64;armv7s" - ``` - -- for iOS-Device, using a specific SDK revision (iOS 12.4, in this example): - - ```cmake - cmake ~/sdl -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_SYSROOT=iphoneos12.4 -DCMAKE_OSX_ARCHITECTURES=arm64 - ``` - -- for iOS-Simulator, using the latest, installed SDK, and building SDL test apps (as .app bundles): - - ```cmake - cmake ~/sdl -DSDL_TESTS=1 -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_SYSROOT=iphonesimulator -DCMAKE_OSX_ARCHITECTURES=x86_64 - ``` - -- for tvOS-Simulator, using the latest, installed SDK: - - ```cmake - cmake ~/sdl -DCMAKE_SYSTEM_NAME=tvOS -DCMAKE_OSX_SYSROOT=appletvsimulator -DCMAKE_OSX_ARCHITECTURES=x86_64 - ``` - -- for tvOS-Device, using the latest, installed SDK: - - ```cmake - cmake ~/sdl -DCMAKE_SYSTEM_NAME=tvOS -DCMAKE_OSX_SYSROOT=appletvos -DCMAKE_OSX_ARCHITECTURES=arm64` - ``` - -- for QNX/aarch64, using the latest, installed SDK: - - ```cmake - cmake ~/sdl -DCMAKE_TOOLCHAIN_FILE=~/sdl/build-scripts/cmake-toolchain-qnx-aarch64le.cmake -DSDL_X11=0 - ``` - -## SDL-specific CMake options - -SDL can be customized through (platform-specific) CMake options. -The following table shows generic options that are available for most platforms. -At the end of SDL CMake configuration, a table shows all CMake options along with its detected value. - -| CMake option | Valid values | Description | -|-------------------------------|--------------|-----------------------------------------------------------------------------------------------------| -| `-DSDL_SHARED=` | `ON`/`OFF` | Build SDL shared library (not all platforms support this) (`libSDL3.so`/`libSDL3.dylib`/`SDL3.dll`) | -| `-DSDL_STATIC=` | `ON`/`OFF` | Build SDL static library (`libSDL3.a`/`SDL3-static.lib`) | -| `-DSDL_TEST_LIBRARY=` | `ON`/`OFF` | Build SDL test library (`libSDL3_test.a`/`SDL3_test.lib`) | -| `-DSDL_TESTS=` | `ON`/`OFF` | Build SDL test programs (**requires `-DSDL_TEST_LIBRARY=ON`**) | -| `-DSDL_DISABLE_INSTALL=` | `ON`/`OFF` | Don't create a SDL install target | -| `-DSDL_DISABLE_INSTALL_DOCS=` | `ON`/`OFF` | Don't install the SDL documentation | -| `-DSDL_INSTALL_TESTS=` | `ON`/`OFF` | Install the SDL test programs | - -## Help, it doesn't work! - -Below, a SDL3 CMake project can be found that builds 99.9% of time (assuming you have internet connectivity). -When you have a problem with building or using SDL, please modify it until it reproduces your issue. - -```cmake -cmake_minimum_required(VERSION 3.16) -project(sdl_issue) - -# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -# !!!!!! !!!!!! -# !!!!!! This CMake script is not using "CMake best practices". !!!!!! -# !!!!!! Don't use it in your project. !!!!!! -# !!!!!! !!!!!! -# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - -# 1. Try system SDL3 package first -find_package(SDL3 QUIET) -if(SDL3_FOUND) - message(STATUS "Using SDL3 via find_package") -endif() - -# 2. Try using a vendored SDL library -if(NOT SDL3_FOUND AND EXISTS "${CMAKE_CURRENT_LIST_DIR}/SDL/CMakeLists.txt") - add_subdirectory(SDL) - message(STATUS "Using SDL3 via add_subdirectory") - set(SDL3_FOUND TRUE) -endif() - -# 3. Download SDL, and use that. -if(NOT SDL3_FOUND) - include(FetchContent) - set(SDL_SHARED TRUE CACHE BOOL "Build a SDL shared library (if available)") - set(SDL_STATIC TRUE CACHE BOOL "Build a SDL static library (if available)") - FetchContent_Declare( - SDL - GIT_REPOSITORY https://github.com/libsdl-org/SDL.git - GIT_TAG main # Replace this with a particular git tag or git hash - GIT_SHALLOW TRUE - GIT_PROGRESS TRUE - ) - message(STATUS "Using SDL3 via FetchContent") - FetchContent_MakeAvailable(SDL) - set_property(DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/_deps/sdl-src" PROPERTY EXCLUDE_FROM_ALL TRUE) -endif() - -file(WRITE main.c [===========================================[ -/** - * Modify this source such that it reproduces your problem. - */ - -/* START of source modifications */ - -#include - -int main(int argc, char *argv[]) { - if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { - SDL_Log("SDL_Init failed (%s)", SDL_GetError()); - return 1; - } - - SDL_Window *window = NULL; - SDL_Renderer *renderer = NULL; - - if (SDL_CreateWindowAndRenderer(640, 480, 0, &window, &renderer) < 0) { - SDL_Log("SDL_CreateWindowAndRenderer failed (%s)", SDL_GetError()); - SDL_Quit(); - return 1; - } - SDL_SetWindowTitle(window, "SDL issue"); - - while (1) { - int finished = 0; - SDL_Event event; - while (SDL_PollEvent(&event)) { - if (event.type == SDL_EVENT_QUIT) { - finished = 1; - break; - } - } - if (finished) { - break; - } - - SDL_SetRenderDrawColor(renderer, 80, 80, 80, SDL_ALPHA_OPAQUE); - SDL_RenderClear(renderer); - SDL_RenderPresent(renderer); - } - - SDL_DestroyRenderer(renderer); - SDL_DestroyWindow(window); - - SDL_Quit(); -} - -/* END of source modifications */ - -]===========================================]) - -add_executable(sdl_issue main.c) - -target_link_libraries(sdl_issue PRIVATE SDL3::SDL3) -# target_link_libraries(sdl_issue PRIVATE SDL3::SDL3-shared) -# target_link_libraries(sdl_issue PRIVATE SDL3::SDL3-static) -``` +# CMake + +[www.cmake.org](https://www.cmake.org/) + +The CMake build system is supported on the following platforms: + +* FreeBSD +* Linux +* Microsoft Visual C +* MinGW and Msys +* macOS, iOS, and tvOS, with support for XCode +* Android +* Emscripten +* FreeBSD +* Haiku +* Nintendo 3DS +* Playstation 2 +* Playstation Vita +* QNX 7.x/8.x +* RiscOS + +## Building SDL + +Assuming the source tree of SDL is located at `~/sdl`, +this will configure and build SDL in the `~/build` directory: +```sh +cmake -S ~/sdl -B ~/build +cmake --build ~/build +``` + +Installation can be done using: +```sh +cmake --install ~/build --prefix /usr/local # '--install' requires CMake 3.15, or newer +``` + +This will install SDL to /usr/local. + +### Building SDL tests + +You can build the SDL test programs by adding `-DSDL_TESTS=ON` to the first cmake command above: +```sh +cmake -S ~/sdl -B ~/build -DSDL_TEST_LIBRARY=ON -DSDL_TESTS=ON +``` +and then building normally. In this example, the test programs will be built and can be run from `~/build/tests/`. + +## Including SDL in your project + +SDL can be included in your project in 2 major ways: +- using a system SDL library, provided by your (*nix) distribution or a package manager +- using a vendored SDL library: this is SDL copied or symlinked in a subfolder. + +The following CMake script supports both, depending on the value of `MYGAME_VENDORED`. + +```cmake +cmake_minimum_required(VERSION 3.5) +project(mygame) + +# Create an option to switch between a system sdl library and a vendored SDL library +option(MYGAME_VENDORED "Use vendored libraries" OFF) + +if(MYGAME_VENDORED) + # This assumes you have added SDL as a submodule in vendored/SDL + add_subdirectory(vendored/SDL EXCLUDE_FROM_ALL) +else() + # 1. Look for a SDL3 package, + # 2. look for the SDL3-shared component, and + # 3. fail if the shared component cannot be found. + find_package(SDL3 REQUIRED CONFIG REQUIRED COMPONENTS SDL3-shared) +endif() + +# Create your game executable target as usual +add_executable(mygame WIN32 mygame.c) + +# Link to the actual SDL3 library. +target_link_libraries(mygame PRIVATE SDL3::SDL3) +``` + +### A system SDL library + +For CMake to find SDL, it must be installed in [a default location CMake is looking for](https://cmake.org/cmake/help/latest/command/find_package.html#config-mode-search-procedure). + +The following components are available, to be used as an argument of `find_package`. + +| Component name | Description | +|----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| SDL3-shared | The SDL3 shared library, available through the `SDL3::SDL3-shared` target | +| SDL3-static | The SDL3 static library, available through the `SDL3::SDL3-static` target | +| SDL3_test | The SDL3_test static library, available through the `SDL3::SDL3_test` target | +| SDL3 | The SDL3 library, available through the `SDL3::SDL3` target. This is an alias of `SDL3::SDL3-shared` or `SDL3::SDL3-static`. This component is always available. | +| Headers | The SDL3 headers, available through the `SDL3::Headers` target. This component is always available. | + + +### Using a vendored SDL + +This only requires a copy of SDL in a subdirectory + `add_subdirectory`. +Alternatively, use [FetchContent](https://cmake.org/cmake/help/latest/module/FetchContent.html). +Depending on the configuration, the same targets as a system SDL package are available. + +## CMake configuration options + +### Build optimized library + +By default, CMake provides 4 build types: `Debug`, `Release`, `RelWithDebInfo` and `MinSizeRel`. +The main difference(s) between these are the optimization options and the generation of debug info. +To configure SDL as an optimized `Release` library, configure SDL with: +```sh +cmake ~/SDL -DCMAKE_BUILD_TYPE=Release +``` +To build it, run: +```sh +cmake --build . --config Release +``` + +### Shared or static + +By default, only a shared SDL library is built and installed. +The options `-DSDL_SHARED=` and `-DSDL_STATIC=` accept boolean values to change this. + +### Pass custom compile options to the compiler + +- Use [`CMAKE__FLAGS`](https://cmake.org/cmake/help/latest/variable/CMAKE_LANG_FLAGS.html) to pass extra +flags to the compiler. +- Use [`CMAKE_EXE_LINKER_FLAGS`](https://cmake.org/cmake/help/latest/variable/CMAKE_EXE_LINKER_FLAGS.html) to pass extra option to the linker for executables. +- Use [`CMAKE_SHARED_LINKER_FLAGS`](https://cmake.org/cmake/help/latest/variable/CMAKE_SHARED_LINKER_FLAGS.html) to pass extra options to the linker for shared libraries. + +#### Examples + +- build a SDL library optimized for (more) modern x64 microprocessor architectures. + + With gcc or clang: + ```sh + cmake ~/sdl -DCMAKE_C_FLAGS="-march=x86-64-v3" -DCMAKE_CXX_FLAGS="-march=x86-64-v3" + ``` + With Visual C: + ```sh + cmake .. -DCMAKE_C_FLAGS="/ARCH:AVX2" -DCMAKE_CXX_FLAGS="/ARCH:AVX2" + ``` + +### iOS/tvOS + +CMake 3.14+ natively includes support for iOS and tvOS. SDL binaries may be built +using Xcode or Make, possibly among other build-systems. + +When using a recent version of CMake (3.14+), it should be possible to: + +- build SDL for iOS, both static and dynamic +- build SDL test apps (as iOS/tvOS .app bundles) +- generate a working SDL_build_config.h for iOS (using SDL_build_config.h.cmake as a basis) + +To use, set the following CMake variables when running CMake's configuration stage: + +- `CMAKE_SYSTEM_NAME=` (either `iOS` or `tvOS`) +- `CMAKE_OSX_SYSROOT=` (examples: `iphoneos`, `iphonesimulator`, `iphoneos12.4`, `/full/path/to/iPhoneOS.sdk`, + `appletvos`, `appletvsimulator`, `appletvos12.4`, `/full/path/to/AppleTVOS.sdk`, etc.) +- `CMAKE_OSX_ARCHITECTURES=` (example: "arm64;armv7s;x86_64") + + +#### Examples + +- for iOS-Simulator, using the latest, installed SDK: + + ```bash + cmake ~/sdl -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_SYSROOT=iphonesimulator -DCMAKE_OSX_ARCHITECTURES=x86_64 + ``` + +- for iOS-Device, using the latest, installed SDK, 64-bit only + + ```bash + cmake ~/sdl -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_SYSROOT=iphoneos -DCMAKE_OSX_ARCHITECTURES=arm64 + ``` + +- for iOS-Device, using the latest, installed SDK, mixed 32/64 bit + + ```cmake + cmake ~/sdl -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_SYSROOT=iphoneos -DCMAKE_OSX_ARCHITECTURES="arm64;armv7s" + ``` + +- for iOS-Device, using a specific SDK revision (iOS 12.4, in this example): + + ```cmake + cmake ~/sdl -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_SYSROOT=iphoneos12.4 -DCMAKE_OSX_ARCHITECTURES=arm64 + ``` + +- for iOS-Simulator, using the latest, installed SDK, and building SDL test apps (as .app bundles): + + ```cmake + cmake ~/sdl -DSDL_TESTS=1 -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_SYSROOT=iphonesimulator -DCMAKE_OSX_ARCHITECTURES=x86_64 + ``` + +- for tvOS-Simulator, using the latest, installed SDK: + + ```cmake + cmake ~/sdl -DCMAKE_SYSTEM_NAME=tvOS -DCMAKE_OSX_SYSROOT=appletvsimulator -DCMAKE_OSX_ARCHITECTURES=x86_64 + ``` + +- for tvOS-Device, using the latest, installed SDK: + + ```cmake + cmake ~/sdl -DCMAKE_SYSTEM_NAME=tvOS -DCMAKE_OSX_SYSROOT=appletvos -DCMAKE_OSX_ARCHITECTURES=arm64` + ``` + +- for QNX/aarch64, using the latest, installed SDK: + + ```cmake + cmake ~/sdl -DCMAKE_TOOLCHAIN_FILE=~/sdl/build-scripts/cmake-toolchain-qnx-aarch64le.cmake -DSDL_X11=0 + ``` + +## SDL-specific CMake options + +SDL can be customized through (platform-specific) CMake options. +The following table shows generic options that are available for most platforms. +At the end of SDL CMake configuration, a table shows all CMake options along with its detected value. + +| CMake option | Valid values | Description | +|-------------------------------|--------------|-----------------------------------------------------------------------------------------------------| +| `-DSDL_SHARED=` | `ON`/`OFF` | Build SDL shared library (not all platforms support this) (`libSDL3.so`/`libSDL3.dylib`/`SDL3.dll`) | +| `-DSDL_STATIC=` | `ON`/`OFF` | Build SDL static library (`libSDL3.a`/`SDL3-static.lib`) | +| `-DSDL_TEST_LIBRARY=` | `ON`/`OFF` | Build SDL test library (`libSDL3_test.a`/`SDL3_test.lib`) | +| `-DSDL_TESTS=` | `ON`/`OFF` | Build SDL test programs (**requires `-DSDL_TEST_LIBRARY=ON`**) | +| `-DSDL_DISABLE_INSTALL=` | `ON`/`OFF` | Don't create a SDL install target | +| `-DSDL_DISABLE_INSTALL_DOCS=` | `ON`/`OFF` | Don't install the SDL documentation | +| `-DSDL_INSTALL_TESTS=` | `ON`/`OFF` | Install the SDL test programs | + +## Help, it doesn't work! + +Below, a SDL3 CMake project can be found that builds 99.9% of time (assuming you have internet connectivity). +When you have a problem with building or using SDL, please modify it until it reproduces your issue. + +```cmake +cmake_minimum_required(VERSION 3.16) +project(sdl_issue) + +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +# !!!!!! !!!!!! +# !!!!!! This CMake script is not using "CMake best practices". !!!!!! +# !!!!!! Don't use it in your project. !!!!!! +# !!!!!! !!!!!! +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +# 1. Try system SDL3 package first +find_package(SDL3 QUIET) +if(SDL3_FOUND) + message(STATUS "Using SDL3 via find_package") +endif() + +# 2. Try using a vendored SDL library +if(NOT SDL3_FOUND AND EXISTS "${CMAKE_CURRENT_LIST_DIR}/SDL/CMakeLists.txt") + add_subdirectory(SDL) + message(STATUS "Using SDL3 via add_subdirectory") + set(SDL3_FOUND TRUE) +endif() + +# 3. Download SDL, and use that. +if(NOT SDL3_FOUND) + include(FetchContent) + set(SDL_SHARED TRUE CACHE BOOL "Build a SDL shared library (if available)") + set(SDL_STATIC TRUE CACHE BOOL "Build a SDL static library (if available)") + FetchContent_Declare( + SDL + GIT_REPOSITORY https://github.com/libsdl-org/SDL.git + GIT_TAG main # Replace this with a particular git tag or git hash + GIT_SHALLOW TRUE + GIT_PROGRESS TRUE + ) + message(STATUS "Using SDL3 via FetchContent") + FetchContent_MakeAvailable(SDL) + set_property(DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/_deps/sdl-src" PROPERTY EXCLUDE_FROM_ALL TRUE) +endif() + +file(WRITE main.c [===========================================[ +/** + * Modify this source such that it reproduces your problem. + */ + +/* START of source modifications */ + +#include + +int main(int argc, char *argv[]) { + if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { + SDL_Log("SDL_Init failed (%s)", SDL_GetError()); + return 1; + } + + SDL_Window *window = NULL; + SDL_Renderer *renderer = NULL; + + if (SDL_CreateWindowAndRenderer(640, 480, 0, &window, &renderer) < 0) { + SDL_Log("SDL_CreateWindowAndRenderer failed (%s)", SDL_GetError()); + SDL_Quit(); + return 1; + } + SDL_SetWindowTitle(window, "SDL issue"); + + while (1) { + int finished = 0; + SDL_Event event; + while (SDL_PollEvent(&event)) { + if (event.type == SDL_EVENT_QUIT) { + finished = 1; + break; + } + } + if (finished) { + break; + } + + SDL_SetRenderDrawColor(renderer, 80, 80, 80, SDL_ALPHA_OPAQUE); + SDL_RenderClear(renderer); + SDL_RenderPresent(renderer); + } + + SDL_DestroyRenderer(renderer); + SDL_DestroyWindow(window); + + SDL_Quit(); +} + +/* END of source modifications */ + +]===========================================]) + +add_executable(sdl_issue main.c) + +target_link_libraries(sdl_issue PRIVATE SDL3::SDL3) +# target_link_libraries(sdl_issue PRIVATE SDL3::SDL3-shared) +# target_link_libraries(sdl_issue PRIVATE SDL3::SDL3-static) +``` diff --git a/docs/README-contributing.md b/docs/README-contributing.md index 63b60cdd6..347f0f825 100644 --- a/docs/README-contributing.md +++ b/docs/README-contributing.md @@ -1,97 +1,97 @@ -# Contributing to SDL - -We appreciate your interest in contributing to SDL, this document will describe how to report bugs, contribute code or ideas or edit documentation. - -**Table Of Contents** - -- [Filing a GitHub issue](#filing-a-github-issue) - - [Reporting a bug](#reporting-a-bug) - - [Suggesting enhancements](#suggesting-enhancements) -- [Contributing code](#contributing-code) - - [Forking the project](#forking-the-project) - - [Following the style guide](#following-the-style-guide) - - [Running the tests](#running-the-tests) - - [Opening a pull request](#opening-a-pull-request) -- [Contributing to the documentation](#contributing-to-the-documentation) - - [Editing a function documentation](#editing-a-function-documentation) - - [Editing the wiki](#editing-the-wiki) - -## Filing a GitHub issue - -### Reporting a bug - -If you think you have found a bug and would like to report it, here are the steps you should take: - -- Before opening a new issue, ensure your bug has not already been reported on the [GitHub Issues page](https://github.com/libsdl-org/SDL/issues). -- On the issue tracker, click on [New Issue](https://github.com/libsdl-org/SDL/issues/new). -- Include details about your environment, such as your Operating System and SDL version. -- If possible, provide a small example that reproduces your bug. - -### Suggesting enhancements - -If you want to suggest changes for the project, here are the steps you should take: - -- Check if the suggestion has already been made on: - - the [issue tracker](https://github.com/libsdl-org/SDL/issues); - - the [discourse forum](https://discourse.libsdl.org/); - - or if a [pull request](https://github.com/libsdl-org/SDL/pulls) already exists. -- On the issue tracker, click on [New Issue](https://github.com/libsdl-org/SDL/issues/new). -- Describe what change you would like to happen. - -## Contributing code - -This section will cover how the process of forking the project, making a change and opening a pull request. - -### Forking the project - -The first step consists in making a fork of the project, this is only necessary for the first contribution. - -Head over to https://github.com/libsdl-org/SDL and click on the `Fork` button in the top right corner of your screen, you may leave the fields unchanged and click `Create Fork`. - -You will be redirected to your fork of the repository, click the green `Code` button and copy the git clone link. - -If you had already forked the repository, you may update it from the web page using the `Fetch upstream` button. - -### Following the style guide - -Code formatting is done using a custom `.clang-format` file, you can learn more about how to run it [here](https://clang.llvm.org/docs/ClangFormat.html). - -Some legacy code may not be formatted, as such avoid formatting the whole file at once and only format around your changes. - -For your commit message to be properly displayed on GitHub, it should contain: - -- A short description of the commit of 50 characters or less on the first line. -- If necessary, add a blank line followed by a long description, each line should be 72 characters or less. - -For example: - -``` -Fix crash in SDL_FooBar. - -This addresses the issue #123456 by making sure Foo was successful -before calling Bar. -``` - -### Running the tests - -Tests allow you to verify if your changes did not break any behaviour, here are the steps to follow: - -- Before pushing, run the `testautomation` suite on your machine, there should be no more failing tests after your change than before. -- After pushing to your fork, Continuous Integration (GitHub Actions) will ensure compilation and tests still pass on other systems. - -### Opening a pull request - -- Head over to your fork's GitHub page. -- Click on the `Contribute` button and `Open Pull Request`. -- Fill out the pull request template. -- If any changes are requested, you can add new commits to your fork and they will be automatically added to the pull request. - -## Contributing to the documentation - -### Editing a function documentation - -The wiki documentation for API functions is synchronised from the headers' doxygen comments. As such, all modifications to syntax; function parameters; return value; version; related functions should be done in the header directly. - -### Editing the wiki - -Other changes to the wiki should done directly from https://wiki.libsdl.org/ ... Just click the "edit" link at the bottom of any page! +# Contributing to SDL + +We appreciate your interest in contributing to SDL, this document will describe how to report bugs, contribute code or ideas or edit documentation. + +**Table Of Contents** + +- [Filing a GitHub issue](#filing-a-github-issue) + - [Reporting a bug](#reporting-a-bug) + - [Suggesting enhancements](#suggesting-enhancements) +- [Contributing code](#contributing-code) + - [Forking the project](#forking-the-project) + - [Following the style guide](#following-the-style-guide) + - [Running the tests](#running-the-tests) + - [Opening a pull request](#opening-a-pull-request) +- [Contributing to the documentation](#contributing-to-the-documentation) + - [Editing a function documentation](#editing-a-function-documentation) + - [Editing the wiki](#editing-the-wiki) + +## Filing a GitHub issue + +### Reporting a bug + +If you think you have found a bug and would like to report it, here are the steps you should take: + +- Before opening a new issue, ensure your bug has not already been reported on the [GitHub Issues page](https://github.com/libsdl-org/SDL/issues). +- On the issue tracker, click on [New Issue](https://github.com/libsdl-org/SDL/issues/new). +- Include details about your environment, such as your Operating System and SDL version. +- If possible, provide a small example that reproduces your bug. + +### Suggesting enhancements + +If you want to suggest changes for the project, here are the steps you should take: + +- Check if the suggestion has already been made on: + - the [issue tracker](https://github.com/libsdl-org/SDL/issues); + - the [discourse forum](https://discourse.libsdl.org/); + - or if a [pull request](https://github.com/libsdl-org/SDL/pulls) already exists. +- On the issue tracker, click on [New Issue](https://github.com/libsdl-org/SDL/issues/new). +- Describe what change you would like to happen. + +## Contributing code + +This section will cover how the process of forking the project, making a change and opening a pull request. + +### Forking the project + +The first step consists in making a fork of the project, this is only necessary for the first contribution. + +Head over to https://github.com/libsdl-org/SDL and click on the `Fork` button in the top right corner of your screen, you may leave the fields unchanged and click `Create Fork`. + +You will be redirected to your fork of the repository, click the green `Code` button and copy the git clone link. + +If you had already forked the repository, you may update it from the web page using the `Fetch upstream` button. + +### Following the style guide + +Code formatting is done using a custom `.clang-format` file, you can learn more about how to run it [here](https://clang.llvm.org/docs/ClangFormat.html). + +Some legacy code may not be formatted, as such avoid formatting the whole file at once and only format around your changes. + +For your commit message to be properly displayed on GitHub, it should contain: + +- A short description of the commit of 50 characters or less on the first line. +- If necessary, add a blank line followed by a long description, each line should be 72 characters or less. + +For example: + +``` +Fix crash in SDL_FooBar. + +This addresses the issue #123456 by making sure Foo was successful +before calling Bar. +``` + +### Running the tests + +Tests allow you to verify if your changes did not break any behaviour, here are the steps to follow: + +- Before pushing, run the `testautomation` suite on your machine, there should be no more failing tests after your change than before. +- After pushing to your fork, Continuous Integration (GitHub Actions) will ensure compilation and tests still pass on other systems. + +### Opening a pull request + +- Head over to your fork's GitHub page. +- Click on the `Contribute` button and `Open Pull Request`. +- Fill out the pull request template. +- If any changes are requested, you can add new commits to your fork and they will be automatically added to the pull request. + +## Contributing to the documentation + +### Editing a function documentation + +The wiki documentation for API functions is synchronised from the headers' doxygen comments. As such, all modifications to syntax; function parameters; return value; version; related functions should be done in the header directly. + +### Editing the wiki + +Other changes to the wiki should done directly from https://wiki.libsdl.org/ ... Just click the "edit" link at the bottom of any page! diff --git a/docs/README-dynapi.md b/docs/README-dynapi.md index a0f341244..665b7c65e 100644 --- a/docs/README-dynapi.md +++ b/docs/README-dynapi.md @@ -1,138 +1,138 @@ -# Dynamic API - -Originally posted on Ryan's Google+ account. - -Background: - -- The Steam Runtime has (at least in theory) a really kick-ass build of SDL, - but developers are shipping their own SDL with individual Steam games. - These games might stop getting updates, but a newer SDL might be needed later. - Certainly we'll always be fixing bugs in SDL, even if a new video target isn't - ever needed, and these fixes won't make it to a game shipping its own SDL. -- Even if we replace the SDL in those games with a compatible one, that is to - say, edit a developer's Steam depot (yuck!), there are developers that are - statically linking SDL that we can't do this for. We can't even force the - dynamic loader to ignore their SDL in this case, of course. -- If you don't ship an SDL with the game in some form, people that disabled the - Steam Runtime, or just tried to run the game from the command line instead of - Steam might find themselves unable to run the game, due to a missing dependency. -- If you want to ship on non-Steam platforms like GOG or Humble Bundle, or target - generic Linux boxes that may or may not have SDL installed, you have to ship - the library or risk a total failure to launch. So now, you might have to have - a non-Steam build plus a Steam build (that is, one with and one without SDL - included), which is inconvenient if you could have had one universal build - that works everywhere. -- We like the zlib license, but the biggest complaint from the open source - community about the license change is the static linking. The LGPL forced this - as a legal, not technical issue, but zlib doesn't care. Even those that aren't - concerned about the GNU freedoms found themselves solving the same problems: - swapping in a newer SDL to an older game often times can save the day. - Static linking stops this dead. - -So here's what we did: - -SDL now has, internally, a table of function pointers. So, this is what SDL_Init -now looks like: - -```c -UInt32 SDL_Init(Uint32 flags) -{ - return jump_table.SDL_Init(flags); -} -``` - -Except that is all done with a bunch of macro magic so we don't have to maintain -every one of these. - -What is jump_table.SDL_init()? Eventually, that's a function pointer of the real -SDL_Init() that you've been calling all this time. But at startup, it looks more -like this: - -```c -Uint32 SDL_Init_DEFAULT(Uint32 flags) -{ - SDL_InitDynamicAPI(); - return jump_table.SDL_Init(flags); -} -``` - -SDL_InitDynamicAPI() fills in jump_table with all the actual SDL function -pointers, which means that this `_DEFAULT` function never gets called again. -First call to any SDL function sets the whole thing up. - -So you might be asking, what was the value in that? Isn't this what the operating -system's dynamic loader was supposed to do for us? Yes, but now we've got this -level of indirection, we can do things like this: - -```bash -export SDL3_DYNAMIC_API=/my/actual/libSDL3.so.0 -./MyGameThatIsStaticallyLinkedToSDL -``` - -And now, this game that is statically linked to SDL, can still be overridden -with a newer, or better, SDL. The statically linked one will only be used as -far as calling into the jump table in this case. But in cases where no override -is desired, the statically linked version will provide its own jump table, -and everyone is happy. - -So now: -- Developers can statically link SDL, and users can still replace it. - (We'd still rather you ship a shared library, though!) -- Developers can ship an SDL with their game, Valve can override it for, say, - new features on SteamOS, or distros can override it for their own needs, - but it'll also just work in the default case. -- Developers can ship the same package to everyone (Humble Bundle, GOG, etc), - and it'll do the right thing. -- End users (and Valve) can update a game's SDL in almost any case, - to keep abandoned games running on newer platforms. -- Everyone develops with SDL exactly as they have been doing all along. - Same headers, same ABI. Just get the latest version to enable this magic. - - -A little more about SDL_InitDynamicAPI(): - -Internally, InitAPI does some locking to make sure everything waits until a -single thread initializes everything (although even SDL_CreateThread() goes -through here before spinning a thread, too), and then decides if it should use -an external SDL library. If not, it sets up the jump table using the current -SDL's function pointers (which might be statically linked into a program, or in -a shared library of its own). If so, it loads that library and looks for and -calls a single function: - -```c -SInt32 SDL_DYNAPI_entry(Uint32 version, void *table, Uint32 tablesize); -``` - -That function takes a version number (more on that in a moment), the address of -the jump table, and the size, in bytes, of the table. -Now, we've got policy here: this table's layout never changes; new stuff gets -added to the end. Therefore SDL_DYNAPI_entry() knows that it can provide all -the needed functions if tablesize <= sizeof its own jump table. If tablesize is -bigger (say, SDL 3.0.4 is trying to load SDL 3.0.3), then we know to abort, but -if it's smaller, we know we can provide the entire API that the caller needs. - -The version variable is a failsafe switch. -Right now it's always 1. This number changes when there are major API changes -(so we know if the tablesize might be smaller, or entries in it have changed). -Right now SDL_DYNAPI_entry gives up if the version doesn't match, but it's not -inconceivable to have a small dispatch library that only supplies this one -function and loads different, otherwise-incompatible SDL libraries and has the -right one initialize the jump table based on the version. For something that -must generically catch lots of different versions of SDL over time, like the -Steam Client, this isn't a bad option. - -Finally, I'm sure some people are reading this and thinking, -"I don't want that overhead in my project!" - -To which I would point out that the extra function call through the jump table -probably wouldn't even show up in a profile, but lucky you: this can all be -disabled. You can build SDL without this if you absolutely must, but we would -encourage you not to do that. However, on heavily locked down platforms like -iOS, or maybe when debugging, it makes sense to disable it. The way this is -designed in SDL, you just have to change one #define, and the entire system -vaporizes out, and SDL functions exactly like it always did. Most of it is -macro magic, so the system is contained to one C file and a few headers. -However, this is on by default and you have to edit a header file to turn it -off. Our hopes is that if we make it easy to disable, but not too easy, -everyone will ultimately be able to get what they want, but we've gently -nudged everyone towards what we think is the best solution. +# Dynamic API + +Originally posted on Ryan's Google+ account. + +Background: + +- The Steam Runtime has (at least in theory) a really kick-ass build of SDL, + but developers are shipping their own SDL with individual Steam games. + These games might stop getting updates, but a newer SDL might be needed later. + Certainly we'll always be fixing bugs in SDL, even if a new video target isn't + ever needed, and these fixes won't make it to a game shipping its own SDL. +- Even if we replace the SDL in those games with a compatible one, that is to + say, edit a developer's Steam depot (yuck!), there are developers that are + statically linking SDL that we can't do this for. We can't even force the + dynamic loader to ignore their SDL in this case, of course. +- If you don't ship an SDL with the game in some form, people that disabled the + Steam Runtime, or just tried to run the game from the command line instead of + Steam might find themselves unable to run the game, due to a missing dependency. +- If you want to ship on non-Steam platforms like GOG or Humble Bundle, or target + generic Linux boxes that may or may not have SDL installed, you have to ship + the library or risk a total failure to launch. So now, you might have to have + a non-Steam build plus a Steam build (that is, one with and one without SDL + included), which is inconvenient if you could have had one universal build + that works everywhere. +- We like the zlib license, but the biggest complaint from the open source + community about the license change is the static linking. The LGPL forced this + as a legal, not technical issue, but zlib doesn't care. Even those that aren't + concerned about the GNU freedoms found themselves solving the same problems: + swapping in a newer SDL to an older game often times can save the day. + Static linking stops this dead. + +So here's what we did: + +SDL now has, internally, a table of function pointers. So, this is what SDL_Init +now looks like: + +```c +UInt32 SDL_Init(Uint32 flags) +{ + return jump_table.SDL_Init(flags); +} +``` + +Except that is all done with a bunch of macro magic so we don't have to maintain +every one of these. + +What is jump_table.SDL_init()? Eventually, that's a function pointer of the real +SDL_Init() that you've been calling all this time. But at startup, it looks more +like this: + +```c +Uint32 SDL_Init_DEFAULT(Uint32 flags) +{ + SDL_InitDynamicAPI(); + return jump_table.SDL_Init(flags); +} +``` + +SDL_InitDynamicAPI() fills in jump_table with all the actual SDL function +pointers, which means that this `_DEFAULT` function never gets called again. +First call to any SDL function sets the whole thing up. + +So you might be asking, what was the value in that? Isn't this what the operating +system's dynamic loader was supposed to do for us? Yes, but now we've got this +level of indirection, we can do things like this: + +```bash +export SDL3_DYNAMIC_API=/my/actual/libSDL3.so.0 +./MyGameThatIsStaticallyLinkedToSDL +``` + +And now, this game that is statically linked to SDL, can still be overridden +with a newer, or better, SDL. The statically linked one will only be used as +far as calling into the jump table in this case. But in cases where no override +is desired, the statically linked version will provide its own jump table, +and everyone is happy. + +So now: +- Developers can statically link SDL, and users can still replace it. + (We'd still rather you ship a shared library, though!) +- Developers can ship an SDL with their game, Valve can override it for, say, + new features on SteamOS, or distros can override it for their own needs, + but it'll also just work in the default case. +- Developers can ship the same package to everyone (Humble Bundle, GOG, etc), + and it'll do the right thing. +- End users (and Valve) can update a game's SDL in almost any case, + to keep abandoned games running on newer platforms. +- Everyone develops with SDL exactly as they have been doing all along. + Same headers, same ABI. Just get the latest version to enable this magic. + + +A little more about SDL_InitDynamicAPI(): + +Internally, InitAPI does some locking to make sure everything waits until a +single thread initializes everything (although even SDL_CreateThread() goes +through here before spinning a thread, too), and then decides if it should use +an external SDL library. If not, it sets up the jump table using the current +SDL's function pointers (which might be statically linked into a program, or in +a shared library of its own). If so, it loads that library and looks for and +calls a single function: + +```c +SInt32 SDL_DYNAPI_entry(Uint32 version, void *table, Uint32 tablesize); +``` + +That function takes a version number (more on that in a moment), the address of +the jump table, and the size, in bytes, of the table. +Now, we've got policy here: this table's layout never changes; new stuff gets +added to the end. Therefore SDL_DYNAPI_entry() knows that it can provide all +the needed functions if tablesize <= sizeof its own jump table. If tablesize is +bigger (say, SDL 3.0.4 is trying to load SDL 3.0.3), then we know to abort, but +if it's smaller, we know we can provide the entire API that the caller needs. + +The version variable is a failsafe switch. +Right now it's always 1. This number changes when there are major API changes +(so we know if the tablesize might be smaller, or entries in it have changed). +Right now SDL_DYNAPI_entry gives up if the version doesn't match, but it's not +inconceivable to have a small dispatch library that only supplies this one +function and loads different, otherwise-incompatible SDL libraries and has the +right one initialize the jump table based on the version. For something that +must generically catch lots of different versions of SDL over time, like the +Steam Client, this isn't a bad option. + +Finally, I'm sure some people are reading this and thinking, +"I don't want that overhead in my project!" + +To which I would point out that the extra function call through the jump table +probably wouldn't even show up in a profile, but lucky you: this can all be +disabled. You can build SDL without this if you absolutely must, but we would +encourage you not to do that. However, on heavily locked down platforms like +iOS, or maybe when debugging, it makes sense to disable it. The way this is +designed in SDL, you just have to change one #define, and the entire system +vaporizes out, and SDL functions exactly like it always did. Most of it is +macro magic, so the system is contained to one C file and a few headers. +However, this is on by default and you have to edit a header file to turn it +off. Our hopes is that if we make it easy to disable, but not too easy, +everyone will ultimately be able to get what they want, but we've gently +nudged everyone towards what we think is the best solution. diff --git a/docs/README-emscripten.md b/docs/README-emscripten.md index 5826d847b..31553e069 100644 --- a/docs/README-emscripten.md +++ b/docs/README-emscripten.md @@ -1,365 +1,365 @@ -# Emscripten - -## The state of things - -(As of September 2023, but things move quickly and we don't update this -document often.) - -In modern times, all the browsers you probably care about (Chrome, Firefox, -Edge, and Safari, on Windows, macOS, Linux, iOS and Android), support some -reasonable base configurations: - -- WebAssembly (don't bother with asm.js any more) -- WebGL (which will look like OpenGL ES 2 or 3 to your app). -- Threads (see caveats, though!) -- Game controllers -- Autoupdating (so you can assume they have a recent version of the browser) - -All this to say we're at the point where you don't have to make a lot of -concessions to get even a fairly complex SDL-based game up and running. - - -## RTFM - -This document is a quick rundown of some high-level details. The -documentation at [emscripten.org](https://emscripten.org/) is vast -and extremely detailed for a wide variety of topics, and you should at -least skim through it at some point. - - -## Porting your app to Emscripten - -Many many things just need some simple adjustments and they'll compile -like any other C/C++ code, as long as SDL was handling the platform-specific -work for your program. - -First, you probably need this in at least one of your source files: - -```c -#ifdef __EMSCRIPTEN__ -#include -#endif -``` - -Second: assembly language code has to go. Replace it with C. You can even use -[x86 SIMD intrinsic functions in Emscripten](https://emscripten.org/docs/porting/simd.html)! - -Third: Middleware has to go. If you have a third-party library you link -against, you either need an Emscripten port of it, or the source code to it -to compile yourself, or you need to remove it. - -Fourth: You still start in a function called main(), but you need to get out of -it and into a function that gets called repeatedly, and returns quickly, -called a mainloop. - -Somewhere in your program, you probably have something that looks like a more -complicated version of this: - -```c -void main(void) -{ - initialize_the_game(); - while (game_is_still_running) { - check_for_new_input(); - think_about_stuff(); - draw_the_next_frame(); - } - deinitialize_the_game(); -} -``` - -This will not work on Emscripten, because the main thread needs to be free -to do stuff and can't sit in this loop forever. So Emscripten lets you set up -a [mainloop](https://emscripten.org/docs/porting/emscripten-runtime-environment.html#browser-main-loop). - -```c -static void mainloop(void) /* this will run often, possibly at the monitor's refresh rate */ -{ - if (!game_is_still_running) { - deinitialize_the_game(); - #ifdef __EMSCRIPTEN__ - emscripten_cancel_main_loop(); /* this should "kill" the app. */ - #else - exit(0); - #endif - } - - check_for_new_input(); - think_about_stuff(); - draw_the_next_frame(); -} - -void main(void) -{ - initialize_the_game(); - #ifdef __EMSCRIPTEN__ - emscripten_set_main_loop(mainloop, 0, 1); - #else - while (1) { mainloop(); } - #endif -} -``` - -Basically, `emscripten_set_main_loop(mainloop, 0, 1);` says "run -`mainloop` over and over until I end the program." The function will -run, and return, freeing the main thread for other tasks, and then -run again when it's time. The `1` parameter does some magic to make -your main() function end immediately; this is useful because you -don't want any shutdown code that might be sitting below this code -to actually run if main() were to continue on, since we're just -getting started. - -There's a lot of little details that are beyond the scope of this -document, but that's the biggest intial set of hurdles to porting -your app to the web. - - -## Do you need threads? - -If you plan to use threads, they work on all major browsers now. HOWEVER, -they bring with them a lot of careful considerations. Rendering _must_ -be done on the main thread. This is a general guideline for many -platforms, but a hard requirement on the web. - -Many other things also must happen on the main thread; often times SDL -and Emscripten make efforts to "proxy" work to the main thread that -must be there, but you have to be careful (and read more detailed -documentation than this for the finer points). - -Even when using threads, your main thread needs to set an Emscripten -mainloop that runs quickly and returns, or things will fail to work -correctly. - -You should definitely read [Emscripten's pthreads docs](https://emscripten.org/docs/porting/pthreads.html) -for all the finer points. Mostly SDL's thread API will work as expected, -but is built on pthreads, so it shares the same little incompatibilities -that are documented there, such as where you can use a mutex, and when -a thread will start running, etc. - - -IMPORTANT: You have to decide to either build something that uses -threads or something that doesn't; you can't have one build -that works everywhere. This is an Emscripten (or maybe WebAssembly? -Or just web browsers in general?) limitation. If you aren't using -threads, it's easier to not enable them at all, at build time. - -If you use threads, you _have to_ run from a web server that has -[COOP/COEP headers set correctly](https://web.dev/why-coop-coep/) -or your program will fail to start at all. - -If building with threads, `__EMSCRIPTEN_PTHREADS__` will be defined -for checking with the C preprocessor, so you can build something -different depending on what sort of build you're compiling. - - -## Audio - -Audio works as expected at the API level, but not exactly like other -platforms. - -You'll only see a single default audio device. Audio capture also works; -if the browser pops up a prompt to ask for permission to access the -microphone, the SDL_OpenAudioDevice call will succeed and start producing -silence at a regular interval. Once the user approves the request, real -audio data will flow. If the user denies it, the app is not informed and -will just continue to receive silence. - -Modern web browsers will not permit web pages to produce sound before the -user has interacted with them (clicked or tapped on them, usually); this is -for several reasons, not the least of which being that no one likes when a -random browser tab suddenly starts making noise and the user has to scramble -to figure out which and silence it. - -SDL will allow you to open the audio device for playback in this -circumstance, and your audio callback will fire, but SDL will throw the audio -data away until the user interacts with the page. This helps apps that depend -on the audio callback to make progress, and also keeps audio playback in sync -once the app is finally allowed to make noise. - -There are two reasonable ways to deal with the silence at the app level: -if you are writing some sort of media player thing, where the user expects -there to be a volume control when you mouseover the canvas, just default -that control to a muted state; if the user clicks on the control to unmute -it, on this first click, open the audio device. This allows the media to -play at start, and the user can reasonably opt-in to listening. - -Many games do not have this sort of UI, and are more rigid about starting -audio along with everything else at the start of the process. For these, your -best bet is to write a little Javascript that puts up a "Click here to play!" -UI, and upon the user clicking, remove that UI and then call the Emscripten -app's main() function. As far as the application knows, the audio device was -available to be opened as soon as the program started, and since this magic -happens in a little Javascript, you don't have to change your C/C++ code at -all to make it happen. - -Please see the discussion at https://github.com/libsdl-org/SDL/issues/6385 -for some Javascript code to steal for this approach. - - -## Rendering - -If you use SDL's 2D render API, it will use GLES2 internally, which -Emscripten will turn into WebGL calls. You can also use OpenGL ES 2 -directly by creating a GL context and drawing into it. - -Calling SDL_RenderPresent (or SDL_GL_SwapWindow) will not actually -present anything on the screen until your return from your mainloop -function. - - -## Building SDL/emscripten - -First: do you _really_ need to build SDL from source? - -If you aren't developing SDL itself, have a desire to mess with its source -code, or need something on the bleeding edge, don't build SDL. Just use -Emscripten's packaged version! - -Compile and link your app with `-sUSE_SDL=2` and it'll use a build of -SDL packaged with Emscripten. This comes from the same source code and -fixes the Emscripten project makes to SDL are generally merged into SDL's -revision control, so often this is much easier for app developers. - -`-sUSE_SDL=1` will select Emscripten's JavaScript reimplementation of SDL -1.2 instead; if you need SDL 1.2, this might be fine, but we generally -recommend you don't use SDL 1.2 in modern times. - - -If you want to build SDL, though... - -SDL currently requires at least Emscripten 3.1.35 to build. Newer versions -are likely to work, as well. - - -Build: - -This works on Linux/Unix and macOS. Please send comments about Windows. - -Make sure you've [installed emsdk](https://emscripten.org/docs/getting_started/downloads.html) -first, and run `source emsdk_env.sh` at the command line so it finds the -tools. - -(These cmake options might be overkill, but this has worked for me.) - -```bash -mkdir build -cd build -emcmake cmake .. -# you can also do `emcmake cmake -G Ninja ..` and then use `ninja` instead of this command. -emmake make -j4 -``` - -If you want to build with thread support, something like this works: - -```bash -mkdir build -cd build -emcmake cmake -DSDL_THREADS=On .. -# you can also do `emcmake cmake -G Ninja ..` and then use `ninja` instead of this command. -emmake make -j4 -``` - -To build the tests, add `-DSDL_TESTS=On` to the `emcmake cmake` command line. - - -## Building your app - -You need to compile with `emcc` instead of `gcc` or `clang` or whatever, but -mostly it uses the same command line arguments as Clang. - -Link against the SDL/build/libSDL3.a file you generated by building SDL, -link with `-sUSE_SDL=2` to use Emscripten's prepackaged SDL2 build. - -Usually you would produce a binary like this: - -```bash -gcc -o mygame mygame.c # or whatever -``` - -But for Emscripten, you want to output something else: - -```bash -emcc -o index.html mygame.c -``` - -This will produce several files...support Javascript and WebAssembly (.wasm) -files. The `-o index.html` will produce a simple HTML page that loads and -runs your app. You will (probably) eventually want to replace or customize -that file and do `-o index.js` instead to just build the code pieces. - -If you're working on a program of any serious size, you'll likely need to -link with `-sALLOW_MEMORY_GROWTH=1 -sMAXIMUM_MEMORY=1gb` to get access -to more memory. If using pthreads, you'll need the `-sMAXIMUM_MEMORY=1gb` -or the app will fail to start on iOS browsers, but this might be a bug that -goes away in the future. - - -## Data files - -Your game probably has data files. Here's how to access them. - -Filesystem access works like a Unix filesystem; you have a single directory -tree, possibly interpolated from several mounted locations, no drive letters, -'/' for a path separator. You can access them with standard file APIs like -open() or fopen() or SDL_RWops. You can read or write from the filesystem. - -By default, you probably have a "MEMFS" filesystem (all files are stored in -memory, but access to them is immediate and doesn't need to block). There are -other options, like "IDBFS" (files are stored in a local database, so they -don't need to be in RAM all the time and they can persist between runs of the -program, but access is not synchronous). You can mix and match these file -systems, mounting a MEMFS filesystem at one place and idbfs elsewhere, etc, -but that's beyond the scope of this document. Please refer to Emscripten's -[page on the topic](https://emscripten.org/docs/porting/files/file_systems_overview.html) -for more info. - -The _easiest_ (but not the best) way to get at your data files is to embed -them in the app itself. Emscripten's linker has support for automating this. - -```bash -emcc -o index.html loopwave.c --embed-file=../test/sample.wav@/sounds/sample.wav -``` - -This will pack ../test/sample.wav in your app, and make it available at -"/sounds/sample.wav" at runtime. Emscripten makes sure this data is available -before your main() function runs, and since it's in MEMFS, you can just -read it like you do on other platforms. `--embed-file` can also accept a -directory to pack an entire tree, and you can specify the argument multiple -times to pack unrelated things into the final installation. - -Note that this is absolutely the best approach if you have a few small -files to include and shouldn't worry about the issue further. However, if you -have hundreds of megabytes and/or thousands of files, this is not so great, -since the user will download it all every time they load your page, and it -all has to live in memory at runtime. - -[Emscripten's documentation on the matter](https://emscripten.org/docs/porting/files/packaging_files.html) -gives other options and details, and is worth a read. - - -## Debugging - -Debugging web apps is a mixed bag. You should compile and link with -`-gsource-map`, which embeds a ton of source-level debugging information into -the build, and make sure _the app source code is available on the web server_, -which is often a scary proposition for various reasons. - -When you debug from the browser's tools and hit a breakpoint, you can step -through the actual C/C++ source code, though, which can be nice. - -If you try debugging in Firefox and it doesn't work well for no apparent -reason, try Chrome, and vice-versa. These tools are still relatively new, -and improving all the time. - -SDL_Log() (or even plain old printf) will write to the Javascript console, -and honestly I find printf-style debugging to be easier than setting up a build -for proper debugging, so use whatever tools work best for you. - - -## Questions? - -Please give us feedback on this document at [the SDL bug tracker](https://github.com/libsdl-org/SDL/issues). -If something is wrong or unclear, we want to know! - - - +# Emscripten + +## The state of things + +(As of September 2023, but things move quickly and we don't update this +document often.) + +In modern times, all the browsers you probably care about (Chrome, Firefox, +Edge, and Safari, on Windows, macOS, Linux, iOS and Android), support some +reasonable base configurations: + +- WebAssembly (don't bother with asm.js any more) +- WebGL (which will look like OpenGL ES 2 or 3 to your app). +- Threads (see caveats, though!) +- Game controllers +- Autoupdating (so you can assume they have a recent version of the browser) + +All this to say we're at the point where you don't have to make a lot of +concessions to get even a fairly complex SDL-based game up and running. + + +## RTFM + +This document is a quick rundown of some high-level details. The +documentation at [emscripten.org](https://emscripten.org/) is vast +and extremely detailed for a wide variety of topics, and you should at +least skim through it at some point. + + +## Porting your app to Emscripten + +Many many things just need some simple adjustments and they'll compile +like any other C/C++ code, as long as SDL was handling the platform-specific +work for your program. + +First, you probably need this in at least one of your source files: + +```c +#ifdef __EMSCRIPTEN__ +#include +#endif +``` + +Second: assembly language code has to go. Replace it with C. You can even use +[x86 SIMD intrinsic functions in Emscripten](https://emscripten.org/docs/porting/simd.html)! + +Third: Middleware has to go. If you have a third-party library you link +against, you either need an Emscripten port of it, or the source code to it +to compile yourself, or you need to remove it. + +Fourth: You still start in a function called main(), but you need to get out of +it and into a function that gets called repeatedly, and returns quickly, +called a mainloop. + +Somewhere in your program, you probably have something that looks like a more +complicated version of this: + +```c +void main(void) +{ + initialize_the_game(); + while (game_is_still_running) { + check_for_new_input(); + think_about_stuff(); + draw_the_next_frame(); + } + deinitialize_the_game(); +} +``` + +This will not work on Emscripten, because the main thread needs to be free +to do stuff and can't sit in this loop forever. So Emscripten lets you set up +a [mainloop](https://emscripten.org/docs/porting/emscripten-runtime-environment.html#browser-main-loop). + +```c +static void mainloop(void) /* this will run often, possibly at the monitor's refresh rate */ +{ + if (!game_is_still_running) { + deinitialize_the_game(); + #ifdef __EMSCRIPTEN__ + emscripten_cancel_main_loop(); /* this should "kill" the app. */ + #else + exit(0); + #endif + } + + check_for_new_input(); + think_about_stuff(); + draw_the_next_frame(); +} + +void main(void) +{ + initialize_the_game(); + #ifdef __EMSCRIPTEN__ + emscripten_set_main_loop(mainloop, 0, 1); + #else + while (1) { mainloop(); } + #endif +} +``` + +Basically, `emscripten_set_main_loop(mainloop, 0, 1);` says "run +`mainloop` over and over until I end the program." The function will +run, and return, freeing the main thread for other tasks, and then +run again when it's time. The `1` parameter does some magic to make +your main() function end immediately; this is useful because you +don't want any shutdown code that might be sitting below this code +to actually run if main() were to continue on, since we're just +getting started. + +There's a lot of little details that are beyond the scope of this +document, but that's the biggest intial set of hurdles to porting +your app to the web. + + +## Do you need threads? + +If you plan to use threads, they work on all major browsers now. HOWEVER, +they bring with them a lot of careful considerations. Rendering _must_ +be done on the main thread. This is a general guideline for many +platforms, but a hard requirement on the web. + +Many other things also must happen on the main thread; often times SDL +and Emscripten make efforts to "proxy" work to the main thread that +must be there, but you have to be careful (and read more detailed +documentation than this for the finer points). + +Even when using threads, your main thread needs to set an Emscripten +mainloop that runs quickly and returns, or things will fail to work +correctly. + +You should definitely read [Emscripten's pthreads docs](https://emscripten.org/docs/porting/pthreads.html) +for all the finer points. Mostly SDL's thread API will work as expected, +but is built on pthreads, so it shares the same little incompatibilities +that are documented there, such as where you can use a mutex, and when +a thread will start running, etc. + + +IMPORTANT: You have to decide to either build something that uses +threads or something that doesn't; you can't have one build +that works everywhere. This is an Emscripten (or maybe WebAssembly? +Or just web browsers in general?) limitation. If you aren't using +threads, it's easier to not enable them at all, at build time. + +If you use threads, you _have to_ run from a web server that has +[COOP/COEP headers set correctly](https://web.dev/why-coop-coep/) +or your program will fail to start at all. + +If building with threads, `__EMSCRIPTEN_PTHREADS__` will be defined +for checking with the C preprocessor, so you can build something +different depending on what sort of build you're compiling. + + +## Audio + +Audio works as expected at the API level, but not exactly like other +platforms. + +You'll only see a single default audio device. Audio capture also works; +if the browser pops up a prompt to ask for permission to access the +microphone, the SDL_OpenAudioDevice call will succeed and start producing +silence at a regular interval. Once the user approves the request, real +audio data will flow. If the user denies it, the app is not informed and +will just continue to receive silence. + +Modern web browsers will not permit web pages to produce sound before the +user has interacted with them (clicked or tapped on them, usually); this is +for several reasons, not the least of which being that no one likes when a +random browser tab suddenly starts making noise and the user has to scramble +to figure out which and silence it. + +SDL will allow you to open the audio device for playback in this +circumstance, and your audio callback will fire, but SDL will throw the audio +data away until the user interacts with the page. This helps apps that depend +on the audio callback to make progress, and also keeps audio playback in sync +once the app is finally allowed to make noise. + +There are two reasonable ways to deal with the silence at the app level: +if you are writing some sort of media player thing, where the user expects +there to be a volume control when you mouseover the canvas, just default +that control to a muted state; if the user clicks on the control to unmute +it, on this first click, open the audio device. This allows the media to +play at start, and the user can reasonably opt-in to listening. + +Many games do not have this sort of UI, and are more rigid about starting +audio along with everything else at the start of the process. For these, your +best bet is to write a little Javascript that puts up a "Click here to play!" +UI, and upon the user clicking, remove that UI and then call the Emscripten +app's main() function. As far as the application knows, the audio device was +available to be opened as soon as the program started, and since this magic +happens in a little Javascript, you don't have to change your C/C++ code at +all to make it happen. + +Please see the discussion at https://github.com/libsdl-org/SDL/issues/6385 +for some Javascript code to steal for this approach. + + +## Rendering + +If you use SDL's 2D render API, it will use GLES2 internally, which +Emscripten will turn into WebGL calls. You can also use OpenGL ES 2 +directly by creating a GL context and drawing into it. + +Calling SDL_RenderPresent (or SDL_GL_SwapWindow) will not actually +present anything on the screen until your return from your mainloop +function. + + +## Building SDL/emscripten + +First: do you _really_ need to build SDL from source? + +If you aren't developing SDL itself, have a desire to mess with its source +code, or need something on the bleeding edge, don't build SDL. Just use +Emscripten's packaged version! + +Compile and link your app with `-sUSE_SDL=2` and it'll use a build of +SDL packaged with Emscripten. This comes from the same source code and +fixes the Emscripten project makes to SDL are generally merged into SDL's +revision control, so often this is much easier for app developers. + +`-sUSE_SDL=1` will select Emscripten's JavaScript reimplementation of SDL +1.2 instead; if you need SDL 1.2, this might be fine, but we generally +recommend you don't use SDL 1.2 in modern times. + + +If you want to build SDL, though... + +SDL currently requires at least Emscripten 3.1.35 to build. Newer versions +are likely to work, as well. + + +Build: + +This works on Linux/Unix and macOS. Please send comments about Windows. + +Make sure you've [installed emsdk](https://emscripten.org/docs/getting_started/downloads.html) +first, and run `source emsdk_env.sh` at the command line so it finds the +tools. + +(These cmake options might be overkill, but this has worked for me.) + +```bash +mkdir build +cd build +emcmake cmake .. +# you can also do `emcmake cmake -G Ninja ..` and then use `ninja` instead of this command. +emmake make -j4 +``` + +If you want to build with thread support, something like this works: + +```bash +mkdir build +cd build +emcmake cmake -DSDL_THREADS=On .. +# you can also do `emcmake cmake -G Ninja ..` and then use `ninja` instead of this command. +emmake make -j4 +``` + +To build the tests, add `-DSDL_TESTS=On` to the `emcmake cmake` command line. + + +## Building your app + +You need to compile with `emcc` instead of `gcc` or `clang` or whatever, but +mostly it uses the same command line arguments as Clang. + +Link against the SDL/build/libSDL3.a file you generated by building SDL, +link with `-sUSE_SDL=2` to use Emscripten's prepackaged SDL2 build. + +Usually you would produce a binary like this: + +```bash +gcc -o mygame mygame.c # or whatever +``` + +But for Emscripten, you want to output something else: + +```bash +emcc -o index.html mygame.c +``` + +This will produce several files...support Javascript and WebAssembly (.wasm) +files. The `-o index.html` will produce a simple HTML page that loads and +runs your app. You will (probably) eventually want to replace or customize +that file and do `-o index.js` instead to just build the code pieces. + +If you're working on a program of any serious size, you'll likely need to +link with `-sALLOW_MEMORY_GROWTH=1 -sMAXIMUM_MEMORY=1gb` to get access +to more memory. If using pthreads, you'll need the `-sMAXIMUM_MEMORY=1gb` +or the app will fail to start on iOS browsers, but this might be a bug that +goes away in the future. + + +## Data files + +Your game probably has data files. Here's how to access them. + +Filesystem access works like a Unix filesystem; you have a single directory +tree, possibly interpolated from several mounted locations, no drive letters, +'/' for a path separator. You can access them with standard file APIs like +open() or fopen() or SDL_RWops. You can read or write from the filesystem. + +By default, you probably have a "MEMFS" filesystem (all files are stored in +memory, but access to them is immediate and doesn't need to block). There are +other options, like "IDBFS" (files are stored in a local database, so they +don't need to be in RAM all the time and they can persist between runs of the +program, but access is not synchronous). You can mix and match these file +systems, mounting a MEMFS filesystem at one place and idbfs elsewhere, etc, +but that's beyond the scope of this document. Please refer to Emscripten's +[page on the topic](https://emscripten.org/docs/porting/files/file_systems_overview.html) +for more info. + +The _easiest_ (but not the best) way to get at your data files is to embed +them in the app itself. Emscripten's linker has support for automating this. + +```bash +emcc -o index.html loopwave.c --embed-file=../test/sample.wav@/sounds/sample.wav +``` + +This will pack ../test/sample.wav in your app, and make it available at +"/sounds/sample.wav" at runtime. Emscripten makes sure this data is available +before your main() function runs, and since it's in MEMFS, you can just +read it like you do on other platforms. `--embed-file` can also accept a +directory to pack an entire tree, and you can specify the argument multiple +times to pack unrelated things into the final installation. + +Note that this is absolutely the best approach if you have a few small +files to include and shouldn't worry about the issue further. However, if you +have hundreds of megabytes and/or thousands of files, this is not so great, +since the user will download it all every time they load your page, and it +all has to live in memory at runtime. + +[Emscripten's documentation on the matter](https://emscripten.org/docs/porting/files/packaging_files.html) +gives other options and details, and is worth a read. + + +## Debugging + +Debugging web apps is a mixed bag. You should compile and link with +`-gsource-map`, which embeds a ton of source-level debugging information into +the build, and make sure _the app source code is available on the web server_, +which is often a scary proposition for various reasons. + +When you debug from the browser's tools and hit a breakpoint, you can step +through the actual C/C++ source code, though, which can be nice. + +If you try debugging in Firefox and it doesn't work well for no apparent +reason, try Chrome, and vice-versa. These tools are still relatively new, +and improving all the time. + +SDL_Log() (or even plain old printf) will write to the Javascript console, +and honestly I find printf-style debugging to be easier than setting up a build +for proper debugging, so use whatever tools work best for you. + + +## Questions? + +Please give us feedback on this document at [the SDL bug tracker](https://github.com/libsdl-org/SDL/issues). +If something is wrong or unclear, we want to know! + + + diff --git a/docs/README-gdk.md b/docs/README-gdk.md index fefe16357..6c242b5a0 100644 --- a/docs/README-gdk.md +++ b/docs/README-gdk.md @@ -1,159 +1,159 @@ -GDK -===== - -This port allows SDL applications to run via Microsoft's Game Development Kit (GDK). - -Windows (GDK) and Xbox One/Xbox Series (GDKX) are supported. Although most of the Xbox code is included in the public SDL source code, NDA access is required for a small number of source files. If you have access to GDKX, these required Xbox files are posted on the GDK forums [here](https://forums.xboxlive.com/questions/130003/). - - -Requirements ------------- - -* Microsoft Visual Studio 2022 (in theory, it should also work in 2017 or 2019, but this has not been tested) -* Microsoft GDK June 2022 or newer (public release [here](https://github.com/microsoft/GDK/releases/tag/June_2022)) -* To publish a package or successfully authenticate a user, you will need to create an app id/configure services in Partner Center. However, for local testing purposes (without authenticating on Xbox Live), the identifiers used by the GDK test programs in the included solution will work. - - -Windows GDK Status ------- - -The Windows GDK port supports the full set of Win32 APIs, renderers, controllers, input devices, etc., as the normal Windows x64 build of SDL. - -* Additionally, the GDK port adds the following: - * Compile-time platform detection for SDL programs. The `__GDK__` is `#define`d on every GDK platform, and the `__WINGDK__` is `#define`d on Windows GDK, specifically. (This distinction exists because other GDK platforms support a smaller subset of functionality. This allows you to mark code for "any" GDK separate from Windows GDK.) - * GDK-specific setup: - * Initializing/uninitializing the game runtime, and initializing Xbox Live services - * Creating a global task queue and setting it as the default for the process. When running any async operations, passing in `NULL` as the task queue will make the task get added to the global task queue. - - * An implementation on `WinMain` that performs the above GDK setup that you can use by #include'ing SDL_main.h in the source file that includes your standard main() function. If you are unable to do this, you can instead manually call `SDL_RunApp` from your entry point, passing in your `SDL_main` function and `NULL` as the parameters. To use `SDL_RunApp`, `#define SDL_MAIN_HANDLED` before `#include `. - * Global task queue callbacks are dispatched during `SDL_PumpEvents` (which is also called internally if using `SDL_PollEvent`). - * You can get the handle of the global task queue through `SDL_GDKGetTaskQueue`, if needed. When done with the queue, be sure to use `XTaskQueueCloseHandle` to decrement the reference count (otherwise it will cause a resource leak). - -* Single-player games have some additional features available: - * Call `SDL_GDKGetDefaultUser` to get the default XUserHandle pointer. - * `SDL_GetPrefPath` still works, but only for single-player titles. - -These functions mostly wrap around async APIs, and thus should be treated as synchronous alternatives. Also note that the single-player functions return on any OS errors, so be sure to validate the return values! - -* What doesn't work: - * Compilation with anything other than through the included Visual C++ solution file - -## VisualC-GDK Solution - -The included `VisualC-GDK/SDL.sln` solution includes the following targets for the Gaming.Desktop.x64 configuration: - -* SDL3 (DLL) - This is the typical SDL3.dll, but for Gaming.Desktop.x64. -* tests/testgamecontroller - Standard SDL test program demonstrating controller functionality. -* tests/testgdk - GDK-specific test program that demonstrates using the global task queue to login a user into Xbox Live. - *NOTE*: As of the June 2022 GDK, you cannot test user logins without a valid Title ID and MSAAppId. You will need to manually change the identifiers in the `MicrosoftGame.config` to your valid IDs from Partner Center if you wish to test this. -* tests/testsprite - Standard SDL test program demonstrating sprite drawing functionality. - -If you set one of the test programs as a startup project, you can run it directly from Visual Studio. - -Windows GDK Setup, Detailed Steps ---------------------- - -These steps assume you already have a game using SDL that runs on Windows x64 along with a corresponding Visual Studio solution file for the x64 version. If you don't have this, it's easiest to use one of the test program vcxproj files in the `VisualC-GDK` directory as a starting point, though you will still need to do most of the steps below. - -### 1. Add a Gaming.Desktop.x64 Configuration ### - -In your game's existing Visual Studio Solution, go to Build > Configuration Manager. From the "Active solution platform" drop-down select "New...". From the drop-down list, select Gaming.Desktop.x64 and copy the settings from the x64 configuration. - -### 2. Build SDL3 for GDK ### - -Open `VisualC-GDK/SDL.sln` in Visual Studio, you need to build the SDL3 target for the Gaming.Desktop.x64 platform (Release is recommended). You will need to copy/keep track of the `SDL3.dll`, `XCurl.dll` (which is output by Gaming.Desktop.x64), and `SDL3.lib` output files for your game project. - -*Alternatively*, you could setup your solution file to instead reference the SDL3 project file targets from the SDL source, and add those projects as a dependency. This would mean that SDL3 would be built when your game is built. - -### 3. Configuring Project Settings ### - -While the Gaming.Desktop.x64 configuration sets most of the required settings, there are some additional items to configure for your game project under the Gaming.Desktop.x64 Configuration: - -* Under C/C++ > General > Additional Include Directories, make sure the `SDL/include` path is referenced -* Under Linker > General > Additional Library Directories, make sure to reference the path where the newly-built SDL3.lib are -* Under Linker > Input > Additional Dependencies, you need the following: - * `SDL3.lib` - * `xgameruntime.lib` - * `../Microsoft.Xbox.Services.141.GDK.C.Thunks.lib` -* Note that in general, the GDK libraries depend on the MSVC C/C++ runtime, so there is no way to remove this dependency from a GDK program that links against GDK. - -### 4. Setting up SDL_main ### - -Rather than using your own implementation of `WinMain`, it's recommended that you instead `#include ` and declare a standard main function. If you are unable to do this, you can instead manually call `SDL_RunApp` from your entry point, passing in your `SDL_main` function and `NULL` as the parameters; in that case `#define SDL_MAIN_HANDLED` before including SDL_main.h - -### 5. Required DLLs ### - -The game will not launch in the debugger unless required DLLs are included in the directory that contains the game's .exe file. You need to make sure that the following files are copied into the directory: - -* Your SDL3.dll -* "$(Console_GRDKExtLibRoot)Xbox.Services.API.C\DesignTime\CommonConfiguration\Neutral\Lib\Release\Microsoft.Xbox.Services.141.GDK.C.Thunks.dll" -* XCurl.dll - -You can either copy these in a post-build step, or you can add the dlls into the project and set its Configuration Properties > General > Item type to "Copy file," which will also copy them into the output directory. - -### 6. Setting up MicrosoftGame.config ### - -You can copy `VisualC-GDK/tests/testgdk/MicrosoftGame.config` and use that as a starting point in your project. Minimally, you will want to change the Executable Name attribute, the DefaultDisplayName, and the Description. - -This file must be copied into the same directory as the game's .exe file. As with the DLLs, you can either use a post-build step or the "Copy file" item type. - -For basic testing, you do not need to change anything else in `MicrosoftGame.config`. However, if you want to test any Xbox Live services (such as logging in users) _or_ publish a package, you will need to setup a Game app on Partner Center. - -Then, you need to set the following values to the values from Partner Center: - -* Identity tag - Name and Publisher attributes -* TitleId -* MSAAppId - -### 7. Adding Required Logos - -Several logo PNG files are required to be able to launch the game, even from the debugger. You can use the sample logos provided in `VisualC-GDK/logos`. As with the other files, they must be copied into the same directory as the game's .exe file. - - -### 8. Copying any Data Files ### - -When debugging GDK games, there is no way to specify a working directory. Therefore, any required game data must also be copied into the output directory, likely in a post-build step. - - -### 9. Build and Run from Visual Studio ### - -At this point, you should be able to build and run your game from the Visual Studio Debugger. If you get any linker errors, make sure you double-check that you referenced all the required libs. - -If you are testing Xbox Live functionality, it's likely you will need to change to the Sandbox for your title. To do this: - -1. Run "Desktop VS 2022 Gaming Command Prompt" from the Start Menu -2. Switch the sandbox name with: - `XblPCSandbox SANDBOX.#` -3. (To switch back to the retail sandbox): - `XblPCSandbox RETAIL` - -### 10. Packaging and Installing Locally - -You can use one of the test program's `PackageLayout.xml` as a starting point. Minimally, you will need to change the exe to the correct name and also reference any required game data. As with the other data files, it's easiest if you have this copy to the output directory, although it's not a requirement as you can specify relative paths to files. - -To create the package: - -1. Run "Desktop VS 2022 Gaming Command Prompt" from the Start Menu -2. `cd` to the directory containing the `PackageLayout.xml` with the correct paths (if you use the local path as in the sample package layout, this would be from your .exe output directory) -3. `mkdir Package` to create an output directory -4. To package the file into the `Package` directory, use: - `makepkg pack /f PackageLayout.xml /lt /d . /nogameos /pc /pd Package` -5. To install the package, use: - `wdapp install PACKAGENAME.msixvc` -6. Once the package is installed, you can run it from the start menu. -7. As with when running from Visual Studio, if you need to test any Xbox Live functionality you must switch to the correct sandbox. - - -Troubleshooting ---------------- - -#### Xbox Live Login does not work - -As of June 2022 GDK, you must have a valid Title Id and MSAAppId in order to test Xbox Live functionality such as user login. Make sure these are set correctly in the `MicrosoftGame.config`. This means that even testgdk will not let you login without setting these properties to valid values. - -Furthermore, confirm that your PC is set to the correct sandbox. - - -#### "The current user has already installed an unpackaged version of this app. A packaged version cannot replace this." error when installing - -Prior to June 2022 GDK, running from the Visual Studio debugger would still locally register the app (and it would appear on the start menu). To fix this, you have to uninstall it (it's simplest to right click on it from the start menu to uninstall it). +GDK +===== + +This port allows SDL applications to run via Microsoft's Game Development Kit (GDK). + +Windows (GDK) and Xbox One/Xbox Series (GDKX) are supported. Although most of the Xbox code is included in the public SDL source code, NDA access is required for a small number of source files. If you have access to GDKX, these required Xbox files are posted on the GDK forums [here](https://forums.xboxlive.com/questions/130003/). + + +Requirements +------------ + +* Microsoft Visual Studio 2022 (in theory, it should also work in 2017 or 2019, but this has not been tested) +* Microsoft GDK June 2022 or newer (public release [here](https://github.com/microsoft/GDK/releases/tag/June_2022)) +* To publish a package or successfully authenticate a user, you will need to create an app id/configure services in Partner Center. However, for local testing purposes (without authenticating on Xbox Live), the identifiers used by the GDK test programs in the included solution will work. + + +Windows GDK Status +------ + +The Windows GDK port supports the full set of Win32 APIs, renderers, controllers, input devices, etc., as the normal Windows x64 build of SDL. + +* Additionally, the GDK port adds the following: + * Compile-time platform detection for SDL programs. The `__GDK__` is `#define`d on every GDK platform, and the `__WINGDK__` is `#define`d on Windows GDK, specifically. (This distinction exists because other GDK platforms support a smaller subset of functionality. This allows you to mark code for "any" GDK separate from Windows GDK.) + * GDK-specific setup: + * Initializing/uninitializing the game runtime, and initializing Xbox Live services + * Creating a global task queue and setting it as the default for the process. When running any async operations, passing in `NULL` as the task queue will make the task get added to the global task queue. + + * An implementation on `WinMain` that performs the above GDK setup that you can use by #include'ing SDL_main.h in the source file that includes your standard main() function. If you are unable to do this, you can instead manually call `SDL_RunApp` from your entry point, passing in your `SDL_main` function and `NULL` as the parameters. To use `SDL_RunApp`, `#define SDL_MAIN_HANDLED` before `#include `. + * Global task queue callbacks are dispatched during `SDL_PumpEvents` (which is also called internally if using `SDL_PollEvent`). + * You can get the handle of the global task queue through `SDL_GDKGetTaskQueue`, if needed. When done with the queue, be sure to use `XTaskQueueCloseHandle` to decrement the reference count (otherwise it will cause a resource leak). + +* Single-player games have some additional features available: + * Call `SDL_GDKGetDefaultUser` to get the default XUserHandle pointer. + * `SDL_GetPrefPath` still works, but only for single-player titles. + +These functions mostly wrap around async APIs, and thus should be treated as synchronous alternatives. Also note that the single-player functions return on any OS errors, so be sure to validate the return values! + +* What doesn't work: + * Compilation with anything other than through the included Visual C++ solution file + +## VisualC-GDK Solution + +The included `VisualC-GDK/SDL.sln` solution includes the following targets for the Gaming.Desktop.x64 configuration: + +* SDL3 (DLL) - This is the typical SDL3.dll, but for Gaming.Desktop.x64. +* tests/testgamecontroller - Standard SDL test program demonstrating controller functionality. +* tests/testgdk - GDK-specific test program that demonstrates using the global task queue to login a user into Xbox Live. + *NOTE*: As of the June 2022 GDK, you cannot test user logins without a valid Title ID and MSAAppId. You will need to manually change the identifiers in the `MicrosoftGame.config` to your valid IDs from Partner Center if you wish to test this. +* tests/testsprite - Standard SDL test program demonstrating sprite drawing functionality. + +If you set one of the test programs as a startup project, you can run it directly from Visual Studio. + +Windows GDK Setup, Detailed Steps +--------------------- + +These steps assume you already have a game using SDL that runs on Windows x64 along with a corresponding Visual Studio solution file for the x64 version. If you don't have this, it's easiest to use one of the test program vcxproj files in the `VisualC-GDK` directory as a starting point, though you will still need to do most of the steps below. + +### 1. Add a Gaming.Desktop.x64 Configuration ### + +In your game's existing Visual Studio Solution, go to Build > Configuration Manager. From the "Active solution platform" drop-down select "New...". From the drop-down list, select Gaming.Desktop.x64 and copy the settings from the x64 configuration. + +### 2. Build SDL3 for GDK ### + +Open `VisualC-GDK/SDL.sln` in Visual Studio, you need to build the SDL3 target for the Gaming.Desktop.x64 platform (Release is recommended). You will need to copy/keep track of the `SDL3.dll`, `XCurl.dll` (which is output by Gaming.Desktop.x64), and `SDL3.lib` output files for your game project. + +*Alternatively*, you could setup your solution file to instead reference the SDL3 project file targets from the SDL source, and add those projects as a dependency. This would mean that SDL3 would be built when your game is built. + +### 3. Configuring Project Settings ### + +While the Gaming.Desktop.x64 configuration sets most of the required settings, there are some additional items to configure for your game project under the Gaming.Desktop.x64 Configuration: + +* Under C/C++ > General > Additional Include Directories, make sure the `SDL/include` path is referenced +* Under Linker > General > Additional Library Directories, make sure to reference the path where the newly-built SDL3.lib are +* Under Linker > Input > Additional Dependencies, you need the following: + * `SDL3.lib` + * `xgameruntime.lib` + * `../Microsoft.Xbox.Services.141.GDK.C.Thunks.lib` +* Note that in general, the GDK libraries depend on the MSVC C/C++ runtime, so there is no way to remove this dependency from a GDK program that links against GDK. + +### 4. Setting up SDL_main ### + +Rather than using your own implementation of `WinMain`, it's recommended that you instead `#include ` and declare a standard main function. If you are unable to do this, you can instead manually call `SDL_RunApp` from your entry point, passing in your `SDL_main` function and `NULL` as the parameters; in that case `#define SDL_MAIN_HANDLED` before including SDL_main.h + +### 5. Required DLLs ### + +The game will not launch in the debugger unless required DLLs are included in the directory that contains the game's .exe file. You need to make sure that the following files are copied into the directory: + +* Your SDL3.dll +* "$(Console_GRDKExtLibRoot)Xbox.Services.API.C\DesignTime\CommonConfiguration\Neutral\Lib\Release\Microsoft.Xbox.Services.141.GDK.C.Thunks.dll" +* XCurl.dll + +You can either copy these in a post-build step, or you can add the dlls into the project and set its Configuration Properties > General > Item type to "Copy file," which will also copy them into the output directory. + +### 6. Setting up MicrosoftGame.config ### + +You can copy `VisualC-GDK/tests/testgdk/MicrosoftGame.config` and use that as a starting point in your project. Minimally, you will want to change the Executable Name attribute, the DefaultDisplayName, and the Description. + +This file must be copied into the same directory as the game's .exe file. As with the DLLs, you can either use a post-build step or the "Copy file" item type. + +For basic testing, you do not need to change anything else in `MicrosoftGame.config`. However, if you want to test any Xbox Live services (such as logging in users) _or_ publish a package, you will need to setup a Game app on Partner Center. + +Then, you need to set the following values to the values from Partner Center: + +* Identity tag - Name and Publisher attributes +* TitleId +* MSAAppId + +### 7. Adding Required Logos + +Several logo PNG files are required to be able to launch the game, even from the debugger. You can use the sample logos provided in `VisualC-GDK/logos`. As with the other files, they must be copied into the same directory as the game's .exe file. + + +### 8. Copying any Data Files ### + +When debugging GDK games, there is no way to specify a working directory. Therefore, any required game data must also be copied into the output directory, likely in a post-build step. + + +### 9. Build and Run from Visual Studio ### + +At this point, you should be able to build and run your game from the Visual Studio Debugger. If you get any linker errors, make sure you double-check that you referenced all the required libs. + +If you are testing Xbox Live functionality, it's likely you will need to change to the Sandbox for your title. To do this: + +1. Run "Desktop VS 2022 Gaming Command Prompt" from the Start Menu +2. Switch the sandbox name with: + `XblPCSandbox SANDBOX.#` +3. (To switch back to the retail sandbox): + `XblPCSandbox RETAIL` + +### 10. Packaging and Installing Locally + +You can use one of the test program's `PackageLayout.xml` as a starting point. Minimally, you will need to change the exe to the correct name and also reference any required game data. As with the other data files, it's easiest if you have this copy to the output directory, although it's not a requirement as you can specify relative paths to files. + +To create the package: + +1. Run "Desktop VS 2022 Gaming Command Prompt" from the Start Menu +2. `cd` to the directory containing the `PackageLayout.xml` with the correct paths (if you use the local path as in the sample package layout, this would be from your .exe output directory) +3. `mkdir Package` to create an output directory +4. To package the file into the `Package` directory, use: + `makepkg pack /f PackageLayout.xml /lt /d . /nogameos /pc /pd Package` +5. To install the package, use: + `wdapp install PACKAGENAME.msixvc` +6. Once the package is installed, you can run it from the start menu. +7. As with when running from Visual Studio, if you need to test any Xbox Live functionality you must switch to the correct sandbox. + + +Troubleshooting +--------------- + +#### Xbox Live Login does not work + +As of June 2022 GDK, you must have a valid Title Id and MSAAppId in order to test Xbox Live functionality such as user login. Make sure these are set correctly in the `MicrosoftGame.config`. This means that even testgdk will not let you login without setting these properties to valid values. + +Furthermore, confirm that your PC is set to the correct sandbox. + + +#### "The current user has already installed an unpackaged version of this app. A packaged version cannot replace this." error when installing + +Prior to June 2022 GDK, running from the Visual Studio debugger would still locally register the app (and it would appear on the start menu). To fix this, you have to uninstall it (it's simplest to right click on it from the start menu to uninstall it). diff --git a/docs/README-git.md b/docs/README-git.md index fd12fd9f6..3f03488ae 100644 --- a/docs/README-git.md +++ b/docs/README-git.md @@ -1,19 +1,19 @@ -git -========= - -The latest development version of SDL is available via git. -Git allows you to get up-to-the-minute fixes and enhancements; -as a developer works on a source tree, you can use "git" to mirror that -source tree instead of waiting for an official release. Please look -at the Git website ( https://git-scm.com/ ) for more -information on using git, where you can also download software for -macOS, Windows, and Unix systems. - - git clone https://github.com/libsdl-org/SDL - -If you are building SDL via configure, you will need to run autogen.sh -before running configure. - -There is a web interface to the Git repository at: - http://github.com/libsdl-org/SDL/ - +git +========= + +The latest development version of SDL is available via git. +Git allows you to get up-to-the-minute fixes and enhancements; +as a developer works on a source tree, you can use "git" to mirror that +source tree instead of waiting for an official release. Please look +at the Git website ( https://git-scm.com/ ) for more +information on using git, where you can also download software for +macOS, Windows, and Unix systems. + + git clone https://github.com/libsdl-org/SDL + +If you are building SDL via configure, you will need to run autogen.sh +before running configure. + +There is a web interface to the Git repository at: + http://github.com/libsdl-org/SDL/ + diff --git a/docs/README-hg.md b/docs/README-hg.md index bd4e67263..b42aaa5b2 100644 --- a/docs/README-hg.md +++ b/docs/README-hg.md @@ -1,7 +1,7 @@ -Mercurial -====== - -We are no longer hosted in Mercurial. Please see README-git.md for details. - -Thanks! - +Mercurial +====== + +We are no longer hosted in Mercurial. Please see README-git.md for details. + +Thanks! + diff --git a/docs/README-highdpi.md b/docs/README-highdpi.md index 6c3d51480..fd28575dd 100644 --- a/docs/README-highdpi.md +++ b/docs/README-highdpi.md @@ -1,8 +1,8 @@ - -SDL 3.0 has new support for high DPI displays - -Displays now have a content display scale, which is the expected scale for content based on the DPI settings of the display. For example, a 4K display might have a 2.0 (200%) display scale, which means that the user expects UI elements to be twice as big on this display, to aid in readability. You can query the display content scale using `SDL_GetDisplayContentScale()`, and when this changes you get an `SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED` event. - -The window size is now distinct from the window pixel size, and the ratio between the two is the window pixel density. If the window is created with the `SDL_WINDOW_HIGH_PIXEL_DENSITY` flag, SDL will try to match the native pixel density for the display, otherwise it will try to have the pixel size match the window size. You can query the window pixel density using `SDL_GetWindowPixelDensity()`. You can query the window pixel size using `SDL_GetWindowSizeInPixels()`, and when this changes you get an `SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED` event. You are guaranteed to get a `SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED` event when a window is created and resized, and you can use this event to create and resize your graphics context for the window. - -The window has a display scale, which is the scale from the pixel resolution to the desired content size, e.g. the combination of the pixel density and the content scale. For example, a 3840x2160 window displayed at 200% on Windows, and a 1920x1080 window with the high density flag on a 2x display on macOS will both have a pixel size of 3840x2160 and a display scale of 2.0. You can query the window display scale using `SDL_GetWindowDisplayScale()`, and when this changes you get an `SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED` event. + +SDL 3.0 has new support for high DPI displays + +Displays now have a content display scale, which is the expected scale for content based on the DPI settings of the display. For example, a 4K display might have a 2.0 (200%) display scale, which means that the user expects UI elements to be twice as big on this display, to aid in readability. You can query the display content scale using `SDL_GetDisplayContentScale()`, and when this changes you get an `SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED` event. + +The window size is now distinct from the window pixel size, and the ratio between the two is the window pixel density. If the window is created with the `SDL_WINDOW_HIGH_PIXEL_DENSITY` flag, SDL will try to match the native pixel density for the display, otherwise it will try to have the pixel size match the window size. You can query the window pixel density using `SDL_GetWindowPixelDensity()`. You can query the window pixel size using `SDL_GetWindowSizeInPixels()`, and when this changes you get an `SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED` event. You are guaranteed to get a `SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED` event when a window is created and resized, and you can use this event to create and resize your graphics context for the window. + +The window has a display scale, which is the scale from the pixel resolution to the desired content size, e.g. the combination of the pixel density and the content scale. For example, a 3840x2160 window displayed at 200% on Windows, and a 1920x1080 window with the high density flag on a 2x display on macOS will both have a pixel size of 3840x2160 and a display scale of 2.0. You can query the window display scale using `SDL_GetWindowDisplayScale()`, and when this changes you get an `SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED` event. diff --git a/docs/README-ios.md b/docs/README-ios.md index 6e48af943..221cb27d6 100644 --- a/docs/README-ios.md +++ b/docs/README-ios.md @@ -1,272 +1,272 @@ -iOS -====== - -Building the Simple DirectMedia Layer for iOS 9.0+ -============================================================================== - -Requirements: macOS 10.9 or later and the iOS 9.0 or newer SDK. - -Instructions: - -1. Open SDL.xcodeproj (located in Xcode/SDL) in Xcode. -2. Select your desired target, and hit build. - - -Using the Simple DirectMedia Layer for iOS -============================================================================== - -1. Run Xcode and create a new project using the iOS Game template, selecting the Objective C language and Metal game technology. -2. In the main view, delete all files except for Assets and LaunchScreen -3. Right click the project in the main view, select "Add Files...", and add the SDL project, Xcode/SDL/SDL.xcodeproj -4. Select the project in the main view, go to the "Info" tab and under "Custom iOS Target Properties" remove the line "Main storyboard file base name" -5. Select the project in the main view, go to the "Build Settings" tab, select "All", and edit "Header Search Path" and drag over the SDL "Public Headers" folder from the left -6. Select the project in the main view, go to the "Build Phases" tab, select "Link Binary With Libraries", and add SDL3.framework from "Framework-iOS" -7. Select the project in the main view, go to the "General" tab, scroll down to "Frameworks, Libraries, and Embedded Content", and select "Embed & Sign" for the SDL library. -8. Add the source files that you would normally have for an SDL program, making sure to have #include "SDL.h" at the top of the file containing your main() function. -9. Add any assets that your application needs. -10. Enjoy! - - -TODO: Add information regarding App Store requirements such as icons, etc. - - -Notes -- Retina / High-DPI and window sizes -============================================================================== - -Window and display mode sizes in SDL are in points rather than in pixels. -On iOS this means that a window created on an iPhone 6 will have a size in -points of 375 x 667, rather than a size in pixels of 750 x 1334. All iOS apps -are expected to size their content based on points rather than pixels, -as this allows different iOS devices to have different pixel densities -(Retina versus non-Retina screens, etc.) without apps caring too much. - -SDL_GetWindowSize() and mouse coordinates are in points rather than pixels, -but the window will have a much greater pixel density when the device supports -it, and the SDL_GetWindowSizeInPixels() can be called to determine the size -in pixels of the drawable screen framebuffer. - -The SDL 2D rendering API will automatically handle this for you, by default -providing a rendering area in points, and you can call SDL_SetRenderLogicalPresentation() -to gain access to the higher density resolution. - -Some OpenGL ES functions such as glViewport expect sizes in pixels rather than -sizes in points. When doing 2D rendering with OpenGL ES, an orthographic projection -matrix using the size in points (SDL_GetWindowSize()) can be used in order to -display content at the same scale no matter whether a Retina device is used or not. - - -Notes -- Application events -============================================================================== - -On iOS the application goes through a fixed life cycle and you will get -notifications of state changes via application events. When these events -are delivered you must handle them in an event callback because the OS may -not give you any processing time after the events are delivered. - -e.g. - - int HandleAppEvents(void *userdata, SDL_Event *event) - { - switch (event->type) - { - case SDL_EVENT_TERMINATING: - /* Terminate the app. - Shut everything down before returning from this function. - */ - return 0; - case SDL_EVENT_LOW_MEMORY: - /* You will get this when your app is paused and iOS wants more memory. - Release as much memory as possible. - */ - return 0; - case SDL_EVENT_WILL_ENTER_BACKGROUND: - /* Prepare your app to go into the background. Stop loops, etc. - This gets called when the user hits the home button, or gets a call. - */ - return 0; - case SDL_EVENT_DID_ENTER_BACKGROUND: - /* This will get called if the user accepted whatever sent your app to the background. - If the user got a phone call and canceled it, you'll instead get an SDL_EVENT_DID_ENTER_FOREGROUND event and restart your loops. - When you get this, you have 5 seconds to save all your state or the app will be terminated. - Your app is NOT active at this point. - */ - return 0; - case SDL_EVENT_WILL_ENTER_FOREGROUND: - /* This call happens when your app is coming back to the foreground. - Restore all your state here. - */ - return 0; - case SDL_EVENT_DID_ENTER_FOREGROUND: - /* Restart your loops here. - Your app is interactive and getting CPU again. - */ - return 0; - default: - /* No special processing, add it to the event queue */ - return 1; - } - } - - int main(int argc, char *argv[]) - { - SDL_SetEventFilter(HandleAppEvents, NULL); - - ... run your main loop - - return 0; - } - - -Notes -- Accelerometer as Joystick -============================================================================== - -SDL for iPhone supports polling the built in accelerometer as a joystick device. For an example on how to do this, see the accelerometer.c in the demos directory. - -The main thing to note when using the accelerometer with SDL is that while the iPhone natively reports accelerometer as floating point values in units of g-force, SDL_GetJoystickAxis() reports joystick values as signed integers. Hence, in order to convert between the two, some clamping and scaling is necessary on the part of the iPhone SDL joystick driver. To convert SDL_GetJoystickAxis() reported values BACK to units of g-force, simply multiply the values by SDL_IPHONE_MAX_GFORCE / 0x7FFF. - - -Notes -- Keyboard -============================================================================== - -The SDL keyboard API has been extended to support on-screen keyboards: - -void SDL_StartTextInput() - -- enables text events and reveals the onscreen keyboard. - -void SDL_StopTextInput() - -- disables text events and hides the onscreen keyboard. - -SDL_bool SDL_TextInputActive() - -- returns whether or not text events are enabled (and the onscreen keyboard is visible) - - -Notes -- Mouse -============================================================================== - -iOS now supports Bluetooth mice on iPad, but by default will provide the mouse input as touch. In order for SDL to see the real mouse events, you should set the key UIApplicationSupportsIndirectInputEvents to true in your Info.plist - - -Notes -- Reading and Writing files -============================================================================== - -Each application installed on iPhone resides in a sandbox which includes its own Application Home directory. Your application may not access files outside this directory. - -Once your application is installed its directory tree looks like: - - MySDLApp Home/ - MySDLApp.app - Documents/ - Library/ - Preferences/ - tmp/ - -When your SDL based iPhone application starts up, it sets the working directory to the main bundle (MySDLApp Home/MySDLApp.app), where your application resources are stored. You cannot write to this directory. Instead, I advise you to write document files to "../Documents/" and preferences to "../Library/Preferences". - -More information on this subject is available here: -http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/Introduction/Introduction.html - - -Notes -- xcFramework -============================================================================== - -The SDL.xcodeproj file now includes a target to build SDL3.xcframework. An xcframework is a new (Xcode 11) uber-framework which can handle any combination of processor type and target OS platform. - -In the past, iOS devices were always an ARM variant processor, and the simulator was always i386 or x86_64, and thus libraries could be combined into a single framework for both simulator and device. With the introduction of the Apple Silicon ARM-based machines, regular frameworks would collide as CPU type was no longer sufficient to differentiate the platform. So Apple created the new xcframework library package. - -The xcframework target builds into a Products directory alongside the SDL.xcodeproj file, as SDL3.xcframework. This can be brought in to any iOS project and will function properly for both simulator and device, no matter their CPUs. Note that Intel Macs cannot cross-compile for Apple Silicon Macs. If you need AS compatibility, perform this build on an Apple Silicon Mac. - -This target requires Xcode 11 or later. The target will simply fail to build if attempted on older Xcodes. - -In addition, on Apple platforms, main() cannot be in a dynamically loaded library. -However, unlike in SDL2, in SDL3 SDL_main is implemented inline in SDL_main.h, so you don't need to link against a static libSDL3main.lib, and you don't need to copy a .c file from the SDL3 source either. -This means that iOS apps which used the statically-linked libSDL3.lib and now link with the xcframwork can just `#include ` in the source file that contains their standard `int main(int argc; char *argv[])` function to get a header-only SDL_main implementation that calls the `SDL_RunApp()` with your standard main function. - -Using an xcFramework is similar to using a regular framework. However, issues have been seen with the build system not seeing the headers in the xcFramework. To remedy this, add the path to the xcFramework in your app's target ==> Build Settings ==> Framework Search Paths and mark it recursive (this is critical). Also critical is to remove "*.framework" from Build Settings ==> Sub-Directories to Exclude in Recursive Searches. Clean the build folder, and on your next build the build system should be able to see any of these in your code, as expected: - -#include "SDL_main.h" -#include -#include - - -Notes -- iPhone SDL limitations -============================================================================== - -Windows: - Full-size, single window applications only. You cannot create multi-window SDL applications for iPhone OS. The application window will fill the display, though you have the option of turning on or off the menu-bar (pass SDL_CreateWindow() the flag SDL_WINDOW_BORDERLESS). - -Textures: - The optimal texture formats on iOS are SDL_PIXELFORMAT_ABGR8888, SDL_PIXELFORMAT_ABGR8888, SDL_PIXELFORMAT_XBGR8888, and SDL_PIXELFORMAT_RGB24 pixel formats. - -Loading Shared Objects: - This is disabled by default since it seems to break the terms of the iOS SDK agreement for iOS versions prior to iOS 8. It can be re-enabled in SDL_config_ios.h. - - -Notes -- CoreBluetooth.framework -============================================================================== - -SDL_JOYSTICK_HIDAPI is disabled by default. It can give you access to a lot -more game controller devices, but it requires permission from the user before -your app will be able to talk to the Bluetooth hardware. "Made For iOS" -branded controllers do not need this as we don't have to speak to them -directly with raw bluetooth, so many apps can live without this. - -You'll need to link with CoreBluetooth.framework and add something like this -to your Info.plist: - -NSBluetoothPeripheralUsageDescription -MyApp would like to remain connected to nearby bluetooth Game Controllers and Game Pads even when you're not using the app. - - -Game Center -============================================================================== - -Game Center integration might require that you break up your main loop in order to yield control back to the system. In other words, instead of running an endless main loop, you run each frame in a callback function, using: - - int SDL_iPhoneSetAnimationCallback(SDL_Window * window, int interval, void (*callback)(void*), void *callbackParam); - -This will set up the given function to be called back on the animation callback, and then you have to return from main() to let the Cocoa event loop run. - -e.g. - - extern "C" - void ShowFrame(void*) - { - ... do event handling, frame logic and rendering ... - } - - int main(int argc, char *argv[]) - { - ... initialize game ... - - #ifdef __IOS__ - // Initialize the Game Center for scoring and matchmaking - InitGameCenter(); - - // Set up the game to run in the window animation callback on iOS - // so that Game Center and so forth works correctly. - SDL_iPhoneSetAnimationCallback(window, 1, ShowFrame, NULL); - #else - while ( running ) { - ShowFrame(0); - DelayFrame(); - } - #endif - return 0; - } - - -Deploying to older versions of iOS -============================================================================== - -SDL supports deploying to older versions of iOS than are supported by the latest version of Xcode, all the way back to iOS 8.0 - -In order to do that you need to download an older version of Xcode: -https://developer.apple.com/download/more/?name=Xcode - -Open the package contents of the older Xcode and your newer version of Xcode and copy over the folders in Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport - -Then open the file Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/SDKSettings.plist and add the versions of iOS you want to deploy to the key Root/DefaultProperties/DEPLOYMENT_TARGET_SUGGESTED_VALUES - -Open your project and set your deployment target to the desired version of iOS - -Finally, remove GameController from the list of frameworks linked by your application and edit the build settings for "Other Linker Flags" and add -weak_framework GameController +iOS +====== + +Building the Simple DirectMedia Layer for iOS 9.0+ +============================================================================== + +Requirements: macOS 10.9 or later and the iOS 9.0 or newer SDK. + +Instructions: + +1. Open SDL.xcodeproj (located in Xcode/SDL) in Xcode. +2. Select your desired target, and hit build. + + +Using the Simple DirectMedia Layer for iOS +============================================================================== + +1. Run Xcode and create a new project using the iOS Game template, selecting the Objective C language and Metal game technology. +2. In the main view, delete all files except for Assets and LaunchScreen +3. Right click the project in the main view, select "Add Files...", and add the SDL project, Xcode/SDL/SDL.xcodeproj +4. Select the project in the main view, go to the "Info" tab and under "Custom iOS Target Properties" remove the line "Main storyboard file base name" +5. Select the project in the main view, go to the "Build Settings" tab, select "All", and edit "Header Search Path" and drag over the SDL "Public Headers" folder from the left +6. Select the project in the main view, go to the "Build Phases" tab, select "Link Binary With Libraries", and add SDL3.framework from "Framework-iOS" +7. Select the project in the main view, go to the "General" tab, scroll down to "Frameworks, Libraries, and Embedded Content", and select "Embed & Sign" for the SDL library. +8. Add the source files that you would normally have for an SDL program, making sure to have #include "SDL.h" at the top of the file containing your main() function. +9. Add any assets that your application needs. +10. Enjoy! + + +TODO: Add information regarding App Store requirements such as icons, etc. + + +Notes -- Retina / High-DPI and window sizes +============================================================================== + +Window and display mode sizes in SDL are in points rather than in pixels. +On iOS this means that a window created on an iPhone 6 will have a size in +points of 375 x 667, rather than a size in pixels of 750 x 1334. All iOS apps +are expected to size their content based on points rather than pixels, +as this allows different iOS devices to have different pixel densities +(Retina versus non-Retina screens, etc.) without apps caring too much. + +SDL_GetWindowSize() and mouse coordinates are in points rather than pixels, +but the window will have a much greater pixel density when the device supports +it, and the SDL_GetWindowSizeInPixels() can be called to determine the size +in pixels of the drawable screen framebuffer. + +The SDL 2D rendering API will automatically handle this for you, by default +providing a rendering area in points, and you can call SDL_SetRenderLogicalPresentation() +to gain access to the higher density resolution. + +Some OpenGL ES functions such as glViewport expect sizes in pixels rather than +sizes in points. When doing 2D rendering with OpenGL ES, an orthographic projection +matrix using the size in points (SDL_GetWindowSize()) can be used in order to +display content at the same scale no matter whether a Retina device is used or not. + + +Notes -- Application events +============================================================================== + +On iOS the application goes through a fixed life cycle and you will get +notifications of state changes via application events. When these events +are delivered you must handle them in an event callback because the OS may +not give you any processing time after the events are delivered. + +e.g. + + int HandleAppEvents(void *userdata, SDL_Event *event) + { + switch (event->type) + { + case SDL_EVENT_TERMINATING: + /* Terminate the app. + Shut everything down before returning from this function. + */ + return 0; + case SDL_EVENT_LOW_MEMORY: + /* You will get this when your app is paused and iOS wants more memory. + Release as much memory as possible. + */ + return 0; + case SDL_EVENT_WILL_ENTER_BACKGROUND: + /* Prepare your app to go into the background. Stop loops, etc. + This gets called when the user hits the home button, or gets a call. + */ + return 0; + case SDL_EVENT_DID_ENTER_BACKGROUND: + /* This will get called if the user accepted whatever sent your app to the background. + If the user got a phone call and canceled it, you'll instead get an SDL_EVENT_DID_ENTER_FOREGROUND event and restart your loops. + When you get this, you have 5 seconds to save all your state or the app will be terminated. + Your app is NOT active at this point. + */ + return 0; + case SDL_EVENT_WILL_ENTER_FOREGROUND: + /* This call happens when your app is coming back to the foreground. + Restore all your state here. + */ + return 0; + case SDL_EVENT_DID_ENTER_FOREGROUND: + /* Restart your loops here. + Your app is interactive and getting CPU again. + */ + return 0; + default: + /* No special processing, add it to the event queue */ + return 1; + } + } + + int main(int argc, char *argv[]) + { + SDL_SetEventFilter(HandleAppEvents, NULL); + + ... run your main loop + + return 0; + } + + +Notes -- Accelerometer as Joystick +============================================================================== + +SDL for iPhone supports polling the built in accelerometer as a joystick device. For an example on how to do this, see the accelerometer.c in the demos directory. + +The main thing to note when using the accelerometer with SDL is that while the iPhone natively reports accelerometer as floating point values in units of g-force, SDL_GetJoystickAxis() reports joystick values as signed integers. Hence, in order to convert between the two, some clamping and scaling is necessary on the part of the iPhone SDL joystick driver. To convert SDL_GetJoystickAxis() reported values BACK to units of g-force, simply multiply the values by SDL_IPHONE_MAX_GFORCE / 0x7FFF. + + +Notes -- Keyboard +============================================================================== + +The SDL keyboard API has been extended to support on-screen keyboards: + +void SDL_StartTextInput() + -- enables text events and reveals the onscreen keyboard. + +void SDL_StopTextInput() + -- disables text events and hides the onscreen keyboard. + +SDL_bool SDL_TextInputActive() + -- returns whether or not text events are enabled (and the onscreen keyboard is visible) + + +Notes -- Mouse +============================================================================== + +iOS now supports Bluetooth mice on iPad, but by default will provide the mouse input as touch. In order for SDL to see the real mouse events, you should set the key UIApplicationSupportsIndirectInputEvents to true in your Info.plist + + +Notes -- Reading and Writing files +============================================================================== + +Each application installed on iPhone resides in a sandbox which includes its own Application Home directory. Your application may not access files outside this directory. + +Once your application is installed its directory tree looks like: + + MySDLApp Home/ + MySDLApp.app + Documents/ + Library/ + Preferences/ + tmp/ + +When your SDL based iPhone application starts up, it sets the working directory to the main bundle (MySDLApp Home/MySDLApp.app), where your application resources are stored. You cannot write to this directory. Instead, I advise you to write document files to "../Documents/" and preferences to "../Library/Preferences". + +More information on this subject is available here: +http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/Introduction/Introduction.html + + +Notes -- xcFramework +============================================================================== + +The SDL.xcodeproj file now includes a target to build SDL3.xcframework. An xcframework is a new (Xcode 11) uber-framework which can handle any combination of processor type and target OS platform. + +In the past, iOS devices were always an ARM variant processor, and the simulator was always i386 or x86_64, and thus libraries could be combined into a single framework for both simulator and device. With the introduction of the Apple Silicon ARM-based machines, regular frameworks would collide as CPU type was no longer sufficient to differentiate the platform. So Apple created the new xcframework library package. + +The xcframework target builds into a Products directory alongside the SDL.xcodeproj file, as SDL3.xcframework. This can be brought in to any iOS project and will function properly for both simulator and device, no matter their CPUs. Note that Intel Macs cannot cross-compile for Apple Silicon Macs. If you need AS compatibility, perform this build on an Apple Silicon Mac. + +This target requires Xcode 11 or later. The target will simply fail to build if attempted on older Xcodes. + +In addition, on Apple platforms, main() cannot be in a dynamically loaded library. +However, unlike in SDL2, in SDL3 SDL_main is implemented inline in SDL_main.h, so you don't need to link against a static libSDL3main.lib, and you don't need to copy a .c file from the SDL3 source either. +This means that iOS apps which used the statically-linked libSDL3.lib and now link with the xcframwork can just `#include ` in the source file that contains their standard `int main(int argc; char *argv[])` function to get a header-only SDL_main implementation that calls the `SDL_RunApp()` with your standard main function. + +Using an xcFramework is similar to using a regular framework. However, issues have been seen with the build system not seeing the headers in the xcFramework. To remedy this, add the path to the xcFramework in your app's target ==> Build Settings ==> Framework Search Paths and mark it recursive (this is critical). Also critical is to remove "*.framework" from Build Settings ==> Sub-Directories to Exclude in Recursive Searches. Clean the build folder, and on your next build the build system should be able to see any of these in your code, as expected: + +#include "SDL_main.h" +#include +#include + + +Notes -- iPhone SDL limitations +============================================================================== + +Windows: + Full-size, single window applications only. You cannot create multi-window SDL applications for iPhone OS. The application window will fill the display, though you have the option of turning on or off the menu-bar (pass SDL_CreateWindow() the flag SDL_WINDOW_BORDERLESS). + +Textures: + The optimal texture formats on iOS are SDL_PIXELFORMAT_ABGR8888, SDL_PIXELFORMAT_ABGR8888, SDL_PIXELFORMAT_XBGR8888, and SDL_PIXELFORMAT_RGB24 pixel formats. + +Loading Shared Objects: + This is disabled by default since it seems to break the terms of the iOS SDK agreement for iOS versions prior to iOS 8. It can be re-enabled in SDL_config_ios.h. + + +Notes -- CoreBluetooth.framework +============================================================================== + +SDL_JOYSTICK_HIDAPI is disabled by default. It can give you access to a lot +more game controller devices, but it requires permission from the user before +your app will be able to talk to the Bluetooth hardware. "Made For iOS" +branded controllers do not need this as we don't have to speak to them +directly with raw bluetooth, so many apps can live without this. + +You'll need to link with CoreBluetooth.framework and add something like this +to your Info.plist: + +NSBluetoothPeripheralUsageDescription +MyApp would like to remain connected to nearby bluetooth Game Controllers and Game Pads even when you're not using the app. + + +Game Center +============================================================================== + +Game Center integration might require that you break up your main loop in order to yield control back to the system. In other words, instead of running an endless main loop, you run each frame in a callback function, using: + + int SDL_iPhoneSetAnimationCallback(SDL_Window * window, int interval, void (*callback)(void*), void *callbackParam); + +This will set up the given function to be called back on the animation callback, and then you have to return from main() to let the Cocoa event loop run. + +e.g. + + extern "C" + void ShowFrame(void*) + { + ... do event handling, frame logic and rendering ... + } + + int main(int argc, char *argv[]) + { + ... initialize game ... + + #ifdef __IOS__ + // Initialize the Game Center for scoring and matchmaking + InitGameCenter(); + + // Set up the game to run in the window animation callback on iOS + // so that Game Center and so forth works correctly. + SDL_iPhoneSetAnimationCallback(window, 1, ShowFrame, NULL); + #else + while ( running ) { + ShowFrame(0); + DelayFrame(); + } + #endif + return 0; + } + + +Deploying to older versions of iOS +============================================================================== + +SDL supports deploying to older versions of iOS than are supported by the latest version of Xcode, all the way back to iOS 8.0 + +In order to do that you need to download an older version of Xcode: +https://developer.apple.com/download/more/?name=Xcode + +Open the package contents of the older Xcode and your newer version of Xcode and copy over the folders in Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport + +Then open the file Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/SDKSettings.plist and add the versions of iOS you want to deploy to the key Root/DefaultProperties/DEPLOYMENT_TARGET_SUGGESTED_VALUES + +Open your project and set your deployment target to the desired version of iOS + +Finally, remove GameController from the list of frameworks linked by your application and edit the build settings for "Other Linker Flags" and add -weak_framework GameController diff --git a/docs/README-kmsbsd.md b/docs/README-kmsbsd.md index 1bd6d0fdb..760481707 100644 --- a/docs/README-kmsbsd.md +++ b/docs/README-kmsbsd.md @@ -1,27 +1,27 @@ -KMSDRM on *BSD -================================================== - -KMSDRM is supported on FreeBSD and OpenBSD. DragonFlyBSD works but requires being a root user. NetBSD isn't supported yet because the application will crash when creating the KMSDRM screen. - -WSCONS support has been brought back, but only as an input backend. It will not be brought back as a video backend to ease maintenance. - -OpenBSD note: Note that the video backend assumes that the user has read/write permissions to the /dev/drm* devices. - - -SDL WSCONS input backend features -=================================================== -1. It is keymap-aware; it will work properly with different keymaps. -2. It has mouse support. -3. Accent input is supported. -4. Compose keys are supported. -5. AltGr and Meta Shift keys work as intended. - -Partially working or no input on OpenBSD/NetBSD. -================================================== - -The WSCONS input backend needs read/write access to the /dev/wskbd* devices, without which it will not work properly. /dev/wsmouse must also be read/write accessible, otherwise mouse input will not work. - -Partially working or no input on FreeBSD. -================================================== - -The evdev devices are only accessible to the root user by default. Edit devfs rules to allow access to such devices. The /dev/kbd* devices are also only accessible to the root user by default. Edit devfs rules to allow access to such devices. +KMSDRM on *BSD +================================================== + +KMSDRM is supported on FreeBSD and OpenBSD. DragonFlyBSD works but requires being a root user. NetBSD isn't supported yet because the application will crash when creating the KMSDRM screen. + +WSCONS support has been brought back, but only as an input backend. It will not be brought back as a video backend to ease maintenance. + +OpenBSD note: Note that the video backend assumes that the user has read/write permissions to the /dev/drm* devices. + + +SDL WSCONS input backend features +=================================================== +1. It is keymap-aware; it will work properly with different keymaps. +2. It has mouse support. +3. Accent input is supported. +4. Compose keys are supported. +5. AltGr and Meta Shift keys work as intended. + +Partially working or no input on OpenBSD/NetBSD. +================================================== + +The WSCONS input backend needs read/write access to the /dev/wskbd* devices, without which it will not work properly. /dev/wsmouse must also be read/write accessible, otherwise mouse input will not work. + +Partially working or no input on FreeBSD. +================================================== + +The evdev devices are only accessible to the root user by default. Edit devfs rules to allow access to such devices. The /dev/kbd* devices are also only accessible to the root user by default. Edit devfs rules to allow access to such devices. diff --git a/docs/README-linux.md b/docs/README-linux.md index 768a71252..4ef7b97d6 100644 --- a/docs/README-linux.md +++ b/docs/README-linux.md @@ -1,88 +1,88 @@ -Linux -================================================================================ - -By default SDL will only link against glibc, the rest of the features will be -enabled dynamically at runtime depending on the available features on the target -system. So, for example if you built SDL with XRandR support and the target -system does not have the XRandR libraries installed, it will be disabled -at runtime, and you won't get a missing library error, at least with the -default configuration parameters. - - -Build Dependencies --------------------------------------------------------------------------------- - -Ubuntu 18.04, all available features enabled: - - sudo apt-get install build-essential git make \ - pkg-config cmake ninja-build gnome-desktop-testing libasound2-dev libpulse-dev \ - libaudio-dev libjack-dev libsndio-dev libx11-dev libxext-dev \ - libxrandr-dev libxcursor-dev libxfixes-dev libxi-dev libxss-dev \ - libxkbcommon-dev libdrm-dev libgbm-dev libgl1-mesa-dev libgles2-mesa-dev \ - libegl1-mesa-dev libdbus-1-dev libibus-1.0-dev libudev-dev fcitx-libs-dev - -Ubuntu 22.04+ can also add `libpipewire-0.3-dev libwayland-dev libdecor-0-dev` to that command line. - -Fedora 35, all available features enabled: - - sudo yum install gcc git-core make cmake \ - alsa-lib-devel pulseaudio-libs-devel nas-devel pipewire-devel \ - libX11-devel libXext-devel libXrandr-devel libXcursor-devel libXfixes-devel \ - libXi-devel libXScrnSaver-devel dbus-devel ibus-devel fcitx-devel \ - systemd-devel mesa-libGL-devel libxkbcommon-devel mesa-libGLES-devel \ - mesa-libEGL-devel vulkan-devel wayland-devel wayland-protocols-devel \ - libdrm-devel mesa-libgbm-devel libusb-devel libdecor-devel \ - pipewire-jack-audio-connection-kit-devel \ - -NOTES: -- The sndio audio target is unavailable on Fedora (but probably not what you - should want to use anyhow). - - -Joystick does not work --------------------------------------------------------------------------------- - -If you compiled or are using a version of SDL with udev support (and you should!) -there's a few issues that may cause SDL to fail to detect your joystick. To -debug this, start by installing the evtest utility. On Ubuntu/Debian: - - sudo apt-get install evtest - -Then run: - - sudo evtest - -You'll hopefully see your joystick listed along with a name like "/dev/input/eventXX" -Now run: - - cat /dev/input/event/XX - -If you get a permission error, you need to set a udev rule to change the mode of -your device (see below) - -Also, try: - - sudo udevadm info --query=all --name=input/eventXX - -If you see a line stating ID_INPUT_JOYSTICK=1, great, if you don't see it, -you need to set up an udev rule to force this variable. - -A combined rule for the Saitek Pro Flight Rudder Pedals to fix both issues looks -like: - - SUBSYSTEM=="input", ATTRS{idProduct}=="0763", ATTRS{idVendor}=="06a3", MODE="0666", ENV{ID_INPUT_JOYSTICK}="1" - SUBSYSTEM=="input", ATTRS{idProduct}=="0764", ATTRS{idVendor}=="06a3", MODE="0666", ENV{ID_INPUT_JOYSTICK}="1" - -You can set up similar rules for your device by changing the values listed in -idProduct and idVendor. To obtain these values, try: - - sudo udevadm info -a --name=input/eventXX | grep idVendor - sudo udevadm info -a --name=input/eventXX | grep idProduct - -If multiple values come up for each of these, the one you want is the first one of each. - -On other systems which ship with an older udev (such as CentOS), you may need -to set up a rule such as: - - SUBSYSTEM=="input", ENV{ID_CLASS}=="joystick", ENV{ID_INPUT_JOYSTICK}="1" - +Linux +================================================================================ + +By default SDL will only link against glibc, the rest of the features will be +enabled dynamically at runtime depending on the available features on the target +system. So, for example if you built SDL with XRandR support and the target +system does not have the XRandR libraries installed, it will be disabled +at runtime, and you won't get a missing library error, at least with the +default configuration parameters. + + +Build Dependencies +-------------------------------------------------------------------------------- + +Ubuntu 18.04, all available features enabled: + + sudo apt-get install build-essential git make \ + pkg-config cmake ninja-build gnome-desktop-testing libasound2-dev libpulse-dev \ + libaudio-dev libjack-dev libsndio-dev libx11-dev libxext-dev \ + libxrandr-dev libxcursor-dev libxfixes-dev libxi-dev libxss-dev \ + libxkbcommon-dev libdrm-dev libgbm-dev libgl1-mesa-dev libgles2-mesa-dev \ + libegl1-mesa-dev libdbus-1-dev libibus-1.0-dev libudev-dev fcitx-libs-dev + +Ubuntu 22.04+ can also add `libpipewire-0.3-dev libwayland-dev libdecor-0-dev` to that command line. + +Fedora 35, all available features enabled: + + sudo yum install gcc git-core make cmake \ + alsa-lib-devel pulseaudio-libs-devel nas-devel pipewire-devel \ + libX11-devel libXext-devel libXrandr-devel libXcursor-devel libXfixes-devel \ + libXi-devel libXScrnSaver-devel dbus-devel ibus-devel fcitx-devel \ + systemd-devel mesa-libGL-devel libxkbcommon-devel mesa-libGLES-devel \ + mesa-libEGL-devel vulkan-devel wayland-devel wayland-protocols-devel \ + libdrm-devel mesa-libgbm-devel libusb-devel libdecor-devel \ + pipewire-jack-audio-connection-kit-devel \ + +NOTES: +- The sndio audio target is unavailable on Fedora (but probably not what you + should want to use anyhow). + + +Joystick does not work +-------------------------------------------------------------------------------- + +If you compiled or are using a version of SDL with udev support (and you should!) +there's a few issues that may cause SDL to fail to detect your joystick. To +debug this, start by installing the evtest utility. On Ubuntu/Debian: + + sudo apt-get install evtest + +Then run: + + sudo evtest + +You'll hopefully see your joystick listed along with a name like "/dev/input/eventXX" +Now run: + + cat /dev/input/event/XX + +If you get a permission error, you need to set a udev rule to change the mode of +your device (see below) + +Also, try: + + sudo udevadm info --query=all --name=input/eventXX + +If you see a line stating ID_INPUT_JOYSTICK=1, great, if you don't see it, +you need to set up an udev rule to force this variable. + +A combined rule for the Saitek Pro Flight Rudder Pedals to fix both issues looks +like: + + SUBSYSTEM=="input", ATTRS{idProduct}=="0763", ATTRS{idVendor}=="06a3", MODE="0666", ENV{ID_INPUT_JOYSTICK}="1" + SUBSYSTEM=="input", ATTRS{idProduct}=="0764", ATTRS{idVendor}=="06a3", MODE="0666", ENV{ID_INPUT_JOYSTICK}="1" + +You can set up similar rules for your device by changing the values listed in +idProduct and idVendor. To obtain these values, try: + + sudo udevadm info -a --name=input/eventXX | grep idVendor + sudo udevadm info -a --name=input/eventXX | grep idProduct + +If multiple values come up for each of these, the one you want is the first one of each. + +On other systems which ship with an older udev (such as CentOS), you may need +to set up a rule such as: + + SUBSYSTEM=="input", ENV{ID_CLASS}=="joystick", ENV{ID_INPUT_JOYSTICK}="1" + diff --git a/docs/README-macos.md b/docs/README-macos.md index d66aa4284..832278fa7 100644 --- a/docs/README-macos.md +++ b/docs/README-macos.md @@ -1,252 +1,252 @@ -# macOS - -These instructions are for people using Apple's macOS. - -From the developer's point of view, macOS is a sort of hybrid Mac and -Unix system, and you have the option of using either traditional -command line tools or Apple's IDE Xcode. - -# Command Line Build - -To build SDL using the command line, use the CMake build script: - -```bash -mkdir build -cd build -cmake .. -cmake --build . -sudo cmake --install . -``` - - -You can also build SDL as a Universal library (a single binary for both -64-bit Intel and ARM architectures): - -```bash -mkdir build -cd build -cmake .. "-DCMAKE_OSX_ARCHITECTURES=arm64;x86_64" -cmake --build . -sudo cmake --install . -``` - -Please note that building SDL requires at least Xcode 6 and the 10.9 SDK. -PowerPC support for macOS has been officially dropped as of SDL 2.0.2. -32-bit Intel and macOS 10.8 runtime support has been officially dropped as -of SDL 2.24.0. - -To use the library once it's built, you essential have two possibilities: -use the traditional autoconf/automake/make method, or use Xcode. - - -# Caveats for using SDL with macOS - -If you register your own NSApplicationDelegate (using [NSApp setDelegate:]), -SDL will not register its own. This means that SDL will not terminate using -SDL_Quit if it receives a termination request, it will terminate like a -normal app, and it will not send a SDL_EVENT_DROP_FILE when you request to open a -file with the app. To solve these issues, put the following code in your -NSApplicationDelegate implementation: - - -```objc -- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender -{ - if (SDL_GetEventState(SDL_EVENT_QUIT) == SDL_ENABLE) { - SDL_Event event; - event.type = SDL_EVENT_QUIT; - SDL_PushEvent(&event); - } - - return NSTerminateCancel; -} - -- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename -{ - if (SDL_GetEventState(SDL_EVENT_DROP_FILE) == SDL_ENABLE) { - SDL_Event event; - event.type = SDL_EVENT_DROP_FILE; - event.drop.file = SDL_strdup([filename UTF8String]); - return (SDL_PushEvent(&event) > 0); - } - - return NO; -} -``` - -# Using the Simple DirectMedia Layer with a traditional Makefile - -An existing build system for your SDL app has good chances to work almost -unchanged on macOS, as long as you link with the SDL framework. However, -to produce a "real" Mac binary that you can distribute to users, you need -to put the generated binary into a so called "bundle", which is basically -a fancy folder with a name like "MyCoolGame.app". - -To get this build automatically, add something like the following rule to -your Makefile.am: - -```make -bundle_contents = APP_NAME.app/Contents -APP_NAME_bundle: EXE_NAME - mkdir -p $(bundle_contents)/MacOS - mkdir -p $(bundle_contents)/Resources - echo "APPL????" > $(bundle_contents)/PkgInfo - $(INSTALL_PROGRAM) $< $(bundle_contents)/MacOS/ -``` - -You should replace `EXE_NAME` with the name of the executable. `APP_NAME` is -what will be visible to the user in the Finder. Usually it will be the same -as `EXE_NAME` but capitalized. E.g. if `EXE_NAME` is "testgame" then `APP_NAME` -usually is "TestGame". You might also want to use `@PACKAGE@` to use the -package name as specified in your configure.ac file. - -If your project builds more than one application, you will have to do a bit -more. For each of your target applications, you need a separate rule. - -If you want the created bundles to be installed, you may want to add this -rule to your Makefile.am: - -```make -install-exec-hook: APP_NAME_bundle - rm -rf $(DESTDIR)$(prefix)/Applications/APP_NAME.app - mkdir -p $(DESTDIR)$(prefix)/Applications/ - cp -r $< /$(DESTDIR)$(prefix)Applications/ -``` - -This rule takes the Bundle created by the rule from step 3 and installs them -into "$(DESTDIR)$(prefix)/Applications/". - -Again, if you want to install multiple applications, you will have to augment -the make rule accordingly. - -But beware! That is only part of the story! With the above, you end up with -a barebones .app bundle, which is double-clickable from the Finder. But -there are some more things you should do before shipping your product... - -1. You'll need to copy the SDL framework into the Contents/Frameworks - folder in your bundle, so it is included along with your application. - -2. Add an 'Info.plist' to your application. That is a special XML file which - contains some meta-information about your application (like some copyright - information, the version of your app, the name of an optional icon file, - and other things). Part of that information is displayed by the Finder - when you click on the .app, or if you look at the "Get Info" window. - More information about Info.plist files can be found on Apple's homepage. - - -As a final remark, let me add that I use some of the techniques (and some -variations of them) in [Exult](https://github.com/exult/exult) and -[ScummVM](https://github.com/scummvm/scummvm); both are available in source on -the net, so feel free to take a peek at them for inspiration! - - -# Using the Simple DirectMedia Layer with Xcode - -These instructions are for using Apple's Xcode IDE to build SDL applications. - -## First steps - -The first thing to do is to unpack the Xcode.tar.gz archive in the -top level SDL directory (where the Xcode.tar.gz archive resides). -Because Stuffit Expander will unpack the archive into a subdirectory, -you should unpack the archive manually from the command line: - -```bash -cd [path_to_SDL_source] -tar zxf Xcode.tar.gz -``` - -This will create a new folder called Xcode, which you can browse -normally from the Finder. - -## Building the Framework - -The SDL Library is packaged as a framework bundle, an organized -relocatable folder hierarchy of executable code, interface headers, -and additional resources. For practical purposes, you can think of a -framework as a more user and system-friendly shared library, whose library -file behaves more or less like a standard UNIX shared library. - -To build the framework, simply open the framework project and build it. -By default, the framework bundle "SDL.framework" is installed in -/Library/Frameworks. Therefore, the testers and project stationary expect -it to be located there. However, it will function the same in any of the -following locations: - -* ~/Library/Frameworks -* /Local/Library/Frameworks -* /System/Library/Frameworks - -## Build Options - -There are two "Build Styles" (See the "Targets" tab) for SDL. -"Deployment" should be used if you aren't tweaking the SDL library. -"Development" should be used to debug SDL apps or the library itself. - -## Building the Testers - -Open the SDLTest project and build away! - -## Using the Project Stationary - -Copy the stationary to the indicated folders to access it from -the "New Project" and "Add target" menus. What could be easier? - -## Setting up a new project by hand - -Some of you won't want to use the Stationary so I'll give some tips: - -(this is accurate as of Xcode 12.5.) - -* Click "File" -> "New" -> "Project... -* Choose "macOS" and then "App" from the "Application" section. -* Fill out the options in the next window. User interface is "XIB" and - Language is "Objective-C". -* Remove "main.m" from your project -* Remove "MainMenu.xib" from your project -* Remove "AppDelegates.*" from your project -* Add "\$(HOME)/Library/Frameworks/SDL.framework/Headers" to include path -* Add "\$(HOME)/Library/Frameworks" to the frameworks search path -* Add "-framework SDL -framework Foundation -framework AppKit" to "OTHER_LDFLAGS" -* Add your files -* Clean and build - -## Building from command line - -Use `xcode-build` in the same directory as your .pbxproj file - -## Running your app - -You can send command line args to your app by either invoking it from -the command line (in *.app/Contents/MacOS) or by entering them in the -Executables" panel of the target settings. - -# Implementation Notes - -Some things that may be of interest about how it all works... - -## Working directory - -In SDL 1.2, the working directory of your SDL app is by default set to its -parent, but this is no longer the case in SDL 2.0. SDL2 does change the -working directory, which means it'll be whatever the command line prompt -that launched the program was using, or if launched by double-clicking in -the finger, it will be "/", the _root of the filesystem_. Plan accordingly! -You can use SDL_GetBasePath() to find where the program is running from and -chdir() there directly. - - -## You have a Cocoa App! - -Your SDL app is essentially a Cocoa application. When your app -starts up and the libraries finish loading, a Cocoa procedure is called, -which sets up the working directory and calls your main() method. -You are free to modify your Cocoa app with generally no consequence -to SDL. You cannot, however, easily change the SDL window itself. -Functionality may be added in the future to help this. - -# Bug reports - -Bugs are tracked at [the GitHub issue tracker](https://github.com/libsdl-org/SDL/issues/). -Please feel free to report bugs there! - +# macOS + +These instructions are for people using Apple's macOS. + +From the developer's point of view, macOS is a sort of hybrid Mac and +Unix system, and you have the option of using either traditional +command line tools or Apple's IDE Xcode. + +# Command Line Build + +To build SDL using the command line, use the CMake build script: + +```bash +mkdir build +cd build +cmake .. +cmake --build . +sudo cmake --install . +``` + + +You can also build SDL as a Universal library (a single binary for both +64-bit Intel and ARM architectures): + +```bash +mkdir build +cd build +cmake .. "-DCMAKE_OSX_ARCHITECTURES=arm64;x86_64" +cmake --build . +sudo cmake --install . +``` + +Please note that building SDL requires at least Xcode 6 and the 10.9 SDK. +PowerPC support for macOS has been officially dropped as of SDL 2.0.2. +32-bit Intel and macOS 10.8 runtime support has been officially dropped as +of SDL 2.24.0. + +To use the library once it's built, you essential have two possibilities: +use the traditional autoconf/automake/make method, or use Xcode. + + +# Caveats for using SDL with macOS + +If you register your own NSApplicationDelegate (using [NSApp setDelegate:]), +SDL will not register its own. This means that SDL will not terminate using +SDL_Quit if it receives a termination request, it will terminate like a +normal app, and it will not send a SDL_EVENT_DROP_FILE when you request to open a +file with the app. To solve these issues, put the following code in your +NSApplicationDelegate implementation: + + +```objc +- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender +{ + if (SDL_GetEventState(SDL_EVENT_QUIT) == SDL_ENABLE) { + SDL_Event event; + event.type = SDL_EVENT_QUIT; + SDL_PushEvent(&event); + } + + return NSTerminateCancel; +} + +- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename +{ + if (SDL_GetEventState(SDL_EVENT_DROP_FILE) == SDL_ENABLE) { + SDL_Event event; + event.type = SDL_EVENT_DROP_FILE; + event.drop.file = SDL_strdup([filename UTF8String]); + return (SDL_PushEvent(&event) > 0); + } + + return NO; +} +``` + +# Using the Simple DirectMedia Layer with a traditional Makefile + +An existing build system for your SDL app has good chances to work almost +unchanged on macOS, as long as you link with the SDL framework. However, +to produce a "real" Mac binary that you can distribute to users, you need +to put the generated binary into a so called "bundle", which is basically +a fancy folder with a name like "MyCoolGame.app". + +To get this build automatically, add something like the following rule to +your Makefile.am: + +```make +bundle_contents = APP_NAME.app/Contents +APP_NAME_bundle: EXE_NAME + mkdir -p $(bundle_contents)/MacOS + mkdir -p $(bundle_contents)/Resources + echo "APPL????" > $(bundle_contents)/PkgInfo + $(INSTALL_PROGRAM) $< $(bundle_contents)/MacOS/ +``` + +You should replace `EXE_NAME` with the name of the executable. `APP_NAME` is +what will be visible to the user in the Finder. Usually it will be the same +as `EXE_NAME` but capitalized. E.g. if `EXE_NAME` is "testgame" then `APP_NAME` +usually is "TestGame". You might also want to use `@PACKAGE@` to use the +package name as specified in your configure.ac file. + +If your project builds more than one application, you will have to do a bit +more. For each of your target applications, you need a separate rule. + +If you want the created bundles to be installed, you may want to add this +rule to your Makefile.am: + +```make +install-exec-hook: APP_NAME_bundle + rm -rf $(DESTDIR)$(prefix)/Applications/APP_NAME.app + mkdir -p $(DESTDIR)$(prefix)/Applications/ + cp -r $< /$(DESTDIR)$(prefix)Applications/ +``` + +This rule takes the Bundle created by the rule from step 3 and installs them +into "$(DESTDIR)$(prefix)/Applications/". + +Again, if you want to install multiple applications, you will have to augment +the make rule accordingly. + +But beware! That is only part of the story! With the above, you end up with +a barebones .app bundle, which is double-clickable from the Finder. But +there are some more things you should do before shipping your product... + +1. You'll need to copy the SDL framework into the Contents/Frameworks + folder in your bundle, so it is included along with your application. + +2. Add an 'Info.plist' to your application. That is a special XML file which + contains some meta-information about your application (like some copyright + information, the version of your app, the name of an optional icon file, + and other things). Part of that information is displayed by the Finder + when you click on the .app, or if you look at the "Get Info" window. + More information about Info.plist files can be found on Apple's homepage. + + +As a final remark, let me add that I use some of the techniques (and some +variations of them) in [Exult](https://github.com/exult/exult) and +[ScummVM](https://github.com/scummvm/scummvm); both are available in source on +the net, so feel free to take a peek at them for inspiration! + + +# Using the Simple DirectMedia Layer with Xcode + +These instructions are for using Apple's Xcode IDE to build SDL applications. + +## First steps + +The first thing to do is to unpack the Xcode.tar.gz archive in the +top level SDL directory (where the Xcode.tar.gz archive resides). +Because Stuffit Expander will unpack the archive into a subdirectory, +you should unpack the archive manually from the command line: + +```bash +cd [path_to_SDL_source] +tar zxf Xcode.tar.gz +``` + +This will create a new folder called Xcode, which you can browse +normally from the Finder. + +## Building the Framework + +The SDL Library is packaged as a framework bundle, an organized +relocatable folder hierarchy of executable code, interface headers, +and additional resources. For practical purposes, you can think of a +framework as a more user and system-friendly shared library, whose library +file behaves more or less like a standard UNIX shared library. + +To build the framework, simply open the framework project and build it. +By default, the framework bundle "SDL.framework" is installed in +/Library/Frameworks. Therefore, the testers and project stationary expect +it to be located there. However, it will function the same in any of the +following locations: + +* ~/Library/Frameworks +* /Local/Library/Frameworks +* /System/Library/Frameworks + +## Build Options + +There are two "Build Styles" (See the "Targets" tab) for SDL. +"Deployment" should be used if you aren't tweaking the SDL library. +"Development" should be used to debug SDL apps or the library itself. + +## Building the Testers + +Open the SDLTest project and build away! + +## Using the Project Stationary + +Copy the stationary to the indicated folders to access it from +the "New Project" and "Add target" menus. What could be easier? + +## Setting up a new project by hand + +Some of you won't want to use the Stationary so I'll give some tips: + +(this is accurate as of Xcode 12.5.) + +* Click "File" -> "New" -> "Project... +* Choose "macOS" and then "App" from the "Application" section. +* Fill out the options in the next window. User interface is "XIB" and + Language is "Objective-C". +* Remove "main.m" from your project +* Remove "MainMenu.xib" from your project +* Remove "AppDelegates.*" from your project +* Add "\$(HOME)/Library/Frameworks/SDL.framework/Headers" to include path +* Add "\$(HOME)/Library/Frameworks" to the frameworks search path +* Add "-framework SDL -framework Foundation -framework AppKit" to "OTHER_LDFLAGS" +* Add your files +* Clean and build + +## Building from command line + +Use `xcode-build` in the same directory as your .pbxproj file + +## Running your app + +You can send command line args to your app by either invoking it from +the command line (in *.app/Contents/MacOS) or by entering them in the +Executables" panel of the target settings. + +# Implementation Notes + +Some things that may be of interest about how it all works... + +## Working directory + +In SDL 1.2, the working directory of your SDL app is by default set to its +parent, but this is no longer the case in SDL 2.0. SDL2 does change the +working directory, which means it'll be whatever the command line prompt +that launched the program was using, or if launched by double-clicking in +the finger, it will be "/", the _root of the filesystem_. Plan accordingly! +You can use SDL_GetBasePath() to find where the program is running from and +chdir() there directly. + + +## You have a Cocoa App! + +Your SDL app is essentially a Cocoa application. When your app +starts up and the libraries finish loading, a Cocoa procedure is called, +which sets up the working directory and calls your main() method. +You are free to modify your Cocoa app with generally no consequence +to SDL. You cannot, however, easily change the SDL window itself. +Functionality may be added in the future to help this. + +# Bug reports + +Bugs are tracked at [the GitHub issue tracker](https://github.com/libsdl-org/SDL/issues/). +Please feel free to report bugs there! + diff --git a/docs/README-main-functions.md b/docs/README-main-functions.md index 072bf826d..40908bfdd 100644 --- a/docs/README-main-functions.md +++ b/docs/README-main-functions.md @@ -1,194 +1,194 @@ -# Where an SDL program starts running. - -## History - -SDL has a long, complicated history with starting a program. - -In most of the civilized world, an application starts in a C-callable -function named "main". You probably learned it a long time ago: - -```c -int main(int argc, char **argv) -{ - printf("Hello world!\n"); - return 0; -} -``` - -But not all platforms work like this. Windows apps might want a different -function named "WinMain", for example, so SDL set out to paper over this -difference. - -Generally how this would work is: your app would always use the "standard" -`main(argc, argv)` function as its entry point, and `#include` the proper -SDL header before that, which did some macro magic. On platforms that used -a standard `main`, it would do nothing and what you saw was what you got. - -But those other platforms! If they needed something that _wasn't_ `main`, -SDL's macro magic would quietly rename your function to `SDL_main`, and -provide its own entry point that called it. Your app was none the wiser and -your code worked everywhere without changes. - - -## The main entry point in SDL3 - -Previous versions of SDL had a static library, SDLmain, that you would link -your app against. SDL3 still has the same macro tricks, but the static library -is gone. Now it's supplied by a "single-header library," which means you -`#include ` and that header will insert a small amount of -code into the source file that included it, so you no longer have to worry -about linking against an extra library that you might need on some platforms. -You just build your app and it works. - -You should _only_ include SDL_main.h from one file (the umbrella header, -SDL.h, does _not_ include it), and know that it will `#define main` to -something else, so if you use this symbol elsewhere as a variable name, etc, -it can cause you unexpected problems. - -SDL_main.h will also include platform-specific code (WinMain or whatnot) that -calls your _actual_ main function. This is compiled directly into your -program. - -If for some reason you need to include SDL_main.h in a file but also _don't_ -want it to generate this platform-specific code, you should define a special -macro before includin the header: - - -```c -#define SDL_MAIN_NOIMPL -``` - -If you are moving from SDL2, remove any references to the SDLmain static -library from your build system, and you should be done. Things should work as -they always have. - -If you have never controlled your process's entry point (you are using SDL -as a module from a general-purpose scripting language interpreter, or you're -using SDL in a plugin for some otherwise-unrelated app), then there is nothing -required of you here; there is no startup code in SDL's entry point code that -is required, so using SDL_main.h is completely optional. Just start using -the SDL API when you are ready. - - -## Main callbacks in SDL3 - -There is a second option in SDL3 for how to structure your program. This is -completely optional and you can ignore it if you're happy using a standard -"main" function. - -Some platforms would rather your program operate in chunks. Most of the time, -games tend to look like this at the highest level: - -```c -int main(int argc, char **argv) -{ - initialize(); - while (keep_running()) { - handle_new_events(); - do_one_frame_of_stuff(); - } - deinitialize(); -} -``` - -There are platforms that would rather be in charge of that `while` loop: -iOS would rather you return from main() immediately and then it will let you -know that it's time to update and draw the next frame of video. Emscripten -(programs that run on a web page) absolutely requires this to function at all. -Video targets like Wayland can notify the app when to draw a new frame, to -save battery life and cooperate with the compositor more closely. - -In most cases, you can add special-case code to your program to deal with this -on different platforms, but SDL3 offers a system to handle this transparently on -the app's behalf. - -To use this, you have to redesign the highest level of your app a little. Once -you do, it'll work on all supported SDL platforms without problems and -`#ifdef`s in your code. - -Instead of providing a "main" function, under this system, you would provide -several functions that SDL will call as appropriate. - -Using the callback entry points works on every platform, because on platforms -that don't require them, we can fake them with a simple loop in an internal -implementation of the usual SDL_main. - -The primary way we expect people to write SDL apps is still with SDL_main, and -this is not intended to replace it. If the app chooses to use this, it just -removes some platform-specific details they might have to otherwise manage, -and maybe removes a barrier to entry on some future platform. And you might -find you enjoy structuring your program like this more! - - -## How to use main callbacks in SDL3 - -To enable the callback entry points, you include SDL_main.h with an extra define, -from a single source file in your project: - -```c -#define SDL_MAIN_USE_CALLBACKS -#include -``` - -Once you do this, you do not write a "main" function at all (and if you do, -the app will likely fail to link). Instead, you provide the following -functions: - -First: - -```c -int SDL_AppInit(int argc, char **argv); -``` - -This will be called _once_ before anything else. argc/argv work like they -always do. If this returns 0, the app runs. If it returns < 0, the app calls -SDL_AppQuit and terminates with an exit code that reports an error to the -platform. If it returns > 0, the app calls SDL_AppQuit and terminates with -an exit code that reports success to the platform. This function should not -go into an infinite mainloop; it should do any one-time startup it requires -and then return. - -Then: - -```c -int SDL_AppIterate(void); -``` - -This is called over and over, possibly at the refresh rate of the display or -some other metric that the platform dictates. This is where the heart of your -app runs. It should return as quickly as reasonably possible, but it's not a -"run one memcpy and that's all the time you have" sort of thing. The app -should do any game updates, and render a frame of video. If it returns < 0, -SDL will call SDL_AppQuit and terminate the process with an exit code that -reports an error to the platform. If it returns > 0, the app calls -SDL_AppQuit and terminates with an exit code that reports success to the -platform. If it returns 0, then SDL_AppIterate will be called again at some -regular frequency. The platform may choose to run this more or less (perhaps -less in the background, etc), or it might just call this function in a loop -as fast as possible. You do not check the event queue in this function -(SDL_AppEvent exists for that). - -Next: - -```c -int SDL_AppEvent(const SDL_Event *event); -``` - -This will be called whenever an SDL event arrives, on the thread that runs -SDL_AppIterate. Your app should also not call SDL_PollEvent, SDL_PumpEvent, -etc, as SDL will manage all this for you. Return values are the same as from -SDL_AppIterate(), so you can terminate in response to SDL_EVENT_QUIT, etc. - - -Finally: - -```c -void SDL_AppQuit(void); -``` - -This is called once before terminating the app--assuming the app isn't being -forcibly killed or crashed--as a last chance to clean up. After this returns, -SDL will call SDL_Quit so the app doesn't have to (but it's safe for the app -to call it, too). Process termination proceeds as if the app returned normally -from main(), so atexit handles will run, if your platform supports that. - +# Where an SDL program starts running. + +## History + +SDL has a long, complicated history with starting a program. + +In most of the civilized world, an application starts in a C-callable +function named "main". You probably learned it a long time ago: + +```c +int main(int argc, char **argv) +{ + printf("Hello world!\n"); + return 0; +} +``` + +But not all platforms work like this. Windows apps might want a different +function named "WinMain", for example, so SDL set out to paper over this +difference. + +Generally how this would work is: your app would always use the "standard" +`main(argc, argv)` function as its entry point, and `#include` the proper +SDL header before that, which did some macro magic. On platforms that used +a standard `main`, it would do nothing and what you saw was what you got. + +But those other platforms! If they needed something that _wasn't_ `main`, +SDL's macro magic would quietly rename your function to `SDL_main`, and +provide its own entry point that called it. Your app was none the wiser and +your code worked everywhere without changes. + + +## The main entry point in SDL3 + +Previous versions of SDL had a static library, SDLmain, that you would link +your app against. SDL3 still has the same macro tricks, but the static library +is gone. Now it's supplied by a "single-header library," which means you +`#include ` and that header will insert a small amount of +code into the source file that included it, so you no longer have to worry +about linking against an extra library that you might need on some platforms. +You just build your app and it works. + +You should _only_ include SDL_main.h from one file (the umbrella header, +SDL.h, does _not_ include it), and know that it will `#define main` to +something else, so if you use this symbol elsewhere as a variable name, etc, +it can cause you unexpected problems. + +SDL_main.h will also include platform-specific code (WinMain or whatnot) that +calls your _actual_ main function. This is compiled directly into your +program. + +If for some reason you need to include SDL_main.h in a file but also _don't_ +want it to generate this platform-specific code, you should define a special +macro before includin the header: + + +```c +#define SDL_MAIN_NOIMPL +``` + +If you are moving from SDL2, remove any references to the SDLmain static +library from your build system, and you should be done. Things should work as +they always have. + +If you have never controlled your process's entry point (you are using SDL +as a module from a general-purpose scripting language interpreter, or you're +using SDL in a plugin for some otherwise-unrelated app), then there is nothing +required of you here; there is no startup code in SDL's entry point code that +is required, so using SDL_main.h is completely optional. Just start using +the SDL API when you are ready. + + +## Main callbacks in SDL3 + +There is a second option in SDL3 for how to structure your program. This is +completely optional and you can ignore it if you're happy using a standard +"main" function. + +Some platforms would rather your program operate in chunks. Most of the time, +games tend to look like this at the highest level: + +```c +int main(int argc, char **argv) +{ + initialize(); + while (keep_running()) { + handle_new_events(); + do_one_frame_of_stuff(); + } + deinitialize(); +} +``` + +There are platforms that would rather be in charge of that `while` loop: +iOS would rather you return from main() immediately and then it will let you +know that it's time to update and draw the next frame of video. Emscripten +(programs that run on a web page) absolutely requires this to function at all. +Video targets like Wayland can notify the app when to draw a new frame, to +save battery life and cooperate with the compositor more closely. + +In most cases, you can add special-case code to your program to deal with this +on different platforms, but SDL3 offers a system to handle this transparently on +the app's behalf. + +To use this, you have to redesign the highest level of your app a little. Once +you do, it'll work on all supported SDL platforms without problems and +`#ifdef`s in your code. + +Instead of providing a "main" function, under this system, you would provide +several functions that SDL will call as appropriate. + +Using the callback entry points works on every platform, because on platforms +that don't require them, we can fake them with a simple loop in an internal +implementation of the usual SDL_main. + +The primary way we expect people to write SDL apps is still with SDL_main, and +this is not intended to replace it. If the app chooses to use this, it just +removes some platform-specific details they might have to otherwise manage, +and maybe removes a barrier to entry on some future platform. And you might +find you enjoy structuring your program like this more! + + +## How to use main callbacks in SDL3 + +To enable the callback entry points, you include SDL_main.h with an extra define, +from a single source file in your project: + +```c +#define SDL_MAIN_USE_CALLBACKS +#include +``` + +Once you do this, you do not write a "main" function at all (and if you do, +the app will likely fail to link). Instead, you provide the following +functions: + +First: + +```c +int SDL_AppInit(int argc, char **argv); +``` + +This will be called _once_ before anything else. argc/argv work like they +always do. If this returns 0, the app runs. If it returns < 0, the app calls +SDL_AppQuit and terminates with an exit code that reports an error to the +platform. If it returns > 0, the app calls SDL_AppQuit and terminates with +an exit code that reports success to the platform. This function should not +go into an infinite mainloop; it should do any one-time startup it requires +and then return. + +Then: + +```c +int SDL_AppIterate(void); +``` + +This is called over and over, possibly at the refresh rate of the display or +some other metric that the platform dictates. This is where the heart of your +app runs. It should return as quickly as reasonably possible, but it's not a +"run one memcpy and that's all the time you have" sort of thing. The app +should do any game updates, and render a frame of video. If it returns < 0, +SDL will call SDL_AppQuit and terminate the process with an exit code that +reports an error to the platform. If it returns > 0, the app calls +SDL_AppQuit and terminates with an exit code that reports success to the +platform. If it returns 0, then SDL_AppIterate will be called again at some +regular frequency. The platform may choose to run this more or less (perhaps +less in the background, etc), or it might just call this function in a loop +as fast as possible. You do not check the event queue in this function +(SDL_AppEvent exists for that). + +Next: + +```c +int SDL_AppEvent(const SDL_Event *event); +``` + +This will be called whenever an SDL event arrives, on the thread that runs +SDL_AppIterate. Your app should also not call SDL_PollEvent, SDL_PumpEvent, +etc, as SDL will manage all this for you. Return values are the same as from +SDL_AppIterate(), so you can terminate in response to SDL_EVENT_QUIT, etc. + + +Finally: + +```c +void SDL_AppQuit(void); +``` + +This is called once before terminating the app--assuming the app isn't being +forcibly killed or crashed--as a last chance to clean up. After this returns, +SDL will call SDL_Quit so the app doesn't have to (but it's safe for the app +to call it, too). Process termination proceeds as if the app returned normally +from main(), so atexit handles will run, if your platform supports that. + diff --git a/docs/README-migration.md b/docs/README-migration.md index 92351965f..a7a97015e 100644 --- a/docs/README-migration.md +++ b/docs/README-migration.md @@ -1,1356 +1,1356 @@ -# Migrating to SDL 3.0 - -This guide provides useful information for migrating applications from SDL 2.0 to SDL 3.0. - -Details on API changes are organized by SDL 2.0 header below. - -The file with your main() function should include , as that is no longer included in SDL.h. - -Many functions and symbols have been renamed. We have provided a handy Python script [rename_symbols.py](https://github.com/libsdl-org/SDL/blob/main/build-scripts/rename_symbols.py) to rename SDL2 functions to their SDL3 counterparts: -```sh -rename_symbols.py --all-symbols source_code_path -``` - -It's also possible to apply a semantic patch to migrate more easily to SDL3: [SDL_migration.cocci](https://github.com/libsdl-org/SDL/blob/main/build-scripts/SDL_migration.cocci) - -SDL headers should now be included as `#include `. Typically that's the only header you'll need in your application unless you are using OpenGL or Vulkan functionality. We have provided a handy Python script [rename_headers.py](https://github.com/libsdl-org/SDL/blob/main/build-scripts/rename_headers.py) to rename SDL2 headers to their SDL3 counterparts: -```sh -rename_headers.py source_code_path -``` - -CMake users should use this snippet to include SDL support in their project: -``` -find_package(SDL3 REQUIRED CONFIG REQUIRED COMPONENTS SDL3) -target_link_libraries(mygame PRIVATE SDL3::SDL3) -``` - -Autotools users should use this snippet to include SDL support in their project: -``` -PKG_CHECK_MODULES([SDL3], [sdl3]) -``` -and then add $SDL3_CFLAGS to their project CFLAGS and $SDL3_LIBS to their project LDFLAGS - -Makefile users can use this snippet to include SDL support in their project: -``` -CFLAGS += $(shell pkg-config sdl3 --cflags) -LDFLAGS += $(shell pkg-config sdl3 --libs) -``` - -The SDL3test library has been renamed SDL3_test. - -The SDLmain library has been removed, it's been entirely replaced by SDL_main.h. - -The vi format comments have been removed from source code. Vim users can use the [editorconfig plugin](https://github.com/editorconfig/editorconfig-vim) to automatically set tab spacing for the SDL coding style. - -## SDL_atomic.h - -The following structures have been renamed: -- SDL_atomic_t => SDL_AtomicInt - -## SDL_audio.h - -The audio subsystem in SDL3 is dramatically different than SDL2. The primary way to play audio is no longer an audio callback; instead you bind SDL_AudioStreams to devices; however, there is still a callback method available if needed. - -The SDL 1.2 audio compatibility API has also been removed, as it was a simplified version of the audio callback interface. - -SDL3 will not implicitly initialize the audio subsystem on your behalf if you open a device without doing so. Please explicitly call SDL_Init(SDL_INIT_AUDIO) at some point. - -SDL3's audio subsystem offers an enormous amount of power over SDL2, but if you just want a simple migration of your existing code, you can ignore most of it. The simplest migration path from SDL2 looks something like this: - -In SDL2, you might have done something like this to play audio... - -```c - void SDLCALL MyAudioCallback(void *userdata, Uint8 * stream, int len) - { - /* Calculate a little more audio here, maybe using `userdata`, write it to `stream` */ - } - - /* ...somewhere near startup... */ - SDL_AudioSpec my_desired_audio_format; - SDL_zero(my_desired_audio_format); - my_desired_audio_format.format = AUDIO_S16; - my_desired_audio_format.channels = 2; - my_desired_audio_format.freq = 44100; - my_desired_audio_format.samples = 1024; - my_desired_audio_format.callback = MyAudioCallback; - my_desired_audio_format.userdata = &my_audio_callback_user_data; - SDL_AudioDeviceID my_audio_device = SDL_OpenAudioDevice(NULL, 0, &my_desired_audio_format, NULL, 0); - SDL_PauseAudioDevice(my_audio_device, 0); -``` - -...in SDL3, you can do this... - -```c - void SDLCALL MyNewAudioCallback(void *userdata, SDL_AudioStream *stream, int additional_amount, int total_amount) - { - /* Calculate a little more audio here, maybe using `userdata`, write it to `stream` - * - * If you want to use the original callback, you could do something like this: - */ - if (additional_amount > 0) { - Uint8 *data = SDL_stack_alloc(Uint8, additional_amount); - if (data) { - MyAudioCallback(userdata, data, additional_amount); - SDL_PutAudioStreamData(stream, data, additional_amount); - SDL_stack_free(data); - } - } - } - - /* ...somewhere near startup... */ - const SDL_AudioSpec spec = { SDL_AUDIO_S16, 2, 44100 }; - SDL_AudioStream *stream = SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_OUTPUT, &spec, MyNewAudioCallback, &my_audio_callback_user_data); - SDL_ResumeAudioDevice(SDL_GetAudioStreamDevice(stream)); -``` - -If you used SDL_QueueAudio instead of a callback in SDL2, this is also straightforward. - -```c - /* ...somewhere near startup... */ - const SDL_AudioSpec spec = { SDL_AUDIO_S16, 2, 44100 }; - SDL_AudioStream *stream = SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_OUTPUT, &spec, NULL, NULL); - SDL_ResumeAudioDevice(SDL_GetAudioStreamDevice(stream)); - - /* ...in your main loop... */ - /* calculate a little more audio into `buf`, add it to `stream` */ - SDL_PutAudioStreamData(stream, buf, buflen); - -``` - -...these same migration examples apply to audio capture, just using SDL_GetAudioStreamData instead of SDL_PutAudioStreamData. - -SDL_AudioInit() and SDL_AudioQuit() have been removed. Instead you can call SDL_InitSubSystem() and SDL_QuitSubSystem() with SDL_INIT_AUDIO, which will properly refcount the subsystems. You can choose a specific audio driver using SDL_AUDIO_DRIVER hint. - -The `SDL_AUDIO_ALLOW_*` symbols have been removed; now one may request the format they desire from the audio device, but ultimately SDL_AudioStream will manage the difference. One can use SDL_GetAudioDeviceFormat() to see what the final format is, if any "allowed" changes should be accomodated by the app. - -SDL_AudioDeviceID now represents both an open audio device's handle (a "logical" device) and the instance ID that the hardware owns as long as it exists on the system (a "physical" device). The separation between device instances and device indexes is gone, and logical and physical devices are almost entirely interchangeable at the API level. - -Devices are opened by physical device instance ID, and a new logical instance ID is generated by the open operation; This allows any device to be opened multiple times, possibly by unrelated pieces of code. SDL will manage the logical devices to provide a single stream of audio to the physical device behind the scenes. - -Devices are not opened by an arbitrary string name anymore, but by device instance ID (or magic numbers to request a reasonable default, like a NULL string in SDL2). In SDL2, the string was used to open both a standard list of system devices, but also allowed for arbitrary devices, such as hostnames of network sound servers. In SDL3, many of the backends that supported arbitrary device names are obsolete and have been removed; of those that remain, arbitrary devices will be opened with a default device ID and an SDL_hint, so specific end-users can set an environment variable to fit their needs and apps don't have to concern themselves with it. - -Many functions that would accept a device index and an `iscapture` parameter now just take an SDL_AudioDeviceID, as they are unique across all devices, instead of separate indices into output and capture device lists. - -Rather than iterating over audio devices using a device index, there are new functions, SDL_GetAudioOutputDevices() and SDL_GetAudioCaptureDevices(), to get the current list of devices, and new functions to get information about devices from their instance ID: - -```c -{ - if (SDL_InitSubSystem(SDL_INIT_AUDIO) == 0) { - int i, num_devices; - SDL_AudioDeviceID *devices = SDL_GetAudioOutputDevices(&num_devices); - if (devices) { - for (i = 0; i < num_devices; ++i) { - SDL_AudioDeviceID instance_id = devices[i]; - char *name = SDL_GetAudioDeviceName(instance_id); - SDL_Log("AudioDevice %" SDL_PRIu32 ": %s\n", instance_id, name); - SDL_free(name); - } - SDL_free(devices); - } - SDL_QuitSubSystem(SDL_INIT_AUDIO); - } -} -``` - -SDL_LockAudioDevice() and SDL_UnlockAudioDevice() have been removed, since there is no callback in another thread to protect. SDL's audio subsystem and SDL_AudioStream maintain their own locks internally, so audio streams are safe to use from any thread. If the app assigns a callback to a specific stream, it can use the stream's lock through SDL_LockAudioStream() if necessary. - -SDL_PauseAudioDevice() no longer takes a second argument; it always pauses the device. To unpause, use SDL_ResumeAudioDevice(). - -Audio devices, opened by SDL_OpenAudioDevice(), no longer start in a paused state, as they don't begin processing audio until a stream is bound. - -SDL_GetAudioDeviceStatus() has been removed; there is now SDL_AudioDevicePaused(). - -SDL_QueueAudio(), SDL_DequeueAudio, and SDL_ClearQueuedAudio and SDL_GetQueuedAudioSize() have been removed; an SDL_AudioStream bound to a device provides the exact same functionality. - -APIs that use channel counts used to use a Uint8 for the channel; now they use int. - -SDL_AudioSpec has been reduced; now it only holds format, channel, and sample rate. SDL_GetSilenceValueForFormat() can provide the information from the SDL_AudioSpec's `silence` field. The other SDL2 SDL_AudioSpec fields aren't relevant anymore. - -SDL_GetAudioDeviceSpec() is removed; use SDL_GetAudioDeviceFormat() instead. - -SDL_GetDefaultAudioInfo() is removed; SDL_GetAudioDeviceFormat() with SDL_AUDIO_DEVICE_DEFAULT_OUTPUT or SDL_AUDIO_DEVICE_DEFAULT_CAPTURE. There is no replacement for querying the default device name; the string is no longer used to open devices, and SDL3 will migrate between physical devices on the fly if the system default changes, so if you must show this to the user, a generic name like "System default" is recommended. - -SDL_MixAudio() has been removed, as it relied on legacy SDL 1.2 quirks; SDL_MixAudioFormat() remains and offers the same functionality. - -SDL_AudioInit() and SDL_AudioQuit() have been removed. Instead you can call SDL_InitSubSystem() and SDL_QuitSubSystem() with SDL_INIT_AUDIO, which will properly refcount the subsystems. You can choose a specific audio driver using SDL_AUDIO_DRIVER hint. - -SDL_FreeWAV has been removed and calls can be replaced with SDL_free. - -SDL_LoadWAV() is a proper function now and no longer a macro (but offers the same functionality otherwise). - -SDL_LoadWAV_RW() and SDL_LoadWAV() return an int now: zero on success, -1 on error, like most of SDL. They no longer return a pointer to an SDL_AudioSpec. - -SDL_AudioCVT interface has been removed, the SDL_AudioStream interface (for audio supplied in pieces) or the new SDL_ConvertAudioSamples() function (for converting a complete audio buffer in one call) can be used instead. - -Code that used to look like this: -```c - SDL_AudioCVT cvt; - SDL_BuildAudioCVT(&cvt, src_format, src_channels, src_rate, dst_format, dst_channels, dst_rate); - cvt.len = src_len; - cvt.buf = (Uint8 *) SDL_malloc(src_len * cvt.len_mult); - SDL_memcpy(cvt.buf, src_data, src_len); - SDL_ConvertAudio(&cvt); - do_something(cvt.buf, cvt.len_cvt); -``` -should be changed to: -```c - Uint8 *dst_data = NULL; - int dst_len = 0; - const SDL_AudioSpec src_spec = { src_format, src_channels, src_rate }; - const SDL_AudioSpec dst_spec = { dst_format, dst_channels, dst_rate }; - if (SDL_ConvertAudioSamples(&src_spec, src_data, src_len, &dst_spec, &dst_data, &dst_len) < 0) { - /* error */ - } - do_something(dst_data, dst_len); - SDL_free(dst_data); -``` - -AUDIO_U16, AUDIO_U16LSB, AUDIO_U16MSB, and AUDIO_U16SYS have been removed. They were not heavily used, and one could not memset a buffer in this format to silence with a single byte value. Use a different audio format. - -If you need to convert U16 audio data to a still-supported format at runtime, the fastest, lossless conversion is to SDL_AUDIO_S16: - -```c - /* this converts the buffer in-place. The buffer size does not change. */ - Sint16 *audio_ui16_to_si16(Uint16 *buffer, const size_t num_samples) - { - size_t i; - const Uint16 *src = buffer; - Sint16 *dst = (Sint16 *) buffer; - - for (i = 0; i < num_samples; i++) { - dst[i] = (Sint16) (src[i] ^ 0x8000); - } - - return dst; - } -``` - -All remaining `AUDIO_*` symbols have been renamed to `SDL_AUDIO_*` for API consistency, but othewise are identical in value and usage. - -In SDL2, SDL_AudioStream would convert/resample audio data during input (via SDL_AudioStreamPut). In SDL3, it does this work when requesting audio (via SDL_GetAudioStreamData, which would have been SDL_AudioStreamGet in SDL2). The way you use an AudioStream is roughly the same, just be aware that the workload moved to a different phase. - -In SDL2, SDL_AudioStreamAvailable() returns 0 if passed a NULL stream. In SDL3, the equivalent SDL_GetAudioStreamAvailable() call returns -1 and sets an error string, which matches other audiostream APIs' behavior. - -In SDL2, SDL_AUDIODEVICEREMOVED events would fire for open devices with the `which` field set to the SDL_AudioDeviceID of the lost device, and in later SDL2 releases, would also fire this event with a `which` field of zero for unopened devices, to signify that the app might want to refresh the available device list. In SDL3, this event works the same, except it won't ever fire with a zero; in this case it'll return the physical device's SDL_AudioDeviceID. Any still-open SDL_AudioDeviceIDs generated from this device with SDL_OpenAudioDevice() will also fire a separate event. - -The following functions have been renamed: -* SDL_AudioStreamAvailable() => SDL_GetAudioStreamAvailable() -* SDL_AudioStreamClear() => SDL_ClearAudioStream() -* SDL_AudioStreamFlush() => SDL_FlushAudioStream() -* SDL_AudioStreamGet() => SDL_GetAudioStreamData() -* SDL_AudioStreamPut() => SDL_PutAudioStreamData() -* SDL_FreeAudioStream() => SDL_DestroyAudioStream() -* SDL_NewAudioStream() => SDL_CreateAudioStream() - - -The following functions have been removed: -* SDL_GetNumAudioDevices() -* SDL_GetAudioDeviceSpec() -* SDL_ConvertAudio() -* SDL_BuildAudioCVT() -* SDL_OpenAudio() -* SDL_CloseAudio() -* SDL_PauseAudio() -* SDL_GetAudioStatus() -* SDL_GetAudioDeviceStatus() -* SDL_GetDefaultAudioInfo() -* SDL_LockAudio() -* SDL_LockAudioDevice() -* SDL_UnlockAudio() -* SDL_UnlockAudioDevice() -* SDL_MixAudio() -* SDL_QueueAudio() -* SDL_DequeueAudio() -* SDL_ClearAudioQueue() -* SDL_GetQueuedAudioSize() - -The following symbols have been renamed: -* AUDIO_F32 => SDL_AUDIO_F32LE -* AUDIO_F32LSB => SDL_AUDIO_F32LE -* AUDIO_F32MSB => SDL_AUDIO_F32BE -* AUDIO_F32SYS => SDL_AUDIO_F32 -* AUDIO_S16 => SDL_AUDIO_S16LE -* AUDIO_S16LSB => SDL_AUDIO_S16LE -* AUDIO_S16MSB => SDL_AUDIO_S16BE -* AUDIO_S16SYS => SDL_AUDIO_S16 -* AUDIO_S32 => SDL_AUDIO_S32LE -* AUDIO_S32LSB => SDL_AUDIO_S32LE -* AUDIO_S32MSB => SDL_AUDIO_S32BE -* AUDIO_S32SYS => SDL_AUDIO_S32 -* AUDIO_S8 => SDL_AUDIO_S8 -* AUDIO_U8 => SDL_AUDIO_U8 - -## SDL_cpuinfo.h - -The intrinsics headers (mmintrin.h, etc.) have been moved to `` and are no longer automatically included in SDL.h. - -SDL_Has3DNow() has been removed; there is no replacement. - -SDL_HasRDTSC() has been removed; there is no replacement. Don't use the RDTSC opcode in modern times, use SDL_GetPerformanceCounter and SDL_GetPerformanceFrequency instead. - -SDL_SIMDAlloc(), SDL_SIMDRealloc(), and SDL_SIMDFree() have been removed. You can use SDL_aligned_alloc() and SDL_aligned_free() with SDL_SIMDGetAlignment() to get the same functionality. - -## SDL_events.h - -The timestamp member of the SDL_Event structure now represents nanoseconds, and is populated with SDL_GetTicksNS() - -The timestamp_us member of the sensor events has been renamed sensor_timestamp and now represents nanoseconds. This value is filled in from the hardware, if available, and may not be synchronized with values returned from SDL_GetTicksNS(). - -You should set the event.common.timestamp field before passing an event to SDL_PushEvent(). If the timestamp is 0 it will be filled in with SDL_GetTicksNS(). - -Event memory is now managed by SDL, so you should not free the data in SDL_EVENT_DROP_FILE, and if you want to hold onto the text in SDL_EVENT_TEXT_EDITING and SDL_EVENT_TEXT_INPUT events, you should make a copy of it. - -Mouse events use floating point values for mouse coordinates and relative motion values. You can get sub-pixel motion depending on the platform and display scaling. - -The SDL_DISPLAYEVENT_* events have been moved to top level events, and SDL_DISPLAYEVENT has been removed. In general, handling this change just means checking for the individual events instead of first checking for SDL_DISPLAYEVENT and then checking for display events. You can compare the event >= SDL_EVENT_DISPLAY_FIRST and <= SDL_EVENT_DISPLAY_LAST if you need to see whether it's a display event. - -The SDL_WINDOWEVENT_* events have been moved to top level events, and SDL_WINDOWEVENT has been removed. In general, handling this change just means checking for the individual events instead of first checking for SDL_WINDOWEVENT and then checking for window events. You can compare the event >= SDL_EVENT_WINDOW_FIRST and <= SDL_EVENT_WINDOW_LAST if you need to see whether it's a window event. - -The SDL_EVENT_WINDOW_RESIZED event is always sent, even in response to SDL_SetWindowSize(). - -The SDL_EVENT_WINDOW_SIZE_CHANGED event has been removed, and you can use SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED to detect window backbuffer size changes. - -The gamepad event structures caxis, cbutton, cdevice, ctouchpad, and csensor have been renamed gaxis, gbutton, gdevice, gtouchpad, and gsensor. - -SDL_QUERY, SDL_IGNORE, SDL_ENABLE, and SDL_DISABLE have been removed. You can use the functions SDL_SetEventEnabled() and SDL_EventEnabled() to set and query event processing state. - -SDL_AddEventWatch() now returns -1 if it fails because it ran out of memory and couldn't add the event watch callback. - -The following symbols have been renamed: -* SDL_APP_DIDENTERBACKGROUND => SDL_EVENT_DID_ENTER_BACKGROUND -* SDL_APP_DIDENTERFOREGROUND => SDL_EVENT_DID_ENTER_FOREGROUND -* SDL_APP_LOWMEMORY => SDL_EVENT_LOW_MEMORY -* SDL_APP_TERMINATING => SDL_EVENT_TERMINATING -* SDL_APP_WILLENTERBACKGROUND => SDL_EVENT_WILL_ENTER_BACKGROUND -* SDL_APP_WILLENTERFOREGROUND => SDL_EVENT_WILL_ENTER_FOREGROUND -* SDL_AUDIODEVICEADDED => SDL_EVENT_AUDIO_DEVICE_ADDED -* SDL_AUDIODEVICEREMOVED => SDL_EVENT_AUDIO_DEVICE_REMOVED -* SDL_CLIPBOARDUPDATE => SDL_EVENT_CLIPBOARD_UPDATE -* SDL_CONTROLLERAXISMOTION => SDL_EVENT_GAMEPAD_AXIS_MOTION -* SDL_CONTROLLERBUTTONDOWN => SDL_EVENT_GAMEPAD_BUTTON_DOWN -* SDL_CONTROLLERBUTTONUP => SDL_EVENT_GAMEPAD_BUTTON_UP -* SDL_CONTROLLERDEVICEADDED => SDL_EVENT_GAMEPAD_ADDED -* SDL_CONTROLLERDEVICEREMAPPED => SDL_EVENT_GAMEPAD_REMAPPED -* SDL_CONTROLLERDEVICEREMOVED => SDL_EVENT_GAMEPAD_REMOVED -* SDL_CONTROLLERSENSORUPDATE => SDL_EVENT_GAMEPAD_SENSOR_UPDATE -* SDL_CONTROLLERTOUCHPADDOWN => SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN -* SDL_CONTROLLERTOUCHPADMOTION => SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION -* SDL_CONTROLLERTOUCHPADUP => SDL_EVENT_GAMEPAD_TOUCHPAD_UP -* SDL_DROPBEGIN => SDL_EVENT_DROP_BEGIN -* SDL_DROPCOMPLETE => SDL_EVENT_DROP_COMPLETE -* SDL_DROPFILE => SDL_EVENT_DROP_FILE -* SDL_DROPTEXT => SDL_EVENT_DROP_TEXT -* SDL_FINGERDOWN => SDL_EVENT_FINGER_DOWN -* SDL_FINGERMOTION => SDL_EVENT_FINGER_MOTION -* SDL_FINGERUP => SDL_EVENT_FINGER_UP -* SDL_FIRSTEVENT => SDL_EVENT_FIRST -* SDL_JOYAXISMOTION => SDL_EVENT_JOYSTICK_AXIS_MOTION -* SDL_JOYBATTERYUPDATED => SDL_EVENT_JOYSTICK_BATTERY_UPDATED -* SDL_JOYBUTTONDOWN => SDL_EVENT_JOYSTICK_BUTTON_DOWN -* SDL_JOYBUTTONUP => SDL_EVENT_JOYSTICK_BUTTON_UP -* SDL_JOYDEVICEADDED => SDL_EVENT_JOYSTICK_ADDED -* SDL_JOYDEVICEREMOVED => SDL_EVENT_JOYSTICK_REMOVED -* SDL_JOYHATMOTION => SDL_EVENT_JOYSTICK_HAT_MOTION -* SDL_KEYDOWN => SDL_EVENT_KEY_DOWN -* SDL_KEYMAPCHANGED => SDL_EVENT_KEYMAP_CHANGED -* SDL_KEYUP => SDL_EVENT_KEY_UP -* SDL_LASTEVENT => SDL_EVENT_LAST -* SDL_LOCALECHANGED => SDL_EVENT_LOCALE_CHANGED -* SDL_MOUSEBUTTONDOWN => SDL_EVENT_MOUSE_BUTTON_DOWN -* SDL_MOUSEBUTTONUP => SDL_EVENT_MOUSE_BUTTON_UP -* SDL_MOUSEMOTION => SDL_EVENT_MOUSE_MOTION -* SDL_MOUSEWHEEL => SDL_EVENT_MOUSE_WHEEL -* SDL_POLLSENTINEL => SDL_EVENT_POLL_SENTINEL -* SDL_QUIT => SDL_EVENT_QUIT -* SDL_RENDER_DEVICE_RESET => SDL_EVENT_RENDER_DEVICE_RESET -* SDL_RENDER_TARGETS_RESET => SDL_EVENT_RENDER_TARGETS_RESET -* SDL_SENSORUPDATE => SDL_EVENT_SENSOR_UPDATE -* SDL_SYSWMEVENT => SDL_EVENT_SYSWM -* SDL_TEXTEDITING => SDL_EVENT_TEXT_EDITING -* SDL_TEXTEDITING_EXT => SDL_EVENT_TEXT_EDITING_EXT -* SDL_TEXTINPUT => SDL_EVENT_TEXT_INPUT -* SDL_USEREVENT => SDL_EVENT_USER - -The following structures have been renamed: -* SDL_ControllerAxisEvent => SDL_GamepadAxisEvent -* SDL_ControllerButtonEvent => SDL_GamepadButtonEvent -* SDL_ControllerDeviceEvent => SDL_GamepadDeviceEvent -* SDL_ControllerSensorEvent => SDL_GamepadSensorEvent -* SDL_ControllerTouchpadEvent => SDL_GamepadTouchpadEvent - -The following functions have been removed: -* SDL_EventState() - replaced with SDL_SetEventEnabled() -* SDL_GetEventState() - replaced with SDL_EventEnabled() - -## SDL_gamecontroller.h - -SDL_gamecontroller.h has been renamed SDL_gamepad.h, and all APIs have been renamed to match. - -The SDL_EVENT_GAMEPAD_ADDED event now provides the joystick instance ID in the which member of the cdevice event structure. - -The functions SDL_GetGamepads(), SDL_GetGamepadInstanceName(), SDL_GetGamepadInstancePath(), SDL_GetGamepadInstancePlayerIndex(), SDL_GetGamepadInstanceGUID(), SDL_GetGamepadInstanceVendor(), SDL_GetGamepadInstanceProduct(), SDL_GetGamepadInstanceProductVersion(), and SDL_GetGamepadInstanceType() have been added to directly query the list of available gamepads. - -The gamepad face buttons have been renamed from A/B/X/Y to North/South/East/West to indicate that they are positional rather than hardware-specific. You can use SDL_GetGamepadButtonLabel() to get the labels for the face buttons, e.g. A/B/X/Y or Cross/Circle/Square/Triangle. The hint SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS is ignored, and mappings that use this hint are translated correctly into positional buttons. Applications will now need to provide a way for users to swap between South/East as their accept/cancel buttons, as this varies based on region and muscle memory. Using South as the accept button and East as the cancel button is a good default. - -SDL_GameControllerGetSensorDataWithTimestamp() has been removed. If you want timestamps for the sensor data, you should use the sensor_timestamp member of SDL_EVENT_GAMEPAD_SENSOR_UPDATE events. - -SDL_CONTROLLER_TYPE_VIRTUAL has been removed, so virtual controllers can emulate other gamepad types. If you need to know whether a controller is virtual, you can use SDL_IsJoystickVirtual(). - -SDL_CONTROLLER_TYPE_AMAZON_LUNA has been removed, and can be replaced with this code: -```c -SDL_bool SDL_IsJoystickAmazonLunaController(Uint16 vendor_id, Uint16 product_id) -{ - return ((vendor_id == 0x1949 && product_id == 0x0419) || - (vendor_id == 0x0171 && product_id == 0x0419)); -} -``` - -SDL_CONTROLLER_TYPE_GOOGLE_STADIA has been removed, and can be replaced with this code: -```c -SDL_bool SDL_IsJoystickGoogleStadiaController(Uint16 vendor_id, Uint16 product_id) -{ - return (vendor_id == 0x18d1 && product_id == 0x9400); -} -``` - -SDL_CONTROLLER_TYPE_NVIDIA_SHIELD has been removed, and can be replaced with this code: -```c -SDL_bool SDL_IsJoystickNVIDIASHIELDController(Uint16 vendor_id, Uint16 product_id) -{ - return (vendor_id == 0x0955 && (product_id == 0x7210 || product_id == 0x7214)); -} -``` - -The following enums have been renamed: -* SDL_GameControllerAxis => SDL_GamepadAxis -* SDL_GameControllerBindType => SDL_GamepadBindingType -* SDL_GameControllerButton => SDL_GamepadButton -* SDL_GameControllerType => SDL_GamepadType - -The following structures have been renamed: -* SDL_GameController => SDL_Gamepad - -The following functions have been renamed: -* SDL_GameControllerAddMapping() => SDL_AddGamepadMapping() -* SDL_GameControllerAddMappingsFromFile() => SDL_AddGamepadMappingsFromFile() -* SDL_GameControllerAddMappingsFromRW() => SDL_AddGamepadMappingsFromRW() -* SDL_GameControllerClose() => SDL_CloseGamepad() -* SDL_GameControllerFromInstanceID() => SDL_GetGamepadFromInstanceID() -* SDL_GameControllerFromPlayerIndex() => SDL_GetGamepadFromPlayerIndex() -* SDL_GameControllerGetAppleSFSymbolsNameForAxis() => SDL_GetGamepadAppleSFSymbolsNameForAxis() -* SDL_GameControllerGetAppleSFSymbolsNameForButton() => SDL_GetGamepadAppleSFSymbolsNameForButton() -* SDL_GameControllerGetAttached() => SDL_GamepadConnected() -* SDL_GameControllerGetAxis() => SDL_GetGamepadAxis() -* SDL_GameControllerGetAxisFromString() => SDL_GetGamepadAxisFromString() -* SDL_GameControllerGetButton() => SDL_GetGamepadButton() -* SDL_GameControllerGetButtonFromString() => SDL_GetGamepadButtonFromString() -* SDL_GameControllerGetFirmwareVersion() => SDL_GetGamepadFirmwareVersion() -* SDL_GameControllerGetJoystick() => SDL_GetGamepadJoystick() -* SDL_GameControllerGetNumTouchpadFingers() => SDL_GetNumGamepadTouchpadFingers() -* SDL_GameControllerGetNumTouchpads() => SDL_GetNumGamepadTouchpads() -* SDL_GameControllerGetPlayerIndex() => SDL_GetGamepadPlayerIndex() -* SDL_GameControllerGetProduct() => SDL_GetGamepadProduct() -* SDL_GameControllerGetProductVersion() => SDL_GetGamepadProductVersion() -* SDL_GameControllerGetSensorData() => SDL_GetGamepadSensorData() -* SDL_GameControllerGetSensorDataRate() => SDL_GetGamepadSensorDataRate() -* SDL_GameControllerGetSerial() => SDL_GetGamepadSerial() -* SDL_GameControllerGetStringForAxis() => SDL_GetGamepadStringForAxis() -* SDL_GameControllerGetStringForButton() => SDL_GetGamepadStringForButton() -* SDL_GameControllerGetTouchpadFinger() => SDL_GetGamepadTouchpadFinger() -* SDL_GameControllerGetType() => SDL_GetGamepadType() -* SDL_GameControllerGetVendor() => SDL_GetGamepadVendor() -* SDL_GameControllerHasAxis() => SDL_GamepadHasAxis() -* SDL_GameControllerHasButton() => SDL_GamepadHasButton() -* SDL_GameControllerHasLED() => SDL_GamepadHasLED() -* SDL_GameControllerHasRumble() => SDL_GamepadHasRumble() -* SDL_GameControllerHasRumbleTriggers() => SDL_GamepadHasRumbleTriggers() -* SDL_GameControllerHasSensor() => SDL_GamepadHasSensor() -* SDL_GameControllerIsSensorEnabled() => SDL_GamepadSensorEnabled() -* SDL_GameControllerMapping() => SDL_GetGamepadMapping() -* SDL_GameControllerMappingForGUID() => SDL_GetGamepadMappingForGUID() -* SDL_GameControllerMappingForIndex() => SDL_GetGamepadMappingForIndex() -* SDL_GameControllerName() => SDL_GetGamepadName() -* SDL_GameControllerNumMappings() => SDL_GetNumGamepadMappings() -* SDL_GameControllerOpen() => SDL_OpenGamepad() -* SDL_GameControllerPath() => SDL_GetGamepadPath() -* SDL_GameControllerRumble() => SDL_RumbleGamepad() -* SDL_GameControllerRumbleTriggers() => SDL_RumbleGamepadTriggers() -* SDL_GameControllerSendEffect() => SDL_SendGamepadEffect() -* SDL_GameControllerSetLED() => SDL_SetGamepadLED() -* SDL_GameControllerSetPlayerIndex() => SDL_SetGamepadPlayerIndex() -* SDL_GameControllerSetSensorEnabled() => SDL_SetGamepadSensorEnabled() -* SDL_GameControllerUpdate() => SDL_UpdateGamepads() -* SDL_IsGameController() => SDL_IsGamepad() - -The following functions have been removed: -* SDL_GameControllerEventState() - replaced with SDL_SetGamepadEventsEnabled() and SDL_GamepadEventsEnabled() -* SDL_GameControllerGetBindForAxis() - replaced with SDL_GetGamepadBindings() -* SDL_GameControllerGetBindForButton() - replaced with SDL_GetGamepadBindings() -* SDL_GameControllerMappingForDeviceIndex() - replaced with SDL_GetGamepadInstanceMapping() -* SDL_GameControllerNameForIndex() - replaced with SDL_GetGamepadInstanceName() -* SDL_GameControllerPathForIndex() - replaced with SDL_GetGamepadInstancePath() -* SDL_GameControllerTypeForIndex() - replaced with SDL_GetGamepadInstanceType() - -The following symbols have been renamed: -* SDL_CONTROLLER_AXIS_INVALID => SDL_GAMEPAD_AXIS_INVALID -* SDL_CONTROLLER_AXIS_LEFTX => SDL_GAMEPAD_AXIS_LEFTX -* SDL_CONTROLLER_AXIS_LEFTY => SDL_GAMEPAD_AXIS_LEFTY -* SDL_CONTROLLER_AXIS_MAX => SDL_GAMEPAD_AXIS_MAX -* SDL_CONTROLLER_AXIS_RIGHTX => SDL_GAMEPAD_AXIS_RIGHTX -* SDL_CONTROLLER_AXIS_RIGHTY => SDL_GAMEPAD_AXIS_RIGHTY -* SDL_CONTROLLER_AXIS_TRIGGERLEFT => SDL_GAMEPAD_AXIS_LEFT_TRIGGER -* SDL_CONTROLLER_AXIS_TRIGGERRIGHT => SDL_GAMEPAD_AXIS_RIGHT_TRIGGER -* SDL_CONTROLLER_BINDTYPE_AXIS => SDL_GAMEPAD_BINDTYPE_AXIS -* SDL_CONTROLLER_BINDTYPE_BUTTON => SDL_GAMEPAD_BINDTYPE_BUTTON -* SDL_CONTROLLER_BINDTYPE_HAT => SDL_GAMEPAD_BINDTYPE_HAT -* SDL_CONTROLLER_BINDTYPE_NONE => SDL_GAMEPAD_BINDTYPE_NONE -* SDL_CONTROLLER_BUTTON_A => SDL_GAMEPAD_BUTTON_SOUTH -* SDL_CONTROLLER_BUTTON_B => SDL_GAMEPAD_BUTTON_EAST -* SDL_CONTROLLER_BUTTON_BACK => SDL_GAMEPAD_BUTTON_BACK -* SDL_CONTROLLER_BUTTON_DPAD_DOWN => SDL_GAMEPAD_BUTTON_DPAD_DOWN -* SDL_CONTROLLER_BUTTON_DPAD_LEFT => SDL_GAMEPAD_BUTTON_DPAD_LEFT -* SDL_CONTROLLER_BUTTON_DPAD_RIGHT => SDL_GAMEPAD_BUTTON_DPAD_RIGHT -* SDL_CONTROLLER_BUTTON_DPAD_UP => SDL_GAMEPAD_BUTTON_DPAD_UP -* SDL_CONTROLLER_BUTTON_GUIDE => SDL_GAMEPAD_BUTTON_GUIDE -* SDL_CONTROLLER_BUTTON_INVALID => SDL_GAMEPAD_BUTTON_INVALID -* SDL_CONTROLLER_BUTTON_LEFTSHOULDER => SDL_GAMEPAD_BUTTON_LEFT_SHOULDER -* SDL_CONTROLLER_BUTTON_LEFTSTICK => SDL_GAMEPAD_BUTTON_LEFT_STICK -* SDL_CONTROLLER_BUTTON_MAX => SDL_GAMEPAD_BUTTON_MAX -* SDL_CONTROLLER_BUTTON_MISC1 => SDL_GAMEPAD_BUTTON_MISC1 -* SDL_CONTROLLER_BUTTON_PADDLE1 => SDL_GAMEPAD_BUTTON_RIGHT_PADDLE1 -* SDL_CONTROLLER_BUTTON_PADDLE2 => SDL_GAMEPAD_BUTTON_LEFT_PADDLE1 -* SDL_CONTROLLER_BUTTON_PADDLE3 => SDL_GAMEPAD_BUTTON_RIGHT_PADDLE2 -* SDL_CONTROLLER_BUTTON_PADDLE4 => SDL_GAMEPAD_BUTTON_LEFT_PADDLE2 -* SDL_CONTROLLER_BUTTON_RIGHTSHOULDER => SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER -* SDL_CONTROLLER_BUTTON_RIGHTSTICK => SDL_GAMEPAD_BUTTON_RIGHT_STICK -* SDL_CONTROLLER_BUTTON_START => SDL_GAMEPAD_BUTTON_START -* SDL_CONTROLLER_BUTTON_TOUCHPAD => SDL_GAMEPAD_BUTTON_TOUCHPAD -* SDL_CONTROLLER_BUTTON_X => SDL_GAMEPAD_BUTTON_WEST -* SDL_CONTROLLER_BUTTON_Y => SDL_GAMEPAD_BUTTON_NORTH -* SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_LEFT => SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT -* SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_PAIR => SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_PAIR -* SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT => SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT -* SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO => SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO -* SDL_CONTROLLER_TYPE_PS3 => SDL_GAMEPAD_TYPE_PS3 -* SDL_CONTROLLER_TYPE_PS4 => SDL_GAMEPAD_TYPE_PS4 -* SDL_CONTROLLER_TYPE_PS5 => SDL_GAMEPAD_TYPE_PS5 -* SDL_CONTROLLER_TYPE_UNKNOWN => SDL_GAMEPAD_TYPE_STANDARD -* SDL_CONTROLLER_TYPE_VIRTUAL => SDL_GAMEPAD_TYPE_VIRTUAL -* SDL_CONTROLLER_TYPE_XBOX360 => SDL_GAMEPAD_TYPE_XBOX360 -* SDL_CONTROLLER_TYPE_XBOXONE => SDL_GAMEPAD_TYPE_XBOXONE - -## SDL_gesture.h - -The gesture API has been removed. There is no replacement planned in SDL3. -However, the SDL2 code has been moved to a single-header library that can -be dropped into an SDL3 or SDL2 program, to continue to provide this -functionality to your app and aid migration. That is located in the -[SDL_gesture GitHub repository](https://github.com/libsdl-org/SDL_gesture). - -## SDL_hints.h - -SDL_AddHintCallback() now returns a standard int result instead of void, returning 0 if the function succeeds or a negative error code if there was an error. - -Calling SDL_GetHint() with the name of the hint being changed from within a hint callback will now return the new value rather than the old value. The old value is still passed as a parameter to the hint callback. - -The following hints have been removed: -* SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS - gamepad buttons are always positional -* SDL_HINT_IDLE_TIMER_DISABLED - use SDL_DisableScreenSaver instead -* SDL_HINT_IME_SUPPORT_EXTENDED_TEXT - the normal text editing event has extended text -* SDL_HINT_MOUSE_RELATIVE_SCALING - mouse coordinates are no longer automatically scaled by the SDL renderer -* SDL_HINT_RENDER_LOGICAL_SIZE_MODE - the logical size mode is explicitly set with SDL_SetRenderLogicalPresentation() -* SDL_HINT_RENDER_BATCHING - Render batching is always enabled, apps should call SDL_FlushRenderer() before calling into a lower-level graphics API. -* SDL_HINT_VIDEO_FOREIGN_WINDOW_OPENGL - replaced with the "opengl" property in SDL_CreateWindowWithProperties() -* SDL_HINT_VIDEO_FOREIGN_WINDOW_VULKAN - replaced with the "vulkan" property in SDL_CreateWindowWithProperties() -* SDL_HINT_VIDEO_HIGHDPI_DISABLED - high DPI support is always enabled -* SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT - replaced with the "win32.pixel_format_hwnd" in SDL_CreateWindowWithProperties() -* SDL_HINT_VIDEO_X11_FORCE_EGL - use SDL_HINT_VIDEO_FORCE_EGL instead -* SDL_HINT_VIDEO_X11_XINERAMA - Xinerama no longer supported by the X11 backend -* SDL_HINT_VIDEO_X11_XVIDMODE - Xvidmode no longer supported by the X11 backend - -* Renamed hints SDL_HINT_VIDEODRIVER and SDL_HINT_AUDIODRIVER to SDL_HINT_VIDEO_DRIVER and SDL_HINT_AUDIO_DRIVER -* Renamed environment variables SDL_VIDEODRIVER and SDL_AUDIODRIVER to SDL_VIDEO_DRIVER and SDL_AUDIO_DRIVER -* The environment variables SDL_VIDEO_X11_WMCLASS and SDL_VIDEO_WAYLAND_WMCLASS have been removed and replaced with the unified hint SDL_HINT_APP_ID - -## SDL_init.h - -The following symbols have been renamed: -* SDL_INIT_GAMECONTROLLER => SDL_INIT_GAMEPAD - -The following symbols have been removed: -* SDL_INIT_NOPARACHUTE - -## SDL_joystick.h - -SDL_JoystickID has changed from Sint32 to Uint32, with an invalid ID being 0. - -Rather than iterating over joysticks using device index, there is a new function SDL_GetJoysticks() to get the current list of joysticks, and new functions to get information about joysticks from their instance ID: -```c -{ - if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) == 0) { - int i, num_joysticks; - SDL_JoystickID *joysticks = SDL_GetJoysticks(&num_joysticks); - if (joysticks) { - for (i = 0; i < num_joysticks; ++i) { - SDL_JoystickID instance_id = joysticks[i]; - const char *name = SDL_GetJoystickInstanceName(instance_id); - const char *path = SDL_GetJoystickInstancePath(instance_id); - - SDL_Log("Joystick %" SDL_PRIu32 ": %s%s%s VID 0x%.4x, PID 0x%.4x\n", - instance_id, name ? name : "Unknown", path ? ", " : "", path ? path : "", SDL_GetJoystickInstanceVendor(instance_id), SDL_GetJoystickInstanceProduct(instance_id)); - } - SDL_free(joysticks); - } - SDL_QuitSubSystem(SDL_INIT_JOYSTICK); - } -} -``` - -The SDL_EVENT_JOYSTICK_ADDED event now provides the joystick instance ID in the `which` member of the jdevice event structure. - -The functions SDL_GetJoysticks(), SDL_GetJoystickInstanceName(), SDL_GetJoystickInstancePath(), SDL_GetJoystickInstancePlayerIndex(), SDL_GetJoystickInstanceGUID(), SDL_GetJoystickInstanceVendor(), SDL_GetJoystickInstanceProduct(), SDL_GetJoystickInstanceProductVersion(), and SDL_GetJoystickInstanceType() have been added to directly query the list of available joysticks. - -SDL_AttachVirtualJoystick() and SDL_AttachVirtualJoystickEx() now return the joystick instance ID instead of a device index, and return 0 if there was an error. - -The following functions have been renamed: -* SDL_JoystickAttachVirtual() => SDL_AttachVirtualJoystick() -* SDL_JoystickAttachVirtualEx() => SDL_AttachVirtualJoystickEx() -* SDL_JoystickClose() => SDL_CloseJoystick() -* SDL_JoystickCurrentPowerLevel() => SDL_GetJoystickPowerLevel() -* SDL_JoystickDetachVirtual() => SDL_DetachVirtualJoystick() -* SDL_JoystickFromInstanceID() => SDL_GetJoystickFromInstanceID() -* SDL_JoystickFromPlayerIndex() => SDL_GetJoystickFromPlayerIndex() -* SDL_JoystickGetAttached() => SDL_JoystickConnected() -* SDL_JoystickGetAxis() => SDL_GetJoystickAxis() -* SDL_JoystickGetAxisInitialState() => SDL_GetJoystickAxisInitialState() -* SDL_JoystickGetButton() => SDL_GetJoystickButton() -* SDL_JoystickGetFirmwareVersion() => SDL_GetJoystickFirmwareVersion() -* SDL_JoystickGetGUID() => SDL_GetJoystickGUID() -* SDL_JoystickGetGUIDFromString() => SDL_GetJoystickGUIDFromString() -* SDL_JoystickGetGUIDString() => SDL_GetJoystickGUIDString() -* SDL_JoystickGetHat() => SDL_GetJoystickHat() -* SDL_JoystickGetPlayerIndex() => SDL_GetJoystickPlayerIndex() -* SDL_JoystickGetProduct() => SDL_GetJoystickProduct() -* SDL_JoystickGetProductVersion() => SDL_GetJoystickProductVersion() -* SDL_JoystickGetSerial() => SDL_GetJoystickSerial() -* SDL_JoystickGetType() => SDL_GetJoystickType() -* SDL_JoystickGetVendor() => SDL_GetJoystickVendor() -* SDL_JoystickInstanceID() => SDL_GetJoystickInstanceID() -* SDL_JoystickIsVirtual() => SDL_IsJoystickVirtual() -* SDL_JoystickName() => SDL_GetJoystickName() -* SDL_JoystickNumAxes() => SDL_GetNumJoystickAxes() -* SDL_JoystickNumButtons() => SDL_GetNumJoystickButtons() -* SDL_JoystickNumHats() => SDL_GetNumJoystickHats() -* SDL_JoystickOpen() => SDL_OpenJoystick() -* SDL_JoystickPath() => SDL_GetJoystickPath() -* SDL_JoystickRumble() => SDL_RumbleJoystick() -* SDL_JoystickRumbleTriggers() => SDL_RumbleJoystickTriggers() -* SDL_JoystickSendEffect() => SDL_SendJoystickEffect() -* SDL_JoystickSetLED() => SDL_SetJoystickLED() -* SDL_JoystickSetPlayerIndex() => SDL_SetJoystickPlayerIndex() -* SDL_JoystickSetVirtualAxis() => SDL_SetJoystickVirtualAxis() -* SDL_JoystickSetVirtualButton() => SDL_SetJoystickVirtualButton() -* SDL_JoystickSetVirtualHat() => SDL_SetJoystickVirtualHat() -* SDL_JoystickUpdate() => SDL_UpdateJoysticks() - -The following symbols have been renamed: -* SDL_JOYSTICK_TYPE_GAMECONTROLLER => SDL_JOYSTICK_TYPE_GAMEPAD - -The following functions have been removed: -* SDL_JoystickEventState() - replaced with SDL_SetJoystickEventsEnabled() and SDL_JoystickEventsEnabled() -* SDL_JoystickGetDeviceGUID() - replaced with SDL_GetJoystickInstanceGUID() -* SDL_JoystickGetDeviceInstanceID() -* SDL_JoystickGetDevicePlayerIndex() - replaced with SDL_GetJoystickInstancePlayerIndex() -* SDL_JoystickGetDeviceProduct() - replaced with SDL_GetJoystickInstanceProduct() -* SDL_JoystickGetDeviceProductVersion() - replaced with SDL_GetJoystickInstanceProductVersion() -* SDL_JoystickGetDeviceType() - replaced with SDL_GetJoystickInstanceType() -* SDL_JoystickGetDeviceVendor() - replaced with SDL_GetJoystickInstanceVendor() -* SDL_JoystickNameForIndex() - replaced with SDL_GetJoystickInstanceName() -* SDL_JoystickNumBalls() - API has been removed, see https://github.com/libsdl-org/SDL/issues/6766 -* SDL_JoystickPathForIndex() - replaced with SDL_GetJoystickInstancePath() -* SDL_NumJoysticks() - replaced with SDL_GetJoysticks() - -The following symbols have been removed: -* SDL_JOYBALLMOTION - -## SDL_keyboard.h - -The following functions have been renamed: -* SDL_IsScreenKeyboardShown() => SDL_ScreenKeyboardShown() -* SDL_IsTextInputActive() => SDL_TextInputActive() -* SDL_IsTextInputShown() => SDL_TextInputShown() - -## SDL_keycode.h - -The following symbols have been renamed: -* KMOD_ALT => SDL_KMOD_ALT -* KMOD_CAPS => SDL_KMOD_CAPS -* KMOD_CTRL => SDL_KMOD_CTRL -* KMOD_GUI => SDL_KMOD_GUI -* KMOD_LALT => SDL_KMOD_LALT -* KMOD_LCTRL => SDL_KMOD_LCTRL -* KMOD_LGUI => SDL_KMOD_LGUI -* KMOD_LSHIFT => SDL_KMOD_LSHIFT -* KMOD_MODE => SDL_KMOD_MODE -* KMOD_NONE => SDL_KMOD_NONE -* KMOD_NUM => SDL_KMOD_NUM -* KMOD_RALT => SDL_KMOD_RALT -* KMOD_RCTRL => SDL_KMOD_RCTRL -* KMOD_RESERVED => SDL_KMOD_RESERVED -* KMOD_RGUI => SDL_KMOD_RGUI -* KMOD_RSHIFT => SDL_KMOD_RSHIFT -* KMOD_SCROLL => SDL_KMOD_SCROLL -* KMOD_SHIFT => SDL_KMOD_SHIFT - -## SDL_loadso.h - -SDL_LoadFunction() now returns `SDL_FunctionPointer` instead of `void *`, and should be cast to the appropriate function type. You can define SDL_FUNCTION_POINTER_IS_VOID_POINTER in your project to restore the previous behavior. - -## SDL_main.h - -SDL3 doesn't have a static libSDLmain to link against anymore. -Instead SDL_main.h is now a header-only library **and not included by SDL.h anymore**. - -Using it is really simple: Just `#include ` in the source file with your standard -`int main(int argc, char* argv[])` function. - -## SDL_metal.h - -SDL_Metal_GetDrawableSize() has been removed. SDL_GetWindowSizeInPixels() can be used in its place. - -## SDL_mouse.h - -SDL_ShowCursor() has been split into three functions: SDL_ShowCursor(), SDL_HideCursor(), and SDL_CursorVisible() - -SDL_GetMouseState(), SDL_GetGlobalMouseState(), SDL_GetRelativeMouseState(), SDL_WarpMouseInWindow(), and SDL_WarpMouseGlobal() all use floating point mouse positions, to provide sub-pixel precision on platforms that support it. - -The following functions have been renamed: -* SDL_FreeCursor() => SDL_DestroyCursor() - -## SDL_mutex.h - -SDL_MUTEX_MAXWAIT has been removed; it suggested there was a maximum timeout one could outlive, instead of an infinite wait. Instead, pass a -1 to functions that accepted this symbol. - -SDL_LockMutex and SDL_UnlockMutex now return void; if the mutex is valid (including being a NULL pointer, which returns immediately), these functions never fail. If the mutex is invalid or the caller does something illegal, like unlock another thread's mutex, this is considered undefined behavior. - -The following functions have been renamed: -* SDL_CondBroadcast() => SDL_BroadcastCondition() -* SDL_CondSignal() => SDL_SignalCondition() -* SDL_CondWait() => SDL_WaitCondition() -* SDL_CondWaitTimeout() => SDL_WaitConditionTimeout() -* SDL_CreateCond() => SDL_CreateCondition() -* SDL_DestroyCond() => SDL_DestroyCondition() -* SDL_SemPost() => SDL_PostSemaphore() -* SDL_SemTryWait() => SDL_TryWaitSemaphore() -* SDL_SemValue() => SDL_GetSemaphoreValue() -* SDL_SemWait() => SDL_WaitSemaphore() -* SDL_SemWaitTimeout() => SDL_WaitSemaphoreTimeout() - -The following symbols have been renamed: -* SDL_cond => SDL_Condition -* SDL_mutex => SDL_Mutex -* SDL_sem => SDL_Semaphore - -## SDL_pixels.h - -SDL_CalculateGammaRamp has been removed, because SDL_SetWindowGammaRamp has been removed as well due to poor support in modern operating systems (see [SDL_video.h](#sdl_videoh)). - -The following functions have been renamed: -* SDL_AllocFormat() => SDL_CreatePixelFormat() -* SDL_AllocPalette() => SDL_CreatePalette() -* SDL_FreeFormat() => SDL_DestroyPixelFormat() -* SDL_FreePalette() => SDL_DestroyPalette() -* SDL_MasksToPixelFormatEnum() => SDL_GetPixelFormatEnumForMasks() -* SDL_PixelFormatEnumToMasks() => SDL_GetMasksForPixelFormatEnum() - -The following symbols have been renamed: -* SDL_DISPLAYEVENT_DISCONNECTED => SDL_EVENT_DISPLAY_REMOVED -* SDL_DISPLAYEVENT_MOVED => SDL_EVENT_DISPLAY_MOVED -* SDL_DISPLAYEVENT_ORIENTATION => SDL_EVENT_DISPLAY_ORIENTATION -* SDL_WINDOWEVENT_CLOSE => SDL_EVENT_WINDOW_CLOSE_REQUESTED -* SDL_WINDOWEVENT_DISPLAY_CHANGED => SDL_EVENT_WINDOW_DISPLAY_CHANGED -* SDL_WINDOWEVENT_ENTER => SDL_EVENT_WINDOW_ENTER -* SDL_WINDOWEVENT_EXPOSED => SDL_EVENT_WINDOW_EXPOSED -* SDL_WINDOWEVENT_FOCUS_GAINED => SDL_EVENT_WINDOW_FOCUS_GAINED -* SDL_WINDOWEVENT_FOCUS_LOST => SDL_EVENT_WINDOW_FOCUS_LOST -* SDL_WINDOWEVENT_HIDDEN => SDL_EVENT_WINDOW_HIDDEN -* SDL_WINDOWEVENT_HIT_TEST => SDL_EVENT_WINDOW_HIT_TEST -* SDL_WINDOWEVENT_ICCPROF_CHANGED => SDL_EVENT_WINDOW_ICCPROF_CHANGED -* SDL_WINDOWEVENT_LEAVE => SDL_EVENT_WINDOW_LEAVE -* SDL_WINDOWEVENT_MAXIMIZED => SDL_EVENT_WINDOW_MAXIMIZED -* SDL_WINDOWEVENT_MINIMIZED => SDL_EVENT_WINDOW_MINIMIZED -* SDL_WINDOWEVENT_MOVED => SDL_EVENT_WINDOW_MOVED -* SDL_WINDOWEVENT_RESIZED => SDL_EVENT_WINDOW_RESIZED -* SDL_WINDOWEVENT_RESTORED => SDL_EVENT_WINDOW_RESTORED -* SDL_WINDOWEVENT_SHOWN => SDL_EVENT_WINDOW_SHOWN -* SDL_WINDOWEVENT_SIZE_CHANGED => SDL_EVENT_WINDOW_SIZE_CHANGED -* SDL_WINDOWEVENT_TAKE_FOCUS => SDL_EVENT_WINDOW_TAKE_FOCUS - - -## SDL_platform.h - -The preprocessor symbol `__MACOSX__` has been renamed `__MACOS__`, and `__IPHONEOS__` has been renamed `__IOS__` - -## SDL_rect.h - -The following functions have been renamed: -* SDL_EncloseFPoints() => SDL_GetRectEnclosingPointsFloat() -* SDL_EnclosePoints() => SDL_GetRectEnclosingPoints() -* SDL_FRectEmpty() => SDL_RectEmptyFloat() -* SDL_FRectEquals() => SDL_RectsEqualFloat() -* SDL_FRectEqualsEpsilon() => SDL_RectsEqualEpsilon() -* SDL_HasIntersection() => SDL_HasRectIntersection() -* SDL_HasIntersectionF() => SDL_HasRectIntersectionFloat() -* SDL_IntersectFRect() => SDL_GetRectIntersectionFloat() -* SDL_IntersectFRectAndLine() => SDL_GetRectAndLineIntersectionFloat() -* SDL_IntersectRect() => SDL_GetRectIntersection() -* SDL_IntersectRectAndLine() => SDL_GetRectAndLineIntersection() -* SDL_PointInFRect() => SDL_PointInRectFloat() -* SDL_RectEquals() => SDL_RectsEqual() -* SDL_UnionFRect() => SDL_GetRectUnionFloat() -* SDL_UnionRect() => SDL_GetRectUnion() - -## SDL_render.h - -The 2D renderer API always uses batching in SDL3. There is no magic to turn -it on and off; it doesn't matter if you select a specific renderer or try to -use any hint. This means that all apps that use SDL3's 2D renderer and also -want to call directly into the platform's lower-layer graphics API _must_ call -SDL_RenderFlush() before doing so. This will make sure any pending rendering -work from SDL is done before the app starts directly drawing. - -SDL_GetRenderDriverInfo() has been removed, since most of the information it reported were -estimates and could not be accurate before creating a renderer. Often times this function -was used to figure out the index of a driver, so one would call it in a for-loop, looking -for the driver named "opengl" or whatnot. SDL_GetRenderDriver() has been added for this -functionality, which returns only the name of the driver. - -Additionally, SDL_CreateRenderer()'s second argument is no longer an integer index, but a -`const char *` representing a renderer's name; if you were just using a for-loop to find -which index is the "opengl" or whatnot driver, you can just pass that string directly -here, now. Passing NULL is the same as passing -1 here in SDL2, to signify you want SDL -to decide for you. - -The SDL_RENDERER_TARGETTEXTURE flag has been removed, all current renderers support target texture functionality. - -When a renderer is created, it will automatically set the logical size to the size of -the window in points. For high DPI displays, this will set up scaling from points to -pixels. You can disable this scaling with: -```c - SDL_SetRenderLogicalPresentation(renderer, 0, 0, SDL_LOGICAL_PRESENTATION_DISABLED, SDL_SCALEMODE_NEAREST); -``` - -Mouse and touch events are no longer filtered to change their coordinates, instead you -can call SDL_ConvertEventToRenderCoordinates() to explicitly map event coordinates into -the rendering viewport. - -SDL_RenderWindowToLogical() and SDL_RenderLogicalToWindow() have been renamed SDL_RenderCoordinatesFromWindow() and SDL_RenderCoordinatesToWindow() and take floating point coordinates in both directions. - -The viewport, clipping state, and scale for render targets are now persistent and will remain set whenever they are active. - -The following functions have been renamed: -* SDL_GetRendererOutputSize() => SDL_GetCurrentRenderOutputSize() -* SDL_RenderCopy() => SDL_RenderTexture() -* SDL_RenderCopyEx() => SDL_RenderTextureRotated() -* SDL_RenderCopyExF() => SDL_RenderTextureRotated() -* SDL_RenderCopyF() => SDL_RenderTexture() -* SDL_RenderDrawLine() => SDL_RenderLine() -* SDL_RenderDrawLineF() => SDL_RenderLine() -* SDL_RenderDrawLines() => SDL_RenderLines() -* SDL_RenderDrawLinesF() => SDL_RenderLines() -* SDL_RenderDrawPoint() => SDL_RenderPoint() -* SDL_RenderDrawPointF() => SDL_RenderPoint() -* SDL_RenderDrawPoints() => SDL_RenderPoints() -* SDL_RenderDrawPointsF() => SDL_RenderPoints() -* SDL_RenderDrawRect() => SDL_RenderRect() -* SDL_RenderDrawRectF() => SDL_RenderRect() -* SDL_RenderDrawRects() => SDL_RenderRects() -* SDL_RenderDrawRectsF() => SDL_RenderRects() -* SDL_RenderFillRectF() => SDL_RenderFillRect() -* SDL_RenderFillRectsF() => SDL_RenderFillRects() -* SDL_RenderGetClipRect() => SDL_GetRenderClipRect() -* SDL_RenderGetIntegerScale() => SDL_GetRenderIntegerScale() -* SDL_RenderGetLogicalSize() => SDL_GetRenderLogicalPresentation() -* SDL_RenderGetMetalCommandEncoder() => SDL_GetRenderMetalCommandEncoder() -* SDL_RenderGetMetalLayer() => SDL_GetRenderMetalLayer() -* SDL_RenderGetScale() => SDL_GetRenderScale() -* SDL_RenderGetViewport() => SDL_GetRenderViewport() -* SDL_RenderGetWindow() => SDL_GetRenderWindow() -* SDL_RenderIsClipEnabled() => SDL_RenderClipEnabled() -* SDL_RenderLogicalToWindow() => SDL_RenderCoordinatesToWindow() -* SDL_RenderSetClipRect() => SDL_SetRenderClipRect() -* SDL_RenderSetIntegerScale() => SDL_SetRenderIntegerScale() -* SDL_RenderSetLogicalSize() => SDL_SetRenderLogicalPresentation() -* SDL_RenderSetScale() => SDL_SetRenderScale() -* SDL_RenderSetVSync() => SDL_SetRenderVSync() -* SDL_RenderSetViewport() => SDL_SetRenderViewport() -* SDL_RenderWindowToLogical() => SDL_RenderCoordinatesFromWindow() - -The following functions have been removed: -* SDL_GetTextureUserData() - use SDL_GetTextureProperties() instead -* SDL_RenderGetIntegerScale() -* SDL_RenderSetIntegerScale() - this is now explicit with SDL_LOGICAL_PRESENTATION_INTEGER_SCALE -* SDL_RenderTargetSupported() - render targets are always supported -* SDL_SetTextureUserData() - use SDL_GetTextureProperties() instead - -The following symbols have been renamed: -* SDL_ScaleModeBest => SDL_SCALEMODE_BEST -* SDL_ScaleModeLinear => SDL_SCALEMODE_LINEAR -* SDL_ScaleModeNearest => SDL_SCALEMODE_NEAREST - -## SDL_rwops.h - -The following symbols have been renamed: -* RW_SEEK_CUR => SDL_RW_SEEK_CUR -* RW_SEEK_END => SDL_RW_SEEK_END -* RW_SEEK_SET => SDL_RW_SEEK_SET - -SDL_RWread and SDL_RWwrite (and SDL_RWops::read, SDL_RWops::write) have a different function signature in SDL3. - -Previously they looked more like stdio: - -```c -size_t SDL_RWread(SDL_RWops *context, void *ptr, size_t size, size_t maxnum); -size_t SDL_RWwrite(SDL_RWops *context, const void *ptr, size_t size, size_t maxnum); -``` - -But now they look more like POSIX: - -```c -size_t SDL_RWread(SDL_RWops *context, void *ptr, size_t size); -size_t SDL_RWwrite(SDL_RWops *context, const void *ptr, size_t size); -``` - -Code that used to look like this: -``` -size_t custom_read(void *ptr, size_t size, size_t nitems, SDL_RWops *stream) -{ - return SDL_RWread(stream, ptr, size, nitems); -} -``` -should be changed to: -``` -size_t custom_read(void *ptr, size_t size, size_t nitems, SDL_RWops *stream) -{ - if (size > 0 && nitems > 0) { - return SDL_RWread(stream, ptr, size * nitems) / size; - } - return 0; -} -``` - -SDL_RWFromFP has been removed from the API, due to issues when the SDL library uses a different C runtime from the application. - -You can implement this in your own code easily: -```c -#include - - -static Sint64 SDLCALL stdio_seek(SDL_RWops *context, Sint64 offset, int whence) -{ - int stdiowhence; - - switch (whence) { - case SDL_RW_SEEK_SET: - stdiowhence = SEEK_SET; - break; - case SDL_RW_SEEK_CUR: - stdiowhence = SEEK_CUR; - break; - case SDL_RW_SEEK_END: - stdiowhence = SEEK_END; - break; - default: - return SDL_SetError("Unknown value for 'whence'"); - } - - if (fseek((FILE *)context->hidden.stdio.fp, (fseek_off_t)offset, stdiowhence) == 0) { - Sint64 pos = ftell((FILE *)context->hidden.stdio.fp); - if (pos < 0) { - return SDL_SetError("Couldn't get stream offset"); - } - return pos; - } - return SDL_Error(SDL_EFSEEK); -} - -static size_t SDLCALL stdio_read(SDL_RWops *context, void *ptr, size_t size) -{ - size_t bytes; - - bytes = fread(ptr, 1, size, (FILE *)context->hidden.stdio.fp); - if (bytes == 0 && ferror((FILE *)context->hidden.stdio.fp)) { - SDL_Error(SDL_EFREAD); - } - return bytes; -} - -static size_t SDLCALL stdio_write(SDL_RWops *context, const void *ptr, size_t size) -{ - size_t bytes; - - bytes = fwrite(ptr, 1, size, (FILE *)context->hidden.stdio.fp); - if (bytes == 0 && ferror((FILE *)context->hidden.stdio.fp)) { - SDL_Error(SDL_EFWRITE); - } - return bytes; -} - -static int SDLCALL stdio_close(SDL_RWops *context) -{ - int status = 0; - if (context->hidden.stdio.autoclose) { - if (fclose((FILE *)context->hidden.stdio.fp) != 0) { - status = SDL_Error(SDL_EFWRITE); - } - } - SDL_DestroyRW(context); - return status; -} - -SDL_RWops *SDL_RWFromFP(void *fp, SDL_bool autoclose) -{ - SDL_RWops *rwops = NULL; - - rwops = SDL_CreateRW(); - if (rwops != NULL) { - rwops->seek = stdio_seek; - rwops->read = stdio_read; - rwops->write = stdio_write; - rwops->close = stdio_close; - rwops->hidden.stdio.fp = fp; - rwops->hidden.stdio.autoclose = autoclose; - rwops->type = SDL_RWOPS_STDFILE; - } - return rwops; -} -``` - -The functions SDL_ReadU8(), SDL_ReadU16LE(), SDL_ReadU16BE(), SDL_ReadU32LE(), SDL_ReadU32BE(), SDL_ReadU64LE(), and SDL_ReadU64BE() now return SDL_TRUE if the read succeeded and SDL_FALSE if it didn't, and store the data in a pointer passed in as a parameter. - -The following functions have been renamed: -* SDL_AllocRW() => SDL_CreateRW() -* SDL_FreeRW() => SDL_DestroyRW() -* SDL_ReadBE16() => SDL_ReadU16BE() -* SDL_ReadBE32() => SDL_ReadU32BE() -* SDL_ReadBE64() => SDL_ReadU64BE() -* SDL_ReadLE16() => SDL_ReadU16LE() -* SDL_ReadLE32() => SDL_ReadU32LE() -* SDL_ReadLE64() => SDL_ReadU64LE() -* SDL_WriteBE16() => SDL_WriteU16BE() -* SDL_WriteBE32() => SDL_WriteU32BE() -* SDL_WriteBE64() => SDL_WriteU64BE() -* SDL_WriteLE16() => SDL_WriteU16LE() -* SDL_WriteLE32() => SDL_WriteU32LE() -* SDL_WriteLE64() => SDL_WriteU64LE() - -## SDL_sensor.h - -SDL_SensorID has changed from Sint32 to Uint32, with an invalid ID being 0. - -Rather than iterating over sensors using device index, there is a new function SDL_GetSensors() to get the current list of sensors, and new functions to get information about sensors from their instance ID: -```c -{ - if (SDL_InitSubSystem(SDL_INIT_SENSOR) == 0) { - int i, num_sensors; - SDL_SensorID *sensors = SDL_GetSensors(&num_sensors); - if (sensors) { - for (i = 0; i < num_sensors; ++i) { - SDL_Log("Sensor %" SDL_PRIu32 ": %s, type %d, platform type %d\n", - sensors[i], - SDL_GetSensorInstanceName(sensors[i]), - SDL_GetSensorInstanceType(sensors[i]), - SDL_GetSensorInstanceNonPortableType(sensors[i])); - } - SDL_free(sensors); - } - SDL_QuitSubSystem(SDL_INIT_SENSOR); - } -} -``` - -Removed SDL_SensorGetDataWithTimestamp(), if you want timestamps for the sensor data, you should use the sensor_timestamp member of SDL_EVENT_SENSOR_UPDATE events. - - -The following functions have been renamed: -* SDL_SensorClose() => SDL_CloseSensor() -* SDL_SensorFromInstanceID() => SDL_GetSensorFromInstanceID() -* SDL_SensorGetData() => SDL_GetSensorData() -* SDL_SensorGetInstanceID() => SDL_GetSensorInstanceID() -* SDL_SensorGetName() => SDL_GetSensorName() -* SDL_SensorGetNonPortableType() => SDL_GetSensorNonPortableType() -* SDL_SensorGetType() => SDL_GetSensorType() -* SDL_SensorOpen() => SDL_OpenSensor() -* SDL_SensorUpdate() => SDL_UpdateSensors() - -The following functions have been removed: -* SDL_LockSensors() -* SDL_NumSensors() - replaced with SDL_GetSensors() -* SDL_SensorGetDeviceInstanceID() -* SDL_SensorGetDeviceName() - replaced with SDL_GetSensorInstanceName() -* SDL_SensorGetDeviceNonPortableType() - replaced with SDL_GetSensorInstanceNonPortableType() -* SDL_SensorGetDeviceType() - replaced with SDL_GetSensorInstanceType() -* SDL_UnlockSensors() - -## SDL_shape.h - -This header has been removed. You can create a window with the SDL_WINDOW_TRANSPARENT flag and then render using the alpha channel to achieve a similar effect. You can see an example of this in test/testshape.c - -## SDL_stdinc.h - -The standard C headers like stdio.h and stdlib.h are no longer included, you should include them directly in your project if you use non-SDL C runtime functions. -M_PI is no longer defined in SDL_stdinc.h, you can use the new symbols SDL_PI_D (double) and SDL_PI_F (float) instead. - - -The following functions have been renamed: -* SDL_strtokr() => SDL_strtok_r() - -## SDL_surface.h - -The userdata member of SDL_Surface has been replaced with a more general properties interface, which can be queried with SDL_GetSurfaceProperties() - -Removed unused 'flags' parameter from SDL_ConvertSurface and SDL_ConvertSurfaceFormat. - -SDL_CreateRGBSurface() and SDL_CreateRGBSurfaceWithFormat() have been combined into a new function SDL_CreateSurface(). -SDL_CreateRGBSurfaceFrom() and SDL_CreateRGBSurfaceWithFormatFrom() have been combined into a new function SDL_CreateSurfaceFrom(). - -You can implement the old functions in your own code easily: -```c -SDL_Surface *SDL_CreateRGBSurface(Uint32 flags, int width, int height, int depth, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask) -{ - return SDL_CreateSurface(width, height, - SDL_GetPixelFormatEnumForMasks(depth, Rmask, Gmask, Bmask, Amask)); -} - -SDL_Surface *SDL_CreateRGBSurfaceWithFormat(Uint32 flags, int width, int height, int depth, Uint32 format) -{ - return SDL_CreateSurface(width, height, format); -} - -SDL_Surface *SDL_CreateRGBSurfaceFrom(void *pixels, int width, int height, int depth, int pitch, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask) -{ - return SDL_CreateSurfaceFrom(pixels, width, height, pitch, - SDL_GetPixelFormatEnumForMasks(depth, Rmask, Gmask, Bmask, Amask)); -} - -SDL_Surface *SDL_CreateRGBSurfaceWithFormatFrom(void *pixels, int width, int height, int depth, int pitch, Uint32 format) -{ - return SDL_CreateSurfaceFrom(pixels, width, height, pitch, format); -} - -``` - -But if you're migrating your code which uses masks, you probably have a format in mind, possibly one of these: -```c -// Various mask (R, G, B, A) and their corresponding format: -0xFF000000 0x00FF0000 0x0000FF00 0x000000FF => SDL_PIXELFORMAT_RGBA8888 -0x00FF0000 0x0000FF00 0x000000FF 0xFF000000 => SDL_PIXELFORMAT_ARGB8888 -0x0000FF00 0x00FF0000 0xFF000000 0x000000FF => SDL_PIXELFORMAT_BGRA8888 -0x000000FF 0x0000FF00 0x00FF0000 0xFF000000 => SDL_PIXELFORMAT_ABGR8888 -0x0000F800 0x000007E0 0x0000001F 0x00000000 => SDL_PIXELFORMAT_RGB565 -``` - - -The following functions have been renamed: -* SDL_FillRect() => SDL_FillSurfaceRect() -* SDL_FillRects() => SDL_FillSurfaceRects() -* SDL_FreeSurface() => SDL_DestroySurface() -* SDL_GetClipRect() => SDL_GetSurfaceClipRect() -* SDL_GetColorKey() => SDL_GetSurfaceColorKey() -* SDL_HasColorKey() => SDL_SurfaceHasColorKey() -* SDL_HasSurfaceRLE() => SDL_SurfaceHasRLE() -* SDL_LowerBlit() => SDL_BlitSurfaceUnchecked() -* SDL_LowerBlitScaled() => SDL_BlitSurfaceUncheckedScaled() -* SDL_SetClipRect() => SDL_SetSurfaceClipRect() -* SDL_SetColorKey() => SDL_SetSurfaceColorKey() -* SDL_UpperBlit() => SDL_BlitSurface() -* SDL_UpperBlitScaled() => SDL_BlitSurfaceScaled() - -## SDL_system.h - -SDL_WindowsMessageHook has changed signatures so the message may be modified and it can block further message processing. - -SDL_AndroidGetExternalStorageState() takes the state as an output parameter and returns 0 if the function succeeds or a negative error code if there was an error. - -The following functions have been removed: -* SDL_RenderGetD3D11Device() - replaced with the "SDL.renderer.d3d11.device" property -* SDL_RenderGetD3D12Device() - replaced with the "SDL.renderer.d3d12.device" property -* SDL_RenderGetD3D9Device() - replaced with the "SDL.renderer.d3d9.device" property - -## SDL_syswm.h - -This header has been removed. - -The Windows and X11 events are now available via callbacks which you can set with SDL_SetWindowsMessageHook() and SDL_SetX11EventHook(). - -The information previously available in SDL_GetWindowWMInfo() is now available as window properties, e.g. -```c - HWND hwnd = NULL; - SDL_SysWMinfo info; - SDL_VERSION(&info.version); - if (SDL_GetWindowWMInfo(window, &info) && info.subsystem == SDL_SYSWM_WINDOWS) { - hwnd = info.info.win.window; - } - if (hwnd) { - ... - } -``` -becomes: -```c - HWND hwnd = (HWND)SDL_GetProperty(SDL_GetWindowProperties(window), "SDL.window.win32.hwnd"); - if (hwnd) { - ... - } -``` - -## SDL_thread.h - -The following functions have been renamed: -* SDL_TLSCleanup() => SDL_CleanupTLS() -* SDL_TLSCreate() => SDL_CreateTLS() -* SDL_TLSGet() => SDL_GetTLS() -* SDL_TLSSet() => SDL_SetTLS() - -## SDL_timer.h - -SDL_GetTicks() now returns a 64-bit value. Instead of using the SDL_TICKS_PASSED macro, you can directly compare tick values, e.g. -```c -Uint32 deadline = SDL_GetTicks() + 1000; -... -if (SDL_TICKS_PASSED(SDL_GetTicks(), deadline)) { - ... -} -``` -becomes: -```c -Uint64 deadline = SDL_GetTicks() + 1000 -... -if (SDL_GetTicks() >= deadline) { - ... -} -``` - -If you were using this macro for other things besides SDL ticks values, you can define it in your own code as: -```c -#define SDL_TICKS_PASSED(A, B) ((Sint32)((B) - (A)) <= 0) -``` - -## SDL_touch.h - -SDL_GetNumTouchFingers() returns a negative error code if there was an error. - -## SDL_version.h - -SDL_GetRevisionNumber() has been removed from the API, it always returned 0 in SDL 2.0. - - -## SDL_video.h - -SDL_VideoInit() and SDL_VideoQuit() have been removed. Instead you can call SDL_InitSubSystem() and SDL_QuitSubSystem() with SDL_INIT_VIDEO, which will properly refcount the subsystems. You can choose a specific video driver using SDL_VIDEO_DRIVER hint. - -Rather than iterating over displays using display index, there is a new function SDL_GetDisplays() to get the current list of displays, and functions which used to take a display index now take SDL_DisplayID, with an invalid ID being 0. -```c -{ - if (SDL_InitSubSystem(SDL_INIT_VIDEO) == 0) { - int i, num_displays = 0; - SDL_DisplayID *displays = SDL_GetDisplays(&num_displays); - if (displays) { - for (i = 0; i < num_displays; ++i) { - SDL_DisplayID instance_id = displays[i]; - const char *name = SDL_GetDisplayName(instance_id); - - SDL_Log("Display %" SDL_PRIu32 ": %s\n", instance_id, name ? name : "Unknown"); - } - SDL_free(displays); - } - SDL_QuitSubSystem(SDL_INIT_VIDEO); - } -} -``` - -SDL_CreateWindow() has been simplified and no longer takes a window position. You can use SDL_CreateWindowWithProperties() if you need to set the window position when creating it. - -The SDL_WINDOWPOS_UNDEFINED_DISPLAY() and SDL_WINDOWPOS_CENTERED_DISPLAY() macros take a display ID instead of display index. The display ID 0 has a special meaning in this case, and is used to indicate the primary display. - -The SDL_WINDOW_SHOWN flag has been removed. Windows are shown by default and can be created hidden by using the SDL_WINDOW_HIDDEN flag. - -The SDL_WINDOW_SKIP_TASKBAR flag has been replaced by the SDL_WINDOW_UTILITY flag, which has the same functionality. - -SDL_DisplayMode now includes the pixel density which can be greater than 1.0 for display modes that have a higher pixel size than the mode size. You should use SDL_GetWindowSizeInPixels() to get the actual pixel size of the window back buffer. - -The refresh rate in SDL_DisplayMode is now a float. - -Rather than iterating over display modes using an index, there is a new function SDL_GetFullscreenDisplayModes() to get the list of available fullscreen modes on a display. -```c -{ - SDL_DisplayID display = SDL_GetPrimaryDisplay(); - int num_modes = 0; - SDL_DisplayMode **modes = SDL_GetFullscreenDisplayModes(display, &num_modes); - if (modes) { - for (i = 0; i < num_modes; ++i) { - SDL_DisplayMode *mode = modes[i]; - SDL_Log("Display %" SDL_PRIu32 " mode %d: %dx%d@%gx %gHz\n", - display, i, mode->w, mode->h, mode->pixel_density, mode->refresh_rate); - } - SDL_free(modes); - } -} -``` - -SDL_GetDesktopDisplayMode() and SDL_GetCurrentDisplayMode() return pointers to display modes rather than filling in application memory. - -Windows now have an explicit fullscreen mode that is set, using SDL_SetWindowFullscreenMode(). The fullscreen mode for a window can be queried with SDL_GetWindowFullscreenMode(), which returns a pointer to the mode, or NULL if the window will be fullscreen desktop. SDL_SetWindowFullscreen() just takes a boolean value, setting the correct fullscreen state based on the selected mode. - -SDL_WINDOW_FULLSCREEN_DESKTOP has been removed, and you can call SDL_GetWindowFullscreenMode() to see whether an exclusive fullscreen mode will be used or the fullscreen desktop mode will be used when the window is fullscreen. - -SDL_SetWindowBrightness and SDL_SetWindowGammaRamp have been removed from the API, because they interact poorly with modern operating systems and aren't able to limit their effects to the SDL window. - -Programs which have access to shaders can implement more robust versions of those functions using custom shader code rendered as a post-process effect. - -Removed SDL_GL_CONTEXT_EGL from OpenGL configuration attributes. You can instead use `SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);` - -SDL_GL_GetProcAddress() and SDL_EGL_GetProcAddress() now return `SDL_FunctionPointer` instead of `void *`, and should be cast to the appropriate function type. You can define SDL_FUNCTION_POINTER_IS_VOID_POINTER in your project to restore the previous behavior. - -SDL_GL_SwapWindow() returns 0 if the function succeeds or a negative error code if there was an error. - -SDL_GL_GetSwapInterval() takes the interval as an output parameter and returns 0 if the function succeeds or a negative error code if there was an error. - -SDL_GL_GetDrawableSize() has been removed. SDL_GetWindowSizeInPixels() can be used in its place. - -The SDL_WINDOW_TOOLTIP and SDL_WINDOW_POPUP_MENU window flags are now supported on Windows, Mac (Cocoa), X11, and Wayland. Creating windows with these flags must happen via the `SDL_CreatePopupWindow()` function. This function requires passing in the handle to a valid parent window for the popup, and the popup window is positioned relative to the parent. - -The following functions have been renamed: -* SDL_GetClosestDisplayMode() => SDL_GetClosestFullscreenDisplayMode() -* SDL_GetDisplayOrientation() => SDL_GetCurrentDisplayOrientation() -* SDL_GetPointDisplayIndex() => SDL_GetDisplayForPoint() -* SDL_GetRectDisplayIndex() => SDL_GetDisplayForRect() -* SDL_GetWindowDisplayIndex() => SDL_GetDisplayForWindow() -* SDL_GetWindowDisplayMode() => SDL_GetWindowFullscreenMode() -* SDL_IsScreenSaverEnabled() => SDL_ScreenSaverEnabled() -* SDL_SetWindowDisplayMode() => SDL_SetWindowFullscreenMode() - -The following functions have been removed: -* SDL_GetClosestFullscreenDisplayMode() -* SDL_GetDisplayDPI() - not reliable across platforms, approximately replaced by multiplying `display_scale` in the structure returned by SDL_GetDesktopDisplayMode() times 160 on iPhone and Android, and 96 on other platforms. -* SDL_GetDisplayMode() -* SDL_GetNumDisplayModes() - replaced with SDL_GetFullscreenDisplayModes() -* SDL_GetNumVideoDisplays() - replaced with SDL_GetDisplays() -* SDL_GetWindowData() - use SDL_GetWindowProperties() instead -* SDL_SetWindowData() - use SDL_GetWindowProperties() instead -* SDL_CreateWindowFrom() - use SDL_CreateWindowWithProperties() with the properties that allow you to wrap an existing window - -SDL_Window id type is named SDL_WindowID - -The following symbols have been renamed: -* SDL_WINDOW_ALLOW_HIGHDPI => SDL_WINDOW_HIGH_PIXEL_DENSITY -* SDL_WINDOW_INPUT_GRABBED => SDL_WINDOW_MOUSE_GRABBED - -## SDL_vulkan.h - -SDL_Vulkan_GetInstanceExtensions() no longer takes a window parameter, and no longer makes the app allocate query/allocate space for the result, instead returning a static const internal string. - -SDL_Vulkan_GetVkGetInstanceProcAddr() now returns `SDL_FunctionPointer` instead of `void *`, and should be cast to PFN_vkGetInstanceProcAddr. - -SDL_Vulkan_CreateSurface() now takes a VkAllocationCallbacks pointer as its third parameter. If you don't have an allocator to supply, pass a NULL here to use the system default allocator (SDL2 always used the system default allocator here). - -SDL_Vulkan_GetDrawableSize() has been removed. SDL_GetWindowSizeInPixels() can be used in its place. +# Migrating to SDL 3.0 + +This guide provides useful information for migrating applications from SDL 2.0 to SDL 3.0. + +Details on API changes are organized by SDL 2.0 header below. + +The file with your main() function should include , as that is no longer included in SDL.h. + +Many functions and symbols have been renamed. We have provided a handy Python script [rename_symbols.py](https://github.com/libsdl-org/SDL/blob/main/build-scripts/rename_symbols.py) to rename SDL2 functions to their SDL3 counterparts: +```sh +rename_symbols.py --all-symbols source_code_path +``` + +It's also possible to apply a semantic patch to migrate more easily to SDL3: [SDL_migration.cocci](https://github.com/libsdl-org/SDL/blob/main/build-scripts/SDL_migration.cocci) + +SDL headers should now be included as `#include `. Typically that's the only header you'll need in your application unless you are using OpenGL or Vulkan functionality. We have provided a handy Python script [rename_headers.py](https://github.com/libsdl-org/SDL/blob/main/build-scripts/rename_headers.py) to rename SDL2 headers to their SDL3 counterparts: +```sh +rename_headers.py source_code_path +``` + +CMake users should use this snippet to include SDL support in their project: +``` +find_package(SDL3 REQUIRED CONFIG REQUIRED COMPONENTS SDL3) +target_link_libraries(mygame PRIVATE SDL3::SDL3) +``` + +Autotools users should use this snippet to include SDL support in their project: +``` +PKG_CHECK_MODULES([SDL3], [sdl3]) +``` +and then add $SDL3_CFLAGS to their project CFLAGS and $SDL3_LIBS to their project LDFLAGS + +Makefile users can use this snippet to include SDL support in their project: +``` +CFLAGS += $(shell pkg-config sdl3 --cflags) +LDFLAGS += $(shell pkg-config sdl3 --libs) +``` + +The SDL3test library has been renamed SDL3_test. + +The SDLmain library has been removed, it's been entirely replaced by SDL_main.h. + +The vi format comments have been removed from source code. Vim users can use the [editorconfig plugin](https://github.com/editorconfig/editorconfig-vim) to automatically set tab spacing for the SDL coding style. + +## SDL_atomic.h + +The following structures have been renamed: +- SDL_atomic_t => SDL_AtomicInt + +## SDL_audio.h + +The audio subsystem in SDL3 is dramatically different than SDL2. The primary way to play audio is no longer an audio callback; instead you bind SDL_AudioStreams to devices; however, there is still a callback method available if needed. + +The SDL 1.2 audio compatibility API has also been removed, as it was a simplified version of the audio callback interface. + +SDL3 will not implicitly initialize the audio subsystem on your behalf if you open a device without doing so. Please explicitly call SDL_Init(SDL_INIT_AUDIO) at some point. + +SDL3's audio subsystem offers an enormous amount of power over SDL2, but if you just want a simple migration of your existing code, you can ignore most of it. The simplest migration path from SDL2 looks something like this: + +In SDL2, you might have done something like this to play audio... + +```c + void SDLCALL MyAudioCallback(void *userdata, Uint8 * stream, int len) + { + /* Calculate a little more audio here, maybe using `userdata`, write it to `stream` */ + } + + /* ...somewhere near startup... */ + SDL_AudioSpec my_desired_audio_format; + SDL_zero(my_desired_audio_format); + my_desired_audio_format.format = AUDIO_S16; + my_desired_audio_format.channels = 2; + my_desired_audio_format.freq = 44100; + my_desired_audio_format.samples = 1024; + my_desired_audio_format.callback = MyAudioCallback; + my_desired_audio_format.userdata = &my_audio_callback_user_data; + SDL_AudioDeviceID my_audio_device = SDL_OpenAudioDevice(NULL, 0, &my_desired_audio_format, NULL, 0); + SDL_PauseAudioDevice(my_audio_device, 0); +``` + +...in SDL3, you can do this... + +```c + void SDLCALL MyNewAudioCallback(void *userdata, SDL_AudioStream *stream, int additional_amount, int total_amount) + { + /* Calculate a little more audio here, maybe using `userdata`, write it to `stream` + * + * If you want to use the original callback, you could do something like this: + */ + if (additional_amount > 0) { + Uint8 *data = SDL_stack_alloc(Uint8, additional_amount); + if (data) { + MyAudioCallback(userdata, data, additional_amount); + SDL_PutAudioStreamData(stream, data, additional_amount); + SDL_stack_free(data); + } + } + } + + /* ...somewhere near startup... */ + const SDL_AudioSpec spec = { SDL_AUDIO_S16, 2, 44100 }; + SDL_AudioStream *stream = SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_OUTPUT, &spec, MyNewAudioCallback, &my_audio_callback_user_data); + SDL_ResumeAudioDevice(SDL_GetAudioStreamDevice(stream)); +``` + +If you used SDL_QueueAudio instead of a callback in SDL2, this is also straightforward. + +```c + /* ...somewhere near startup... */ + const SDL_AudioSpec spec = { SDL_AUDIO_S16, 2, 44100 }; + SDL_AudioStream *stream = SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_OUTPUT, &spec, NULL, NULL); + SDL_ResumeAudioDevice(SDL_GetAudioStreamDevice(stream)); + + /* ...in your main loop... */ + /* calculate a little more audio into `buf`, add it to `stream` */ + SDL_PutAudioStreamData(stream, buf, buflen); + +``` + +...these same migration examples apply to audio capture, just using SDL_GetAudioStreamData instead of SDL_PutAudioStreamData. + +SDL_AudioInit() and SDL_AudioQuit() have been removed. Instead you can call SDL_InitSubSystem() and SDL_QuitSubSystem() with SDL_INIT_AUDIO, which will properly refcount the subsystems. You can choose a specific audio driver using SDL_AUDIO_DRIVER hint. + +The `SDL_AUDIO_ALLOW_*` symbols have been removed; now one may request the format they desire from the audio device, but ultimately SDL_AudioStream will manage the difference. One can use SDL_GetAudioDeviceFormat() to see what the final format is, if any "allowed" changes should be accomodated by the app. + +SDL_AudioDeviceID now represents both an open audio device's handle (a "logical" device) and the instance ID that the hardware owns as long as it exists on the system (a "physical" device). The separation between device instances and device indexes is gone, and logical and physical devices are almost entirely interchangeable at the API level. + +Devices are opened by physical device instance ID, and a new logical instance ID is generated by the open operation; This allows any device to be opened multiple times, possibly by unrelated pieces of code. SDL will manage the logical devices to provide a single stream of audio to the physical device behind the scenes. + +Devices are not opened by an arbitrary string name anymore, but by device instance ID (or magic numbers to request a reasonable default, like a NULL string in SDL2). In SDL2, the string was used to open both a standard list of system devices, but also allowed for arbitrary devices, such as hostnames of network sound servers. In SDL3, many of the backends that supported arbitrary device names are obsolete and have been removed; of those that remain, arbitrary devices will be opened with a default device ID and an SDL_hint, so specific end-users can set an environment variable to fit their needs and apps don't have to concern themselves with it. + +Many functions that would accept a device index and an `iscapture` parameter now just take an SDL_AudioDeviceID, as they are unique across all devices, instead of separate indices into output and capture device lists. + +Rather than iterating over audio devices using a device index, there are new functions, SDL_GetAudioOutputDevices() and SDL_GetAudioCaptureDevices(), to get the current list of devices, and new functions to get information about devices from their instance ID: + +```c +{ + if (SDL_InitSubSystem(SDL_INIT_AUDIO) == 0) { + int i, num_devices; + SDL_AudioDeviceID *devices = SDL_GetAudioOutputDevices(&num_devices); + if (devices) { + for (i = 0; i < num_devices; ++i) { + SDL_AudioDeviceID instance_id = devices[i]; + char *name = SDL_GetAudioDeviceName(instance_id); + SDL_Log("AudioDevice %" SDL_PRIu32 ": %s\n", instance_id, name); + SDL_free(name); + } + SDL_free(devices); + } + SDL_QuitSubSystem(SDL_INIT_AUDIO); + } +} +``` + +SDL_LockAudioDevice() and SDL_UnlockAudioDevice() have been removed, since there is no callback in another thread to protect. SDL's audio subsystem and SDL_AudioStream maintain their own locks internally, so audio streams are safe to use from any thread. If the app assigns a callback to a specific stream, it can use the stream's lock through SDL_LockAudioStream() if necessary. + +SDL_PauseAudioDevice() no longer takes a second argument; it always pauses the device. To unpause, use SDL_ResumeAudioDevice(). + +Audio devices, opened by SDL_OpenAudioDevice(), no longer start in a paused state, as they don't begin processing audio until a stream is bound. + +SDL_GetAudioDeviceStatus() has been removed; there is now SDL_AudioDevicePaused(). + +SDL_QueueAudio(), SDL_DequeueAudio, and SDL_ClearQueuedAudio and SDL_GetQueuedAudioSize() have been removed; an SDL_AudioStream bound to a device provides the exact same functionality. + +APIs that use channel counts used to use a Uint8 for the channel; now they use int. + +SDL_AudioSpec has been reduced; now it only holds format, channel, and sample rate. SDL_GetSilenceValueForFormat() can provide the information from the SDL_AudioSpec's `silence` field. The other SDL2 SDL_AudioSpec fields aren't relevant anymore. + +SDL_GetAudioDeviceSpec() is removed; use SDL_GetAudioDeviceFormat() instead. + +SDL_GetDefaultAudioInfo() is removed; SDL_GetAudioDeviceFormat() with SDL_AUDIO_DEVICE_DEFAULT_OUTPUT or SDL_AUDIO_DEVICE_DEFAULT_CAPTURE. There is no replacement for querying the default device name; the string is no longer used to open devices, and SDL3 will migrate between physical devices on the fly if the system default changes, so if you must show this to the user, a generic name like "System default" is recommended. + +SDL_MixAudio() has been removed, as it relied on legacy SDL 1.2 quirks; SDL_MixAudioFormat() remains and offers the same functionality. + +SDL_AudioInit() and SDL_AudioQuit() have been removed. Instead you can call SDL_InitSubSystem() and SDL_QuitSubSystem() with SDL_INIT_AUDIO, which will properly refcount the subsystems. You can choose a specific audio driver using SDL_AUDIO_DRIVER hint. + +SDL_FreeWAV has been removed and calls can be replaced with SDL_free. + +SDL_LoadWAV() is a proper function now and no longer a macro (but offers the same functionality otherwise). + +SDL_LoadWAV_RW() and SDL_LoadWAV() return an int now: zero on success, -1 on error, like most of SDL. They no longer return a pointer to an SDL_AudioSpec. + +SDL_AudioCVT interface has been removed, the SDL_AudioStream interface (for audio supplied in pieces) or the new SDL_ConvertAudioSamples() function (for converting a complete audio buffer in one call) can be used instead. + +Code that used to look like this: +```c + SDL_AudioCVT cvt; + SDL_BuildAudioCVT(&cvt, src_format, src_channels, src_rate, dst_format, dst_channels, dst_rate); + cvt.len = src_len; + cvt.buf = (Uint8 *) SDL_malloc(src_len * cvt.len_mult); + SDL_memcpy(cvt.buf, src_data, src_len); + SDL_ConvertAudio(&cvt); + do_something(cvt.buf, cvt.len_cvt); +``` +should be changed to: +```c + Uint8 *dst_data = NULL; + int dst_len = 0; + const SDL_AudioSpec src_spec = { src_format, src_channels, src_rate }; + const SDL_AudioSpec dst_spec = { dst_format, dst_channels, dst_rate }; + if (SDL_ConvertAudioSamples(&src_spec, src_data, src_len, &dst_spec, &dst_data, &dst_len) < 0) { + /* error */ + } + do_something(dst_data, dst_len); + SDL_free(dst_data); +``` + +AUDIO_U16, AUDIO_U16LSB, AUDIO_U16MSB, and AUDIO_U16SYS have been removed. They were not heavily used, and one could not memset a buffer in this format to silence with a single byte value. Use a different audio format. + +If you need to convert U16 audio data to a still-supported format at runtime, the fastest, lossless conversion is to SDL_AUDIO_S16: + +```c + /* this converts the buffer in-place. The buffer size does not change. */ + Sint16 *audio_ui16_to_si16(Uint16 *buffer, const size_t num_samples) + { + size_t i; + const Uint16 *src = buffer; + Sint16 *dst = (Sint16 *) buffer; + + for (i = 0; i < num_samples; i++) { + dst[i] = (Sint16) (src[i] ^ 0x8000); + } + + return dst; + } +``` + +All remaining `AUDIO_*` symbols have been renamed to `SDL_AUDIO_*` for API consistency, but othewise are identical in value and usage. + +In SDL2, SDL_AudioStream would convert/resample audio data during input (via SDL_AudioStreamPut). In SDL3, it does this work when requesting audio (via SDL_GetAudioStreamData, which would have been SDL_AudioStreamGet in SDL2). The way you use an AudioStream is roughly the same, just be aware that the workload moved to a different phase. + +In SDL2, SDL_AudioStreamAvailable() returns 0 if passed a NULL stream. In SDL3, the equivalent SDL_GetAudioStreamAvailable() call returns -1 and sets an error string, which matches other audiostream APIs' behavior. + +In SDL2, SDL_AUDIODEVICEREMOVED events would fire for open devices with the `which` field set to the SDL_AudioDeviceID of the lost device, and in later SDL2 releases, would also fire this event with a `which` field of zero for unopened devices, to signify that the app might want to refresh the available device list. In SDL3, this event works the same, except it won't ever fire with a zero; in this case it'll return the physical device's SDL_AudioDeviceID. Any still-open SDL_AudioDeviceIDs generated from this device with SDL_OpenAudioDevice() will also fire a separate event. + +The following functions have been renamed: +* SDL_AudioStreamAvailable() => SDL_GetAudioStreamAvailable() +* SDL_AudioStreamClear() => SDL_ClearAudioStream() +* SDL_AudioStreamFlush() => SDL_FlushAudioStream() +* SDL_AudioStreamGet() => SDL_GetAudioStreamData() +* SDL_AudioStreamPut() => SDL_PutAudioStreamData() +* SDL_FreeAudioStream() => SDL_DestroyAudioStream() +* SDL_NewAudioStream() => SDL_CreateAudioStream() + + +The following functions have been removed: +* SDL_GetNumAudioDevices() +* SDL_GetAudioDeviceSpec() +* SDL_ConvertAudio() +* SDL_BuildAudioCVT() +* SDL_OpenAudio() +* SDL_CloseAudio() +* SDL_PauseAudio() +* SDL_GetAudioStatus() +* SDL_GetAudioDeviceStatus() +* SDL_GetDefaultAudioInfo() +* SDL_LockAudio() +* SDL_LockAudioDevice() +* SDL_UnlockAudio() +* SDL_UnlockAudioDevice() +* SDL_MixAudio() +* SDL_QueueAudio() +* SDL_DequeueAudio() +* SDL_ClearAudioQueue() +* SDL_GetQueuedAudioSize() + +The following symbols have been renamed: +* AUDIO_F32 => SDL_AUDIO_F32LE +* AUDIO_F32LSB => SDL_AUDIO_F32LE +* AUDIO_F32MSB => SDL_AUDIO_F32BE +* AUDIO_F32SYS => SDL_AUDIO_F32 +* AUDIO_S16 => SDL_AUDIO_S16LE +* AUDIO_S16LSB => SDL_AUDIO_S16LE +* AUDIO_S16MSB => SDL_AUDIO_S16BE +* AUDIO_S16SYS => SDL_AUDIO_S16 +* AUDIO_S32 => SDL_AUDIO_S32LE +* AUDIO_S32LSB => SDL_AUDIO_S32LE +* AUDIO_S32MSB => SDL_AUDIO_S32BE +* AUDIO_S32SYS => SDL_AUDIO_S32 +* AUDIO_S8 => SDL_AUDIO_S8 +* AUDIO_U8 => SDL_AUDIO_U8 + +## SDL_cpuinfo.h + +The intrinsics headers (mmintrin.h, etc.) have been moved to `` and are no longer automatically included in SDL.h. + +SDL_Has3DNow() has been removed; there is no replacement. + +SDL_HasRDTSC() has been removed; there is no replacement. Don't use the RDTSC opcode in modern times, use SDL_GetPerformanceCounter and SDL_GetPerformanceFrequency instead. + +SDL_SIMDAlloc(), SDL_SIMDRealloc(), and SDL_SIMDFree() have been removed. You can use SDL_aligned_alloc() and SDL_aligned_free() with SDL_SIMDGetAlignment() to get the same functionality. + +## SDL_events.h + +The timestamp member of the SDL_Event structure now represents nanoseconds, and is populated with SDL_GetTicksNS() + +The timestamp_us member of the sensor events has been renamed sensor_timestamp and now represents nanoseconds. This value is filled in from the hardware, if available, and may not be synchronized with values returned from SDL_GetTicksNS(). + +You should set the event.common.timestamp field before passing an event to SDL_PushEvent(). If the timestamp is 0 it will be filled in with SDL_GetTicksNS(). + +Event memory is now managed by SDL, so you should not free the data in SDL_EVENT_DROP_FILE, and if you want to hold onto the text in SDL_EVENT_TEXT_EDITING and SDL_EVENT_TEXT_INPUT events, you should make a copy of it. + +Mouse events use floating point values for mouse coordinates and relative motion values. You can get sub-pixel motion depending on the platform and display scaling. + +The SDL_DISPLAYEVENT_* events have been moved to top level events, and SDL_DISPLAYEVENT has been removed. In general, handling this change just means checking for the individual events instead of first checking for SDL_DISPLAYEVENT and then checking for display events. You can compare the event >= SDL_EVENT_DISPLAY_FIRST and <= SDL_EVENT_DISPLAY_LAST if you need to see whether it's a display event. + +The SDL_WINDOWEVENT_* events have been moved to top level events, and SDL_WINDOWEVENT has been removed. In general, handling this change just means checking for the individual events instead of first checking for SDL_WINDOWEVENT and then checking for window events. You can compare the event >= SDL_EVENT_WINDOW_FIRST and <= SDL_EVENT_WINDOW_LAST if you need to see whether it's a window event. + +The SDL_EVENT_WINDOW_RESIZED event is always sent, even in response to SDL_SetWindowSize(). + +The SDL_EVENT_WINDOW_SIZE_CHANGED event has been removed, and you can use SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED to detect window backbuffer size changes. + +The gamepad event structures caxis, cbutton, cdevice, ctouchpad, and csensor have been renamed gaxis, gbutton, gdevice, gtouchpad, and gsensor. + +SDL_QUERY, SDL_IGNORE, SDL_ENABLE, and SDL_DISABLE have been removed. You can use the functions SDL_SetEventEnabled() and SDL_EventEnabled() to set and query event processing state. + +SDL_AddEventWatch() now returns -1 if it fails because it ran out of memory and couldn't add the event watch callback. + +The following symbols have been renamed: +* SDL_APP_DIDENTERBACKGROUND => SDL_EVENT_DID_ENTER_BACKGROUND +* SDL_APP_DIDENTERFOREGROUND => SDL_EVENT_DID_ENTER_FOREGROUND +* SDL_APP_LOWMEMORY => SDL_EVENT_LOW_MEMORY +* SDL_APP_TERMINATING => SDL_EVENT_TERMINATING +* SDL_APP_WILLENTERBACKGROUND => SDL_EVENT_WILL_ENTER_BACKGROUND +* SDL_APP_WILLENTERFOREGROUND => SDL_EVENT_WILL_ENTER_FOREGROUND +* SDL_AUDIODEVICEADDED => SDL_EVENT_AUDIO_DEVICE_ADDED +* SDL_AUDIODEVICEREMOVED => SDL_EVENT_AUDIO_DEVICE_REMOVED +* SDL_CLIPBOARDUPDATE => SDL_EVENT_CLIPBOARD_UPDATE +* SDL_CONTROLLERAXISMOTION => SDL_EVENT_GAMEPAD_AXIS_MOTION +* SDL_CONTROLLERBUTTONDOWN => SDL_EVENT_GAMEPAD_BUTTON_DOWN +* SDL_CONTROLLERBUTTONUP => SDL_EVENT_GAMEPAD_BUTTON_UP +* SDL_CONTROLLERDEVICEADDED => SDL_EVENT_GAMEPAD_ADDED +* SDL_CONTROLLERDEVICEREMAPPED => SDL_EVENT_GAMEPAD_REMAPPED +* SDL_CONTROLLERDEVICEREMOVED => SDL_EVENT_GAMEPAD_REMOVED +* SDL_CONTROLLERSENSORUPDATE => SDL_EVENT_GAMEPAD_SENSOR_UPDATE +* SDL_CONTROLLERTOUCHPADDOWN => SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN +* SDL_CONTROLLERTOUCHPADMOTION => SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION +* SDL_CONTROLLERTOUCHPADUP => SDL_EVENT_GAMEPAD_TOUCHPAD_UP +* SDL_DROPBEGIN => SDL_EVENT_DROP_BEGIN +* SDL_DROPCOMPLETE => SDL_EVENT_DROP_COMPLETE +* SDL_DROPFILE => SDL_EVENT_DROP_FILE +* SDL_DROPTEXT => SDL_EVENT_DROP_TEXT +* SDL_FINGERDOWN => SDL_EVENT_FINGER_DOWN +* SDL_FINGERMOTION => SDL_EVENT_FINGER_MOTION +* SDL_FINGERUP => SDL_EVENT_FINGER_UP +* SDL_FIRSTEVENT => SDL_EVENT_FIRST +* SDL_JOYAXISMOTION => SDL_EVENT_JOYSTICK_AXIS_MOTION +* SDL_JOYBATTERYUPDATED => SDL_EVENT_JOYSTICK_BATTERY_UPDATED +* SDL_JOYBUTTONDOWN => SDL_EVENT_JOYSTICK_BUTTON_DOWN +* SDL_JOYBUTTONUP => SDL_EVENT_JOYSTICK_BUTTON_UP +* SDL_JOYDEVICEADDED => SDL_EVENT_JOYSTICK_ADDED +* SDL_JOYDEVICEREMOVED => SDL_EVENT_JOYSTICK_REMOVED +* SDL_JOYHATMOTION => SDL_EVENT_JOYSTICK_HAT_MOTION +* SDL_KEYDOWN => SDL_EVENT_KEY_DOWN +* SDL_KEYMAPCHANGED => SDL_EVENT_KEYMAP_CHANGED +* SDL_KEYUP => SDL_EVENT_KEY_UP +* SDL_LASTEVENT => SDL_EVENT_LAST +* SDL_LOCALECHANGED => SDL_EVENT_LOCALE_CHANGED +* SDL_MOUSEBUTTONDOWN => SDL_EVENT_MOUSE_BUTTON_DOWN +* SDL_MOUSEBUTTONUP => SDL_EVENT_MOUSE_BUTTON_UP +* SDL_MOUSEMOTION => SDL_EVENT_MOUSE_MOTION +* SDL_MOUSEWHEEL => SDL_EVENT_MOUSE_WHEEL +* SDL_POLLSENTINEL => SDL_EVENT_POLL_SENTINEL +* SDL_QUIT => SDL_EVENT_QUIT +* SDL_RENDER_DEVICE_RESET => SDL_EVENT_RENDER_DEVICE_RESET +* SDL_RENDER_TARGETS_RESET => SDL_EVENT_RENDER_TARGETS_RESET +* SDL_SENSORUPDATE => SDL_EVENT_SENSOR_UPDATE +* SDL_SYSWMEVENT => SDL_EVENT_SYSWM +* SDL_TEXTEDITING => SDL_EVENT_TEXT_EDITING +* SDL_TEXTEDITING_EXT => SDL_EVENT_TEXT_EDITING_EXT +* SDL_TEXTINPUT => SDL_EVENT_TEXT_INPUT +* SDL_USEREVENT => SDL_EVENT_USER + +The following structures have been renamed: +* SDL_ControllerAxisEvent => SDL_GamepadAxisEvent +* SDL_ControllerButtonEvent => SDL_GamepadButtonEvent +* SDL_ControllerDeviceEvent => SDL_GamepadDeviceEvent +* SDL_ControllerSensorEvent => SDL_GamepadSensorEvent +* SDL_ControllerTouchpadEvent => SDL_GamepadTouchpadEvent + +The following functions have been removed: +* SDL_EventState() - replaced with SDL_SetEventEnabled() +* SDL_GetEventState() - replaced with SDL_EventEnabled() + +## SDL_gamecontroller.h + +SDL_gamecontroller.h has been renamed SDL_gamepad.h, and all APIs have been renamed to match. + +The SDL_EVENT_GAMEPAD_ADDED event now provides the joystick instance ID in the which member of the cdevice event structure. + +The functions SDL_GetGamepads(), SDL_GetGamepadInstanceName(), SDL_GetGamepadInstancePath(), SDL_GetGamepadInstancePlayerIndex(), SDL_GetGamepadInstanceGUID(), SDL_GetGamepadInstanceVendor(), SDL_GetGamepadInstanceProduct(), SDL_GetGamepadInstanceProductVersion(), and SDL_GetGamepadInstanceType() have been added to directly query the list of available gamepads. + +The gamepad face buttons have been renamed from A/B/X/Y to North/South/East/West to indicate that they are positional rather than hardware-specific. You can use SDL_GetGamepadButtonLabel() to get the labels for the face buttons, e.g. A/B/X/Y or Cross/Circle/Square/Triangle. The hint SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS is ignored, and mappings that use this hint are translated correctly into positional buttons. Applications will now need to provide a way for users to swap between South/East as their accept/cancel buttons, as this varies based on region and muscle memory. Using South as the accept button and East as the cancel button is a good default. + +SDL_GameControllerGetSensorDataWithTimestamp() has been removed. If you want timestamps for the sensor data, you should use the sensor_timestamp member of SDL_EVENT_GAMEPAD_SENSOR_UPDATE events. + +SDL_CONTROLLER_TYPE_VIRTUAL has been removed, so virtual controllers can emulate other gamepad types. If you need to know whether a controller is virtual, you can use SDL_IsJoystickVirtual(). + +SDL_CONTROLLER_TYPE_AMAZON_LUNA has been removed, and can be replaced with this code: +```c +SDL_bool SDL_IsJoystickAmazonLunaController(Uint16 vendor_id, Uint16 product_id) +{ + return ((vendor_id == 0x1949 && product_id == 0x0419) || + (vendor_id == 0x0171 && product_id == 0x0419)); +} +``` + +SDL_CONTROLLER_TYPE_GOOGLE_STADIA has been removed, and can be replaced with this code: +```c +SDL_bool SDL_IsJoystickGoogleStadiaController(Uint16 vendor_id, Uint16 product_id) +{ + return (vendor_id == 0x18d1 && product_id == 0x9400); +} +``` + +SDL_CONTROLLER_TYPE_NVIDIA_SHIELD has been removed, and can be replaced with this code: +```c +SDL_bool SDL_IsJoystickNVIDIASHIELDController(Uint16 vendor_id, Uint16 product_id) +{ + return (vendor_id == 0x0955 && (product_id == 0x7210 || product_id == 0x7214)); +} +``` + +The following enums have been renamed: +* SDL_GameControllerAxis => SDL_GamepadAxis +* SDL_GameControllerBindType => SDL_GamepadBindingType +* SDL_GameControllerButton => SDL_GamepadButton +* SDL_GameControllerType => SDL_GamepadType + +The following structures have been renamed: +* SDL_GameController => SDL_Gamepad + +The following functions have been renamed: +* SDL_GameControllerAddMapping() => SDL_AddGamepadMapping() +* SDL_GameControllerAddMappingsFromFile() => SDL_AddGamepadMappingsFromFile() +* SDL_GameControllerAddMappingsFromRW() => SDL_AddGamepadMappingsFromRW() +* SDL_GameControllerClose() => SDL_CloseGamepad() +* SDL_GameControllerFromInstanceID() => SDL_GetGamepadFromInstanceID() +* SDL_GameControllerFromPlayerIndex() => SDL_GetGamepadFromPlayerIndex() +* SDL_GameControllerGetAppleSFSymbolsNameForAxis() => SDL_GetGamepadAppleSFSymbolsNameForAxis() +* SDL_GameControllerGetAppleSFSymbolsNameForButton() => SDL_GetGamepadAppleSFSymbolsNameForButton() +* SDL_GameControllerGetAttached() => SDL_GamepadConnected() +* SDL_GameControllerGetAxis() => SDL_GetGamepadAxis() +* SDL_GameControllerGetAxisFromString() => SDL_GetGamepadAxisFromString() +* SDL_GameControllerGetButton() => SDL_GetGamepadButton() +* SDL_GameControllerGetButtonFromString() => SDL_GetGamepadButtonFromString() +* SDL_GameControllerGetFirmwareVersion() => SDL_GetGamepadFirmwareVersion() +* SDL_GameControllerGetJoystick() => SDL_GetGamepadJoystick() +* SDL_GameControllerGetNumTouchpadFingers() => SDL_GetNumGamepadTouchpadFingers() +* SDL_GameControllerGetNumTouchpads() => SDL_GetNumGamepadTouchpads() +* SDL_GameControllerGetPlayerIndex() => SDL_GetGamepadPlayerIndex() +* SDL_GameControllerGetProduct() => SDL_GetGamepadProduct() +* SDL_GameControllerGetProductVersion() => SDL_GetGamepadProductVersion() +* SDL_GameControllerGetSensorData() => SDL_GetGamepadSensorData() +* SDL_GameControllerGetSensorDataRate() => SDL_GetGamepadSensorDataRate() +* SDL_GameControllerGetSerial() => SDL_GetGamepadSerial() +* SDL_GameControllerGetStringForAxis() => SDL_GetGamepadStringForAxis() +* SDL_GameControllerGetStringForButton() => SDL_GetGamepadStringForButton() +* SDL_GameControllerGetTouchpadFinger() => SDL_GetGamepadTouchpadFinger() +* SDL_GameControllerGetType() => SDL_GetGamepadType() +* SDL_GameControllerGetVendor() => SDL_GetGamepadVendor() +* SDL_GameControllerHasAxis() => SDL_GamepadHasAxis() +* SDL_GameControllerHasButton() => SDL_GamepadHasButton() +* SDL_GameControllerHasLED() => SDL_GamepadHasLED() +* SDL_GameControllerHasRumble() => SDL_GamepadHasRumble() +* SDL_GameControllerHasRumbleTriggers() => SDL_GamepadHasRumbleTriggers() +* SDL_GameControllerHasSensor() => SDL_GamepadHasSensor() +* SDL_GameControllerIsSensorEnabled() => SDL_GamepadSensorEnabled() +* SDL_GameControllerMapping() => SDL_GetGamepadMapping() +* SDL_GameControllerMappingForGUID() => SDL_GetGamepadMappingForGUID() +* SDL_GameControllerMappingForIndex() => SDL_GetGamepadMappingForIndex() +* SDL_GameControllerName() => SDL_GetGamepadName() +* SDL_GameControllerNumMappings() => SDL_GetNumGamepadMappings() +* SDL_GameControllerOpen() => SDL_OpenGamepad() +* SDL_GameControllerPath() => SDL_GetGamepadPath() +* SDL_GameControllerRumble() => SDL_RumbleGamepad() +* SDL_GameControllerRumbleTriggers() => SDL_RumbleGamepadTriggers() +* SDL_GameControllerSendEffect() => SDL_SendGamepadEffect() +* SDL_GameControllerSetLED() => SDL_SetGamepadLED() +* SDL_GameControllerSetPlayerIndex() => SDL_SetGamepadPlayerIndex() +* SDL_GameControllerSetSensorEnabled() => SDL_SetGamepadSensorEnabled() +* SDL_GameControllerUpdate() => SDL_UpdateGamepads() +* SDL_IsGameController() => SDL_IsGamepad() + +The following functions have been removed: +* SDL_GameControllerEventState() - replaced with SDL_SetGamepadEventsEnabled() and SDL_GamepadEventsEnabled() +* SDL_GameControllerGetBindForAxis() - replaced with SDL_GetGamepadBindings() +* SDL_GameControllerGetBindForButton() - replaced with SDL_GetGamepadBindings() +* SDL_GameControllerMappingForDeviceIndex() - replaced with SDL_GetGamepadInstanceMapping() +* SDL_GameControllerNameForIndex() - replaced with SDL_GetGamepadInstanceName() +* SDL_GameControllerPathForIndex() - replaced with SDL_GetGamepadInstancePath() +* SDL_GameControllerTypeForIndex() - replaced with SDL_GetGamepadInstanceType() + +The following symbols have been renamed: +* SDL_CONTROLLER_AXIS_INVALID => SDL_GAMEPAD_AXIS_INVALID +* SDL_CONTROLLER_AXIS_LEFTX => SDL_GAMEPAD_AXIS_LEFTX +* SDL_CONTROLLER_AXIS_LEFTY => SDL_GAMEPAD_AXIS_LEFTY +* SDL_CONTROLLER_AXIS_MAX => SDL_GAMEPAD_AXIS_MAX +* SDL_CONTROLLER_AXIS_RIGHTX => SDL_GAMEPAD_AXIS_RIGHTX +* SDL_CONTROLLER_AXIS_RIGHTY => SDL_GAMEPAD_AXIS_RIGHTY +* SDL_CONTROLLER_AXIS_TRIGGERLEFT => SDL_GAMEPAD_AXIS_LEFT_TRIGGER +* SDL_CONTROLLER_AXIS_TRIGGERRIGHT => SDL_GAMEPAD_AXIS_RIGHT_TRIGGER +* SDL_CONTROLLER_BINDTYPE_AXIS => SDL_GAMEPAD_BINDTYPE_AXIS +* SDL_CONTROLLER_BINDTYPE_BUTTON => SDL_GAMEPAD_BINDTYPE_BUTTON +* SDL_CONTROLLER_BINDTYPE_HAT => SDL_GAMEPAD_BINDTYPE_HAT +* SDL_CONTROLLER_BINDTYPE_NONE => SDL_GAMEPAD_BINDTYPE_NONE +* SDL_CONTROLLER_BUTTON_A => SDL_GAMEPAD_BUTTON_SOUTH +* SDL_CONTROLLER_BUTTON_B => SDL_GAMEPAD_BUTTON_EAST +* SDL_CONTROLLER_BUTTON_BACK => SDL_GAMEPAD_BUTTON_BACK +* SDL_CONTROLLER_BUTTON_DPAD_DOWN => SDL_GAMEPAD_BUTTON_DPAD_DOWN +* SDL_CONTROLLER_BUTTON_DPAD_LEFT => SDL_GAMEPAD_BUTTON_DPAD_LEFT +* SDL_CONTROLLER_BUTTON_DPAD_RIGHT => SDL_GAMEPAD_BUTTON_DPAD_RIGHT +* SDL_CONTROLLER_BUTTON_DPAD_UP => SDL_GAMEPAD_BUTTON_DPAD_UP +* SDL_CONTROLLER_BUTTON_GUIDE => SDL_GAMEPAD_BUTTON_GUIDE +* SDL_CONTROLLER_BUTTON_INVALID => SDL_GAMEPAD_BUTTON_INVALID +* SDL_CONTROLLER_BUTTON_LEFTSHOULDER => SDL_GAMEPAD_BUTTON_LEFT_SHOULDER +* SDL_CONTROLLER_BUTTON_LEFTSTICK => SDL_GAMEPAD_BUTTON_LEFT_STICK +* SDL_CONTROLLER_BUTTON_MAX => SDL_GAMEPAD_BUTTON_MAX +* SDL_CONTROLLER_BUTTON_MISC1 => SDL_GAMEPAD_BUTTON_MISC1 +* SDL_CONTROLLER_BUTTON_PADDLE1 => SDL_GAMEPAD_BUTTON_RIGHT_PADDLE1 +* SDL_CONTROLLER_BUTTON_PADDLE2 => SDL_GAMEPAD_BUTTON_LEFT_PADDLE1 +* SDL_CONTROLLER_BUTTON_PADDLE3 => SDL_GAMEPAD_BUTTON_RIGHT_PADDLE2 +* SDL_CONTROLLER_BUTTON_PADDLE4 => SDL_GAMEPAD_BUTTON_LEFT_PADDLE2 +* SDL_CONTROLLER_BUTTON_RIGHTSHOULDER => SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER +* SDL_CONTROLLER_BUTTON_RIGHTSTICK => SDL_GAMEPAD_BUTTON_RIGHT_STICK +* SDL_CONTROLLER_BUTTON_START => SDL_GAMEPAD_BUTTON_START +* SDL_CONTROLLER_BUTTON_TOUCHPAD => SDL_GAMEPAD_BUTTON_TOUCHPAD +* SDL_CONTROLLER_BUTTON_X => SDL_GAMEPAD_BUTTON_WEST +* SDL_CONTROLLER_BUTTON_Y => SDL_GAMEPAD_BUTTON_NORTH +* SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_LEFT => SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT +* SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_PAIR => SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_PAIR +* SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT => SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT +* SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO => SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO +* SDL_CONTROLLER_TYPE_PS3 => SDL_GAMEPAD_TYPE_PS3 +* SDL_CONTROLLER_TYPE_PS4 => SDL_GAMEPAD_TYPE_PS4 +* SDL_CONTROLLER_TYPE_PS5 => SDL_GAMEPAD_TYPE_PS5 +* SDL_CONTROLLER_TYPE_UNKNOWN => SDL_GAMEPAD_TYPE_STANDARD +* SDL_CONTROLLER_TYPE_VIRTUAL => SDL_GAMEPAD_TYPE_VIRTUAL +* SDL_CONTROLLER_TYPE_XBOX360 => SDL_GAMEPAD_TYPE_XBOX360 +* SDL_CONTROLLER_TYPE_XBOXONE => SDL_GAMEPAD_TYPE_XBOXONE + +## SDL_gesture.h + +The gesture API has been removed. There is no replacement planned in SDL3. +However, the SDL2 code has been moved to a single-header library that can +be dropped into an SDL3 or SDL2 program, to continue to provide this +functionality to your app and aid migration. That is located in the +[SDL_gesture GitHub repository](https://github.com/libsdl-org/SDL_gesture). + +## SDL_hints.h + +SDL_AddHintCallback() now returns a standard int result instead of void, returning 0 if the function succeeds or a negative error code if there was an error. + +Calling SDL_GetHint() with the name of the hint being changed from within a hint callback will now return the new value rather than the old value. The old value is still passed as a parameter to the hint callback. + +The following hints have been removed: +* SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS - gamepad buttons are always positional +* SDL_HINT_IDLE_TIMER_DISABLED - use SDL_DisableScreenSaver instead +* SDL_HINT_IME_SUPPORT_EXTENDED_TEXT - the normal text editing event has extended text +* SDL_HINT_MOUSE_RELATIVE_SCALING - mouse coordinates are no longer automatically scaled by the SDL renderer +* SDL_HINT_RENDER_LOGICAL_SIZE_MODE - the logical size mode is explicitly set with SDL_SetRenderLogicalPresentation() +* SDL_HINT_RENDER_BATCHING - Render batching is always enabled, apps should call SDL_FlushRenderer() before calling into a lower-level graphics API. +* SDL_HINT_VIDEO_FOREIGN_WINDOW_OPENGL - replaced with the "opengl" property in SDL_CreateWindowWithProperties() +* SDL_HINT_VIDEO_FOREIGN_WINDOW_VULKAN - replaced with the "vulkan" property in SDL_CreateWindowWithProperties() +* SDL_HINT_VIDEO_HIGHDPI_DISABLED - high DPI support is always enabled +* SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT - replaced with the "win32.pixel_format_hwnd" in SDL_CreateWindowWithProperties() +* SDL_HINT_VIDEO_X11_FORCE_EGL - use SDL_HINT_VIDEO_FORCE_EGL instead +* SDL_HINT_VIDEO_X11_XINERAMA - Xinerama no longer supported by the X11 backend +* SDL_HINT_VIDEO_X11_XVIDMODE - Xvidmode no longer supported by the X11 backend + +* Renamed hints SDL_HINT_VIDEODRIVER and SDL_HINT_AUDIODRIVER to SDL_HINT_VIDEO_DRIVER and SDL_HINT_AUDIO_DRIVER +* Renamed environment variables SDL_VIDEODRIVER and SDL_AUDIODRIVER to SDL_VIDEO_DRIVER and SDL_AUDIO_DRIVER +* The environment variables SDL_VIDEO_X11_WMCLASS and SDL_VIDEO_WAYLAND_WMCLASS have been removed and replaced with the unified hint SDL_HINT_APP_ID + +## SDL_init.h + +The following symbols have been renamed: +* SDL_INIT_GAMECONTROLLER => SDL_INIT_GAMEPAD + +The following symbols have been removed: +* SDL_INIT_NOPARACHUTE + +## SDL_joystick.h + +SDL_JoystickID has changed from Sint32 to Uint32, with an invalid ID being 0. + +Rather than iterating over joysticks using device index, there is a new function SDL_GetJoysticks() to get the current list of joysticks, and new functions to get information about joysticks from their instance ID: +```c +{ + if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) == 0) { + int i, num_joysticks; + SDL_JoystickID *joysticks = SDL_GetJoysticks(&num_joysticks); + if (joysticks) { + for (i = 0; i < num_joysticks; ++i) { + SDL_JoystickID instance_id = joysticks[i]; + const char *name = SDL_GetJoystickInstanceName(instance_id); + const char *path = SDL_GetJoystickInstancePath(instance_id); + + SDL_Log("Joystick %" SDL_PRIu32 ": %s%s%s VID 0x%.4x, PID 0x%.4x\n", + instance_id, name ? name : "Unknown", path ? ", " : "", path ? path : "", SDL_GetJoystickInstanceVendor(instance_id), SDL_GetJoystickInstanceProduct(instance_id)); + } + SDL_free(joysticks); + } + SDL_QuitSubSystem(SDL_INIT_JOYSTICK); + } +} +``` + +The SDL_EVENT_JOYSTICK_ADDED event now provides the joystick instance ID in the `which` member of the jdevice event structure. + +The functions SDL_GetJoysticks(), SDL_GetJoystickInstanceName(), SDL_GetJoystickInstancePath(), SDL_GetJoystickInstancePlayerIndex(), SDL_GetJoystickInstanceGUID(), SDL_GetJoystickInstanceVendor(), SDL_GetJoystickInstanceProduct(), SDL_GetJoystickInstanceProductVersion(), and SDL_GetJoystickInstanceType() have been added to directly query the list of available joysticks. + +SDL_AttachVirtualJoystick() and SDL_AttachVirtualJoystickEx() now return the joystick instance ID instead of a device index, and return 0 if there was an error. + +The following functions have been renamed: +* SDL_JoystickAttachVirtual() => SDL_AttachVirtualJoystick() +* SDL_JoystickAttachVirtualEx() => SDL_AttachVirtualJoystickEx() +* SDL_JoystickClose() => SDL_CloseJoystick() +* SDL_JoystickCurrentPowerLevel() => SDL_GetJoystickPowerLevel() +* SDL_JoystickDetachVirtual() => SDL_DetachVirtualJoystick() +* SDL_JoystickFromInstanceID() => SDL_GetJoystickFromInstanceID() +* SDL_JoystickFromPlayerIndex() => SDL_GetJoystickFromPlayerIndex() +* SDL_JoystickGetAttached() => SDL_JoystickConnected() +* SDL_JoystickGetAxis() => SDL_GetJoystickAxis() +* SDL_JoystickGetAxisInitialState() => SDL_GetJoystickAxisInitialState() +* SDL_JoystickGetButton() => SDL_GetJoystickButton() +* SDL_JoystickGetFirmwareVersion() => SDL_GetJoystickFirmwareVersion() +* SDL_JoystickGetGUID() => SDL_GetJoystickGUID() +* SDL_JoystickGetGUIDFromString() => SDL_GetJoystickGUIDFromString() +* SDL_JoystickGetGUIDString() => SDL_GetJoystickGUIDString() +* SDL_JoystickGetHat() => SDL_GetJoystickHat() +* SDL_JoystickGetPlayerIndex() => SDL_GetJoystickPlayerIndex() +* SDL_JoystickGetProduct() => SDL_GetJoystickProduct() +* SDL_JoystickGetProductVersion() => SDL_GetJoystickProductVersion() +* SDL_JoystickGetSerial() => SDL_GetJoystickSerial() +* SDL_JoystickGetType() => SDL_GetJoystickType() +* SDL_JoystickGetVendor() => SDL_GetJoystickVendor() +* SDL_JoystickInstanceID() => SDL_GetJoystickInstanceID() +* SDL_JoystickIsVirtual() => SDL_IsJoystickVirtual() +* SDL_JoystickName() => SDL_GetJoystickName() +* SDL_JoystickNumAxes() => SDL_GetNumJoystickAxes() +* SDL_JoystickNumButtons() => SDL_GetNumJoystickButtons() +* SDL_JoystickNumHats() => SDL_GetNumJoystickHats() +* SDL_JoystickOpen() => SDL_OpenJoystick() +* SDL_JoystickPath() => SDL_GetJoystickPath() +* SDL_JoystickRumble() => SDL_RumbleJoystick() +* SDL_JoystickRumbleTriggers() => SDL_RumbleJoystickTriggers() +* SDL_JoystickSendEffect() => SDL_SendJoystickEffect() +* SDL_JoystickSetLED() => SDL_SetJoystickLED() +* SDL_JoystickSetPlayerIndex() => SDL_SetJoystickPlayerIndex() +* SDL_JoystickSetVirtualAxis() => SDL_SetJoystickVirtualAxis() +* SDL_JoystickSetVirtualButton() => SDL_SetJoystickVirtualButton() +* SDL_JoystickSetVirtualHat() => SDL_SetJoystickVirtualHat() +* SDL_JoystickUpdate() => SDL_UpdateJoysticks() + +The following symbols have been renamed: +* SDL_JOYSTICK_TYPE_GAMECONTROLLER => SDL_JOYSTICK_TYPE_GAMEPAD + +The following functions have been removed: +* SDL_JoystickEventState() - replaced with SDL_SetJoystickEventsEnabled() and SDL_JoystickEventsEnabled() +* SDL_JoystickGetDeviceGUID() - replaced with SDL_GetJoystickInstanceGUID() +* SDL_JoystickGetDeviceInstanceID() +* SDL_JoystickGetDevicePlayerIndex() - replaced with SDL_GetJoystickInstancePlayerIndex() +* SDL_JoystickGetDeviceProduct() - replaced with SDL_GetJoystickInstanceProduct() +* SDL_JoystickGetDeviceProductVersion() - replaced with SDL_GetJoystickInstanceProductVersion() +* SDL_JoystickGetDeviceType() - replaced with SDL_GetJoystickInstanceType() +* SDL_JoystickGetDeviceVendor() - replaced with SDL_GetJoystickInstanceVendor() +* SDL_JoystickNameForIndex() - replaced with SDL_GetJoystickInstanceName() +* SDL_JoystickNumBalls() - API has been removed, see https://github.com/libsdl-org/SDL/issues/6766 +* SDL_JoystickPathForIndex() - replaced with SDL_GetJoystickInstancePath() +* SDL_NumJoysticks() - replaced with SDL_GetJoysticks() + +The following symbols have been removed: +* SDL_JOYBALLMOTION + +## SDL_keyboard.h + +The following functions have been renamed: +* SDL_IsScreenKeyboardShown() => SDL_ScreenKeyboardShown() +* SDL_IsTextInputActive() => SDL_TextInputActive() +* SDL_IsTextInputShown() => SDL_TextInputShown() + +## SDL_keycode.h + +The following symbols have been renamed: +* KMOD_ALT => SDL_KMOD_ALT +* KMOD_CAPS => SDL_KMOD_CAPS +* KMOD_CTRL => SDL_KMOD_CTRL +* KMOD_GUI => SDL_KMOD_GUI +* KMOD_LALT => SDL_KMOD_LALT +* KMOD_LCTRL => SDL_KMOD_LCTRL +* KMOD_LGUI => SDL_KMOD_LGUI +* KMOD_LSHIFT => SDL_KMOD_LSHIFT +* KMOD_MODE => SDL_KMOD_MODE +* KMOD_NONE => SDL_KMOD_NONE +* KMOD_NUM => SDL_KMOD_NUM +* KMOD_RALT => SDL_KMOD_RALT +* KMOD_RCTRL => SDL_KMOD_RCTRL +* KMOD_RESERVED => SDL_KMOD_RESERVED +* KMOD_RGUI => SDL_KMOD_RGUI +* KMOD_RSHIFT => SDL_KMOD_RSHIFT +* KMOD_SCROLL => SDL_KMOD_SCROLL +* KMOD_SHIFT => SDL_KMOD_SHIFT + +## SDL_loadso.h + +SDL_LoadFunction() now returns `SDL_FunctionPointer` instead of `void *`, and should be cast to the appropriate function type. You can define SDL_FUNCTION_POINTER_IS_VOID_POINTER in your project to restore the previous behavior. + +## SDL_main.h + +SDL3 doesn't have a static libSDLmain to link against anymore. +Instead SDL_main.h is now a header-only library **and not included by SDL.h anymore**. + +Using it is really simple: Just `#include ` in the source file with your standard +`int main(int argc, char* argv[])` function. + +## SDL_metal.h + +SDL_Metal_GetDrawableSize() has been removed. SDL_GetWindowSizeInPixels() can be used in its place. + +## SDL_mouse.h + +SDL_ShowCursor() has been split into three functions: SDL_ShowCursor(), SDL_HideCursor(), and SDL_CursorVisible() + +SDL_GetMouseState(), SDL_GetGlobalMouseState(), SDL_GetRelativeMouseState(), SDL_WarpMouseInWindow(), and SDL_WarpMouseGlobal() all use floating point mouse positions, to provide sub-pixel precision on platforms that support it. + +The following functions have been renamed: +* SDL_FreeCursor() => SDL_DestroyCursor() + +## SDL_mutex.h + +SDL_MUTEX_MAXWAIT has been removed; it suggested there was a maximum timeout one could outlive, instead of an infinite wait. Instead, pass a -1 to functions that accepted this symbol. + +SDL_LockMutex and SDL_UnlockMutex now return void; if the mutex is valid (including being a NULL pointer, which returns immediately), these functions never fail. If the mutex is invalid or the caller does something illegal, like unlock another thread's mutex, this is considered undefined behavior. + +The following functions have been renamed: +* SDL_CondBroadcast() => SDL_BroadcastCondition() +* SDL_CondSignal() => SDL_SignalCondition() +* SDL_CondWait() => SDL_WaitCondition() +* SDL_CondWaitTimeout() => SDL_WaitConditionTimeout() +* SDL_CreateCond() => SDL_CreateCondition() +* SDL_DestroyCond() => SDL_DestroyCondition() +* SDL_SemPost() => SDL_PostSemaphore() +* SDL_SemTryWait() => SDL_TryWaitSemaphore() +* SDL_SemValue() => SDL_GetSemaphoreValue() +* SDL_SemWait() => SDL_WaitSemaphore() +* SDL_SemWaitTimeout() => SDL_WaitSemaphoreTimeout() + +The following symbols have been renamed: +* SDL_cond => SDL_Condition +* SDL_mutex => SDL_Mutex +* SDL_sem => SDL_Semaphore + +## SDL_pixels.h + +SDL_CalculateGammaRamp has been removed, because SDL_SetWindowGammaRamp has been removed as well due to poor support in modern operating systems (see [SDL_video.h](#sdl_videoh)). + +The following functions have been renamed: +* SDL_AllocFormat() => SDL_CreatePixelFormat() +* SDL_AllocPalette() => SDL_CreatePalette() +* SDL_FreeFormat() => SDL_DestroyPixelFormat() +* SDL_FreePalette() => SDL_DestroyPalette() +* SDL_MasksToPixelFormatEnum() => SDL_GetPixelFormatEnumForMasks() +* SDL_PixelFormatEnumToMasks() => SDL_GetMasksForPixelFormatEnum() + +The following symbols have been renamed: +* SDL_DISPLAYEVENT_DISCONNECTED => SDL_EVENT_DISPLAY_REMOVED +* SDL_DISPLAYEVENT_MOVED => SDL_EVENT_DISPLAY_MOVED +* SDL_DISPLAYEVENT_ORIENTATION => SDL_EVENT_DISPLAY_ORIENTATION +* SDL_WINDOWEVENT_CLOSE => SDL_EVENT_WINDOW_CLOSE_REQUESTED +* SDL_WINDOWEVENT_DISPLAY_CHANGED => SDL_EVENT_WINDOW_DISPLAY_CHANGED +* SDL_WINDOWEVENT_ENTER => SDL_EVENT_WINDOW_ENTER +* SDL_WINDOWEVENT_EXPOSED => SDL_EVENT_WINDOW_EXPOSED +* SDL_WINDOWEVENT_FOCUS_GAINED => SDL_EVENT_WINDOW_FOCUS_GAINED +* SDL_WINDOWEVENT_FOCUS_LOST => SDL_EVENT_WINDOW_FOCUS_LOST +* SDL_WINDOWEVENT_HIDDEN => SDL_EVENT_WINDOW_HIDDEN +* SDL_WINDOWEVENT_HIT_TEST => SDL_EVENT_WINDOW_HIT_TEST +* SDL_WINDOWEVENT_ICCPROF_CHANGED => SDL_EVENT_WINDOW_ICCPROF_CHANGED +* SDL_WINDOWEVENT_LEAVE => SDL_EVENT_WINDOW_LEAVE +* SDL_WINDOWEVENT_MAXIMIZED => SDL_EVENT_WINDOW_MAXIMIZED +* SDL_WINDOWEVENT_MINIMIZED => SDL_EVENT_WINDOW_MINIMIZED +* SDL_WINDOWEVENT_MOVED => SDL_EVENT_WINDOW_MOVED +* SDL_WINDOWEVENT_RESIZED => SDL_EVENT_WINDOW_RESIZED +* SDL_WINDOWEVENT_RESTORED => SDL_EVENT_WINDOW_RESTORED +* SDL_WINDOWEVENT_SHOWN => SDL_EVENT_WINDOW_SHOWN +* SDL_WINDOWEVENT_SIZE_CHANGED => SDL_EVENT_WINDOW_SIZE_CHANGED +* SDL_WINDOWEVENT_TAKE_FOCUS => SDL_EVENT_WINDOW_TAKE_FOCUS + + +## SDL_platform.h + +The preprocessor symbol `__MACOSX__` has been renamed `__MACOS__`, and `__IPHONEOS__` has been renamed `__IOS__` + +## SDL_rect.h + +The following functions have been renamed: +* SDL_EncloseFPoints() => SDL_GetRectEnclosingPointsFloat() +* SDL_EnclosePoints() => SDL_GetRectEnclosingPoints() +* SDL_FRectEmpty() => SDL_RectEmptyFloat() +* SDL_FRectEquals() => SDL_RectsEqualFloat() +* SDL_FRectEqualsEpsilon() => SDL_RectsEqualEpsilon() +* SDL_HasIntersection() => SDL_HasRectIntersection() +* SDL_HasIntersectionF() => SDL_HasRectIntersectionFloat() +* SDL_IntersectFRect() => SDL_GetRectIntersectionFloat() +* SDL_IntersectFRectAndLine() => SDL_GetRectAndLineIntersectionFloat() +* SDL_IntersectRect() => SDL_GetRectIntersection() +* SDL_IntersectRectAndLine() => SDL_GetRectAndLineIntersection() +* SDL_PointInFRect() => SDL_PointInRectFloat() +* SDL_RectEquals() => SDL_RectsEqual() +* SDL_UnionFRect() => SDL_GetRectUnionFloat() +* SDL_UnionRect() => SDL_GetRectUnion() + +## SDL_render.h + +The 2D renderer API always uses batching in SDL3. There is no magic to turn +it on and off; it doesn't matter if you select a specific renderer or try to +use any hint. This means that all apps that use SDL3's 2D renderer and also +want to call directly into the platform's lower-layer graphics API _must_ call +SDL_RenderFlush() before doing so. This will make sure any pending rendering +work from SDL is done before the app starts directly drawing. + +SDL_GetRenderDriverInfo() has been removed, since most of the information it reported were +estimates and could not be accurate before creating a renderer. Often times this function +was used to figure out the index of a driver, so one would call it in a for-loop, looking +for the driver named "opengl" or whatnot. SDL_GetRenderDriver() has been added for this +functionality, which returns only the name of the driver. + +Additionally, SDL_CreateRenderer()'s second argument is no longer an integer index, but a +`const char *` representing a renderer's name; if you were just using a for-loop to find +which index is the "opengl" or whatnot driver, you can just pass that string directly +here, now. Passing NULL is the same as passing -1 here in SDL2, to signify you want SDL +to decide for you. + +The SDL_RENDERER_TARGETTEXTURE flag has been removed, all current renderers support target texture functionality. + +When a renderer is created, it will automatically set the logical size to the size of +the window in points. For high DPI displays, this will set up scaling from points to +pixels. You can disable this scaling with: +```c + SDL_SetRenderLogicalPresentation(renderer, 0, 0, SDL_LOGICAL_PRESENTATION_DISABLED, SDL_SCALEMODE_NEAREST); +``` + +Mouse and touch events are no longer filtered to change their coordinates, instead you +can call SDL_ConvertEventToRenderCoordinates() to explicitly map event coordinates into +the rendering viewport. + +SDL_RenderWindowToLogical() and SDL_RenderLogicalToWindow() have been renamed SDL_RenderCoordinatesFromWindow() and SDL_RenderCoordinatesToWindow() and take floating point coordinates in both directions. + +The viewport, clipping state, and scale for render targets are now persistent and will remain set whenever they are active. + +The following functions have been renamed: +* SDL_GetRendererOutputSize() => SDL_GetCurrentRenderOutputSize() +* SDL_RenderCopy() => SDL_RenderTexture() +* SDL_RenderCopyEx() => SDL_RenderTextureRotated() +* SDL_RenderCopyExF() => SDL_RenderTextureRotated() +* SDL_RenderCopyF() => SDL_RenderTexture() +* SDL_RenderDrawLine() => SDL_RenderLine() +* SDL_RenderDrawLineF() => SDL_RenderLine() +* SDL_RenderDrawLines() => SDL_RenderLines() +* SDL_RenderDrawLinesF() => SDL_RenderLines() +* SDL_RenderDrawPoint() => SDL_RenderPoint() +* SDL_RenderDrawPointF() => SDL_RenderPoint() +* SDL_RenderDrawPoints() => SDL_RenderPoints() +* SDL_RenderDrawPointsF() => SDL_RenderPoints() +* SDL_RenderDrawRect() => SDL_RenderRect() +* SDL_RenderDrawRectF() => SDL_RenderRect() +* SDL_RenderDrawRects() => SDL_RenderRects() +* SDL_RenderDrawRectsF() => SDL_RenderRects() +* SDL_RenderFillRectF() => SDL_RenderFillRect() +* SDL_RenderFillRectsF() => SDL_RenderFillRects() +* SDL_RenderGetClipRect() => SDL_GetRenderClipRect() +* SDL_RenderGetIntegerScale() => SDL_GetRenderIntegerScale() +* SDL_RenderGetLogicalSize() => SDL_GetRenderLogicalPresentation() +* SDL_RenderGetMetalCommandEncoder() => SDL_GetRenderMetalCommandEncoder() +* SDL_RenderGetMetalLayer() => SDL_GetRenderMetalLayer() +* SDL_RenderGetScale() => SDL_GetRenderScale() +* SDL_RenderGetViewport() => SDL_GetRenderViewport() +* SDL_RenderGetWindow() => SDL_GetRenderWindow() +* SDL_RenderIsClipEnabled() => SDL_RenderClipEnabled() +* SDL_RenderLogicalToWindow() => SDL_RenderCoordinatesToWindow() +* SDL_RenderSetClipRect() => SDL_SetRenderClipRect() +* SDL_RenderSetIntegerScale() => SDL_SetRenderIntegerScale() +* SDL_RenderSetLogicalSize() => SDL_SetRenderLogicalPresentation() +* SDL_RenderSetScale() => SDL_SetRenderScale() +* SDL_RenderSetVSync() => SDL_SetRenderVSync() +* SDL_RenderSetViewport() => SDL_SetRenderViewport() +* SDL_RenderWindowToLogical() => SDL_RenderCoordinatesFromWindow() + +The following functions have been removed: +* SDL_GetTextureUserData() - use SDL_GetTextureProperties() instead +* SDL_RenderGetIntegerScale() +* SDL_RenderSetIntegerScale() - this is now explicit with SDL_LOGICAL_PRESENTATION_INTEGER_SCALE +* SDL_RenderTargetSupported() - render targets are always supported +* SDL_SetTextureUserData() - use SDL_GetTextureProperties() instead + +The following symbols have been renamed: +* SDL_ScaleModeBest => SDL_SCALEMODE_BEST +* SDL_ScaleModeLinear => SDL_SCALEMODE_LINEAR +* SDL_ScaleModeNearest => SDL_SCALEMODE_NEAREST + +## SDL_rwops.h + +The following symbols have been renamed: +* RW_SEEK_CUR => SDL_RW_SEEK_CUR +* RW_SEEK_END => SDL_RW_SEEK_END +* RW_SEEK_SET => SDL_RW_SEEK_SET + +SDL_RWread and SDL_RWwrite (and SDL_RWops::read, SDL_RWops::write) have a different function signature in SDL3. + +Previously they looked more like stdio: + +```c +size_t SDL_RWread(SDL_RWops *context, void *ptr, size_t size, size_t maxnum); +size_t SDL_RWwrite(SDL_RWops *context, const void *ptr, size_t size, size_t maxnum); +``` + +But now they look more like POSIX: + +```c +size_t SDL_RWread(SDL_RWops *context, void *ptr, size_t size); +size_t SDL_RWwrite(SDL_RWops *context, const void *ptr, size_t size); +``` + +Code that used to look like this: +``` +size_t custom_read(void *ptr, size_t size, size_t nitems, SDL_RWops *stream) +{ + return SDL_RWread(stream, ptr, size, nitems); +} +``` +should be changed to: +``` +size_t custom_read(void *ptr, size_t size, size_t nitems, SDL_RWops *stream) +{ + if (size > 0 && nitems > 0) { + return SDL_RWread(stream, ptr, size * nitems) / size; + } + return 0; +} +``` + +SDL_RWFromFP has been removed from the API, due to issues when the SDL library uses a different C runtime from the application. + +You can implement this in your own code easily: +```c +#include + + +static Sint64 SDLCALL stdio_seek(SDL_RWops *context, Sint64 offset, int whence) +{ + int stdiowhence; + + switch (whence) { + case SDL_RW_SEEK_SET: + stdiowhence = SEEK_SET; + break; + case SDL_RW_SEEK_CUR: + stdiowhence = SEEK_CUR; + break; + case SDL_RW_SEEK_END: + stdiowhence = SEEK_END; + break; + default: + return SDL_SetError("Unknown value for 'whence'"); + } + + if (fseek((FILE *)context->hidden.stdio.fp, (fseek_off_t)offset, stdiowhence) == 0) { + Sint64 pos = ftell((FILE *)context->hidden.stdio.fp); + if (pos < 0) { + return SDL_SetError("Couldn't get stream offset"); + } + return pos; + } + return SDL_Error(SDL_EFSEEK); +} + +static size_t SDLCALL stdio_read(SDL_RWops *context, void *ptr, size_t size) +{ + size_t bytes; + + bytes = fread(ptr, 1, size, (FILE *)context->hidden.stdio.fp); + if (bytes == 0 && ferror((FILE *)context->hidden.stdio.fp)) { + SDL_Error(SDL_EFREAD); + } + return bytes; +} + +static size_t SDLCALL stdio_write(SDL_RWops *context, const void *ptr, size_t size) +{ + size_t bytes; + + bytes = fwrite(ptr, 1, size, (FILE *)context->hidden.stdio.fp); + if (bytes == 0 && ferror((FILE *)context->hidden.stdio.fp)) { + SDL_Error(SDL_EFWRITE); + } + return bytes; +} + +static int SDLCALL stdio_close(SDL_RWops *context) +{ + int status = 0; + if (context->hidden.stdio.autoclose) { + if (fclose((FILE *)context->hidden.stdio.fp) != 0) { + status = SDL_Error(SDL_EFWRITE); + } + } + SDL_DestroyRW(context); + return status; +} + +SDL_RWops *SDL_RWFromFP(void *fp, SDL_bool autoclose) +{ + SDL_RWops *rwops = NULL; + + rwops = SDL_CreateRW(); + if (rwops != NULL) { + rwops->seek = stdio_seek; + rwops->read = stdio_read; + rwops->write = stdio_write; + rwops->close = stdio_close; + rwops->hidden.stdio.fp = fp; + rwops->hidden.stdio.autoclose = autoclose; + rwops->type = SDL_RWOPS_STDFILE; + } + return rwops; +} +``` + +The functions SDL_ReadU8(), SDL_ReadU16LE(), SDL_ReadU16BE(), SDL_ReadU32LE(), SDL_ReadU32BE(), SDL_ReadU64LE(), and SDL_ReadU64BE() now return SDL_TRUE if the read succeeded and SDL_FALSE if it didn't, and store the data in a pointer passed in as a parameter. + +The following functions have been renamed: +* SDL_AllocRW() => SDL_CreateRW() +* SDL_FreeRW() => SDL_DestroyRW() +* SDL_ReadBE16() => SDL_ReadU16BE() +* SDL_ReadBE32() => SDL_ReadU32BE() +* SDL_ReadBE64() => SDL_ReadU64BE() +* SDL_ReadLE16() => SDL_ReadU16LE() +* SDL_ReadLE32() => SDL_ReadU32LE() +* SDL_ReadLE64() => SDL_ReadU64LE() +* SDL_WriteBE16() => SDL_WriteU16BE() +* SDL_WriteBE32() => SDL_WriteU32BE() +* SDL_WriteBE64() => SDL_WriteU64BE() +* SDL_WriteLE16() => SDL_WriteU16LE() +* SDL_WriteLE32() => SDL_WriteU32LE() +* SDL_WriteLE64() => SDL_WriteU64LE() + +## SDL_sensor.h + +SDL_SensorID has changed from Sint32 to Uint32, with an invalid ID being 0. + +Rather than iterating over sensors using device index, there is a new function SDL_GetSensors() to get the current list of sensors, and new functions to get information about sensors from their instance ID: +```c +{ + if (SDL_InitSubSystem(SDL_INIT_SENSOR) == 0) { + int i, num_sensors; + SDL_SensorID *sensors = SDL_GetSensors(&num_sensors); + if (sensors) { + for (i = 0; i < num_sensors; ++i) { + SDL_Log("Sensor %" SDL_PRIu32 ": %s, type %d, platform type %d\n", + sensors[i], + SDL_GetSensorInstanceName(sensors[i]), + SDL_GetSensorInstanceType(sensors[i]), + SDL_GetSensorInstanceNonPortableType(sensors[i])); + } + SDL_free(sensors); + } + SDL_QuitSubSystem(SDL_INIT_SENSOR); + } +} +``` + +Removed SDL_SensorGetDataWithTimestamp(), if you want timestamps for the sensor data, you should use the sensor_timestamp member of SDL_EVENT_SENSOR_UPDATE events. + + +The following functions have been renamed: +* SDL_SensorClose() => SDL_CloseSensor() +* SDL_SensorFromInstanceID() => SDL_GetSensorFromInstanceID() +* SDL_SensorGetData() => SDL_GetSensorData() +* SDL_SensorGetInstanceID() => SDL_GetSensorInstanceID() +* SDL_SensorGetName() => SDL_GetSensorName() +* SDL_SensorGetNonPortableType() => SDL_GetSensorNonPortableType() +* SDL_SensorGetType() => SDL_GetSensorType() +* SDL_SensorOpen() => SDL_OpenSensor() +* SDL_SensorUpdate() => SDL_UpdateSensors() + +The following functions have been removed: +* SDL_LockSensors() +* SDL_NumSensors() - replaced with SDL_GetSensors() +* SDL_SensorGetDeviceInstanceID() +* SDL_SensorGetDeviceName() - replaced with SDL_GetSensorInstanceName() +* SDL_SensorGetDeviceNonPortableType() - replaced with SDL_GetSensorInstanceNonPortableType() +* SDL_SensorGetDeviceType() - replaced with SDL_GetSensorInstanceType() +* SDL_UnlockSensors() + +## SDL_shape.h + +This header has been removed. You can create a window with the SDL_WINDOW_TRANSPARENT flag and then render using the alpha channel to achieve a similar effect. You can see an example of this in test/testshape.c + +## SDL_stdinc.h + +The standard C headers like stdio.h and stdlib.h are no longer included, you should include them directly in your project if you use non-SDL C runtime functions. +M_PI is no longer defined in SDL_stdinc.h, you can use the new symbols SDL_PI_D (double) and SDL_PI_F (float) instead. + + +The following functions have been renamed: +* SDL_strtokr() => SDL_strtok_r() + +## SDL_surface.h + +The userdata member of SDL_Surface has been replaced with a more general properties interface, which can be queried with SDL_GetSurfaceProperties() + +Removed unused 'flags' parameter from SDL_ConvertSurface and SDL_ConvertSurfaceFormat. + +SDL_CreateRGBSurface() and SDL_CreateRGBSurfaceWithFormat() have been combined into a new function SDL_CreateSurface(). +SDL_CreateRGBSurfaceFrom() and SDL_CreateRGBSurfaceWithFormatFrom() have been combined into a new function SDL_CreateSurfaceFrom(). + +You can implement the old functions in your own code easily: +```c +SDL_Surface *SDL_CreateRGBSurface(Uint32 flags, int width, int height, int depth, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask) +{ + return SDL_CreateSurface(width, height, + SDL_GetPixelFormatEnumForMasks(depth, Rmask, Gmask, Bmask, Amask)); +} + +SDL_Surface *SDL_CreateRGBSurfaceWithFormat(Uint32 flags, int width, int height, int depth, Uint32 format) +{ + return SDL_CreateSurface(width, height, format); +} + +SDL_Surface *SDL_CreateRGBSurfaceFrom(void *pixels, int width, int height, int depth, int pitch, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask) +{ + return SDL_CreateSurfaceFrom(pixels, width, height, pitch, + SDL_GetPixelFormatEnumForMasks(depth, Rmask, Gmask, Bmask, Amask)); +} + +SDL_Surface *SDL_CreateRGBSurfaceWithFormatFrom(void *pixels, int width, int height, int depth, int pitch, Uint32 format) +{ + return SDL_CreateSurfaceFrom(pixels, width, height, pitch, format); +} + +``` + +But if you're migrating your code which uses masks, you probably have a format in mind, possibly one of these: +```c +// Various mask (R, G, B, A) and their corresponding format: +0xFF000000 0x00FF0000 0x0000FF00 0x000000FF => SDL_PIXELFORMAT_RGBA8888 +0x00FF0000 0x0000FF00 0x000000FF 0xFF000000 => SDL_PIXELFORMAT_ARGB8888 +0x0000FF00 0x00FF0000 0xFF000000 0x000000FF => SDL_PIXELFORMAT_BGRA8888 +0x000000FF 0x0000FF00 0x00FF0000 0xFF000000 => SDL_PIXELFORMAT_ABGR8888 +0x0000F800 0x000007E0 0x0000001F 0x00000000 => SDL_PIXELFORMAT_RGB565 +``` + + +The following functions have been renamed: +* SDL_FillRect() => SDL_FillSurfaceRect() +* SDL_FillRects() => SDL_FillSurfaceRects() +* SDL_FreeSurface() => SDL_DestroySurface() +* SDL_GetClipRect() => SDL_GetSurfaceClipRect() +* SDL_GetColorKey() => SDL_GetSurfaceColorKey() +* SDL_HasColorKey() => SDL_SurfaceHasColorKey() +* SDL_HasSurfaceRLE() => SDL_SurfaceHasRLE() +* SDL_LowerBlit() => SDL_BlitSurfaceUnchecked() +* SDL_LowerBlitScaled() => SDL_BlitSurfaceUncheckedScaled() +* SDL_SetClipRect() => SDL_SetSurfaceClipRect() +* SDL_SetColorKey() => SDL_SetSurfaceColorKey() +* SDL_UpperBlit() => SDL_BlitSurface() +* SDL_UpperBlitScaled() => SDL_BlitSurfaceScaled() + +## SDL_system.h + +SDL_WindowsMessageHook has changed signatures so the message may be modified and it can block further message processing. + +SDL_AndroidGetExternalStorageState() takes the state as an output parameter and returns 0 if the function succeeds or a negative error code if there was an error. + +The following functions have been removed: +* SDL_RenderGetD3D11Device() - replaced with the "SDL.renderer.d3d11.device" property +* SDL_RenderGetD3D12Device() - replaced with the "SDL.renderer.d3d12.device" property +* SDL_RenderGetD3D9Device() - replaced with the "SDL.renderer.d3d9.device" property + +## SDL_syswm.h + +This header has been removed. + +The Windows and X11 events are now available via callbacks which you can set with SDL_SetWindowsMessageHook() and SDL_SetX11EventHook(). + +The information previously available in SDL_GetWindowWMInfo() is now available as window properties, e.g. +```c + HWND hwnd = NULL; + SDL_SysWMinfo info; + SDL_VERSION(&info.version); + if (SDL_GetWindowWMInfo(window, &info) && info.subsystem == SDL_SYSWM_WINDOWS) { + hwnd = info.info.win.window; + } + if (hwnd) { + ... + } +``` +becomes: +```c + HWND hwnd = (HWND)SDL_GetProperty(SDL_GetWindowProperties(window), "SDL.window.win32.hwnd"); + if (hwnd) { + ... + } +``` + +## SDL_thread.h + +The following functions have been renamed: +* SDL_TLSCleanup() => SDL_CleanupTLS() +* SDL_TLSCreate() => SDL_CreateTLS() +* SDL_TLSGet() => SDL_GetTLS() +* SDL_TLSSet() => SDL_SetTLS() + +## SDL_timer.h + +SDL_GetTicks() now returns a 64-bit value. Instead of using the SDL_TICKS_PASSED macro, you can directly compare tick values, e.g. +```c +Uint32 deadline = SDL_GetTicks() + 1000; +... +if (SDL_TICKS_PASSED(SDL_GetTicks(), deadline)) { + ... +} +``` +becomes: +```c +Uint64 deadline = SDL_GetTicks() + 1000 +... +if (SDL_GetTicks() >= deadline) { + ... +} +``` + +If you were using this macro for other things besides SDL ticks values, you can define it in your own code as: +```c +#define SDL_TICKS_PASSED(A, B) ((Sint32)((B) - (A)) <= 0) +``` + +## SDL_touch.h + +SDL_GetNumTouchFingers() returns a negative error code if there was an error. + +## SDL_version.h + +SDL_GetRevisionNumber() has been removed from the API, it always returned 0 in SDL 2.0. + + +## SDL_video.h + +SDL_VideoInit() and SDL_VideoQuit() have been removed. Instead you can call SDL_InitSubSystem() and SDL_QuitSubSystem() with SDL_INIT_VIDEO, which will properly refcount the subsystems. You can choose a specific video driver using SDL_VIDEO_DRIVER hint. + +Rather than iterating over displays using display index, there is a new function SDL_GetDisplays() to get the current list of displays, and functions which used to take a display index now take SDL_DisplayID, with an invalid ID being 0. +```c +{ + if (SDL_InitSubSystem(SDL_INIT_VIDEO) == 0) { + int i, num_displays = 0; + SDL_DisplayID *displays = SDL_GetDisplays(&num_displays); + if (displays) { + for (i = 0; i < num_displays; ++i) { + SDL_DisplayID instance_id = displays[i]; + const char *name = SDL_GetDisplayName(instance_id); + + SDL_Log("Display %" SDL_PRIu32 ": %s\n", instance_id, name ? name : "Unknown"); + } + SDL_free(displays); + } + SDL_QuitSubSystem(SDL_INIT_VIDEO); + } +} +``` + +SDL_CreateWindow() has been simplified and no longer takes a window position. You can use SDL_CreateWindowWithProperties() if you need to set the window position when creating it. + +The SDL_WINDOWPOS_UNDEFINED_DISPLAY() and SDL_WINDOWPOS_CENTERED_DISPLAY() macros take a display ID instead of display index. The display ID 0 has a special meaning in this case, and is used to indicate the primary display. + +The SDL_WINDOW_SHOWN flag has been removed. Windows are shown by default and can be created hidden by using the SDL_WINDOW_HIDDEN flag. + +The SDL_WINDOW_SKIP_TASKBAR flag has been replaced by the SDL_WINDOW_UTILITY flag, which has the same functionality. + +SDL_DisplayMode now includes the pixel density which can be greater than 1.0 for display modes that have a higher pixel size than the mode size. You should use SDL_GetWindowSizeInPixels() to get the actual pixel size of the window back buffer. + +The refresh rate in SDL_DisplayMode is now a float. + +Rather than iterating over display modes using an index, there is a new function SDL_GetFullscreenDisplayModes() to get the list of available fullscreen modes on a display. +```c +{ + SDL_DisplayID display = SDL_GetPrimaryDisplay(); + int num_modes = 0; + SDL_DisplayMode **modes = SDL_GetFullscreenDisplayModes(display, &num_modes); + if (modes) { + for (i = 0; i < num_modes; ++i) { + SDL_DisplayMode *mode = modes[i]; + SDL_Log("Display %" SDL_PRIu32 " mode %d: %dx%d@%gx %gHz\n", + display, i, mode->w, mode->h, mode->pixel_density, mode->refresh_rate); + } + SDL_free(modes); + } +} +``` + +SDL_GetDesktopDisplayMode() and SDL_GetCurrentDisplayMode() return pointers to display modes rather than filling in application memory. + +Windows now have an explicit fullscreen mode that is set, using SDL_SetWindowFullscreenMode(). The fullscreen mode for a window can be queried with SDL_GetWindowFullscreenMode(), which returns a pointer to the mode, or NULL if the window will be fullscreen desktop. SDL_SetWindowFullscreen() just takes a boolean value, setting the correct fullscreen state based on the selected mode. + +SDL_WINDOW_FULLSCREEN_DESKTOP has been removed, and you can call SDL_GetWindowFullscreenMode() to see whether an exclusive fullscreen mode will be used or the fullscreen desktop mode will be used when the window is fullscreen. + +SDL_SetWindowBrightness and SDL_SetWindowGammaRamp have been removed from the API, because they interact poorly with modern operating systems and aren't able to limit their effects to the SDL window. + +Programs which have access to shaders can implement more robust versions of those functions using custom shader code rendered as a post-process effect. + +Removed SDL_GL_CONTEXT_EGL from OpenGL configuration attributes. You can instead use `SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);` + +SDL_GL_GetProcAddress() and SDL_EGL_GetProcAddress() now return `SDL_FunctionPointer` instead of `void *`, and should be cast to the appropriate function type. You can define SDL_FUNCTION_POINTER_IS_VOID_POINTER in your project to restore the previous behavior. + +SDL_GL_SwapWindow() returns 0 if the function succeeds or a negative error code if there was an error. + +SDL_GL_GetSwapInterval() takes the interval as an output parameter and returns 0 if the function succeeds or a negative error code if there was an error. + +SDL_GL_GetDrawableSize() has been removed. SDL_GetWindowSizeInPixels() can be used in its place. + +The SDL_WINDOW_TOOLTIP and SDL_WINDOW_POPUP_MENU window flags are now supported on Windows, Mac (Cocoa), X11, and Wayland. Creating windows with these flags must happen via the `SDL_CreatePopupWindow()` function. This function requires passing in the handle to a valid parent window for the popup, and the popup window is positioned relative to the parent. + +The following functions have been renamed: +* SDL_GetClosestDisplayMode() => SDL_GetClosestFullscreenDisplayMode() +* SDL_GetDisplayOrientation() => SDL_GetCurrentDisplayOrientation() +* SDL_GetPointDisplayIndex() => SDL_GetDisplayForPoint() +* SDL_GetRectDisplayIndex() => SDL_GetDisplayForRect() +* SDL_GetWindowDisplayIndex() => SDL_GetDisplayForWindow() +* SDL_GetWindowDisplayMode() => SDL_GetWindowFullscreenMode() +* SDL_IsScreenSaverEnabled() => SDL_ScreenSaverEnabled() +* SDL_SetWindowDisplayMode() => SDL_SetWindowFullscreenMode() + +The following functions have been removed: +* SDL_GetClosestFullscreenDisplayMode() +* SDL_GetDisplayDPI() - not reliable across platforms, approximately replaced by multiplying `display_scale` in the structure returned by SDL_GetDesktopDisplayMode() times 160 on iPhone and Android, and 96 on other platforms. +* SDL_GetDisplayMode() +* SDL_GetNumDisplayModes() - replaced with SDL_GetFullscreenDisplayModes() +* SDL_GetNumVideoDisplays() - replaced with SDL_GetDisplays() +* SDL_GetWindowData() - use SDL_GetWindowProperties() instead +* SDL_SetWindowData() - use SDL_GetWindowProperties() instead +* SDL_CreateWindowFrom() - use SDL_CreateWindowWithProperties() with the properties that allow you to wrap an existing window + +SDL_Window id type is named SDL_WindowID + +The following symbols have been renamed: +* SDL_WINDOW_ALLOW_HIGHDPI => SDL_WINDOW_HIGH_PIXEL_DENSITY +* SDL_WINDOW_INPUT_GRABBED => SDL_WINDOW_MOUSE_GRABBED + +## SDL_vulkan.h + +SDL_Vulkan_GetInstanceExtensions() no longer takes a window parameter, and no longer makes the app allocate query/allocate space for the result, instead returning a static const internal string. + +SDL_Vulkan_GetVkGetInstanceProcAddr() now returns `SDL_FunctionPointer` instead of `void *`, and should be cast to PFN_vkGetInstanceProcAddr. + +SDL_Vulkan_CreateSurface() now takes a VkAllocationCallbacks pointer as its third parameter. If you don't have an allocator to supply, pass a NULL here to use the system default allocator (SDL2 always used the system default allocator here). + +SDL_Vulkan_GetDrawableSize() has been removed. SDL_GetWindowSizeInPixels() can be used in its place. diff --git a/docs/README-n3ds.md b/docs/README-n3ds.md index 80da3802d..8f9547390 100644 --- a/docs/README-n3ds.md +++ b/docs/README-n3ds.md @@ -1,28 +1,28 @@ -# Nintendo 3DS - -SDL port for the Nintendo 3DS [Homebrew toolchain](https://devkitpro.org/) contributed by: - -- [Pierre Wendling](https://github.com/FtZPetruska) - -Credits to: - -- The awesome people who ported SDL to other homebrew platforms. -- The Devkitpro team for making all the tools necessary to achieve this. - -## Building - -To build for the Nintendo 3DS, make sure you have devkitARM and cmake installed and run: - -```bash -cmake -S. -Bbuild -DCMAKE_TOOLCHAIN_FILE="$DEVKITPRO/cmake/3DS.cmake" -DCMAKE_BUILD_TYPE=Release -cmake --build build -cmake --install build -``` - -## Notes - -- Currently only software rendering is supported. -- SDL3_main should be used to ensure ROMFS is enabled - this is done with `#include ` in the source file that contains your main function. -- By default, the extra L2 cache and higher clock speeds of the New 2/3DS lineup are enabled. If you wish to turn it off, use `osSetSpeedupEnable(false)` in your main function. -- `SDL_GetBasePath` returns the romfs root instead of the executable's directory. -- The Nintendo 3DS uses a cooperative threading model on a single core, meaning a thread will never yield unless done manually through the `SDL_Delay` functions, or blocking waits (`SDL_LockMutex`, `SDL_WaitSemaphore`, `SDL_WaitCondition`, `SDL_WaitThread`). To avoid starving other threads, `SDL_TryWaitSemaphore` and `SDL_WaitSemaphoreTimeout` will yield if they fail to acquire the semaphore, see https://github.com/libsdl-org/SDL/pull/6776 for more information. +# Nintendo 3DS + +SDL port for the Nintendo 3DS [Homebrew toolchain](https://devkitpro.org/) contributed by: + +- [Pierre Wendling](https://github.com/FtZPetruska) + +Credits to: + +- The awesome people who ported SDL to other homebrew platforms. +- The Devkitpro team for making all the tools necessary to achieve this. + +## Building + +To build for the Nintendo 3DS, make sure you have devkitARM and cmake installed and run: + +```bash +cmake -S. -Bbuild -DCMAKE_TOOLCHAIN_FILE="$DEVKITPRO/cmake/3DS.cmake" -DCMAKE_BUILD_TYPE=Release +cmake --build build +cmake --install build +``` + +## Notes + +- Currently only software rendering is supported. +- SDL3_main should be used to ensure ROMFS is enabled - this is done with `#include ` in the source file that contains your main function. +- By default, the extra L2 cache and higher clock speeds of the New 2/3DS lineup are enabled. If you wish to turn it off, use `osSetSpeedupEnable(false)` in your main function. +- `SDL_GetBasePath` returns the romfs root instead of the executable's directory. +- The Nintendo 3DS uses a cooperative threading model on a single core, meaning a thread will never yield unless done manually through the `SDL_Delay` functions, or blocking waits (`SDL_LockMutex`, `SDL_WaitSemaphore`, `SDL_WaitCondition`, `SDL_WaitThread`). To avoid starving other threads, `SDL_TryWaitSemaphore` and `SDL_WaitSemaphoreTimeout` will yield if they fail to acquire the semaphore, see https://github.com/libsdl-org/SDL/pull/6776 for more information. diff --git a/docs/README-ngage.md b/docs/README-ngage.md index ec4a7121a..363760b99 100644 --- a/docs/README-ngage.md +++ b/docs/README-ngage.md @@ -1,44 +1,44 @@ -Nokia N-Gage -============ - -SDL port for Symbian S60v1 and v2 with a main focus on the Nokia N-Gage -(Classic and QD) by [Michael Fitzmayer](https://github.com/mupfdev). - -Compiling ---------- - -SDL is part of the [N-Gage SDK.](https://github.com/ngagesdk) project. -The library is included in the -[toolchain](https://github.com/ngagesdk/ngage-toolchain) as a -sub-module. - -A complete example project based on SDL can be found in the GitHub -account of the SDK: [Wordle](https://github.com/ngagesdk/wordle). - -Current level of implementation -------------------------------- - -The video driver currently provides full screen video support with -keyboard input. - -At the moment only the software renderer works. - -Audio is not yet implemented. - -Acknowledgements ----------------- - -Thanks to Hannu Viitala, Kimmo Kinnunen and Markus Mertama for the -valuable insight into Symbian programming. Without the SDL 1.2 port -which was specially developed for CDoom (Doom for the Nokia 9210), this -adaptation would not have been possible. - -I would like to thank my friends -[Razvan](https://twitter.com/bewarerazvan) and [Dan -Whelan](https://danwhelan.ie/), for their continuous support. Without -you and the [N-Gage community](https://discord.gg/dbUzqJ26vs), I would -have lost my patience long ago. - -Last but not least, I would like to thank the development team of -[EKA2L1](https://12z1.com/) (an experimental Symbian OS emulator). Your -patience and support in troubleshooting helped me a lot. +Nokia N-Gage +============ + +SDL port for Symbian S60v1 and v2 with a main focus on the Nokia N-Gage +(Classic and QD) by [Michael Fitzmayer](https://github.com/mupfdev). + +Compiling +--------- + +SDL is part of the [N-Gage SDK.](https://github.com/ngagesdk) project. +The library is included in the +[toolchain](https://github.com/ngagesdk/ngage-toolchain) as a +sub-module. + +A complete example project based on SDL can be found in the GitHub +account of the SDK: [Wordle](https://github.com/ngagesdk/wordle). + +Current level of implementation +------------------------------- + +The video driver currently provides full screen video support with +keyboard input. + +At the moment only the software renderer works. + +Audio is not yet implemented. + +Acknowledgements +---------------- + +Thanks to Hannu Viitala, Kimmo Kinnunen and Markus Mertama for the +valuable insight into Symbian programming. Without the SDL 1.2 port +which was specially developed for CDoom (Doom for the Nokia 9210), this +adaptation would not have been possible. + +I would like to thank my friends +[Razvan](https://twitter.com/bewarerazvan) and [Dan +Whelan](https://danwhelan.ie/), for their continuous support. Without +you and the [N-Gage community](https://discord.gg/dbUzqJ26vs), I would +have lost my patience long ago. + +Last but not least, I would like to thank the development team of +[EKA2L1](https://12z1.com/) (an experimental Symbian OS emulator). Your +patience and support in troubleshooting helped me a lot. diff --git a/docs/README-platforms.md b/docs/README-platforms.md index 711557dc0..14454ec5d 100644 --- a/docs/README-platforms.md +++ b/docs/README-platforms.md @@ -1,8 +1,8 @@ -Platforms -========= - -We maintain the list of supported platforms on our wiki now, and how to -build and install SDL for those platforms: - - https://wiki.libsdl.org/Installation - +Platforms +========= + +We maintain the list of supported platforms on our wiki now, and how to +build and install SDL for those platforms: + + https://wiki.libsdl.org/Installation + diff --git a/docs/README-porting.md b/docs/README-porting.md index e2e4d0faa..db6b61413 100644 --- a/docs/README-porting.md +++ b/docs/README-porting.md @@ -1,65 +1,65 @@ -Porting -======= - -* Porting To A New Platform - - The first thing you have to do when porting to a new platform, is look at -include/SDL_platform.h and create an entry there for your operating system. -The standard format is "__PLATFORM__", where PLATFORM is the name of the OS. -Ideally SDL_platform_defines.h will be able to auto-detect the system it's building -on based on C preprocessor symbols. - -There are two basic ways of building SDL at the moment: - -1. CMake: cmake -S . -B build && cmake --build build && cmake --install install - - If you have a system that supports CMake, then you might try this. Edit CMakeLists.txt, - - take a look at the large section labelled: - - "Platform-specific options and settings!" - - Add a section for your platform, and then re-run 'cmake -S . -B build' and build! - -2. Using an IDE: - - If you're using an IDE or other non-configure build system, you'll probably want to create a custom `SDL_build_config.h` for your platform. Edit `include/build_config/SDL_build_config.h`, add a section for your platform, and create a custom `SDL_build_config_{platform}.h`, based on `SDL_build_config_minimal.h` and `SDL_build_config.h.cmake` - - Add the top level include directory to the header search path, and then add - the following sources to the project: - - src/*.c - src/atomic/*.c - src/audio/*.c - src/cpuinfo/*.c - src/events/*.c - src/file/*.c - src/haptic/*.c - src/joystick/*.c - src/power/*.c - src/render/*.c - src/render/software/*.c - src/stdlib/*.c - src/thread/*.c - src/timer/*.c - src/video/*.c - src/audio/disk/*.c - src/audio/dummy/*.c - src/filesystem/dummy/*.c - src/video/dummy/*.c - src/haptic/dummy/*.c - src/joystick/dummy/*.c - src/thread/generic/*.c - src/timer/dummy/*.c - src/loadso/dummy/*.c - - -Once you have a working library without any drivers, you can go back to each -of the major subsystems and start implementing drivers for your platform. - -If you have any questions, don't hesitate to ask on the SDL mailing list: - http://www.libsdl.org/mailing-list.php - -Enjoy! - Sam Lantinga (slouken@libsdl.org) - +Porting +======= + +* Porting To A New Platform + + The first thing you have to do when porting to a new platform, is look at +include/SDL_platform.h and create an entry there for your operating system. +The standard format is "__PLATFORM__", where PLATFORM is the name of the OS. +Ideally SDL_platform_defines.h will be able to auto-detect the system it's building +on based on C preprocessor symbols. + +There are two basic ways of building SDL at the moment: + +1. CMake: cmake -S . -B build && cmake --build build && cmake --install install + + If you have a system that supports CMake, then you might try this. Edit CMakeLists.txt, + + take a look at the large section labelled: + + "Platform-specific options and settings!" + + Add a section for your platform, and then re-run 'cmake -S . -B build' and build! + +2. Using an IDE: + + If you're using an IDE or other non-configure build system, you'll probably want to create a custom `SDL_build_config.h` for your platform. Edit `include/build_config/SDL_build_config.h`, add a section for your platform, and create a custom `SDL_build_config_{platform}.h`, based on `SDL_build_config_minimal.h` and `SDL_build_config.h.cmake` + + Add the top level include directory to the header search path, and then add + the following sources to the project: + + src/*.c + src/atomic/*.c + src/audio/*.c + src/cpuinfo/*.c + src/events/*.c + src/file/*.c + src/haptic/*.c + src/joystick/*.c + src/power/*.c + src/render/*.c + src/render/software/*.c + src/stdlib/*.c + src/thread/*.c + src/timer/*.c + src/video/*.c + src/audio/disk/*.c + src/audio/dummy/*.c + src/filesystem/dummy/*.c + src/video/dummy/*.c + src/haptic/dummy/*.c + src/joystick/dummy/*.c + src/thread/generic/*.c + src/timer/dummy/*.c + src/loadso/dummy/*.c + + +Once you have a working library without any drivers, you can go back to each +of the major subsystems and start implementing drivers for your platform. + +If you have any questions, don't hesitate to ask on the SDL mailing list: + http://www.libsdl.org/mailing-list.php + +Enjoy! + Sam Lantinga (slouken@libsdl.org) + diff --git a/docs/README-ps2.md b/docs/README-ps2.md index 579ad9860..ade0b6d85 100644 --- a/docs/README-ps2.md +++ b/docs/README-ps2.md @@ -1,51 +1,51 @@ -PS2 -====== -SDL port for the Sony Playstation 2 contributed by: -- Francisco Javier Trujillo Mata - - -Credit to - - The guys that ported SDL to PSP & Vita because I'm taking them as reference. - - David G. F. for helping me with several issues and tests. - -## Building -To build SDL library for the PS2, make sure you have the latest PS2Dev status and run: -```bash -cmake -S. -Bbuild -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=$PS2DEV/ps2sdk/ps2dev.cmake -cmake --build build -cmake --install build -``` - -## Hints -The PS2 port has a special Hint for having a dynamic VSYNC. The Hint is `SDL_HINT_PS2_DYNAMIC_VSYNC`. -If you enabled the dynamic vsync having as well `SDL_RENDERER_PRESENTVSYNC` enabled, then if the app is not able to run at 60 FPS, automatically the `vsync` will be disabled having a better performance, instead of dropping FPS to 30. - -## Notes -If you trying to debug a SDL app through [ps2client](https://github.com/ps2dev/ps2client) you need to avoid the IOP reset, otherwise you will lose the connection with your computer. -So to avoid the reset of the IOP CPU, you need to call to the macro `SDL_PS2_SKIP_IOP_RESET();`. -It could be something similar as: -```c -..... - -SDL_PS2_SKIP_IOP_RESET(); - -int main(int argc, char *argv[]) -{ -..... -``` -For a release binary is recommendable to reset the IOP always. - -Remember to do a clean compilation everytime you enable or disable the `SDL_PS2_SKIP_IOP_RESET` otherwise the change won't be reflected. - -## Getting PS2 Dev -[Installing PS2 Dev](https://github.com/ps2dev/ps2dev) - -## Running on PCSX2 Emulator -[PCSX2](https://github.com/PCSX2/pcsx2) - -[More PCSX2 information](https://pcsx2.net/) - -## To Do -- PS2 Screen Keyboard -- Dialogs -- Others +PS2 +====== +SDL port for the Sony Playstation 2 contributed by: +- Francisco Javier Trujillo Mata + + +Credit to + - The guys that ported SDL to PSP & Vita because I'm taking them as reference. + - David G. F. for helping me with several issues and tests. + +## Building +To build SDL library for the PS2, make sure you have the latest PS2Dev status and run: +```bash +cmake -S. -Bbuild -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=$PS2DEV/ps2sdk/ps2dev.cmake +cmake --build build +cmake --install build +``` + +## Hints +The PS2 port has a special Hint for having a dynamic VSYNC. The Hint is `SDL_HINT_PS2_DYNAMIC_VSYNC`. +If you enabled the dynamic vsync having as well `SDL_RENDERER_PRESENTVSYNC` enabled, then if the app is not able to run at 60 FPS, automatically the `vsync` will be disabled having a better performance, instead of dropping FPS to 30. + +## Notes +If you trying to debug a SDL app through [ps2client](https://github.com/ps2dev/ps2client) you need to avoid the IOP reset, otherwise you will lose the connection with your computer. +So to avoid the reset of the IOP CPU, you need to call to the macro `SDL_PS2_SKIP_IOP_RESET();`. +It could be something similar as: +```c +..... + +SDL_PS2_SKIP_IOP_RESET(); + +int main(int argc, char *argv[]) +{ +..... +``` +For a release binary is recommendable to reset the IOP always. + +Remember to do a clean compilation everytime you enable or disable the `SDL_PS2_SKIP_IOP_RESET` otherwise the change won't be reflected. + +## Getting PS2 Dev +[Installing PS2 Dev](https://github.com/ps2dev/ps2dev) + +## Running on PCSX2 Emulator +[PCSX2](https://github.com/PCSX2/pcsx2) + +[More PCSX2 information](https://pcsx2.net/) + +## To Do +- PS2 Screen Keyboard +- Dialogs +- Others diff --git a/docs/README-psp.md b/docs/README-psp.md index e10f5c2dd..c010c6093 100644 --- a/docs/README-psp.md +++ b/docs/README-psp.md @@ -1,36 +1,36 @@ -PSP -====== -SDL port for the Sony PSP contributed by: -- Captian Lex -- Francisco Javier Trujillo Mata -- Wouter Wijsman - - -Credit to - Marcus R.Brown,Jim Paris,Matthew H for the original SDL 1.2 for PSP - Geecko for his PSP GU lib "Glib2d" - -## Building -To build SDL library for the PSP, make sure you have the latest PSPDev status and run: -```bash -cmake -S. -Bbuild -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=$PSPDEV/psp/share/pspdev.cmake -cmake --build build -cmake --install build -``` - - -## Getting PSP Dev -[Installing PSP Dev](https://github.com/pspdev/pspdev) - -## Running on PPSSPP Emulator -[PPSSPP](https://github.com/hrydgard/ppsspp) - -[Build Instructions](https://github.com/hrydgard/ppsspp/wiki/Build-instructions) - - -## Compiling a HelloWorld -[PSP Hello World](https://psp-dev.org/doku.php?id=tutorial:hello_world) - -## To Do -- PSP Screen Keyboard -- Dialogs +PSP +====== +SDL port for the Sony PSP contributed by: +- Captian Lex +- Francisco Javier Trujillo Mata +- Wouter Wijsman + + +Credit to + Marcus R.Brown,Jim Paris,Matthew H for the original SDL 1.2 for PSP + Geecko for his PSP GU lib "Glib2d" + +## Building +To build SDL library for the PSP, make sure you have the latest PSPDev status and run: +```bash +cmake -S. -Bbuild -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=$PSPDEV/psp/share/pspdev.cmake +cmake --build build +cmake --install build +``` + + +## Getting PSP Dev +[Installing PSP Dev](https://github.com/pspdev/pspdev) + +## Running on PPSSPP Emulator +[PPSSPP](https://github.com/hrydgard/ppsspp) + +[Build Instructions](https://github.com/hrydgard/ppsspp/wiki/Build-instructions) + + +## Compiling a HelloWorld +[PSP Hello World](https://psp-dev.org/doku.php?id=tutorial:hello_world) + +## To Do +- PSP Screen Keyboard +- Dialogs diff --git a/docs/README-raspberrypi.md b/docs/README-raspberrypi.md index 94093f023..9984ec6d1 100644 --- a/docs/README-raspberrypi.md +++ b/docs/README-raspberrypi.md @@ -1,180 +1,180 @@ -Raspberry Pi -============ - -Requirements: - -Raspbian (other Linux distros may work as well). - -Features --------- - -* Works without X11 -* Hardware accelerated OpenGL ES 2.x -* Sound via ALSA -* Input (mouse/keyboard/joystick) via EVDEV -* Hotplugging of input devices via UDEV - - -Raspbian Build Dependencies ---------------------------- - -sudo apt-get install libudev-dev libasound2-dev libdbus-1-dev - -You also need the VideoCore binary stuff that ships in /opt/vc for EGL and -OpenGL ES 2.x, it usually comes pre-installed, but in any case: - -sudo apt-get install libraspberrypi0 libraspberrypi-bin libraspberrypi-dev - - -NEON ----- - -If your Pi has NEON support, make sure you add -mfpu=neon to your CFLAGS so -that SDL will select some otherwise-disabled highly-optimized code. The -original Pi units don't have NEON, the Pi2 probably does, and the Pi3 -definitely does. - - -Cross compiling from x86 Linux ------------------------------- - -To cross compile SDL for Raspbian from your desktop machine, you'll need a -Raspbian system root and the cross compilation tools. We'll assume these tools -will be placed in /opt/rpi-tools - - sudo git clone --depth 1 https://github.com/raspberrypi/tools /opt/rpi-tools - -You'll also need a Raspbian binary image. -Get it from: http://downloads.raspberrypi.org/raspbian_latest -After unzipping, you'll get file with a name like: "-wheezy-raspbian.img" -Let's assume the sysroot will be built in /opt/rpi-sysroot. - - export SYSROOT=/opt/rpi-sysroot - sudo kpartx -a -v .img - sudo mount -o loop /dev/mapper/loop0p2 /mnt - sudo cp -r /mnt $SYSROOT - sudo apt-get install qemu binfmt-support qemu-user-static - sudo cp /usr/bin/qemu-arm-static $SYSROOT/usr/bin - sudo mount --bind /dev $SYSROOT/dev - sudo mount --bind /proc $SYSROOT/proc - sudo mount --bind /sys $SYSROOT/sys - -Now, before chrooting into the ARM sysroot, you'll need to apply a workaround, -edit $SYSROOT/etc/ld.so.preload and comment out all lines in it. - - sudo chroot $SYSROOT - apt-get install libudev-dev libasound2-dev libdbus-1-dev libraspberrypi0 libraspberrypi-bin libraspberrypi-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev - exit - sudo umount $SYSROOT/dev - sudo umount $SYSROOT/proc - sudo umount $SYSROOT/sys - sudo umount /mnt - -There's one more fix required, as the libdl.so symlink uses an absolute path -which doesn't quite work in our setup. - - sudo rm -rf $SYSROOT/usr/lib/arm-linux-gnueabihf/libdl.so - sudo ln -s ../../../lib/arm-linux-gnueabihf/libdl.so.2 $SYSROOT/usr/lib/arm-linux-gnueabihf/libdl.so - -The final step is compiling SDL itself. - - export CC="/opt/rpi-tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-gcc --sysroot=$SYSROOT -I$SYSROOT/opt/vc/include -I$SYSROOT/usr/include -I$SYSROOT/opt/vc/include/interface/vcos/pthreads -I$SYSROOT/opt/vc/include/interface/vmcs_host/linux" - cd - mkdir -p build;cd build - LDFLAGS="-L$SYSROOT/opt/vc/lib" ../configure --with-sysroot=$SYSROOT --host=arm-raspberry-linux-gnueabihf --prefix=$PWD/rpi-sdl3-installed --disable-pulseaudio --disable-esd - make - make install - -To be able to deploy this to /usr/local in the Raspbian system you need to fix up a few paths: - - perl -w -pi -e "s#$PWD/rpi-sdl3-installed#/usr/local#g;" ./rpi-sdl3-installed/lib/libSDL3.la ./rpi-sdl3-installed/lib/pkgconfig/sdl3.pc - -Apps don't work or poor video/audio performance ------------------------------------------------ - -If you get sound problems, buffer underruns, etc, run "sudo rpi-update" to -update the RPi's firmware. Note that doing so will fix these problems, but it -will also render the CMA - Dynamic Memory Split functionality useless. - -Also, by default the Raspbian distro configures the GPU RAM at 64MB, this is too -low in general, specially if a 1080p TV is hooked up. - -See here how to configure this setting: http://elinux.org/RPiconfig - -Using a fixed gpu_mem=128 is the best option (specially if you updated the -firmware, using CMA probably won't work, at least it's the current case). - -No input --------- - -Make sure you belong to the "input" group. - - sudo usermod -aG input `whoami` - -No HDMI Audio -------------- - -If you notice that ALSA works but there's no audio over HDMI, try adding: - - hdmi_drive=2 - -to your config.txt file and reboot. - -Reference: http://www.raspberrypi.org/phpBB3/viewtopic.php?t=5062 - -Text Input API support ----------------------- - -The Text Input API is supported, with translation of scan codes done via the -kernel symbol tables. For this to work, SDL needs access to a valid console. -If you notice there's no SDL_EVENT_TEXT_INPUT message being emitted, double check that -your app has read access to one of the following: - -* /proc/self/fd/0 -* /dev/tty -* /dev/tty[0...6] -* /dev/vc/0 -* /dev/console - -This is usually not a problem if you run from the physical terminal (as opposed -to running from a pseudo terminal, such as via SSH). If running from a PTS, a -quick workaround is to run your app as root or add yourself to the tty group, -then re-login to the system. - - sudo usermod -aG tty `whoami` - -The keyboard layout used by SDL is the same as the one the kernel uses. -To configure the layout on Raspbian: - - sudo dpkg-reconfigure keyboard-configuration - -To configure the locale, which controls which keys are interpreted as letters, -this determining the CAPS LOCK behavior: - - sudo dpkg-reconfigure locales - - -OpenGL problems ---------------- - -If you have desktop OpenGL headers installed at build time in your RPi or cross -compilation environment, support for it will be built in. However, the chipset -does not actually have support for it, which causes issues in certain SDL apps -since the presence of OpenGL support supersedes the ES/ES2 variants. -The workaround is to disable OpenGL at configuration time: - - ./configure --disable-video-opengl - -Or if the application uses the Render functions, you can use the SDL_RENDER_DRIVER -environment variable: - - export SDL_RENDER_DRIVER=opengles2 - -Notes ------ - -* When launching apps remotely (via SSH), SDL can prevent local keystrokes from - leaking into the console only if it has root privileges. Launching apps locally - does not suffer from this issue. - - +Raspberry Pi +============ + +Requirements: + +Raspbian (other Linux distros may work as well). + +Features +-------- + +* Works without X11 +* Hardware accelerated OpenGL ES 2.x +* Sound via ALSA +* Input (mouse/keyboard/joystick) via EVDEV +* Hotplugging of input devices via UDEV + + +Raspbian Build Dependencies +--------------------------- + +sudo apt-get install libudev-dev libasound2-dev libdbus-1-dev + +You also need the VideoCore binary stuff that ships in /opt/vc for EGL and +OpenGL ES 2.x, it usually comes pre-installed, but in any case: + +sudo apt-get install libraspberrypi0 libraspberrypi-bin libraspberrypi-dev + + +NEON +---- + +If your Pi has NEON support, make sure you add -mfpu=neon to your CFLAGS so +that SDL will select some otherwise-disabled highly-optimized code. The +original Pi units don't have NEON, the Pi2 probably does, and the Pi3 +definitely does. + + +Cross compiling from x86 Linux +------------------------------ + +To cross compile SDL for Raspbian from your desktop machine, you'll need a +Raspbian system root and the cross compilation tools. We'll assume these tools +will be placed in /opt/rpi-tools + + sudo git clone --depth 1 https://github.com/raspberrypi/tools /opt/rpi-tools + +You'll also need a Raspbian binary image. +Get it from: http://downloads.raspberrypi.org/raspbian_latest +After unzipping, you'll get file with a name like: "-wheezy-raspbian.img" +Let's assume the sysroot will be built in /opt/rpi-sysroot. + + export SYSROOT=/opt/rpi-sysroot + sudo kpartx -a -v .img + sudo mount -o loop /dev/mapper/loop0p2 /mnt + sudo cp -r /mnt $SYSROOT + sudo apt-get install qemu binfmt-support qemu-user-static + sudo cp /usr/bin/qemu-arm-static $SYSROOT/usr/bin + sudo mount --bind /dev $SYSROOT/dev + sudo mount --bind /proc $SYSROOT/proc + sudo mount --bind /sys $SYSROOT/sys + +Now, before chrooting into the ARM sysroot, you'll need to apply a workaround, +edit $SYSROOT/etc/ld.so.preload and comment out all lines in it. + + sudo chroot $SYSROOT + apt-get install libudev-dev libasound2-dev libdbus-1-dev libraspberrypi0 libraspberrypi-bin libraspberrypi-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev + exit + sudo umount $SYSROOT/dev + sudo umount $SYSROOT/proc + sudo umount $SYSROOT/sys + sudo umount /mnt + +There's one more fix required, as the libdl.so symlink uses an absolute path +which doesn't quite work in our setup. + + sudo rm -rf $SYSROOT/usr/lib/arm-linux-gnueabihf/libdl.so + sudo ln -s ../../../lib/arm-linux-gnueabihf/libdl.so.2 $SYSROOT/usr/lib/arm-linux-gnueabihf/libdl.so + +The final step is compiling SDL itself. + + export CC="/opt/rpi-tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-gcc --sysroot=$SYSROOT -I$SYSROOT/opt/vc/include -I$SYSROOT/usr/include -I$SYSROOT/opt/vc/include/interface/vcos/pthreads -I$SYSROOT/opt/vc/include/interface/vmcs_host/linux" + cd + mkdir -p build;cd build + LDFLAGS="-L$SYSROOT/opt/vc/lib" ../configure --with-sysroot=$SYSROOT --host=arm-raspberry-linux-gnueabihf --prefix=$PWD/rpi-sdl3-installed --disable-pulseaudio --disable-esd + make + make install + +To be able to deploy this to /usr/local in the Raspbian system you need to fix up a few paths: + + perl -w -pi -e "s#$PWD/rpi-sdl3-installed#/usr/local#g;" ./rpi-sdl3-installed/lib/libSDL3.la ./rpi-sdl3-installed/lib/pkgconfig/sdl3.pc + +Apps don't work or poor video/audio performance +----------------------------------------------- + +If you get sound problems, buffer underruns, etc, run "sudo rpi-update" to +update the RPi's firmware. Note that doing so will fix these problems, but it +will also render the CMA - Dynamic Memory Split functionality useless. + +Also, by default the Raspbian distro configures the GPU RAM at 64MB, this is too +low in general, specially if a 1080p TV is hooked up. + +See here how to configure this setting: http://elinux.org/RPiconfig + +Using a fixed gpu_mem=128 is the best option (specially if you updated the +firmware, using CMA probably won't work, at least it's the current case). + +No input +-------- + +Make sure you belong to the "input" group. + + sudo usermod -aG input `whoami` + +No HDMI Audio +------------- + +If you notice that ALSA works but there's no audio over HDMI, try adding: + + hdmi_drive=2 + +to your config.txt file and reboot. + +Reference: http://www.raspberrypi.org/phpBB3/viewtopic.php?t=5062 + +Text Input API support +---------------------- + +The Text Input API is supported, with translation of scan codes done via the +kernel symbol tables. For this to work, SDL needs access to a valid console. +If you notice there's no SDL_EVENT_TEXT_INPUT message being emitted, double check that +your app has read access to one of the following: + +* /proc/self/fd/0 +* /dev/tty +* /dev/tty[0...6] +* /dev/vc/0 +* /dev/console + +This is usually not a problem if you run from the physical terminal (as opposed +to running from a pseudo terminal, such as via SSH). If running from a PTS, a +quick workaround is to run your app as root or add yourself to the tty group, +then re-login to the system. + + sudo usermod -aG tty `whoami` + +The keyboard layout used by SDL is the same as the one the kernel uses. +To configure the layout on Raspbian: + + sudo dpkg-reconfigure keyboard-configuration + +To configure the locale, which controls which keys are interpreted as letters, +this determining the CAPS LOCK behavior: + + sudo dpkg-reconfigure locales + + +OpenGL problems +--------------- + +If you have desktop OpenGL headers installed at build time in your RPi or cross +compilation environment, support for it will be built in. However, the chipset +does not actually have support for it, which causes issues in certain SDL apps +since the presence of OpenGL support supersedes the ES/ES2 variants. +The workaround is to disable OpenGL at configuration time: + + ./configure --disable-video-opengl + +Or if the application uses the Render functions, you can use the SDL_RENDER_DRIVER +environment variable: + + export SDL_RENDER_DRIVER=opengles2 + +Notes +----- + +* When launching apps remotely (via SSH), SDL can prevent local keystrokes from + leaking into the console only if it has root privileges. Launching apps locally + does not suffer from this issue. + + diff --git a/docs/README-riscos.md b/docs/README-riscos.md index 483042206..5af80a7f3 100644 --- a/docs/README-riscos.md +++ b/docs/README-riscos.md @@ -1,35 +1,35 @@ -RISC OS -======= - -Requirements: - -* RISC OS 3.5 or later. -* [SharedUnixLibrary](http://www.riscos.info/packages/LibraryDetails.html#SharedUnixLibraryarm). -* [DigitalRenderer](http://www.riscos.info/packages/LibraryDetails.html#DRendererarm), for audio support. -* [Iconv](http://www.netsurf-browser.org/projects/iconv/), for `SDL_iconv` and related functions. - - -Compiling: ----------- - -Currently, SDL for RISC OS only supports compiling with GCCSDK under Linux. - -The following commands can be used to build SDL for RISC OS using CMake: - - cmake -Bbuild-riscos -DCMAKE_TOOLCHAIN_FILE=$GCCSDK_INSTALL_ENV/toolchain-riscos.cmake -DRISCOS=ON -DCMAKE_INSTALL_PREFIX=$GCCSDK_INSTALL_ENV -DCMAKE_BUILD_TYPE=Release - cmake --build build-riscos - cmake --install build-riscos - -When using GCCSDK 4.7.4 release 6 or earlier versions, the builtin atomic functions are broken, meaning it's currently necessary to compile with `-DSDL_GCC_ATOMICS=OFF` using CMake. Newer versions of GCCSDK don't have this problem. - - -Current level of implementation -------------------------------- - -The video driver currently provides full screen video support with keyboard and mouse input. Windowed mode is not yet supported, but is planned in the future. Only software rendering is supported. - -The filesystem APIs return either Unix-style paths or RISC OS-style paths based on the value of the `__riscosify_control` symbol, as is standard for UnixLib functions. - -The audio, loadso, thread and timer APIs are currently provided by UnixLib. - -The joystick, locale and power APIs are not yet implemented. +RISC OS +======= + +Requirements: + +* RISC OS 3.5 or later. +* [SharedUnixLibrary](http://www.riscos.info/packages/LibraryDetails.html#SharedUnixLibraryarm). +* [DigitalRenderer](http://www.riscos.info/packages/LibraryDetails.html#DRendererarm), for audio support. +* [Iconv](http://www.netsurf-browser.org/projects/iconv/), for `SDL_iconv` and related functions. + + +Compiling: +---------- + +Currently, SDL for RISC OS only supports compiling with GCCSDK under Linux. + +The following commands can be used to build SDL for RISC OS using CMake: + + cmake -Bbuild-riscos -DCMAKE_TOOLCHAIN_FILE=$GCCSDK_INSTALL_ENV/toolchain-riscos.cmake -DRISCOS=ON -DCMAKE_INSTALL_PREFIX=$GCCSDK_INSTALL_ENV -DCMAKE_BUILD_TYPE=Release + cmake --build build-riscos + cmake --install build-riscos + +When using GCCSDK 4.7.4 release 6 or earlier versions, the builtin atomic functions are broken, meaning it's currently necessary to compile with `-DSDL_GCC_ATOMICS=OFF` using CMake. Newer versions of GCCSDK don't have this problem. + + +Current level of implementation +------------------------------- + +The video driver currently provides full screen video support with keyboard and mouse input. Windowed mode is not yet supported, but is planned in the future. Only software rendering is supported. + +The filesystem APIs return either Unix-style paths or RISC OS-style paths based on the value of the `__riscosify_control` symbol, as is standard for UnixLib functions. + +The audio, loadso, thread and timer APIs are currently provided by UnixLib. + +The joystick, locale and power APIs are not yet implemented. diff --git a/docs/README-touch.md b/docs/README-touch.md index 94d4e7233..569feb606 100644 --- a/docs/README-touch.md +++ b/docs/README-touch.md @@ -1,81 +1,81 @@ -Touch -=========================================================================== -System Specific Notes -=========================================================================== -Linux: -The linux touch system is currently based off event streams, and proc/bus/devices. The active user must be given permissions to read /dev/input/TOUCHDEVICE, where TOUCHDEVICE is the event stream for your device. Currently only Wacom tablets are supported. If you have an unsupported tablet contact me at jim.tla+sdl_touch@gmail.com and I will help you get support for it. - -Mac: -The Mac and iPhone APIs are pretty. If your touch device supports them then you'll be fine. If it doesn't, then there isn't much we can do. - -iPhone: -Works out of box. - -Windows: -Unfortunately there is no windows support as of yet. Support for Windows 7 is planned, but we currently have no way to test. If you have a Windows 7 WM_TOUCH supported device, and are willing to help test please contact me at jim.tla+sdl_touch@gmail.com - -=========================================================================== -Events -=========================================================================== -SDL_EVENT_FINGER_DOWN: -Sent when a finger (or stylus) is placed on a touch device. -Fields: -* event.tfinger.touchId - the Id of the touch device. -* event.tfinger.fingerId - the Id of the finger which just went down. -* event.tfinger.x - the x coordinate of the touch (0..1) -* event.tfinger.y - the y coordinate of the touch (0..1) -* event.tfinger.pressure - the pressure of the touch (0..1) - -SDL_EVENT_FINGER_MOTION: -Sent when a finger (or stylus) is moved on the touch device. -Fields: -Same as SDL_EVENT_FINGER_DOWN but with additional: -* event.tfinger.dx - change in x coordinate during this motion event. -* event.tfinger.dy - change in y coordinate during this motion event. - -SDL_EVENT_FINGER_UP: -Sent when a finger (or stylus) is lifted from the touch device. -Fields: -Same as SDL_EVENT_FINGER_DOWN. - - -=========================================================================== -Functions -=========================================================================== -SDL provides the ability to access the underlying SDL_Finger structures. -These structures should _never_ be modified. - -The following functions are included from SDL_touch.h - -To get a SDL_TouchID call SDL_GetTouchDevice(int index). -This returns a SDL_TouchID. -IMPORTANT: If the touch has been removed, or there is no touch with the given index, SDL_GetTouchDevice() will return 0. Be sure to check for this! - -The number of touch devices can be queried with SDL_GetNumTouchDevices(). - -A SDL_TouchID may be used to get pointers to SDL_Finger. - -SDL_GetNumTouchFingers(touchID) may be used to get the number of fingers currently down on the device. - -The most common reason to access SDL_Finger is to query the fingers outside the event. In most cases accessing the fingers is using the event. This would be accomplished by code like the following: - - float x = event.tfinger.x; - float y = event.tfinger.y; - - - -To get a SDL_Finger, call SDL_GetTouchFinger(SDL_TouchID touchID, int index), where touchID is a SDL_TouchID, and index is the requested finger. -This returns a SDL_Finger *, or NULL if the finger does not exist, or has been removed. -A SDL_Finger is guaranteed to be persistent for the duration of a touch, but it will be de-allocated as soon as the finger is removed. This occurs when the SDL_EVENT_FINGER_UP event is _added_ to the event queue, and thus _before_ the SDL_EVENT_FINGER_UP event is polled. -As a result, be very careful to check for NULL return values. - -A SDL_Finger has the following fields: -* x, y: - The current coordinates of the touch. -* pressure: - The pressure of the touch. - - -Please direct questions/comments to: - jim.tla+sdl_touch@gmail.com - (original author, API was changed since) +Touch +=========================================================================== +System Specific Notes +=========================================================================== +Linux: +The linux touch system is currently based off event streams, and proc/bus/devices. The active user must be given permissions to read /dev/input/TOUCHDEVICE, where TOUCHDEVICE is the event stream for your device. Currently only Wacom tablets are supported. If you have an unsupported tablet contact me at jim.tla+sdl_touch@gmail.com and I will help you get support for it. + +Mac: +The Mac and iPhone APIs are pretty. If your touch device supports them then you'll be fine. If it doesn't, then there isn't much we can do. + +iPhone: +Works out of box. + +Windows: +Unfortunately there is no windows support as of yet. Support for Windows 7 is planned, but we currently have no way to test. If you have a Windows 7 WM_TOUCH supported device, and are willing to help test please contact me at jim.tla+sdl_touch@gmail.com + +=========================================================================== +Events +=========================================================================== +SDL_EVENT_FINGER_DOWN: +Sent when a finger (or stylus) is placed on a touch device. +Fields: +* event.tfinger.touchId - the Id of the touch device. +* event.tfinger.fingerId - the Id of the finger which just went down. +* event.tfinger.x - the x coordinate of the touch (0..1) +* event.tfinger.y - the y coordinate of the touch (0..1) +* event.tfinger.pressure - the pressure of the touch (0..1) + +SDL_EVENT_FINGER_MOTION: +Sent when a finger (or stylus) is moved on the touch device. +Fields: +Same as SDL_EVENT_FINGER_DOWN but with additional: +* event.tfinger.dx - change in x coordinate during this motion event. +* event.tfinger.dy - change in y coordinate during this motion event. + +SDL_EVENT_FINGER_UP: +Sent when a finger (or stylus) is lifted from the touch device. +Fields: +Same as SDL_EVENT_FINGER_DOWN. + + +=========================================================================== +Functions +=========================================================================== +SDL provides the ability to access the underlying SDL_Finger structures. +These structures should _never_ be modified. + +The following functions are included from SDL_touch.h + +To get a SDL_TouchID call SDL_GetTouchDevice(int index). +This returns a SDL_TouchID. +IMPORTANT: If the touch has been removed, or there is no touch with the given index, SDL_GetTouchDevice() will return 0. Be sure to check for this! + +The number of touch devices can be queried with SDL_GetNumTouchDevices(). + +A SDL_TouchID may be used to get pointers to SDL_Finger. + +SDL_GetNumTouchFingers(touchID) may be used to get the number of fingers currently down on the device. + +The most common reason to access SDL_Finger is to query the fingers outside the event. In most cases accessing the fingers is using the event. This would be accomplished by code like the following: + + float x = event.tfinger.x; + float y = event.tfinger.y; + + + +To get a SDL_Finger, call SDL_GetTouchFinger(SDL_TouchID touchID, int index), where touchID is a SDL_TouchID, and index is the requested finger. +This returns a SDL_Finger *, or NULL if the finger does not exist, or has been removed. +A SDL_Finger is guaranteed to be persistent for the duration of a touch, but it will be de-allocated as soon as the finger is removed. This occurs when the SDL_EVENT_FINGER_UP event is _added_ to the event queue, and thus _before_ the SDL_EVENT_FINGER_UP event is polled. +As a result, be very careful to check for NULL return values. + +A SDL_Finger has the following fields: +* x, y: + The current coordinates of the touch. +* pressure: + The pressure of the touch. + + +Please direct questions/comments to: + jim.tla+sdl_touch@gmail.com + (original author, API was changed since) diff --git a/docs/README-versions.md b/docs/README-versions.md index d54bf40c1..097dba1c7 100644 --- a/docs/README-versions.md +++ b/docs/README-versions.md @@ -1,60 +1,60 @@ -# Versioning - -## Since 2.23.0 - -SDL follows an "odd/even" versioning policy, similar to GLib, GTK, Flatpak -and older versions of the Linux kernel: - -* The major version (first part) increases when backwards compatibility - is broken, which will happen infrequently. - -* If the minor version (second part) is divisible by 2 - (for example 2.24.x, 2.26.x), this indicates a version of SDL that - is believed to be stable and suitable for production use. - - * In stable releases, the patchlevel or micro version (third part) - indicates bugfix releases. Bugfix releases should not add or - remove ABI, so the ".0" release (for example 2.24.0) should be - forwards-compatible with all the bugfix releases from the - same cycle (for example 2.24.1). - - * The minor version increases when new API or ABI is added, or when - other significant changes are made. Newer minor versions are - backwards-compatible, but not fully forwards-compatible. - For example, programs built against SDL 2.24.x should work fine - with SDL 2.26.x, but programs built against SDL 2.26.x will not - necessarily work with 2.24.x. - -* If the minor version (second part) is not divisible by 2 - (for example 2.23.x, 2.25.x), this indicates a development prerelease - of SDL that is not suitable for stable software distributions. - Use with caution. - - * The patchlevel or micro version (third part) increases with - each prerelease. - - * Each prerelease might add new API and/or ABI. - - * Prereleases are backwards-compatible with older stable branches. - For example, 2.25.x will be backwards-compatible with 2.24.x. - - * Prereleases are not guaranteed to be backwards-compatible with - each other. For example, new API or ABI added in 2.25.1 - might be removed or changed in 2.25.2. - If this would be a problem for you, please do not use prereleases. - - * Only upgrade to a prerelease if you can guarantee that you will - promptly upgrade to the stable release that follows it. - For example, do not upgrade to 2.23.x unless you will be able to - upgrade to 2.24.0 when it becomes available. - - * Software distributions that have a freeze policy (in particular Linux - distributions with a release cycle, such as Debian and Fedora) - should usually only package stable releases, and not prereleases. - -## Before 2.23.0 - -Older versions of SDL followed a similar policy, but instead of the -odd/even rule applying to the minor version, it applied to the patchlevel -(micro version, third part). For example, 2.0.22 was a stable release -and 2.0.21 was a prerelease. +# Versioning + +## Since 2.23.0 + +SDL follows an "odd/even" versioning policy, similar to GLib, GTK, Flatpak +and older versions of the Linux kernel: + +* The major version (first part) increases when backwards compatibility + is broken, which will happen infrequently. + +* If the minor version (second part) is divisible by 2 + (for example 2.24.x, 2.26.x), this indicates a version of SDL that + is believed to be stable and suitable for production use. + + * In stable releases, the patchlevel or micro version (third part) + indicates bugfix releases. Bugfix releases should not add or + remove ABI, so the ".0" release (for example 2.24.0) should be + forwards-compatible with all the bugfix releases from the + same cycle (for example 2.24.1). + + * The minor version increases when new API or ABI is added, or when + other significant changes are made. Newer minor versions are + backwards-compatible, but not fully forwards-compatible. + For example, programs built against SDL 2.24.x should work fine + with SDL 2.26.x, but programs built against SDL 2.26.x will not + necessarily work with 2.24.x. + +* If the minor version (second part) is not divisible by 2 + (for example 2.23.x, 2.25.x), this indicates a development prerelease + of SDL that is not suitable for stable software distributions. + Use with caution. + + * The patchlevel or micro version (third part) increases with + each prerelease. + + * Each prerelease might add new API and/or ABI. + + * Prereleases are backwards-compatible with older stable branches. + For example, 2.25.x will be backwards-compatible with 2.24.x. + + * Prereleases are not guaranteed to be backwards-compatible with + each other. For example, new API or ABI added in 2.25.1 + might be removed or changed in 2.25.2. + If this would be a problem for you, please do not use prereleases. + + * Only upgrade to a prerelease if you can guarantee that you will + promptly upgrade to the stable release that follows it. + For example, do not upgrade to 2.23.x unless you will be able to + upgrade to 2.24.0 when it becomes available. + + * Software distributions that have a freeze policy (in particular Linux + distributions with a release cycle, such as Debian and Fedora) + should usually only package stable releases, and not prereleases. + +## Before 2.23.0 + +Older versions of SDL followed a similar policy, but instead of the +odd/even rule applying to the minor version, it applied to the patchlevel +(micro version, third part). For example, 2.0.22 was a stable release +and 2.0.21 was a prerelease. diff --git a/docs/README-visualc.md b/docs/README-visualc.md index 276c83bce..789042147 100644 --- a/docs/README-visualc.md +++ b/docs/README-visualc.md @@ -1,113 +1,113 @@ -Using SDL with Microsoft Visual C++ -=================================== - -### by Lion Kimbro with additions by James Turk - -You can either use the precompiled libraries from the [SDL](https://www.libsdl.org/download.php) web site, or you can build SDL -yourself. - -### Building SDL - -0. To build SDL, your machine must, at a minimum, have the DirectX9.0c SDK installed. It may or may not be retrievable from -the [Microsoft](https://www.microsoft.com) website, so you might need to locate it [online](https://duckduckgo.com/?q=directx9.0c+sdk+download&t=h_&ia=web). -_Editor's note: I've been able to successfully build SDL using Visual Studio 2019 **without** the DX9.0c SDK_ - -1. Open the Visual Studio solution file at `./VisualC/SDL.sln`. - -2. Your IDE will likely prompt you to upgrade this solution file to whatever later version of the IDE you're using. In the `Retarget Projects` dialog, -all of the affected project files should be checked allowing you to use the latest `Windows SDK Version` you have installed, along with -the `Platform Toolset`. - -If you choose *NOT* to upgrade to use the latest `Windows SDK Version` or `Platform Toolset`, then you'll need the `Visual Studio 2010 Platform Toolset`. - -3. Build the `.dll` and `.lib` files by right clicking on each project in turn (Projects are listed in the _Workspace_ -panel in the _FileView_ tab), and selecting `Build`. - -You may get a few warnings, but you should not get any errors. - -Later, we will refer to the following `.lib` and `.dll` files that have just been generated: - -- `./VisualC/Win32/Debug/SDL3.dll` or `./VisualC/Win32/Release/SDL3.dll` -- `./VisualC/Win32/Debug/SDL3.lib` or `./VisualC/Win32/Release/SDL3.lib` - -_Note for the `x64` versions, just replace `Win32` in the path with `x64`_ - -### Creating a Project with SDL - -- Create a project as a `Win32 Application`. - -- Create a C++ file for your project. - -- Set the C runtime to `Multi-threaded DLL` in the menu: -`Project|Settings|C/C++ tab|Code Generation|Runtime Library `. - -- Add the SDL `include` directory to your list of includes in the menu: -`Project|Settings|C/C++ tab|Preprocessor|Additional include directories ` - -*VC7 Specific: Instead of doing this, I find it easier to add the -include and library directories to the list that VC7 keeps. Do this by -selecting Tools|Options|Projects|VC++ Directories and under the "Show -Directories For:" dropbox select "Include Files", and click the "New -Directory Icon" and add the [SDLROOT]\\include directory (e.g. If you -installed to c:\\SDL\\ add c:\\SDL\\include). Proceed to change the -dropbox selection to "Library Files" and add [SDLROOT]\\lib.* - -The "include directory" I am referring to is the `./include` folder. - -Now we're going to use the files that we had created earlier in the *Build SDL* step. - -Copy the following file into your Project directory: - -- `SDL3.dll` - -Add the following file to your project (It is not necessary to copy it to your project directory): - -- `SDL3.lib` - -To add them to your project, right click on your project, and select -`Add files to project`. - -**Instead of adding the files to your project, it is more desirable to add them to the linker options: Project|Properties|Linker|Command Line -and type the names of the libraries to link with in the "Additional Options:" box. Note: This must be done for each build configuration -(e.g. Release,Debug).** - -### Hello SDL - -Here's a sample SDL snippet to verify everything is setup in your IDE: - -``` - #include - #include // only include this one in the source file with main()! - - int main( int argc, char* argv[] ) - { - const int WIDTH = 640; - const int HEIGHT = 480; - SDL_Window* window = NULL; - SDL_Renderer* renderer = NULL; - - SDL_Init(SDL_INIT_VIDEO); - window = SDL_CreateWindow("Hello SDL", WIDTH, HEIGHT, 0); - renderer = SDL_CreateRenderer(window, NULL, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); - - SDL_DestroyRenderer(renderer); - SDL_DestroyWindow(window); - SDL_Quit(); - return 0; - } - ``` - -### That's it! - -I hope that this document has helped you get through the most difficult part of using the SDL: installing it. -Suggestions for improvements should be posted to the [Github Issues](https://github.com/libsdl-org/SDL/issues). - -### Credits - -Thanks to [Paulus Esterhazy](mailto:pesterhazy@gmx.net), for the work on VC++ port. - -This document was originally called "VisualC.txt", and was written by [Sam Lantinga](mailto:slouken@libsdl.org). - -Later, it was converted to HTML and expanded into the document that you see today by [Lion Kimbro](mailto:snowlion@sprynet.com). - -Minor Fixes and Visual C++ 7 Information (In Green) was added by [James Turk](mailto:james@conceptofzero.net) +Using SDL with Microsoft Visual C++ +=================================== + +### by Lion Kimbro with additions by James Turk + +You can either use the precompiled libraries from the [SDL](https://www.libsdl.org/download.php) web site, or you can build SDL +yourself. + +### Building SDL + +0. To build SDL, your machine must, at a minimum, have the DirectX9.0c SDK installed. It may or may not be retrievable from +the [Microsoft](https://www.microsoft.com) website, so you might need to locate it [online](https://duckduckgo.com/?q=directx9.0c+sdk+download&t=h_&ia=web). +_Editor's note: I've been able to successfully build SDL using Visual Studio 2019 **without** the DX9.0c SDK_ + +1. Open the Visual Studio solution file at `./VisualC/SDL.sln`. + +2. Your IDE will likely prompt you to upgrade this solution file to whatever later version of the IDE you're using. In the `Retarget Projects` dialog, +all of the affected project files should be checked allowing you to use the latest `Windows SDK Version` you have installed, along with +the `Platform Toolset`. + +If you choose *NOT* to upgrade to use the latest `Windows SDK Version` or `Platform Toolset`, then you'll need the `Visual Studio 2010 Platform Toolset`. + +3. Build the `.dll` and `.lib` files by right clicking on each project in turn (Projects are listed in the _Workspace_ +panel in the _FileView_ tab), and selecting `Build`. + +You may get a few warnings, but you should not get any errors. + +Later, we will refer to the following `.lib` and `.dll` files that have just been generated: + +- `./VisualC/Win32/Debug/SDL3.dll` or `./VisualC/Win32/Release/SDL3.dll` +- `./VisualC/Win32/Debug/SDL3.lib` or `./VisualC/Win32/Release/SDL3.lib` + +_Note for the `x64` versions, just replace `Win32` in the path with `x64`_ + +### Creating a Project with SDL + +- Create a project as a `Win32 Application`. + +- Create a C++ file for your project. + +- Set the C runtime to `Multi-threaded DLL` in the menu: +`Project|Settings|C/C++ tab|Code Generation|Runtime Library `. + +- Add the SDL `include` directory to your list of includes in the menu: +`Project|Settings|C/C++ tab|Preprocessor|Additional include directories ` + +*VC7 Specific: Instead of doing this, I find it easier to add the +include and library directories to the list that VC7 keeps. Do this by +selecting Tools|Options|Projects|VC++ Directories and under the "Show +Directories For:" dropbox select "Include Files", and click the "New +Directory Icon" and add the [SDLROOT]\\include directory (e.g. If you +installed to c:\\SDL\\ add c:\\SDL\\include). Proceed to change the +dropbox selection to "Library Files" and add [SDLROOT]\\lib.* + +The "include directory" I am referring to is the `./include` folder. + +Now we're going to use the files that we had created earlier in the *Build SDL* step. + +Copy the following file into your Project directory: + +- `SDL3.dll` + +Add the following file to your project (It is not necessary to copy it to your project directory): + +- `SDL3.lib` + +To add them to your project, right click on your project, and select +`Add files to project`. + +**Instead of adding the files to your project, it is more desirable to add them to the linker options: Project|Properties|Linker|Command Line +and type the names of the libraries to link with in the "Additional Options:" box. Note: This must be done for each build configuration +(e.g. Release,Debug).** + +### Hello SDL + +Here's a sample SDL snippet to verify everything is setup in your IDE: + +``` + #include + #include // only include this one in the source file with main()! + + int main( int argc, char* argv[] ) + { + const int WIDTH = 640; + const int HEIGHT = 480; + SDL_Window* window = NULL; + SDL_Renderer* renderer = NULL; + + SDL_Init(SDL_INIT_VIDEO); + window = SDL_CreateWindow("Hello SDL", WIDTH, HEIGHT, 0); + renderer = SDL_CreateRenderer(window, NULL, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); + + SDL_DestroyRenderer(renderer); + SDL_DestroyWindow(window); + SDL_Quit(); + return 0; + } + ``` + +### That's it! + +I hope that this document has helped you get through the most difficult part of using the SDL: installing it. +Suggestions for improvements should be posted to the [Github Issues](https://github.com/libsdl-org/SDL/issues). + +### Credits + +Thanks to [Paulus Esterhazy](mailto:pesterhazy@gmx.net), for the work on VC++ port. + +This document was originally called "VisualC.txt", and was written by [Sam Lantinga](mailto:slouken@libsdl.org). + +Later, it was converted to HTML and expanded into the document that you see today by [Lion Kimbro](mailto:snowlion@sprynet.com). + +Minor Fixes and Visual C++ 7 Information (In Green) was added by [James Turk](mailto:james@conceptofzero.net) diff --git a/docs/README-vita.md b/docs/README-vita.md index 3dbaf1cd4..0a11cf806 100644 --- a/docs/README-vita.md +++ b/docs/README-vita.md @@ -1,33 +1,33 @@ -PS Vita -======= -SDL port for the Sony Playstation Vita and Sony Playstation TV - -Credit to -* xerpi, cpasjuste and rsn8887 for initial (vita2d) port -* vitasdk/dolcesdk devs -* CBPS discord (Namely Graphene and SonicMastr) - -Building --------- -To build for the PSVita, make sure you have vitasdk and cmake installed and run: -``` - cmake -S. -Bbuild -DCMAKE_TOOLCHAIN_FILE=${VITASDK}/share/vita.toolchain.cmake -DCMAKE_BUILD_TYPE=Release - cmake --build build - cmake --install build -``` - - -Notes ------ -* gles1/gles2 support and renderers are disabled by default and can be enabled by configuring with `-DVIDEO_VITA_PVR=ON` - These renderers support 720p and 1080i resolutions. These can be specified with: - `SDL_setenv("VITA_RESOLUTION", "720", 1);` and `SDL_setenv("VITA_RESOLUTION", "1080", 1);` -* Desktop GL 1.X and 2.X support and renderers are also disabled by default and also can be enabled with `-DVIDEO_VITA_PVR=ON` as long as gl4es4vita is present in your SDK. - They support the same resolutions as the gles1/gles2 backends and require specifying `SDL_setenv("VITA_PVR_OGL", "1", 1);` - anytime before video subsystem initialization. -* gles2 support via PIB is disabled by default and can be enabled by configuring with `-DVIDEO_VITA_PIB=ON` -* By default SDL emits mouse events for touch events on every touchscreen. - Vita has two touchscreens, so it's recommended to use `SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0");` and handle touch events instead. - Individual touchscreens can be disabled with: - `SDL_setenv("VITA_DISABLE_TOUCH_FRONT", "1", 1);` and `SDL_setenv("VITA_DISABLE_TOUCH_BACK", "1", 1);` -* Support for L2/R2/R3/R3 buttons, haptic feedback and gamepad led only available on PSTV, or when using external ds4 gamepad on vita. +PS Vita +======= +SDL port for the Sony Playstation Vita and Sony Playstation TV + +Credit to +* xerpi, cpasjuste and rsn8887 for initial (vita2d) port +* vitasdk/dolcesdk devs +* CBPS discord (Namely Graphene and SonicMastr) + +Building +-------- +To build for the PSVita, make sure you have vitasdk and cmake installed and run: +``` + cmake -S. -Bbuild -DCMAKE_TOOLCHAIN_FILE=${VITASDK}/share/vita.toolchain.cmake -DCMAKE_BUILD_TYPE=Release + cmake --build build + cmake --install build +``` + + +Notes +----- +* gles1/gles2 support and renderers are disabled by default and can be enabled by configuring with `-DVIDEO_VITA_PVR=ON` + These renderers support 720p and 1080i resolutions. These can be specified with: + `SDL_setenv("VITA_RESOLUTION", "720", 1);` and `SDL_setenv("VITA_RESOLUTION", "1080", 1);` +* Desktop GL 1.X and 2.X support and renderers are also disabled by default and also can be enabled with `-DVIDEO_VITA_PVR=ON` as long as gl4es4vita is present in your SDK. + They support the same resolutions as the gles1/gles2 backends and require specifying `SDL_setenv("VITA_PVR_OGL", "1", 1);` + anytime before video subsystem initialization. +* gles2 support via PIB is disabled by default and can be enabled by configuring with `-DVIDEO_VITA_PIB=ON` +* By default SDL emits mouse events for touch events on every touchscreen. + Vita has two touchscreens, so it's recommended to use `SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0");` and handle touch events instead. + Individual touchscreens can be disabled with: + `SDL_setenv("VITA_DISABLE_TOUCH_FRONT", "1", 1);` and `SDL_setenv("VITA_DISABLE_TOUCH_BACK", "1", 1);` +* Support for L2/R2/R3/R3 buttons, haptic feedback and gamepad led only available on PSTV, or when using external ds4 gamepad on vita. diff --git a/docs/README-wayland.md b/docs/README-wayland.md index 2bab54f24..a376b48ad 100644 --- a/docs/README-wayland.md +++ b/docs/README-wayland.md @@ -1,45 +1,45 @@ -Wayland -======= -Wayland is a replacement for the X11 window system protocol and architecture and is favored over X11 by default in SDL3 -for communicating with desktop compositors. It works well for the majority of applications, however, applications may -encounter limitations or behavior that is different from other windowing systems. - -## Common issues: - -### Window decorations are missing, or the decorations look strange - -- On some desktops (i.e. GNOME), Wayland applications use a library - called [libdecor](https://gitlab.freedesktop.org/libdecor/libdecor) to provide window decorations. If this library is - not installed, the decorations will be missing. This library uses plugins to generate different decoration styles, and - if a plugin to generate native-looking decorations is not installed (i.e. the GTK plugin), the decorations will not - appear to be 'native'. - -### Windows do not appear immediately after creation - -- Wayland requires that the application initially present a buffer before the window becomes visible. Additionally, - applications _must_ have an event loop and processes messages on a regular basis, or the application can appear - unresponsive to both the user and desktop compositor. - -### ```SDL_SetWindowPosition()``` doesn't work on non-popup windows - -- Wayland does not allow toplevel windows to position themselves programmatically. - -### Retrieving the global mouse cursor position when the cursor is outside a window doesn't work - -- Wayland only provides applications with the cursor position within the borders of the application windows. Querying - the global position when an application window does not have mouse focus returns 0,0 as the actual cursor position is - unknown. In most cases, applications don't actually need the global cursor position and should use the window-relative - coordinates as provided by the mouse movement event or from ```SDL_GetMouseState()``` instead. - -### Warping the global mouse cursor position via ```SDL_WarpMouseGlobal()``` doesn't work - -- For security reasons, Wayland does not allow warping the global mouse cursor position. - -### The application icon can't be set via ```SDL_SetWindowIcon()``` - -- Wayland doesn't support programmatically setting the application icon. To provide a custom icon for your application, - you must create an associated desktop entry file, aka a `.desktop` file, that points to the icon image. Please see the - [Desktop Entry Specification](https://specifications.freedesktop.org/desktop-entry-spec/latest/) for more information - on the format of this file. Note that if your application manually sets the application ID via the `SDL_APP_ID` hint - string, the desktop entry file name should match the application ID. For example, if your application ID is set - to `org.my_org.sdl_app`, the desktop entry file should be named `org.my_org.sdl_app.desktop`. +Wayland +======= +Wayland is a replacement for the X11 window system protocol and architecture and is favored over X11 by default in SDL3 +for communicating with desktop compositors. It works well for the majority of applications, however, applications may +encounter limitations or behavior that is different from other windowing systems. + +## Common issues: + +### Window decorations are missing, or the decorations look strange + +- On some desktops (i.e. GNOME), Wayland applications use a library + called [libdecor](https://gitlab.freedesktop.org/libdecor/libdecor) to provide window decorations. If this library is + not installed, the decorations will be missing. This library uses plugins to generate different decoration styles, and + if a plugin to generate native-looking decorations is not installed (i.e. the GTK plugin), the decorations will not + appear to be 'native'. + +### Windows do not appear immediately after creation + +- Wayland requires that the application initially present a buffer before the window becomes visible. Additionally, + applications _must_ have an event loop and processes messages on a regular basis, or the application can appear + unresponsive to both the user and desktop compositor. + +### ```SDL_SetWindowPosition()``` doesn't work on non-popup windows + +- Wayland does not allow toplevel windows to position themselves programmatically. + +### Retrieving the global mouse cursor position when the cursor is outside a window doesn't work + +- Wayland only provides applications with the cursor position within the borders of the application windows. Querying + the global position when an application window does not have mouse focus returns 0,0 as the actual cursor position is + unknown. In most cases, applications don't actually need the global cursor position and should use the window-relative + coordinates as provided by the mouse movement event or from ```SDL_GetMouseState()``` instead. + +### Warping the global mouse cursor position via ```SDL_WarpMouseGlobal()``` doesn't work + +- For security reasons, Wayland does not allow warping the global mouse cursor position. + +### The application icon can't be set via ```SDL_SetWindowIcon()``` + +- Wayland doesn't support programmatically setting the application icon. To provide a custom icon for your application, + you must create an associated desktop entry file, aka a `.desktop` file, that points to the icon image. Please see the + [Desktop Entry Specification](https://specifications.freedesktop.org/desktop-entry-spec/latest/) for more information + on the format of this file. Note that if your application manually sets the application ID via the `SDL_APP_ID` hint + string, the desktop entry file name should match the application ID. For example, if your application ID is set + to `org.my_org.sdl_app`, the desktop entry file should be named `org.my_org.sdl_app.desktop`. diff --git a/docs/README-windows.md b/docs/README-windows.md index 1e6d59c44..daf80647f 100644 --- a/docs/README-windows.md +++ b/docs/README-windows.md @@ -1,66 +1,66 @@ -# Windows - -## LLVM and Intel C++ compiler support - -SDL will build with the Visual Studio project files with LLVM-based compilers, such as the Intel oneAPI C++ -compiler, but you'll have to manually add the "-msse3" command line option -to at least the SDL_audiocvt.c source file, and possibly others. This may -not be necessary if you build SDL with CMake instead of the included Visual -Studio solution. - -Details are here: https://github.com/libsdl-org/SDL/issues/5186 - - -## OpenGL ES 2.x support - -SDL has support for OpenGL ES 2.x under Windows via two alternative -implementations. - -The most straightforward method consists in running your app in a system with -a graphic card paired with a relatively recent (as of November of 2013) driver -which supports the WGL_EXT_create_context_es2_profile extension. Vendors known -to ship said extension on Windows currently include nVidia and Intel. - -The other method involves using the -[ANGLE library](https://code.google.com/p/angleproject/). If an OpenGL ES 2.x -context is requested and no WGL_EXT_create_context_es2_profile extension is -found, SDL will try to load the libEGL.dll library provided by ANGLE. - -To obtain the ANGLE binaries, you can either compile from source from -https://chromium.googlesource.com/angle/angle or copy the relevant binaries -from a recent Chrome/Chromium install for Windows. The files you need are: - -- libEGL.dll -- libGLESv2.dll -- d3dcompiler_46.dll (supports Windows Vista or later, better shader - compiler) *or* d3dcompiler_43.dll (supports Windows XP or later) - -If you compile ANGLE from source, you can configure it so it does not need the -d3dcompiler_* DLL at all (for details on this, see their documentation). -However, by default SDL will try to preload the d3dcompiler_46.dll to -comply with ANGLE's requirements. If you wish SDL to preload -d3dcompiler_43.dll (to support Windows XP) or to skip this step at all, you -can use the SDL_HINT_VIDEO_WIN_D3DCOMPILER hint (see SDL_hints.h for more -details). - -Known Bugs: - -- SDL_GL_SetSwapInterval is currently a no op when using ANGLE. It appears - that there's a bug in the library which prevents the window contents from - refreshing if this is set to anything other than the default value. - -## Vulkan Surface Support - -Support for creating Vulkan surfaces is configured on by default. To disable -it change the value of `SDL_VIDEO_VULKAN` to 0 in `SDL_config_windows.h`. You -must install the [Vulkan SDK](https://www.lunarg.com/vulkan-sdk/) in order to -use Vulkan graphics in your application. - -## Transparent Window Support - -SDL uses the Desktop Window Manager (DWM) to create transparent windows. DWM is -always enabled from Windows 8 and above. Windows 7 only enables DWM with Aero Glass -theme. - -However, it cannot be guaranteed to work on all hardware configurations (an example -is hybrid GPU systems, such as NVIDIA Optimus laptops). +# Windows + +## LLVM and Intel C++ compiler support + +SDL will build with the Visual Studio project files with LLVM-based compilers, such as the Intel oneAPI C++ +compiler, but you'll have to manually add the "-msse3" command line option +to at least the SDL_audiocvt.c source file, and possibly others. This may +not be necessary if you build SDL with CMake instead of the included Visual +Studio solution. + +Details are here: https://github.com/libsdl-org/SDL/issues/5186 + + +## OpenGL ES 2.x support + +SDL has support for OpenGL ES 2.x under Windows via two alternative +implementations. + +The most straightforward method consists in running your app in a system with +a graphic card paired with a relatively recent (as of November of 2013) driver +which supports the WGL_EXT_create_context_es2_profile extension. Vendors known +to ship said extension on Windows currently include nVidia and Intel. + +The other method involves using the +[ANGLE library](https://code.google.com/p/angleproject/). If an OpenGL ES 2.x +context is requested and no WGL_EXT_create_context_es2_profile extension is +found, SDL will try to load the libEGL.dll library provided by ANGLE. + +To obtain the ANGLE binaries, you can either compile from source from +https://chromium.googlesource.com/angle/angle or copy the relevant binaries +from a recent Chrome/Chromium install for Windows. The files you need are: + +- libEGL.dll +- libGLESv2.dll +- d3dcompiler_46.dll (supports Windows Vista or later, better shader + compiler) *or* d3dcompiler_43.dll (supports Windows XP or later) + +If you compile ANGLE from source, you can configure it so it does not need the +d3dcompiler_* DLL at all (for details on this, see their documentation). +However, by default SDL will try to preload the d3dcompiler_46.dll to +comply with ANGLE's requirements. If you wish SDL to preload +d3dcompiler_43.dll (to support Windows XP) or to skip this step at all, you +can use the SDL_HINT_VIDEO_WIN_D3DCOMPILER hint (see SDL_hints.h for more +details). + +Known Bugs: + +- SDL_GL_SetSwapInterval is currently a no op when using ANGLE. It appears + that there's a bug in the library which prevents the window contents from + refreshing if this is set to anything other than the default value. + +## Vulkan Surface Support + +Support for creating Vulkan surfaces is configured on by default. To disable +it change the value of `SDL_VIDEO_VULKAN` to 0 in `SDL_config_windows.h`. You +must install the [Vulkan SDK](https://www.lunarg.com/vulkan-sdk/) in order to +use Vulkan graphics in your application. + +## Transparent Window Support + +SDL uses the Desktop Window Manager (DWM) to create transparent windows. DWM is +always enabled from Windows 8 and above. Windows 7 only enables DWM with Aero Glass +theme. + +However, it cannot be guaranteed to work on all hardware configurations (an example +is hybrid GPU systems, such as NVIDIA Optimus laptops). diff --git a/docs/README-winrt.md b/docs/README-winrt.md index 619226409..a41b21eb6 100644 --- a/docs/README-winrt.md +++ b/docs/README-winrt.md @@ -1,523 +1,523 @@ -WinRT -===== - -This port allows SDL applications to run on Microsoft's platforms that require -use of "Windows Runtime", aka. "WinRT", APIs. Microsoft may, in some cases, -refer to them as either "Windows Store", or for Windows 10, "UWP" apps. - -In the past, SDL has supported Windows RT 8.x, Windows Phone, etc, but in -modern times this port is focused on UWP apps, which run on Windows 10, -and modern Xbox consoles. - - -Requirements ------------- - -* Microsoft Visual C++ (aka Visual Studio) 2019. - - Free, "Community" or "Express" editions may be used, so long as they - include support for either "Windows Store" or "Windows Phone" apps. - "Express" versions marked as supporting "Windows Desktop" development - typically do not include support for creating WinRT apps, to note. - (The "Community" editions of Visual C++ do, however, support both - desktop/Win32 and WinRT development). -* A valid Microsoft account - This requirement is not imposed by SDL, but - rather by Microsoft's Visual C++ toolchain. This is required to launch or - debug apps. - - -Status ------- - -Here is a rough list of what works, and what doesn't: - -* What works: - * compilation via Visual C++ 2019. - * compile-time platform detection for SDL programs. The C/C++ #define, - `__WINRT__`, will be set to 1 (by SDL) when compiling for WinRT. - * GPU-accelerated 2D rendering, via SDL_Renderer. - * OpenGL ES 2, via the ANGLE library (included separately from SDL) - * software rendering, via either SDL_Surface (optionally in conjunction with - SDL_GetWindowSurface() and SDL_UpdateWindowSurface()) or via the - SDL_Renderer APIs - * threads - * timers (via SDL_GetTicks(), SDL_AddTimer(), SDL_GetPerformanceCounter(), - SDL_GetPerformanceFrequency(), etc.) - * file I/O via SDL_RWops - * mouse input (unsupported on Windows Phone) - * audio, via SDL's WASAPI backend (if you want to record, your app must - have "Microphone" capabilities enabled in its manifest, and the user must - not have blocked access. Otherwise, capture devices will fail to work, - presenting as a device disconnect shortly after opening it.) - * .DLL file loading. Libraries *MUST* be packaged inside applications. Loading - anything outside of the app is not supported. - * system path retrieval via SDL's filesystem APIs - * game controllers. Support is provided via the SDL_Joystick and - SDL_Gamepad APIs, and is backed by Microsoft's XInput API. Please - note, however, that Windows limits game-controller support in UWP apps to, - "Xbox compatible controllers" (many controllers that work in Win32 apps, - do not work in UWP, due to restrictions in UWP itself.) - * multi-touch input - * app events. SDL_APP_WILLENTER* and SDL_APP_DIDENTER* events get sent out as - appropriate. - * window events - * using Direct3D 11.x APIs outside of SDL. Non-XAML / Direct3D-only apps can - choose to render content directly via Direct3D, using SDL to manage the - internal WinRT window, as well as input and audio. (Use - the window properties to get the WinRT 'CoreWindow', and pass it into - IDXGIFactory2::CreateSwapChainForCoreWindow() as appropriate.) - -* What partially works: - * keyboard input. Most of WinRT's documented virtual keys are supported, as - well as many keys with documented hardware scancodes. Converting - SDL_Scancodes to or from SDL_Keycodes may not work, due to missing APIs - (MapVirtualKey()) in Microsoft's Windows Store / UWP APIs. - * SDL_main. WinRT uses a different signature for each app's main() function - and requires it to be implemented in C++, so SDL_main.h must be #include'd - in a C++ source file, that also must be compiled with /ZW. - -* What doesn't work: - * compilation with anything other than Visual C++ - * programmatically-created custom cursors. These don't appear to be supported - by WinRT. Different OS-provided cursors can, however, be created via - SDL_CreateSystemCursor() (unsupported on Windows Phone) - * SDL_WarpMouseInWindow() or SDL_WarpMouseGlobal(). This are not currently - supported by WinRT itself. - * joysticks and game controllers that either are not supported by - Microsoft's XInput API, or are not supported within UWP apps (many - controllers that work in Win32, do not work in UWP, due to restrictions in - UWP itself). - * turning off VSync when rendering on Windows Phone. Attempts to turn VSync - off on Windows Phone result either in Direct3D not drawing anything, or it - forcing VSync back on. As such, SDL_RENDERER_PRESENTVSYNC will always get - turned-on on Windows Phone. This limitation is not present in non-Phone - WinRT (such as Windows 8.x), where turning off VSync appears to work. - * probably anything else that's not listed as supported - - - -Upgrade Notes -------------- - -#### SDL_GetPrefPath() usage when upgrading WinRT apps from SDL 2.0.3 - -SDL 2.0.4 fixes two bugs found in the WinRT version of SDL_GetPrefPath(). -The fixes may affect older, SDL 2.0.3-based apps' save data. Please note -that these changes only apply to SDL-based WinRT apps, and not to apps for -any other platform. - -1. SDL_GetPrefPath() would return an invalid path, one in which the path's - directory had not been created. Attempts to create files there - (via fopen(), for example), would fail, unless that directory was - explicitly created beforehand. - -2. SDL_GetPrefPath(), for non-WinPhone-based apps, would return a path inside - a WinRT 'Roaming' folder, the contents of which get automatically - synchronized across multiple devices. This process can occur while an - application runs, and can cause existing save-data to be overwritten - at unexpected times, with data from other devices. (Windows Phone apps - written with SDL 2.0.3 did not utilize a Roaming folder, due to API - restrictions in Windows Phone 8.0). - - -SDL_GetPrefPath(), starting with SDL 2.0.4, addresses these by: - -1. making sure that SDL_GetPrefPath() returns a directory in which data - can be written to immediately, without first needing to create directories. - -2. basing SDL_GetPrefPath() off of a different, non-Roaming folder, the - contents of which do not automatically get synchronized across devices - (and which require less work to use safely, in terms of data integrity). - -Apps that wish to get their Roaming folder's path can do so either by using -SDL_WinRTGetFSPathUTF8(), SDL_WinRTGetFSPathUNICODE() (which returns a -UCS-2/wide-char string), or directly through the WinRT class, -Windows.Storage.ApplicationData. - - - -Setup, High-Level Steps ------------------------ - -The steps for setting up a project for an SDL/WinRT app looks like the -following, at a high-level: - -1. create a new Visual C++ project using Microsoft's template for a, - "Direct3D App". -2. remove most of the files from the project. -3. make your app's project directly reference SDL/WinRT's own Visual C++ - project file, via use of Visual C++'s "References" dialog. This will setup - the linker, and will copy SDL's .dll files to your app's final output. -4. adjust your app's build settings, at minimum, telling it where to find SDL's - header files. -5. add files that contains a WinRT-appropriate main function, along with some - data to make sure mouse-cursor-hiding (via SDL_ShowCursor(SDL_DISABLE) calls) - work properly. -6. add SDL-specific app code. -7. build and run your app. - - -Setup, Detailed Steps ---------------------- - -### 1. Create a new project ### - -Create a new project using one of Visual C++'s templates for a plain, non-XAML, -"Direct3D App" (XAML support for SDL/WinRT is not yet ready for use). If you -don't see one of these templates, in Visual C++'s 'New Project' dialog, try -using the textbox titled, 'Search Installed Templates' to look for one. - - -### 2. Remove unneeded files from the project ### - -In the new project, delete any file that has one of the following extensions: - -- .cpp -- .h -- .hlsl - -When you are done, you should be left with a few files, each of which will be a -necessary part of your app's project. These files will consist of: - -- an .appxmanifest file, which contains metadata on your WinRT app. This is - similar to an Info.plist file on iOS, or an AndroidManifest.xml on Android. -- a few .png files, one of which is a splash screen (displayed when your app - launches), others are app icons. -- a .pfx file, used for code signing purposes. - - -### 3. Add references to SDL's project files ### - -SDL/WinRT can be built in multiple variations, spanning across three different -CPU architectures (x86, x64, and ARM) and two different configurations -(Debug and Release). WinRT and Visual C++ do not currently provide a means -for combining multiple variations of one library into a single file. -Furthermore, it does not provide an easy means for copying pre-built .dll files -into your app's final output (via Post-Build steps, for example). It does, -however, provide a system whereby an app can reference the MSVC projects of -libraries such that, when the app is built: - -1. each library gets built for the appropriate CPU architecture(s) and WinRT - platform(s). -2. each library's output, such as .dll files, get copied to the app's build - output. - -To set this up for SDL/WinRT, you'll need to run through the following steps: - -1. open up the Solution Explorer inside Visual C++ (under the "View" menu, then - "Solution Explorer") -2. right click on your app's solution. -3. navigate to "Add", then to "Existing Project..." -4. find SDL/WinRT's Visual C++ project file and open it, in the `VisualC-WinRT` - directory. -5. once the project has been added, right-click on your app's project and - select, "References..." -6. click on the button titled, "Add New Reference..." -7. check the box next to SDL -8. click OK to close the dialog -9. SDL will now show up in the list of references. Click OK to close that - dialog. - -Your project is now linked to SDL's project, insofar that when the app is -built, SDL will be built as well, with its build output getting included with -your app. - - -### 4. Adjust Your App's Build Settings ### - -Some build settings need to be changed in your app's project. This guide will -outline the following: - -- making sure that the compiler knows where to find SDL's header files -- **Optional for C++, but NECESSARY for compiling C code:** telling the - compiler not to use Microsoft's C++ extensions for WinRT development. -- **Optional:** telling the compiler not generate errors due to missing - precompiled header files. - -To change these settings: - -1. right-click on the project -2. choose "Properties" -3. in the drop-down box next to "Configuration", choose, "All Configurations" -4. in the drop-down box next to "Platform", choose, "All Platforms" -5. in the left-hand list, expand the "C/C++" section - **Note:** If you don't see this section, you may have to add a .c or .cpp - Source file to the Project first. -6. select "General" -7. edit the "Additional Include Directories" setting, and add a path to SDL's - "include" directory -8. **Optional: to enable compilation of C code:** change the setting for - "Consume Windows Runtime Extension" from "Yes (/ZW)" to "No". If you're - working with a completely C++ based project, this step can usually be - omitted. -9. **Optional: to disable precompiled headers (which can produce - 'stdafx.h'-related build errors, if setup incorrectly:** in the left-hand - list, select "Precompiled Headers", then change the setting for "Precompiled - Header" from "Use (/Yu)" to "Not Using Precompiled Headers". -10. close the dialog, saving settings, by clicking the "OK" button - - -### 5. Add a WinRT-appropriate main function, and a blank-cursor image, to the app. ### - -A few files should be included directly in your app's MSVC project, specifically: -1. a WinRT-appropriate main function (which is different than main() functions on - other platforms) -2. a Win32-style cursor resource, used by SDL_ShowCursor() to hide the mouse cursor - (if and when the app needs to do so). *If this cursor resource is not - included, mouse-position reporting may fail if and when the cursor is - hidden, due to possible bugs/design-oddities in Windows itself.* - -To include these files for C/C++ projects: - -1. right-click on your project (again, in Visual C++'s Solution Explorer), - navigate to "Add", then choose "Existing Item...". -2. navigate to the directory containing SDL's source code, then into its - subdirectory, 'src/main/winrt/'. Select, then add, the following files: - - `SDL3-WinRTResources.rc` - - `SDL3-WinRTResource_BlankCursor.cur` -3. For the next step you need a C++ source file. - - If your standard main() function is implemented in a **C++** source file, - use that file. - - If your standard main() function is implemented in a **plain C** source file, - create an empty .cpp source file (e.g. `main.cpp`) that only contains the line - `#include ` and use that file instead. -4. Right click on the C++ source file from step 3 (as listed in your project), - then click on "Properties...". -5. in the drop-down box next to "Configuration", choose, "All Configurations" -6. in the drop-down box next to "Platform", choose, "All Platforms" -7. in the left-hand list, click on "C/C++" -8. change the setting for "Consume Windows Runtime Extension" to "Yes (/ZW)". -9. click the OK button. This will close the dialog. - -**NOTE: C++/CX compilation is currently required in at least one file of your -app's project. This is to make sure that Visual C++'s linker builds a 'Windows -Metadata' file (.winmd) for your app. Not doing so can lead to build errors.** - -For non-C++ projects, you will need to call SDL_RunApp from your language's -main function, and generate SDL3-WinRTResources.res manually by using `rc` via -the Developer Command Prompt and including it as a within the -first block in your Visual Studio project file. - -### 6. Add app code and assets ### - -At this point, you can add in SDL-specific source code. Be sure to include a -C-style main function (ie: `int main(int argc, char *argv[])`). From there you -should be able to create a single `SDL_Window` (WinRT apps can only have one -window, at present), as well as an `SDL_Renderer`. Direct3D will be used to -draw content. Events are received via SDL's usual event functions -(`SDL_PollEvent`, etc.) If you have a set of existing source files and assets, -you can start adding them to the project now. If not, or if you would like to -make sure that you're setup correctly, some short and simple sample code is -provided below. - - -#### 6.A. ... when creating a new app #### - -If you are creating a new app (rather than porting an existing SDL-based app), -or if you would just like a simple app to test SDL/WinRT with before trying to -get existing code working, some working SDL/WinRT code is provided below. To -set this up: - -1. right click on your app's project -2. select Add, then New Item. An "Add New Item" dialog will show up. -3. from the left-hand list, choose "Visual C++" -4. from the middle/main list, choose "C++ File (.cpp)" -5. near the bottom of the dialog, next to "Name:", type in a name for your -source file, such as, "main.cpp". -6. click on the Add button. This will close the dialog, add the new file to -your project, and open the file in Visual C++'s text editor. -7. Copy and paste the following code into the new file, then save it. - -```c -#include -#include - -int main(int argc, char **argv) -{ - SDL_Window *window = NULL; - SDL_Renderer *renderer = NULL; - SDL_Event evt; - SDL_bool keep_going = SDL_TRUE; - - if (SDL_Init(SDL_INIT_VIDEO) != 0) { - return 1; - } else if (SDL_CreateWindowAndRenderer(0, 0, SDL_WINDOW_FULLSCREEN, &window, &renderer) != 0) { - return 1; - } - - while (keep_going) { - while (SDL_PollEvent(&evt)) { - if ((evt.type == SDL_EVENT_KEY_DOWN) && (evt.key.keysym.sym == SDLK_ESCAPE)) { - keep_going = SDL_FALSE; - } - } - - SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255); - SDL_RenderClear(renderer); - SDL_RenderPresent(renderer); - } - - SDL_Quit(); - return 0; -} -``` - -#### 6.B. Adding code and assets #### - -If you have existing code and assets that you'd like to add, you should be able -to add them now. The process for adding a set of files is as such. - -1. right click on the app's project -2. select Add, then click on "New Item..." -3. open any source, header, or asset files as appropriate. Support for C and -C++ is available. - -Do note that WinRT only supports a subset of the APIs that are available to -Win32-based apps. Many portions of the Win32 API and the C runtime are not -available. - -A list of unsupported C APIs can be found at - - -General information on using the C runtime in WinRT can be found at - - -A list of supported Win32 APIs for WinRT apps can be found at -. To note, -the list of supported Win32 APIs for Windows Phone 8.0 is different. -That list can be found at - - - -### 7. Build and run your app ### - -Your app project should now be setup, and you should be ready to build your app. -To run it on the local machine, open the Debug menu and choose "Start -Debugging". This will build your app, then run your app full-screen. To switch -out of your app, press the Windows key. Alternatively, you can choose to run -your app in a window. To do this, before building and running your app, find -the drop-down menu in Visual C++'s toolbar that says, "Local Machine". Expand -this by clicking on the arrow on the right side of the list, then click on -Simulator. Once you do that, any time you build and run the app, the app will -launch in window, rather than full-screen. - - -#### 7.A. Running apps on older, ARM-based, "Windows RT" devices #### - -**These instructions do not include Windows Phone, despite Windows Phone -typically running on ARM processors.** They are specifically for devices -that use the "Windows RT" operating system, which was a modified version of -Windows 8.x that ran primarily on ARM-based tablet computers. - -To build and run the app on ARM-based, "Windows RT" devices, you'll need to: - -- install Microsoft's "Remote Debugger" on the device. Visual C++ installs and - debugs ARM-based apps via IP networks. -- change a few options on the development machine, both to make sure it builds - for ARM (rather than x86 or x64), and to make sure it knows how to find the - Windows RT device (on the network). - -Microsoft's Remote Debugger can be found at -. Please note -that separate versions of this debugger exist for different versions of Visual -C++, one each for MSVC 2015, 2013, and 2012. - -To setup Visual C++ to launch your app on an ARM device: - -1. make sure the Remote Debugger is running on your ARM device, and that it's on - the same IP network as your development machine. -2. from Visual C++'s toolbar, find a drop-down menu that says, "Win32". Click - it, then change the value to "ARM". -3. make sure Visual C++ knows the hostname or IP address of the ARM device. To - do this: - 1. open the app project's properties - 2. select "Debugging" - 3. next to "Machine Name", enter the hostname or IP address of the ARM - device - 4. if, and only if, you've turned off authentication in the Remote Debugger, - then change the setting for "Require Authentication" to No - 5. click "OK" -4. build and run the app (from Visual C++). The first time you do this, a - prompt will show up on the ARM device, asking for a Microsoft Account. You - do, unfortunately, need to log in here, and will need to follow the - subsequent registration steps in order to launch the app. After you do so, - if the app didn't already launch, try relaunching it again from within Visual - C++. - - -Troubleshooting ---------------- - -#### Build fails with message, "error LNK2038: mismatch detected for 'vccorlib_lib_should_be_specified_before_msvcrt_lib_to_linker'" - -Try adding the following to your linker flags. In MSVC, this can be done by -right-clicking on the app project, navigating to Configuration Properties -> -Linker -> Command Line, then adding them to the Additional Options -section. - -* For Release builds / MSVC-Configurations, add: - - /nodefaultlib:vccorlib /nodefaultlib:msvcrt vccorlib.lib msvcrt.lib - -* For Debug builds / MSVC-Configurations, add: - - /nodefaultlib:vccorlibd /nodefaultlib:msvcrtd vccorlibd.lib msvcrtd.lib - - -#### Mouse-motion events fail to get sent, or SDL_GetMouseState() fails to return updated values - -This may be caused by a bug in Windows itself, whereby hiding the mouse -cursor can cause mouse-position reporting to fail. - -SDL provides a workaround for this, but it requires that an app links to a -set of Win32-style cursor image-resource files. A copy of suitable resource -files can be found in `src/main/winrt/`. Adding them to an app's Visual C++ -project file should be sufficient to get the app to use them. - - -#### SDL's Visual Studio project file fails to open, with message, "The system can't find the file specified." - -This can be caused for any one of a few reasons, which Visual Studio can -report, but won't always do so in an up-front manner. - -To help determine why this error comes up: - -1. open a copy of Visual Studio without opening a project file. This can be - accomplished via Windows' Start Menu, among other means. -2. show Visual Studio's Output window. This can be done by going to VS' - menu bar, then to View, and then to Output. -3. try opening the SDL project file directly by going to VS' menu bar, then - to File, then to Open, then to Project/Solution. When a File-Open dialog - appears, open the SDL project (such as the one in SDL's source code, in its - directory, VisualC-WinRT/UWP_VS2015/). -4. after attempting to open SDL's Visual Studio project file, additional error - information will be output to the Output window. - -If Visual Studio reports (via its Output window) that the project: - -"could not be loaded because it's missing install components. To fix this launch Visual Studio setup with the following selections: -Microsoft.VisualStudio.ComponentGroup.UWP.VC" - -... then you will need to re-launch Visual Studio's installer, and make sure that -the workflow for "Universal Windows Platform development" is checked, and that its -optional component, "C++ Universal Windows Platform tools" is also checked. While -you are there, if you are planning on targeting UWP / Windows 10, also make sure -that you check the optional component, "Windows 10 SDK (10.0.10240.0)". After -making sure these items are checked as-appropriate, install them. - -Once you install these components, try re-launching Visual Studio, and re-opening -the SDL project file. If you still get the error dialog, try using the Output -window, again, seeing what Visual Studio says about it. - - -#### Game controllers / joysticks aren't working! - -Windows only permits certain game controllers and joysticks to work within -WinRT / UWP apps. Even if a game controller or joystick works in a Win32 -app, that device is not guaranteed to work inside a WinRT / UWP app. - -According to Microsoft, "Xbox compatible controllers" should work inside -UWP apps, potentially with more working in the future. This includes, but -may not be limited to, Microsoft-made Xbox controllers and USB adapters. -(Source: https://social.msdn.microsoft.com/Forums/en-US/9064838b-e8c3-4c18-8a83-19bf0dfe150d/xinput-fails-to-detect-game-controllers?forum=wpdevelop) - - +WinRT +===== + +This port allows SDL applications to run on Microsoft's platforms that require +use of "Windows Runtime", aka. "WinRT", APIs. Microsoft may, in some cases, +refer to them as either "Windows Store", or for Windows 10, "UWP" apps. + +In the past, SDL has supported Windows RT 8.x, Windows Phone, etc, but in +modern times this port is focused on UWP apps, which run on Windows 10, +and modern Xbox consoles. + + +Requirements +------------ + +* Microsoft Visual C++ (aka Visual Studio) 2019. + - Free, "Community" or "Express" editions may be used, so long as they + include support for either "Windows Store" or "Windows Phone" apps. + "Express" versions marked as supporting "Windows Desktop" development + typically do not include support for creating WinRT apps, to note. + (The "Community" editions of Visual C++ do, however, support both + desktop/Win32 and WinRT development). +* A valid Microsoft account - This requirement is not imposed by SDL, but + rather by Microsoft's Visual C++ toolchain. This is required to launch or + debug apps. + + +Status +------ + +Here is a rough list of what works, and what doesn't: + +* What works: + * compilation via Visual C++ 2019. + * compile-time platform detection for SDL programs. The C/C++ #define, + `__WINRT__`, will be set to 1 (by SDL) when compiling for WinRT. + * GPU-accelerated 2D rendering, via SDL_Renderer. + * OpenGL ES 2, via the ANGLE library (included separately from SDL) + * software rendering, via either SDL_Surface (optionally in conjunction with + SDL_GetWindowSurface() and SDL_UpdateWindowSurface()) or via the + SDL_Renderer APIs + * threads + * timers (via SDL_GetTicks(), SDL_AddTimer(), SDL_GetPerformanceCounter(), + SDL_GetPerformanceFrequency(), etc.) + * file I/O via SDL_RWops + * mouse input (unsupported on Windows Phone) + * audio, via SDL's WASAPI backend (if you want to record, your app must + have "Microphone" capabilities enabled in its manifest, and the user must + not have blocked access. Otherwise, capture devices will fail to work, + presenting as a device disconnect shortly after opening it.) + * .DLL file loading. Libraries *MUST* be packaged inside applications. Loading + anything outside of the app is not supported. + * system path retrieval via SDL's filesystem APIs + * game controllers. Support is provided via the SDL_Joystick and + SDL_Gamepad APIs, and is backed by Microsoft's XInput API. Please + note, however, that Windows limits game-controller support in UWP apps to, + "Xbox compatible controllers" (many controllers that work in Win32 apps, + do not work in UWP, due to restrictions in UWP itself.) + * multi-touch input + * app events. SDL_APP_WILLENTER* and SDL_APP_DIDENTER* events get sent out as + appropriate. + * window events + * using Direct3D 11.x APIs outside of SDL. Non-XAML / Direct3D-only apps can + choose to render content directly via Direct3D, using SDL to manage the + internal WinRT window, as well as input and audio. (Use + the window properties to get the WinRT 'CoreWindow', and pass it into + IDXGIFactory2::CreateSwapChainForCoreWindow() as appropriate.) + +* What partially works: + * keyboard input. Most of WinRT's documented virtual keys are supported, as + well as many keys with documented hardware scancodes. Converting + SDL_Scancodes to or from SDL_Keycodes may not work, due to missing APIs + (MapVirtualKey()) in Microsoft's Windows Store / UWP APIs. + * SDL_main. WinRT uses a different signature for each app's main() function + and requires it to be implemented in C++, so SDL_main.h must be #include'd + in a C++ source file, that also must be compiled with /ZW. + +* What doesn't work: + * compilation with anything other than Visual C++ + * programmatically-created custom cursors. These don't appear to be supported + by WinRT. Different OS-provided cursors can, however, be created via + SDL_CreateSystemCursor() (unsupported on Windows Phone) + * SDL_WarpMouseInWindow() or SDL_WarpMouseGlobal(). This are not currently + supported by WinRT itself. + * joysticks and game controllers that either are not supported by + Microsoft's XInput API, or are not supported within UWP apps (many + controllers that work in Win32, do not work in UWP, due to restrictions in + UWP itself). + * turning off VSync when rendering on Windows Phone. Attempts to turn VSync + off on Windows Phone result either in Direct3D not drawing anything, or it + forcing VSync back on. As such, SDL_RENDERER_PRESENTVSYNC will always get + turned-on on Windows Phone. This limitation is not present in non-Phone + WinRT (such as Windows 8.x), where turning off VSync appears to work. + * probably anything else that's not listed as supported + + + +Upgrade Notes +------------- + +#### SDL_GetPrefPath() usage when upgrading WinRT apps from SDL 2.0.3 + +SDL 2.0.4 fixes two bugs found in the WinRT version of SDL_GetPrefPath(). +The fixes may affect older, SDL 2.0.3-based apps' save data. Please note +that these changes only apply to SDL-based WinRT apps, and not to apps for +any other platform. + +1. SDL_GetPrefPath() would return an invalid path, one in which the path's + directory had not been created. Attempts to create files there + (via fopen(), for example), would fail, unless that directory was + explicitly created beforehand. + +2. SDL_GetPrefPath(), for non-WinPhone-based apps, would return a path inside + a WinRT 'Roaming' folder, the contents of which get automatically + synchronized across multiple devices. This process can occur while an + application runs, and can cause existing save-data to be overwritten + at unexpected times, with data from other devices. (Windows Phone apps + written with SDL 2.0.3 did not utilize a Roaming folder, due to API + restrictions in Windows Phone 8.0). + + +SDL_GetPrefPath(), starting with SDL 2.0.4, addresses these by: + +1. making sure that SDL_GetPrefPath() returns a directory in which data + can be written to immediately, without first needing to create directories. + +2. basing SDL_GetPrefPath() off of a different, non-Roaming folder, the + contents of which do not automatically get synchronized across devices + (and which require less work to use safely, in terms of data integrity). + +Apps that wish to get their Roaming folder's path can do so either by using +SDL_WinRTGetFSPathUTF8(), SDL_WinRTGetFSPathUNICODE() (which returns a +UCS-2/wide-char string), or directly through the WinRT class, +Windows.Storage.ApplicationData. + + + +Setup, High-Level Steps +----------------------- + +The steps for setting up a project for an SDL/WinRT app looks like the +following, at a high-level: + +1. create a new Visual C++ project using Microsoft's template for a, + "Direct3D App". +2. remove most of the files from the project. +3. make your app's project directly reference SDL/WinRT's own Visual C++ + project file, via use of Visual C++'s "References" dialog. This will setup + the linker, and will copy SDL's .dll files to your app's final output. +4. adjust your app's build settings, at minimum, telling it where to find SDL's + header files. +5. add files that contains a WinRT-appropriate main function, along with some + data to make sure mouse-cursor-hiding (via SDL_ShowCursor(SDL_DISABLE) calls) + work properly. +6. add SDL-specific app code. +7. build and run your app. + + +Setup, Detailed Steps +--------------------- + +### 1. Create a new project ### + +Create a new project using one of Visual C++'s templates for a plain, non-XAML, +"Direct3D App" (XAML support for SDL/WinRT is not yet ready for use). If you +don't see one of these templates, in Visual C++'s 'New Project' dialog, try +using the textbox titled, 'Search Installed Templates' to look for one. + + +### 2. Remove unneeded files from the project ### + +In the new project, delete any file that has one of the following extensions: + +- .cpp +- .h +- .hlsl + +When you are done, you should be left with a few files, each of which will be a +necessary part of your app's project. These files will consist of: + +- an .appxmanifest file, which contains metadata on your WinRT app. This is + similar to an Info.plist file on iOS, or an AndroidManifest.xml on Android. +- a few .png files, one of which is a splash screen (displayed when your app + launches), others are app icons. +- a .pfx file, used for code signing purposes. + + +### 3. Add references to SDL's project files ### + +SDL/WinRT can be built in multiple variations, spanning across three different +CPU architectures (x86, x64, and ARM) and two different configurations +(Debug and Release). WinRT and Visual C++ do not currently provide a means +for combining multiple variations of one library into a single file. +Furthermore, it does not provide an easy means for copying pre-built .dll files +into your app's final output (via Post-Build steps, for example). It does, +however, provide a system whereby an app can reference the MSVC projects of +libraries such that, when the app is built: + +1. each library gets built for the appropriate CPU architecture(s) and WinRT + platform(s). +2. each library's output, such as .dll files, get copied to the app's build + output. + +To set this up for SDL/WinRT, you'll need to run through the following steps: + +1. open up the Solution Explorer inside Visual C++ (under the "View" menu, then + "Solution Explorer") +2. right click on your app's solution. +3. navigate to "Add", then to "Existing Project..." +4. find SDL/WinRT's Visual C++ project file and open it, in the `VisualC-WinRT` + directory. +5. once the project has been added, right-click on your app's project and + select, "References..." +6. click on the button titled, "Add New Reference..." +7. check the box next to SDL +8. click OK to close the dialog +9. SDL will now show up in the list of references. Click OK to close that + dialog. + +Your project is now linked to SDL's project, insofar that when the app is +built, SDL will be built as well, with its build output getting included with +your app. + + +### 4. Adjust Your App's Build Settings ### + +Some build settings need to be changed in your app's project. This guide will +outline the following: + +- making sure that the compiler knows where to find SDL's header files +- **Optional for C++, but NECESSARY for compiling C code:** telling the + compiler not to use Microsoft's C++ extensions for WinRT development. +- **Optional:** telling the compiler not generate errors due to missing + precompiled header files. + +To change these settings: + +1. right-click on the project +2. choose "Properties" +3. in the drop-down box next to "Configuration", choose, "All Configurations" +4. in the drop-down box next to "Platform", choose, "All Platforms" +5. in the left-hand list, expand the "C/C++" section + **Note:** If you don't see this section, you may have to add a .c or .cpp + Source file to the Project first. +6. select "General" +7. edit the "Additional Include Directories" setting, and add a path to SDL's + "include" directory +8. **Optional: to enable compilation of C code:** change the setting for + "Consume Windows Runtime Extension" from "Yes (/ZW)" to "No". If you're + working with a completely C++ based project, this step can usually be + omitted. +9. **Optional: to disable precompiled headers (which can produce + 'stdafx.h'-related build errors, if setup incorrectly:** in the left-hand + list, select "Precompiled Headers", then change the setting for "Precompiled + Header" from "Use (/Yu)" to "Not Using Precompiled Headers". +10. close the dialog, saving settings, by clicking the "OK" button + + +### 5. Add a WinRT-appropriate main function, and a blank-cursor image, to the app. ### + +A few files should be included directly in your app's MSVC project, specifically: +1. a WinRT-appropriate main function (which is different than main() functions on + other platforms) +2. a Win32-style cursor resource, used by SDL_ShowCursor() to hide the mouse cursor + (if and when the app needs to do so). *If this cursor resource is not + included, mouse-position reporting may fail if and when the cursor is + hidden, due to possible bugs/design-oddities in Windows itself.* + +To include these files for C/C++ projects: + +1. right-click on your project (again, in Visual C++'s Solution Explorer), + navigate to "Add", then choose "Existing Item...". +2. navigate to the directory containing SDL's source code, then into its + subdirectory, 'src/main/winrt/'. Select, then add, the following files: + - `SDL3-WinRTResources.rc` + - `SDL3-WinRTResource_BlankCursor.cur` +3. For the next step you need a C++ source file. + - If your standard main() function is implemented in a **C++** source file, + use that file. + - If your standard main() function is implemented in a **plain C** source file, + create an empty .cpp source file (e.g. `main.cpp`) that only contains the line + `#include ` and use that file instead. +4. Right click on the C++ source file from step 3 (as listed in your project), + then click on "Properties...". +5. in the drop-down box next to "Configuration", choose, "All Configurations" +6. in the drop-down box next to "Platform", choose, "All Platforms" +7. in the left-hand list, click on "C/C++" +8. change the setting for "Consume Windows Runtime Extension" to "Yes (/ZW)". +9. click the OK button. This will close the dialog. + +**NOTE: C++/CX compilation is currently required in at least one file of your +app's project. This is to make sure that Visual C++'s linker builds a 'Windows +Metadata' file (.winmd) for your app. Not doing so can lead to build errors.** + +For non-C++ projects, you will need to call SDL_RunApp from your language's +main function, and generate SDL3-WinRTResources.res manually by using `rc` via +the Developer Command Prompt and including it as a within the +first block in your Visual Studio project file. + +### 6. Add app code and assets ### + +At this point, you can add in SDL-specific source code. Be sure to include a +C-style main function (ie: `int main(int argc, char *argv[])`). From there you +should be able to create a single `SDL_Window` (WinRT apps can only have one +window, at present), as well as an `SDL_Renderer`. Direct3D will be used to +draw content. Events are received via SDL's usual event functions +(`SDL_PollEvent`, etc.) If you have a set of existing source files and assets, +you can start adding them to the project now. If not, or if you would like to +make sure that you're setup correctly, some short and simple sample code is +provided below. + + +#### 6.A. ... when creating a new app #### + +If you are creating a new app (rather than porting an existing SDL-based app), +or if you would just like a simple app to test SDL/WinRT with before trying to +get existing code working, some working SDL/WinRT code is provided below. To +set this up: + +1. right click on your app's project +2. select Add, then New Item. An "Add New Item" dialog will show up. +3. from the left-hand list, choose "Visual C++" +4. from the middle/main list, choose "C++ File (.cpp)" +5. near the bottom of the dialog, next to "Name:", type in a name for your +source file, such as, "main.cpp". +6. click on the Add button. This will close the dialog, add the new file to +your project, and open the file in Visual C++'s text editor. +7. Copy and paste the following code into the new file, then save it. + +```c +#include +#include + +int main(int argc, char **argv) +{ + SDL_Window *window = NULL; + SDL_Renderer *renderer = NULL; + SDL_Event evt; + SDL_bool keep_going = SDL_TRUE; + + if (SDL_Init(SDL_INIT_VIDEO) != 0) { + return 1; + } else if (SDL_CreateWindowAndRenderer(0, 0, SDL_WINDOW_FULLSCREEN, &window, &renderer) != 0) { + return 1; + } + + while (keep_going) { + while (SDL_PollEvent(&evt)) { + if ((evt.type == SDL_EVENT_KEY_DOWN) && (evt.key.keysym.sym == SDLK_ESCAPE)) { + keep_going = SDL_FALSE; + } + } + + SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255); + SDL_RenderClear(renderer); + SDL_RenderPresent(renderer); + } + + SDL_Quit(); + return 0; +} +``` + +#### 6.B. Adding code and assets #### + +If you have existing code and assets that you'd like to add, you should be able +to add them now. The process for adding a set of files is as such. + +1. right click on the app's project +2. select Add, then click on "New Item..." +3. open any source, header, or asset files as appropriate. Support for C and +C++ is available. + +Do note that WinRT only supports a subset of the APIs that are available to +Win32-based apps. Many portions of the Win32 API and the C runtime are not +available. + +A list of unsupported C APIs can be found at + + +General information on using the C runtime in WinRT can be found at + + +A list of supported Win32 APIs for WinRT apps can be found at +. To note, +the list of supported Win32 APIs for Windows Phone 8.0 is different. +That list can be found at + + + +### 7. Build and run your app ### + +Your app project should now be setup, and you should be ready to build your app. +To run it on the local machine, open the Debug menu and choose "Start +Debugging". This will build your app, then run your app full-screen. To switch +out of your app, press the Windows key. Alternatively, you can choose to run +your app in a window. To do this, before building and running your app, find +the drop-down menu in Visual C++'s toolbar that says, "Local Machine". Expand +this by clicking on the arrow on the right side of the list, then click on +Simulator. Once you do that, any time you build and run the app, the app will +launch in window, rather than full-screen. + + +#### 7.A. Running apps on older, ARM-based, "Windows RT" devices #### + +**These instructions do not include Windows Phone, despite Windows Phone +typically running on ARM processors.** They are specifically for devices +that use the "Windows RT" operating system, which was a modified version of +Windows 8.x that ran primarily on ARM-based tablet computers. + +To build and run the app on ARM-based, "Windows RT" devices, you'll need to: + +- install Microsoft's "Remote Debugger" on the device. Visual C++ installs and + debugs ARM-based apps via IP networks. +- change a few options on the development machine, both to make sure it builds + for ARM (rather than x86 or x64), and to make sure it knows how to find the + Windows RT device (on the network). + +Microsoft's Remote Debugger can be found at +. Please note +that separate versions of this debugger exist for different versions of Visual +C++, one each for MSVC 2015, 2013, and 2012. + +To setup Visual C++ to launch your app on an ARM device: + +1. make sure the Remote Debugger is running on your ARM device, and that it's on + the same IP network as your development machine. +2. from Visual C++'s toolbar, find a drop-down menu that says, "Win32". Click + it, then change the value to "ARM". +3. make sure Visual C++ knows the hostname or IP address of the ARM device. To + do this: + 1. open the app project's properties + 2. select "Debugging" + 3. next to "Machine Name", enter the hostname or IP address of the ARM + device + 4. if, and only if, you've turned off authentication in the Remote Debugger, + then change the setting for "Require Authentication" to No + 5. click "OK" +4. build and run the app (from Visual C++). The first time you do this, a + prompt will show up on the ARM device, asking for a Microsoft Account. You + do, unfortunately, need to log in here, and will need to follow the + subsequent registration steps in order to launch the app. After you do so, + if the app didn't already launch, try relaunching it again from within Visual + C++. + + +Troubleshooting +--------------- + +#### Build fails with message, "error LNK2038: mismatch detected for 'vccorlib_lib_should_be_specified_before_msvcrt_lib_to_linker'" + +Try adding the following to your linker flags. In MSVC, this can be done by +right-clicking on the app project, navigating to Configuration Properties -> +Linker -> Command Line, then adding them to the Additional Options +section. + +* For Release builds / MSVC-Configurations, add: + + /nodefaultlib:vccorlib /nodefaultlib:msvcrt vccorlib.lib msvcrt.lib + +* For Debug builds / MSVC-Configurations, add: + + /nodefaultlib:vccorlibd /nodefaultlib:msvcrtd vccorlibd.lib msvcrtd.lib + + +#### Mouse-motion events fail to get sent, or SDL_GetMouseState() fails to return updated values + +This may be caused by a bug in Windows itself, whereby hiding the mouse +cursor can cause mouse-position reporting to fail. + +SDL provides a workaround for this, but it requires that an app links to a +set of Win32-style cursor image-resource files. A copy of suitable resource +files can be found in `src/main/winrt/`. Adding them to an app's Visual C++ +project file should be sufficient to get the app to use them. + + +#### SDL's Visual Studio project file fails to open, with message, "The system can't find the file specified." + +This can be caused for any one of a few reasons, which Visual Studio can +report, but won't always do so in an up-front manner. + +To help determine why this error comes up: + +1. open a copy of Visual Studio without opening a project file. This can be + accomplished via Windows' Start Menu, among other means. +2. show Visual Studio's Output window. This can be done by going to VS' + menu bar, then to View, and then to Output. +3. try opening the SDL project file directly by going to VS' menu bar, then + to File, then to Open, then to Project/Solution. When a File-Open dialog + appears, open the SDL project (such as the one in SDL's source code, in its + directory, VisualC-WinRT/UWP_VS2015/). +4. after attempting to open SDL's Visual Studio project file, additional error + information will be output to the Output window. + +If Visual Studio reports (via its Output window) that the project: + +"could not be loaded because it's missing install components. To fix this launch Visual Studio setup with the following selections: +Microsoft.VisualStudio.ComponentGroup.UWP.VC" + +... then you will need to re-launch Visual Studio's installer, and make sure that +the workflow for "Universal Windows Platform development" is checked, and that its +optional component, "C++ Universal Windows Platform tools" is also checked. While +you are there, if you are planning on targeting UWP / Windows 10, also make sure +that you check the optional component, "Windows 10 SDK (10.0.10240.0)". After +making sure these items are checked as-appropriate, install them. + +Once you install these components, try re-launching Visual Studio, and re-opening +the SDL project file. If you still get the error dialog, try using the Output +window, again, seeing what Visual Studio says about it. + + +#### Game controllers / joysticks aren't working! + +Windows only permits certain game controllers and joysticks to work within +WinRT / UWP apps. Even if a game controller or joystick works in a Win32 +app, that device is not guaranteed to work inside a WinRT / UWP app. + +According to Microsoft, "Xbox compatible controllers" should work inside +UWP apps, potentially with more working in the future. This includes, but +may not be limited to, Microsoft-made Xbox controllers and USB adapters. +(Source: https://social.msdn.microsoft.com/Forums/en-US/9064838b-e8c3-4c18-8a83-19bf0dfe150d/xinput-fails-to-detect-game-controllers?forum=wpdevelop) + + diff --git a/docs/README.md b/docs/README.md index 661515c85..469a8394d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,57 +1,57 @@ -# Simple DirectMedia Layer - -https://www.libsdl.org/ - -Simple DirectMedia Layer is a cross-platform development library designed -to provide low level access to audio, keyboard, mouse, joystick, and graphics -hardware via OpenGL and Direct3D. It is used by video playback software, -emulators, and popular games including Valve's award winning catalog -and many Humble Bundle games. - -SDL officially supports Windows, macOS, Linux, iOS, and Android. -Support for other platforms may be found in the source code. - -SDL is written in C, works natively with C++, and there are bindings -available for several other languages, including C# and Python. - -This library is distributed under the zlib license, which can be found -in the file "LICENSE.txt". - -The best way to learn how to use SDL is to check out the header files in -the "include" subdirectory and the programs in the "test" subdirectory. -The header files and test programs are well commented and always up to date. - -More documentation and FAQs are available online at [the wiki](http://wiki.libsdl.org/) - -- [Android](README-android.md) -- [CMake](README-cmake.md) -- [DynAPI](README-dynapi.md) -- [Emscripten](README-emscripten.md) -- [GDK](README-gdk.md) -- [Git](README-git.md) -- [iOS](README-ios.md) -- [Linux](README-linux.md) -- [macOS](README-macos.md) -- [Supported Platforms](README-platforms.md) -- [Porting information](README-porting.md) -- [PSP](README-psp.md) -- [PS2](README-ps2.md) -- [Raspberry Pi](README-raspberrypi.md) -- [Touch](README-touch.md) -- [Versions](README-versions.md) -- [Windows](README-windows.md) -- [WinRT](README-winrt.md) -- [PSVita](README-vita.md) -- [Nokia N-Gage](README-ngage.md) - -If you need help with the library, or just want to discuss SDL related -issues, you can join the [SDL Discourse](https://discourse.libsdl.org/), -which can be used as a web forum or a mailing list, at your preference. - -If you want to report bugs or contribute patches, please submit them to -[our bug tracker](https://github.com/libsdl-org/SDL/issues) - -Enjoy! - - -Sam Lantinga +# Simple DirectMedia Layer + +https://www.libsdl.org/ + +Simple DirectMedia Layer is a cross-platform development library designed +to provide low level access to audio, keyboard, mouse, joystick, and graphics +hardware via OpenGL and Direct3D. It is used by video playback software, +emulators, and popular games including Valve's award winning catalog +and many Humble Bundle games. + +SDL officially supports Windows, macOS, Linux, iOS, and Android. +Support for other platforms may be found in the source code. + +SDL is written in C, works natively with C++, and there are bindings +available for several other languages, including C# and Python. + +This library is distributed under the zlib license, which can be found +in the file "LICENSE.txt". + +The best way to learn how to use SDL is to check out the header files in +the "include" subdirectory and the programs in the "test" subdirectory. +The header files and test programs are well commented and always up to date. + +More documentation and FAQs are available online at [the wiki](http://wiki.libsdl.org/) + +- [Android](README-android.md) +- [CMake](README-cmake.md) +- [DynAPI](README-dynapi.md) +- [Emscripten](README-emscripten.md) +- [GDK](README-gdk.md) +- [Git](README-git.md) +- [iOS](README-ios.md) +- [Linux](README-linux.md) +- [macOS](README-macos.md) +- [Supported Platforms](README-platforms.md) +- [Porting information](README-porting.md) +- [PSP](README-psp.md) +- [PS2](README-ps2.md) +- [Raspberry Pi](README-raspberrypi.md) +- [Touch](README-touch.md) +- [Versions](README-versions.md) +- [Windows](README-windows.md) +- [WinRT](README-winrt.md) +- [PSVita](README-vita.md) +- [Nokia N-Gage](README-ngage.md) + +If you need help with the library, or just want to discuss SDL related +issues, you can join the [SDL Discourse](https://discourse.libsdl.org/), +which can be used as a web forum or a mailing list, at your preference. + +If you want to report bugs or contribute patches, please submit them to +[our bug tracker](https://github.com/libsdl-org/SDL/issues) + +Enjoy! + + +Sam Lantinga