SDL: Initial SDL_ps2_main implementation

From 84d69da4e173365ddfdfe0a77ac5bc79b25f1972 Mon Sep 17 00:00:00 2001
From: Francisco Javier Trujillo Mata <[EMAIL REDACTED]>
Date: Sun, 20 Mar 2022 19:42:06 +0100
Subject: [PATCH] Initial SDL_ps2_main implementation

---
 CMakeLists.txt              | 11 ++++++++++-
 include/SDL_main.h          |  3 +++
 src/main/ps2/SDL_ps2_main.c | 36 ++++++++++++++++++++++++++++++++++++
 test/CMakeLists.txt         |  8 ++++++++
 4 files changed, 57 insertions(+), 1 deletion(-)
 create mode 100644 src/main/ps2/SDL_ps2_main.c

diff --git a/CMakeLists.txt b/CMakeLists.txt
index a91aaab3c0d..b82f735506c 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -2539,7 +2539,10 @@ elseif(PSP)
   endif(NOT SDL2_DISABLE_SDL2MAIN)
 
 elseif(PS2)
-  list(APPEND EXTRA_CFLAGS "-DPS2" "-D__PS2__")
+  list(APPEND EXTRA_CFLAGS "-DPS2" "-D__PS2__" "-I${PS2SDK}/ports/include")
+
+  file(GLOB PS2_MAIN_SOURCES ${SDL2_SOURCE_DIR}/src/main/ps2/*.c)
+  set(SDLMAIN_SOURCES ${SDLMAIN_SOURCES} ${PS2_MAIN_SOURCES})
 
   if(SDL_FILESYSTEM)
     set(SDL_FILESYSTEM_PS2 1)
@@ -2559,6 +2562,12 @@ elseif(PS2)
     list(APPEND SOURCE_FILES ${PS2_TIMER_SOURCES})
     set(HAVE_SDL_TIMERS TRUE)
   endif()
+
+  list(APPEND EXTRA_LIBS
+    patches
+    ps2_drivers
+  )
+
 elseif(OS2)
   list(APPEND EXTRA_CFLAGS "-DOS2EMX_PLAIN_CHAR")
 
diff --git a/include/SDL_main.h b/include/SDL_main.h
index b3fec15feb0..a7679f27811 100644
--- a/include/SDL_main.h
+++ b/include/SDL_main.h
@@ -92,6 +92,9 @@
  */
 #define SDL_MAIN_AVAILABLE
 
+#elif defined(__PS2__)
+#define SDL_MAIN_AVAILABLE
+
 #endif
 #endif /* SDL_MAIN_HANDLED */
 
diff --git a/src/main/ps2/SDL_ps2_main.c b/src/main/ps2/SDL_ps2_main.c
new file mode 100644
index 00000000000..60b1fbd0a06
--- /dev/null
+++ b/src/main/ps2/SDL_ps2_main.c
@@ -0,0 +1,36 @@
+/*
+    SDL_ps2_main.c, fjtrujy@gmail.com 
+*/
+
+#include "SDL_config.h"
+
+#ifdef __PS2__
+
+#include "SDL_main.h"
+#include "SDL_error.h"
+
+#include <sifrpc.h>
+#include <iopcontrol.h>
+#include <sbv_patches.h>
+
+#ifdef main
+    #undef main
+#endif
+
+static void prepare_IOP()
+{
+   SifInitRpc(0);
+   sbv_patch_enable_lmb();
+   sbv_patch_disable_prefix_check();
+}
+
+int main(int argc, char *argv[])
+{
+    prepare_IOP();
+
+    return SDL_main(argc, argv);
+}
+
+#endif /* _EE */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt
index 135be4597c8..c2fcc766a0e 100644
--- a/test/CMakeLists.txt
+++ b/test/CMakeLists.txt
@@ -27,6 +27,14 @@ if(PSP)
         psphprm
         psppower
     )
+elseif(PS2)
+link_libraries(
+        SDL2main
+        SDL2_test
+        SDL2-static
+        patches
+        ps2_drivers
+)
 else()
     link_libraries(SDL2::SDL2test SDL2::SDL2-static)
 endif()