diff options
Diffstat (limited to 'platform')
117 files changed, 3386 insertions, 2576 deletions
diff --git a/platform/SCsub b/platform/SCsub index 40cacce674..5194a19518 100644 --- a/platform/SCsub +++ b/platform/SCsub @@ -1,30 +1,30 @@ #!/usr/bin/env python -Import('env') +Import("env") env.platform_sources = [] # Register platform-exclusive APIs reg_apis_inc = '#include "register_platform_apis.h"\n' -reg_apis = 'void register_platform_apis() {\n' -unreg_apis = 'void unregister_platform_apis() {\n' +reg_apis = "void register_platform_apis() {\n" +unreg_apis = "void unregister_platform_apis() {\n" for platform in env.platform_apis: platform_dir = env.Dir(platform) - env.add_source_files(env.platform_sources, platform + '/api/api.cpp') - reg_apis += '\tregister_' + platform + '_api();\n' - unreg_apis += '\tunregister_' + platform + '_api();\n' + env.add_source_files(env.platform_sources, platform + "/api/api.cpp") + reg_apis += "\tregister_" + platform + "_api();\n" + unreg_apis += "\tunregister_" + platform + "_api();\n" reg_apis_inc += '#include "' + platform + '/api/api.h"\n' -reg_apis_inc += '\n' -reg_apis += '}\n\n' -unreg_apis += '}\n' +reg_apis_inc += "\n" +reg_apis += "}\n\n" +unreg_apis += "}\n" # NOTE: It is safe to generate this file here, since this is still execute serially -with open('register_platform_apis.gen.cpp', 'w', encoding="utf-8") as f: +with open("register_platform_apis.gen.cpp", "w", encoding="utf-8") as f: f.write(reg_apis_inc) f.write(reg_apis) f.write(unreg_apis) -env.add_source_files(env.platform_sources, 'register_platform_apis.gen.cpp') +env.add_source_files(env.platform_sources, "register_platform_apis.gen.cpp") -lib = env.add_library('platform', env.platform_sources) +lib = env.add_library("platform", env.platform_sources) env.Prepend(LIBS=[lib]) diff --git a/platform/android/SCsub b/platform/android/SCsub index 5ca5ce548c..ec42bc42b5 100644 --- a/platform/android/SCsub +++ b/platform/android/SCsub @@ -1,24 +1,24 @@ #!/usr/bin/env python -Import('env') +Import("env") android_files = [ - 'os_android.cpp', - 'file_access_android.cpp', - 'audio_driver_opensl.cpp', - 'file_access_jandroid.cpp', - 'dir_access_jandroid.cpp', - 'thread_jandroid.cpp', - 'net_socket_android.cpp', - 'audio_driver_jandroid.cpp', - 'java_godot_lib_jni.cpp', - 'java_class_wrapper.cpp', - 'java_godot_wrapper.cpp', - 'java_godot_io_wrapper.cpp', - 'jni_utils.cpp', - 'android_keys_utils.cpp', - 'vulkan/vk_renderer_jni.cpp', - 'plugin/godot_plugin_jni.cpp' + "os_android.cpp", + "file_access_android.cpp", + "audio_driver_opensl.cpp", + "file_access_jandroid.cpp", + "dir_access_jandroid.cpp", + "thread_jandroid.cpp", + "net_socket_android.cpp", + "audio_driver_jandroid.cpp", + "java_godot_lib_jni.cpp", + "java_class_wrapper.cpp", + "java_godot_wrapper.cpp", + "java_godot_io_wrapper.cpp", + "jni_utils.cpp", + "android_keys_utils.cpp", + "display_server_android.cpp", + "vulkan/vulkan_context_android.cpp", ] env_android = env.Clone() @@ -29,30 +29,34 @@ for x in android_files: env_thirdparty = env_android.Clone() env_thirdparty.disable_warnings() -android_objects.append(env_thirdparty.SharedObject('#thirdparty/misc/ifaddrs-android.cc')) +android_objects.append(env_thirdparty.SharedObject("#thirdparty/misc/ifaddrs-android.cc")) lib = env_android.add_shared_library("#bin/libgodot", [android_objects], SHLIBSUFFIX=env["SHLIBSUFFIX"]) -lib_arch_dir = '' -if env['android_arch'] == 'armv7': - lib_arch_dir = 'armeabi-v7a' -elif env['android_arch'] == 'arm64v8': - lib_arch_dir = 'arm64-v8a' -elif env['android_arch'] == 'x86': - lib_arch_dir = 'x86' -elif env['android_arch'] == 'x86_64': - lib_arch_dir = 'x86_64' +lib_arch_dir = "" +if env["android_arch"] == "armv7": + lib_arch_dir = "armeabi-v7a" +elif env["android_arch"] == "arm64v8": + lib_arch_dir = "arm64-v8a" +elif env["android_arch"] == "x86": + lib_arch_dir = "x86" +elif env["android_arch"] == "x86_64": + lib_arch_dir = "x86_64" else: - print('WARN: Architecture not suitable for embedding into APK; keeping .so at \\bin') + print("WARN: Architecture not suitable for embedding into APK; keeping .so at \\bin") -if lib_arch_dir != '': - if env['target'] == 'release': - lib_type_dir = 'release' +if lib_arch_dir != "": + if env["target"] == "release": + lib_type_dir = "release" else: # release_debug, debug - lib_type_dir = 'debug' + lib_type_dir = "debug" - out_dir = '#platform/android/java/lib/libs/' + lib_type_dir + '/' + lib_arch_dir - env_android.Command(out_dir + '/libgodot_android.so', '#bin/libgodot' + env['SHLIBSUFFIX'], Move("$TARGET", "$SOURCE")) + out_dir = "#platform/android/java/lib/libs/" + lib_type_dir + "/" + lib_arch_dir + env_android.Command( + out_dir + "/libgodot_android.so", "#bin/libgodot" + env["SHLIBSUFFIX"], Move("$TARGET", "$SOURCE") + ) - stl_lib_path = str(env['ANDROID_NDK_ROOT']) + '/sources/cxx-stl/llvm-libc++/libs/' + lib_arch_dir + '/libc++_shared.so' - env_android.Command(out_dir + '/libc++_shared.so', stl_lib_path, Copy("$TARGET", "$SOURCE")) + stl_lib_path = ( + str(env["ANDROID_NDK_ROOT"]) + "/sources/cxx-stl/llvm-libc++/libs/" + lib_arch_dir + "/libc++_shared.so" + ) + env_android.Command(out_dir + "/libc++_shared.so", stl_lib_path, Copy("$TARGET", "$SOURCE")) diff --git a/platform/android/api/api.cpp b/platform/android/api/api.cpp index 7efb545524..ef11b12971 100644 --- a/platform/android/api/api.cpp +++ b/platform/android/api/api.cpp @@ -34,7 +34,7 @@ #include "java_class_wrapper.h" #if !defined(ANDROID_ENABLED) -static JavaClassWrapper *java_class_wrapper = NULL; +static JavaClassWrapper *java_class_wrapper = nullptr; #endif void register_android_api() { @@ -73,7 +73,7 @@ Variant JavaObject::call(const StringName &, const Variant **, int, Callable::Ca return Variant(); } -JavaClassWrapper *JavaClassWrapper::singleton = NULL; +JavaClassWrapper *JavaClassWrapper::singleton = nullptr; Ref<JavaClass> JavaClassWrapper::wrap(const String &) { return Ref<JavaClass>(); diff --git a/platform/android/api/java_class_wrapper.h b/platform/android/api/java_class_wrapper.h index d7322deb81..59fcd94b4d 100644 --- a/platform/android/api/java_class_wrapper.h +++ b/platform/android/api/java_class_wrapper.h @@ -236,7 +236,7 @@ public: Ref<JavaClass> wrap(const String &p_class); #ifdef ANDROID_ENABLED - JavaClassWrapper(jobject p_activity = NULL); + JavaClassWrapper(jobject p_activity = nullptr); #else JavaClassWrapper(); #endif diff --git a/platform/android/audio_driver_jandroid.cpp b/platform/android/audio_driver_jandroid.cpp index e94dad9ac6..802d85e7be 100644 --- a/platform/android/audio_driver_jandroid.cpp +++ b/platform/android/audio_driver_jandroid.cpp @@ -34,7 +34,7 @@ #include "core/project_settings.h" #include "thread_jandroid.h" -AudioDriverAndroid *AudioDriverAndroid::s_ad = NULL; +AudioDriverAndroid *AudioDriverAndroid::s_ad = nullptr; jobject AudioDriverAndroid::io; jmethodID AudioDriverAndroid::_init_audio; @@ -46,10 +46,10 @@ jclass AudioDriverAndroid::cls; int AudioDriverAndroid::audioBufferFrames = 0; int AudioDriverAndroid::mix_rate = 44100; bool AudioDriverAndroid::quit = false; -jobject AudioDriverAndroid::audioBuffer = NULL; -void *AudioDriverAndroid::audioBufferPinned = NULL; +jobject AudioDriverAndroid::audioBuffer = nullptr; +void *AudioDriverAndroid::audioBufferPinned = nullptr; Mutex AudioDriverAndroid::mutex; -int32_t *AudioDriverAndroid::audioBuffer32 = NULL; +int32_t *AudioDriverAndroid::audioBuffer32 = nullptr; const char *AudioDriverAndroid::get_name() const { @@ -83,7 +83,7 @@ Error AudioDriverAndroid::init() { audioBuffer = env->CallObjectMethod(io, _init_audio, mix_rate, buffer_size); - ERR_FAIL_COND_V(audioBuffer == NULL, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(audioBuffer == nullptr, ERR_INVALID_PARAMETER); audioBuffer = env->NewGlobalRef(audioBuffer); @@ -181,8 +181,8 @@ void AudioDriverAndroid::finish() { if (audioBuffer) { env->DeleteGlobalRef(audioBuffer); - audioBuffer = NULL; - audioBufferPinned = NULL; + audioBuffer = nullptr; + audioBufferPinned = nullptr; } active = false; diff --git a/platform/android/audio_driver_opensl.cpp b/platform/android/audio_driver_opensl.cpp index 222120f81f..e59850e016 100644 --- a/platform/android/audio_driver_opensl.cpp +++ b/platform/android/audio_driver_opensl.cpp @@ -83,7 +83,7 @@ void AudioDriverOpenSL::_buffer_callbacks( ad->_buffer_callback(queueItf); } -AudioDriverOpenSL *AudioDriverOpenSL::s_ad = NULL; +AudioDriverOpenSL *AudioDriverOpenSL::s_ad = nullptr; const char *AudioDriverOpenSL::get_name() const { @@ -96,7 +96,7 @@ Error AudioDriverOpenSL::init() { SLEngineOption EngineOption[] = { { (SLuint32)SL_ENGINEOPTION_THREADSAFE, (SLuint32)SL_BOOLEAN_TRUE } }; - res = slCreateEngine(&sl, 1, EngineOption, 0, NULL, NULL); + res = slCreateEngine(&sl, 1, EngineOption, 0, nullptr, nullptr); ERR_FAIL_COND_V_MSG(res != SL_RESULT_SUCCESS, ERR_INVALID_PARAMETER, "Could not initialize OpenSL."); res = (*sl)->Realize(sl, SL_BOOLEAN_FALSE); @@ -161,7 +161,7 @@ void AudioDriverOpenSL::start() { locator_outputmix.locatorType = SL_DATALOCATOR_OUTPUTMIX; locator_outputmix.outputMix = OutputMix; audioSink.pLocator = (void *)&locator_outputmix; - audioSink.pFormat = NULL; + audioSink.pFormat = nullptr; /* Initialize the context for Buffer queue callbacks */ //cntxt.pDataBase = (void*)&pcmData; //cntxt.pData = cntxt.pDataBase; @@ -228,9 +228,9 @@ Error AudioDriverOpenSL::capture_init_device() { SL_DATALOCATOR_IODEVICE, SL_IODEVICE_AUDIOINPUT, SL_DEFAULTDEVICEID_AUDIOINPUT, - NULL + nullptr }; - SLDataSource recSource = { &loc_dev, NULL }; + SLDataSource recSource = { &loc_dev, nullptr }; SLDataLocator_AndroidSimpleBufferQueue loc_bq = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, diff --git a/platform/android/detect.py b/platform/android/detect.py index ff3ca0706c..6da1e5f3d6 100644 --- a/platform/android/detect.py +++ b/platform/android/detect.py @@ -13,7 +13,7 @@ def get_name(): def can_build(): - return ("ANDROID_NDK_ROOT" in os.environ) + return "ANDROID_NDK_ROOT" in os.environ def get_platform(platform): @@ -24,33 +24,33 @@ def get_opts(): from SCons.Variables import BoolVariable, EnumVariable return [ - ('ANDROID_NDK_ROOT', 'Path to the Android NDK', os.environ.get("ANDROID_NDK_ROOT", 0)), - ('ndk_platform', 'Target platform (android-<api>, e.g. "android-18")', "android-18"), - EnumVariable('android_arch', 'Target architecture', "armv7", ('armv7', 'arm64v8', 'x86', 'x86_64')), - BoolVariable('android_neon', 'Enable NEON support (armv7 only)', True), + ("ANDROID_NDK_ROOT", "Path to the Android NDK", os.environ.get("ANDROID_NDK_ROOT", 0)), + ("ndk_platform", 'Target platform (android-<api>, e.g. "android-24")', "android-24"), + EnumVariable("android_arch", "Target architecture", "armv7", ("armv7", "arm64v8", "x86", "x86_64")), + BoolVariable("android_neon", "Enable NEON support (armv7 only)", True), ] def get_flags(): return [ - ('tools', False), + ("tools", False), ] def create(env): - tools = env['TOOLS'] + tools = env["TOOLS"] if "mingw" in tools: - tools.remove('mingw') + tools.remove("mingw") if "applelink" in tools: tools.remove("applelink") - env.Tool('gcc') + env.Tool("gcc") return env.Clone(tools=tools) def configure(env): # Workaround for MinGW. See: # http://www.scons.org/wiki/LongCmdLinesOnWin32 - if (os.name == "nt"): + if os.name == "nt": import subprocess @@ -58,8 +58,15 @@ def configure(env): # print("SPAWNED : " + cmdline) startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW - proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE, - stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, env=env) + proc = subprocess.Popen( + cmdline, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + startupinfo=startupinfo, + shell=False, + env=env, + ) data, err = proc.communicate() rv = proc.wait() if rv: @@ -70,7 +77,7 @@ def configure(env): def mySpawn(sh, escape, cmd, args, env): - newargs = ' '.join(args[1:]) + newargs = " ".join(args[1:]) cmdline = cmd + " " + newargs rv = 0 @@ -85,50 +92,54 @@ def configure(env): return rv - env['SPAWN'] = mySpawn + env["SPAWN"] = mySpawn # Architecture - if env['android_arch'] not in ['armv7', 'arm64v8', 'x86', 'x86_64']: - env['android_arch'] = 'armv7' + if env["android_arch"] not in ["armv7", "arm64v8", "x86", "x86_64"]: + env["android_arch"] = "armv7" neon_text = "" - if env["android_arch"] == "armv7" and env['android_neon']: + if env["android_arch"] == "armv7" and env["android_neon"]: neon_text = " (with NEON)" - print("Building for Android (" + env['android_arch'] + ")" + neon_text) + print("Building for Android, platform " + env["ndk_platform"] + " (" + env["android_arch"] + ")" + neon_text) can_vectorize = True - if env['android_arch'] == 'x86': - env['ARCH'] = 'arch-x86' + if env["android_arch"] == "x86": + env["ARCH"] = "arch-x86" env.extra_suffix = ".x86" + env.extra_suffix target_subpath = "x86-4.9" abi_subpath = "i686-linux-android" arch_subpath = "x86" env["x86_libtheora_opt_gcc"] = True - if env['android_arch'] == 'x86_64': + if env["android_arch"] == "x86_64": if get_platform(env["ndk_platform"]) < 21: - print("WARNING: android_arch=x86_64 is not supported by ndk_platform lower than android-21; setting ndk_platform=android-21") + print( + "WARNING: android_arch=x86_64 is not supported by ndk_platform lower than android-21; setting ndk_platform=android-21" + ) env["ndk_platform"] = "android-21" - env['ARCH'] = 'arch-x86_64' + env["ARCH"] = "arch-x86_64" env.extra_suffix = ".x86_64" + env.extra_suffix target_subpath = "x86_64-4.9" abi_subpath = "x86_64-linux-android" arch_subpath = "x86_64" env["x86_libtheora_opt_gcc"] = True elif env["android_arch"] == "armv7": - env['ARCH'] = 'arch-arm' + env["ARCH"] = "arch-arm" target_subpath = "arm-linux-androideabi-4.9" abi_subpath = "arm-linux-androideabi" arch_subpath = "armeabi-v7a" - if env['android_neon']: + if env["android_neon"]: env.extra_suffix = ".armv7.neon" + env.extra_suffix else: env.extra_suffix = ".armv7" + env.extra_suffix elif env["android_arch"] == "arm64v8": if get_platform(env["ndk_platform"]) < 21: - print("WARNING: android_arch=arm64v8 is not supported by ndk_platform lower than android-21; setting ndk_platform=android-21") + print( + "WARNING: android_arch=arm64v8 is not supported by ndk_platform lower than android-21; setting ndk_platform=android-21" + ) env["ndk_platform"] = "android-21" - env['ARCH'] = 'arch-arm64' + env["ARCH"] = "arch-arm64" target_subpath = "aarch64-linux-android-4.9" abi_subpath = "aarch64-linux-android" arch_subpath = "arm64-v8a" @@ -136,40 +147,40 @@ def configure(env): # Build type - if (env["target"].startswith("release")): - if (env["optimize"] == "speed"): # optimize for speed (default) - env.Append(LINKFLAGS=['-O2']) - env.Append(CCFLAGS=['-O2', '-fomit-frame-pointer']) - env.Append(CPPDEFINES=['NDEBUG']) + if env["target"].startswith("release"): + if env["optimize"] == "speed": # optimize for speed (default) + env.Append(LINKFLAGS=["-O2"]) + env.Append(CCFLAGS=["-O2", "-fomit-frame-pointer"]) + env.Append(CPPDEFINES=["NDEBUG"]) else: # optimize for size - env.Append(CCFLAGS=['-Os']) - env.Append(CPPDEFINES=['NDEBUG']) - env.Append(LINKFLAGS=['-Os']) - - if (can_vectorize): - env.Append(CCFLAGS=['-ftree-vectorize']) - if (env["target"] == "release_debug"): - env.Append(CPPDEFINES=['DEBUG_ENABLED']) - elif (env["target"] == "debug"): - env.Append(LINKFLAGS=['-O0']) - env.Append(CCFLAGS=['-O0', '-g', '-fno-limit-debug-info']) - env.Append(CPPDEFINES=['_DEBUG', 'DEBUG_ENABLED', 'DEBUG_MEMORY_ENABLED']) - env.Append(CPPFLAGS=['-UNDEBUG']) + env.Append(CCFLAGS=["-Os"]) + env.Append(CPPDEFINES=["NDEBUG"]) + env.Append(LINKFLAGS=["-Os"]) + + if can_vectorize: + env.Append(CCFLAGS=["-ftree-vectorize"]) + if env["target"] == "release_debug": + env.Append(CPPDEFINES=["DEBUG_ENABLED"]) + elif env["target"] == "debug": + env.Append(LINKFLAGS=["-O0"]) + env.Append(CCFLAGS=["-O0", "-g", "-fno-limit-debug-info"]) + env.Append(CPPDEFINES=["_DEBUG", "DEBUG_ENABLED", "DEBUG_MEMORY_ENABLED"]) + env.Append(CPPFLAGS=["-UNDEBUG"]) # Compiler configuration - env['SHLIBSUFFIX'] = '.so' + env["SHLIBSUFFIX"] = ".so" - if env['PLATFORM'] == 'win32': - env.Tool('gcc') + if env["PLATFORM"] == "win32": + env.Tool("gcc") env.use_windows_spawn_fix() - if (sys.platform.startswith("linux")): + if sys.platform.startswith("linux"): host_subpath = "linux-x86_64" - elif (sys.platform.startswith("darwin")): + elif sys.platform.startswith("darwin"): host_subpath = "darwin-x86_64" - elif (sys.platform.startswith('win')): - if (platform.machine().endswith('64')): + elif sys.platform.startswith("win"): + if platform.machine().endswith("64"): host_subpath = "windows-x86_64" else: host_subpath = "windows" @@ -179,22 +190,22 @@ def configure(env): tools_path = gcc_toolchain_path + "/" + abi_subpath + "/bin" # For Clang to find NDK tools in preference of those system-wide - env.PrependENVPath('PATH', tools_path) + env.PrependENVPath("PATH", tools_path) ccache_path = os.environ.get("CCACHE") if ccache_path is None: - env['CC'] = compiler_path + '/clang' - env['CXX'] = compiler_path + '/clang++' + env["CC"] = compiler_path + "/clang" + env["CXX"] = compiler_path + "/clang++" else: # there aren't any ccache wrappers available for Android, # to enable caching we need to prepend the path to the ccache binary - env['CC'] = ccache_path + ' ' + compiler_path + '/clang' - env['CXX'] = ccache_path + ' ' + compiler_path + '/clang++' - env['AR'] = tools_path + "/ar" - env['RANLIB'] = tools_path + "/ranlib" - env['AS'] = tools_path + "/as" + env["CC"] = ccache_path + " " + compiler_path + "/clang" + env["CXX"] = ccache_path + " " + compiler_path + "/clang++" + env["AR"] = tools_path + "/ar" + env["RANLIB"] = tools_path + "/ranlib" + env["AS"] = tools_path + "/as" - common_opts = ['-fno-integrated-as', '-gcc-toolchain', gcc_toolchain_path] + common_opts = ["-fno-integrated-as", "-gcc-toolchain", gcc_toolchain_path] # Compile flags @@ -202,14 +213,14 @@ def configure(env): env.Append(CPPFLAGS=["-isystem", env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++abi/include"]) # Disable exceptions and rtti on non-tools (template) builds - if env['tools']: - env.Append(CXXFLAGS=['-frtti']) + if env["tools"]: + env.Append(CXXFLAGS=["-frtti"]) else: - env.Append(CXXFLAGS=['-fno-rtti', '-fno-exceptions']) + env.Append(CXXFLAGS=["-fno-rtti", "-fno-exceptions"]) # Don't use dynamic_cast, necessary with no-rtti. - env.Append(CPPDEFINES=['NO_SAFE_CAST']) + env.Append(CPPDEFINES=["NO_SAFE_CAST"]) - lib_sysroot = env["ANDROID_NDK_ROOT"] + "/platforms/" + env['ndk_platform'] + "/" + env['ARCH'] + lib_sysroot = env["ANDROID_NDK_ROOT"] + "/platforms/" + env["ndk_platform"] + "/" + env["ARCH"] # Using NDK unified headers (NDK r15+) sysroot = env["ANDROID_NDK_ROOT"] + "/sysroot" @@ -217,35 +228,37 @@ def configure(env): env.Append(CPPFLAGS=["-isystem", sysroot + "/usr/include/" + abi_subpath]) env.Append(CPPFLAGS=["-isystem", env["ANDROID_NDK_ROOT"] + "/sources/android/support/include"]) # For unified headers this define has to be set manually - env.Append(CPPDEFINES=[('__ANDROID_API__', str(get_platform(env['ndk_platform'])))]) + env.Append(CPPDEFINES=[("__ANDROID_API__", str(get_platform(env["ndk_platform"])))]) - env.Append(CCFLAGS='-fpic -ffunction-sections -funwind-tables -fstack-protector-strong -fvisibility=hidden -fno-strict-aliasing'.split()) - env.Append(CPPDEFINES=['NO_STATVFS', 'GLES_ENABLED']) + env.Append( + CCFLAGS="-fpic -ffunction-sections -funwind-tables -fstack-protector-strong -fvisibility=hidden -fno-strict-aliasing".split() + ) + env.Append(CPPDEFINES=["NO_STATVFS", "GLES_ENABLED"]) - env['neon_enabled'] = False - if env['android_arch'] == 'x86': - target_opts = ['-target', 'i686-none-linux-android'] + env["neon_enabled"] = False + if env["android_arch"] == "x86": + target_opts = ["-target", "i686-none-linux-android"] # The NDK adds this if targeting API < 21, so we can drop it when Godot targets it at least - env.Append(CCFLAGS=['-mstackrealign']) + env.Append(CCFLAGS=["-mstackrealign"]) - elif env['android_arch'] == 'x86_64': - target_opts = ['-target', 'x86_64-none-linux-android'] + elif env["android_arch"] == "x86_64": + target_opts = ["-target", "x86_64-none-linux-android"] elif env["android_arch"] == "armv7": - target_opts = ['-target', 'armv7-none-linux-androideabi'] - env.Append(CCFLAGS='-march=armv7-a -mfloat-abi=softfp'.split()) - env.Append(CPPDEFINES=['__ARM_ARCH_7__', '__ARM_ARCH_7A__']) - if env['android_neon']: - env['neon_enabled'] = True - env.Append(CCFLAGS=['-mfpu=neon']) - env.Append(CPPDEFINES=['__ARM_NEON__']) + target_opts = ["-target", "armv7-none-linux-androideabi"] + env.Append(CCFLAGS="-march=armv7-a -mfloat-abi=softfp".split()) + env.Append(CPPDEFINES=["__ARM_ARCH_7__", "__ARM_ARCH_7A__"]) + if env["android_neon"]: + env["neon_enabled"] = True + env.Append(CCFLAGS=["-mfpu=neon"]) + env.Append(CPPDEFINES=["__ARM_NEON__"]) else: - env.Append(CCFLAGS=['-mfpu=vfpv3-d16']) + env.Append(CCFLAGS=["-mfpu=vfpv3-d16"]) elif env["android_arch"] == "arm64v8": - target_opts = ['-target', 'aarch64-none-linux-android'] - env.Append(CCFLAGS=['-mfix-cortex-a53-835769']) - env.Append(CPPDEFINES=['__ARM_ARCH_8A__']) + target_opts = ["-target", "aarch64-none-linux-android"] + env.Append(CCFLAGS=["-mfix-cortex-a53-835769"]) + env.Append(CPPDEFINES=["__ARM_ARCH_8A__"]) env.Append(CCFLAGS=target_opts) env.Append(CCFLAGS=common_opts) @@ -254,29 +267,55 @@ def configure(env): ndk_version = get_ndk_version(env["ANDROID_NDK_ROOT"]) if ndk_version != None and LooseVersion(ndk_version) >= LooseVersion("17.1.4828580"): - env.Append(LINKFLAGS=['-Wl,--exclude-libs,libgcc.a', '-Wl,--exclude-libs,libatomic.a', '-nostdlib++']) + env.Append(LINKFLAGS=["-Wl,--exclude-libs,libgcc.a", "-Wl,--exclude-libs,libatomic.a", "-nostdlib++"]) else: - env.Append(LINKFLAGS=[env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/libs/" + arch_subpath + "/libandroid_support.a"]) - env.Append(LINKFLAGS=['-shared', '--sysroot=' + lib_sysroot, '-Wl,--warn-shared-textrel']) + env.Append( + LINKFLAGS=[ + env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/libs/" + arch_subpath + "/libandroid_support.a" + ] + ) + env.Append(LINKFLAGS=["-shared", "--sysroot=" + lib_sysroot, "-Wl,--warn-shared-textrel"]) env.Append(LIBPATH=[env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/libs/" + arch_subpath + "/"]) - env.Append(LINKFLAGS=[env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/libs/" + arch_subpath + "/libc++_shared.so"]) + env.Append( + LINKFLAGS=[env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/libs/" + arch_subpath + "/libc++_shared.so"] + ) if env["android_arch"] == "armv7": - env.Append(LINKFLAGS='-Wl,--fix-cortex-a8'.split()) - env.Append(LINKFLAGS='-Wl,--no-undefined -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now'.split()) - env.Append(LINKFLAGS='-Wl,-soname,libgodot_android.so -Wl,--gc-sections'.split()) + env.Append(LINKFLAGS="-Wl,--fix-cortex-a8".split()) + env.Append(LINKFLAGS="-Wl,--no-undefined -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now".split()) + env.Append(LINKFLAGS="-Wl,-soname,libgodot_android.so -Wl,--gc-sections".split()) env.Append(LINKFLAGS=target_opts) env.Append(LINKFLAGS=common_opts) - env.Append(LIBPATH=[env["ANDROID_NDK_ROOT"] + '/toolchains/' + target_subpath + '/prebuilt/' + - host_subpath + '/lib/gcc/' + abi_subpath + '/4.9.x']) - env.Append(LIBPATH=[env["ANDROID_NDK_ROOT"] + - '/toolchains/' + target_subpath + '/prebuilt/' + host_subpath + '/' + abi_subpath + '/lib']) - - env.Prepend(CPPPATH=['#platform/android']) - env.Append(CPPDEFINES=['ANDROID_ENABLED', 'UNIX_ENABLED', 'NO_FCNTL']) - env.Append(LIBS=['OpenSLES', 'EGL', 'GLESv3', 'GLESv2', 'android', 'log', 'z', 'dl']) + env.Append( + LIBPATH=[ + env["ANDROID_NDK_ROOT"] + + "/toolchains/" + + target_subpath + + "/prebuilt/" + + host_subpath + + "/lib/gcc/" + + abi_subpath + + "/4.9.x" + ] + ) + env.Append( + LIBPATH=[ + env["ANDROID_NDK_ROOT"] + + "/toolchains/" + + target_subpath + + "/prebuilt/" + + host_subpath + + "/" + + abi_subpath + + "/lib" + ] + ) + + env.Prepend(CPPPATH=["#platform/android"]) + env.Append(CPPDEFINES=["ANDROID_ENABLED", "UNIX_ENABLED", "VULKAN_ENABLED", "NO_FCNTL"]) + env.Append(LIBS=["OpenSLES", "EGL", "GLESv2", "vulkan", "android", "log", "z", "dl"]) # Return NDK version string in source.properties (adapted from the Chromium project). diff --git a/platform/android/dir_access_jandroid.cpp b/platform/android/dir_access_jandroid.cpp index ebcac884db..f8571e6277 100644 --- a/platform/android/dir_access_jandroid.cpp +++ b/platform/android/dir_access_jandroid.cpp @@ -34,12 +34,12 @@ #include "string_android.h" #include "thread_jandroid.h" -jobject DirAccessJAndroid::io = NULL; -jclass DirAccessJAndroid::cls = NULL; -jmethodID DirAccessJAndroid::_dir_open = NULL; -jmethodID DirAccessJAndroid::_dir_next = NULL; -jmethodID DirAccessJAndroid::_dir_close = NULL; -jmethodID DirAccessJAndroid::_dir_is_dir = NULL; +jobject DirAccessJAndroid::io = nullptr; +jclass DirAccessJAndroid::cls = nullptr; +jmethodID DirAccessJAndroid::_dir_open = nullptr; +jmethodID DirAccessJAndroid::_dir_next = nullptr; +jmethodID DirAccessJAndroid::_dir_close = nullptr; +jmethodID DirAccessJAndroid::_dir_is_dir = nullptr; DirAccess *DirAccessJAndroid::create_fs() { diff --git a/platform/android/display_server_android.cpp b/platform/android/display_server_android.cpp new file mode 100644 index 0000000000..9534387d35 --- /dev/null +++ b/platform/android/display_server_android.cpp @@ -0,0 +1,655 @@ +/*************************************************************************/ +/* display_server_android.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "display_server_android.h" + +#include "android_keys_utils.h" +#include "core/project_settings.h" +#include "java_godot_io_wrapper.h" +#include "java_godot_wrapper.h" +#include "os_android.h" + +#if defined(OPENGL_ENABLED) +#include "drivers/gles2/rasterizer_gles2.h" +#endif +#if defined(VULKAN_ENABLED) +#include "drivers/vulkan/rendering_device_vulkan.h" +#include "platform/android/vulkan/vulkan_context_android.h" +#include "servers/rendering/rasterizer_rd/rasterizer_rd.h" +#endif + +DisplayServerAndroid *DisplayServerAndroid::get_singleton() { + return (DisplayServerAndroid *)DisplayServer::get_singleton(); +} + +bool DisplayServerAndroid::has_feature(Feature p_feature) const { + switch (p_feature) { + //case FEATURE_CONSOLE_WINDOW: + //case FEATURE_CURSOR_SHAPE: + //case FEATURE_CUSTOM_CURSOR_SHAPE: + //case FEATURE_GLOBAL_MENU: + //case FEATURE_HIDPI: + //case FEATURE_ICON: + //case FEATURE_IME: + //case FEATURE_MOUSE: + //case FEATURE_MOUSE_WARP: + //case FEATURE_NATIVE_DIALOG: + //case FEATURE_NATIVE_ICON: + //case FEATURE_NATIVE_VIDEO: + //case FEATURE_WINDOW_TRANSPARENCY: + case FEATURE_CLIPBOARD: + case FEATURE_KEEP_SCREEN_ON: + case FEATURE_ORIENTATION: + case FEATURE_TOUCHSCREEN: + case FEATURE_VIRTUAL_KEYBOARD: + return true; + default: + return false; + } +} + +String DisplayServerAndroid::get_name() const { + return "Android"; +} + +void DisplayServerAndroid::clipboard_set(const String &p_text) { + GodotJavaWrapper *godot_java = OS_Android::get_singleton()->get_godot_java(); + ERR_FAIL_COND(!godot_java); + + if (godot_java->has_set_clipboard()) { + godot_java->set_clipboard(p_text); + } else { + DisplayServer::clipboard_set(p_text); + } +} + +String DisplayServerAndroid::clipboard_get() const { + GodotJavaWrapper *godot_java = OS_Android::get_singleton()->get_godot_java(); + ERR_FAIL_COND_V(!godot_java, String()); + + if (godot_java->has_get_clipboard()) { + return godot_java->get_clipboard(); + } else { + return DisplayServer::clipboard_get(); + } +} + +void DisplayServerAndroid::screen_set_keep_on(bool p_enable) { + GodotJavaWrapper *godot_java = OS_Android::get_singleton()->get_godot_java(); + ERR_FAIL_COND(!godot_java); + + godot_java->set_keep_screen_on(p_enable); + keep_screen_on = p_enable; +} + +bool DisplayServerAndroid::screen_is_kept_on() const { + return keep_screen_on; +} + +void DisplayServerAndroid::screen_set_orientation(DisplayServer::ScreenOrientation p_orientation, int p_screen) { + GodotIOJavaWrapper *godot_io_java = OS_Android::get_singleton()->get_godot_io_java(); + ERR_FAIL_COND(!godot_io_java); + + godot_io_java->set_screen_orientation(p_orientation); +} + +DisplayServer::ScreenOrientation DisplayServerAndroid::screen_get_orientation(int p_screen) const { + GodotIOJavaWrapper *godot_io_java = OS_Android::get_singleton()->get_godot_io_java(); + ERR_FAIL_COND_V(!godot_io_java, SCREEN_LANDSCAPE); + + return (ScreenOrientation)godot_io_java->get_screen_orientation(); +} + +int DisplayServerAndroid::get_screen_count() const { + return 1; +} + +Point2i DisplayServerAndroid::screen_get_position(int p_screen) const { + return Point2i(0, 0); +} + +Size2i DisplayServerAndroid::screen_get_size(int p_screen) const { + return OS_Android::get_singleton()->get_display_size(); +} + +Rect2i DisplayServerAndroid::screen_get_usable_rect(int p_screen) const { + Size2i display_size = OS_Android::get_singleton()->get_display_size(); + return Rect2i(0, 0, display_size.width, display_size.height); +} + +int DisplayServerAndroid::screen_get_dpi(int p_screen) const { + GodotIOJavaWrapper *godot_io_java = OS_Android::get_singleton()->get_godot_io_java(); + ERR_FAIL_COND_V(!godot_io_java, 0); + + return godot_io_java->get_screen_dpi(); +} + +bool DisplayServerAndroid::screen_is_touchscreen(int p_screen) const { + return true; +} + +void DisplayServerAndroid::virtual_keyboard_show(const String &p_existing_text, const Rect2 &p_screen_rect, int p_max_length) { + GodotIOJavaWrapper *godot_io_java = OS_Android::get_singleton()->get_godot_io_java(); + ERR_FAIL_COND(!godot_io_java); + + if (godot_io_java->has_vk()) { + godot_io_java->show_vk(p_existing_text, p_max_length); + } else { + ERR_PRINT("Virtual keyboard not available"); + } +} + +void DisplayServerAndroid::virtual_keyboard_hide() { + GodotIOJavaWrapper *godot_io_java = OS_Android::get_singleton()->get_godot_io_java(); + ERR_FAIL_COND(!godot_io_java); + + if (godot_io_java->has_vk()) { + godot_io_java->hide_vk(); + } else { + ERR_PRINT("Virtual keyboard not available"); + } +} + +int DisplayServerAndroid::virtual_keyboard_get_height() const { + GodotIOJavaWrapper *godot_io_java = OS_Android::get_singleton()->get_godot_io_java(); + ERR_FAIL_COND_V(!godot_io_java, 0); + + return godot_io_java->get_vk_height(); +} + +void DisplayServerAndroid::window_set_window_event_callback(const Callable &p_callable, DisplayServer::WindowID p_window) { + window_event_callback = p_callable; +} + +void DisplayServerAndroid::window_set_input_event_callback(const Callable &p_callable, DisplayServer::WindowID p_window) { + input_event_callback = p_callable; +} + +void DisplayServerAndroid::window_set_input_text_callback(const Callable &p_callable, DisplayServer::WindowID p_window) { + input_text_callback = p_callable; +} + +void DisplayServerAndroid::window_set_rect_changed_callback(const Callable &p_callable, DisplayServer::WindowID p_window) { + // Not supported on Android. +} + +void DisplayServerAndroid::window_set_drop_files_callback(const Callable &p_callable, DisplayServer::WindowID p_window) { + // Not supported on Android. +} + +void DisplayServerAndroid::_window_callback(const Callable &p_callable, const Variant &p_arg) const { + if (!p_callable.is_null()) { + const Variant *argp = &p_arg; + Variant ret; + Callable::CallError ce; + p_callable.call((const Variant **)&argp, 1, ret, ce); + } +} + +void DisplayServerAndroid::send_window_event(DisplayServer::WindowEvent p_event) const { + _window_callback(window_event_callback, int(p_event)); +} + +void DisplayServerAndroid::send_input_event(const Ref<InputEvent> &p_event) const { + _window_callback(input_event_callback, p_event); +} + +void DisplayServerAndroid::send_input_text(const String &p_text) const { + _window_callback(input_text_callback, p_text); +} + +void DisplayServerAndroid::_dispatch_input_events(const Ref<InputEvent> &p_event) { + DisplayServerAndroid::get_singleton()->send_input_event(p_event); +} + +Vector<DisplayServer::WindowID> DisplayServerAndroid::get_window_list() const { + Vector<WindowID> ret; + ret.push_back(MAIN_WINDOW_ID); + return ret; +} + +DisplayServer::WindowID DisplayServerAndroid::get_window_at_screen_position(const Point2i &p_position) const { + return MAIN_WINDOW_ID; +} + +void DisplayServerAndroid::window_attach_instance_id(ObjectID p_instance, DisplayServer::WindowID p_window) { + window_attached_instance_id = p_instance; +} + +ObjectID DisplayServerAndroid::window_get_attached_instance_id(DisplayServer::WindowID p_window) const { + return window_attached_instance_id; +} + +void DisplayServerAndroid::window_set_title(const String &p_title, DisplayServer::WindowID p_window) { + // Not supported on Android. +} + +int DisplayServerAndroid::window_get_current_screen(DisplayServer::WindowID p_window) const { + return SCREEN_OF_MAIN_WINDOW; +} + +void DisplayServerAndroid::window_set_current_screen(int p_screen, DisplayServer::WindowID p_window) { + // Not supported on Android. +} + +Point2i DisplayServerAndroid::window_get_position(DisplayServer::WindowID p_window) const { + return Point2i(); +} + +void DisplayServerAndroid::window_set_position(const Point2i &p_position, DisplayServer::WindowID p_window) { + // Not supported on Android. +} + +void DisplayServerAndroid::window_set_transient(DisplayServer::WindowID p_window, DisplayServer::WindowID p_parent) { + // Not supported on Android. +} + +void DisplayServerAndroid::window_set_max_size(const Size2i p_size, DisplayServer::WindowID p_window) { + // Not supported on Android. +} + +Size2i DisplayServerAndroid::window_get_max_size(DisplayServer::WindowID p_window) const { + return Size2i(); +} + +void DisplayServerAndroid::window_set_min_size(const Size2i p_size, DisplayServer::WindowID p_window) { + // Not supported on Android. +} + +Size2i DisplayServerAndroid::window_get_min_size(DisplayServer::WindowID p_window) const { + return Size2i(); +} + +void DisplayServerAndroid::window_set_size(const Size2i p_size, DisplayServer::WindowID p_window) { + // Not supported on Android. +} + +Size2i DisplayServerAndroid::window_get_size(DisplayServer::WindowID p_window) const { + return OS_Android::get_singleton()->get_display_size(); +} + +Size2i DisplayServerAndroid::window_get_real_size(DisplayServer::WindowID p_window) const { + return OS_Android::get_singleton()->get_display_size(); +} + +void DisplayServerAndroid::window_set_mode(DisplayServer::WindowMode p_mode, DisplayServer::WindowID p_window) { + // Not supported on Android. +} + +DisplayServer::WindowMode DisplayServerAndroid::window_get_mode(DisplayServer::WindowID p_window) const { + return WINDOW_MODE_FULLSCREEN; +} + +bool DisplayServerAndroid::window_is_maximize_allowed(DisplayServer::WindowID p_window) const { + return false; +} + +void DisplayServerAndroid::window_set_flag(DisplayServer::WindowFlags p_flag, bool p_enabled, DisplayServer::WindowID p_window) { + // Not supported on Android. +} + +bool DisplayServerAndroid::window_get_flag(DisplayServer::WindowFlags p_flag, DisplayServer::WindowID p_window) const { + return false; +} + +void DisplayServerAndroid::window_request_attention(DisplayServer::WindowID p_window) { + // Not supported on Android. +} + +void DisplayServerAndroid::window_move_to_foreground(DisplayServer::WindowID p_window) { + // Not supported on Android. +} + +bool DisplayServerAndroid::window_can_draw(DisplayServer::WindowID p_window) const { + return true; +} + +bool DisplayServerAndroid::can_any_window_draw() const { + return true; +} + +void DisplayServerAndroid::alert(const String &p_alert, const String &p_title) { + GodotJavaWrapper *godot_java = OS_Android::get_singleton()->get_godot_java(); + ERR_FAIL_COND(!godot_java); + + godot_java->alert(p_alert, p_title); +} + +void DisplayServerAndroid::process_events() { + // Nothing to do +} + +Vector<String> DisplayServerAndroid::get_rendering_drivers_func() { + Vector<String> drivers; + +#ifdef OPENGL_ENABLED + drivers.push_back("opengl"); +#endif +#ifdef VULKAN_ENABLED + drivers.push_back("vulkan"); +#endif + + return drivers; +} + +DisplayServer *DisplayServerAndroid::create_func(const String &p_rendering_driver, DisplayServer::WindowMode p_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) { + return memnew(DisplayServerAndroid(p_rendering_driver, p_mode, p_flags, p_resolution, r_error)); +} + +void DisplayServerAndroid::register_android_driver() { + register_create_function("android", create_func, get_rendering_drivers_func); +} + +DisplayServerAndroid::DisplayServerAndroid(const String &p_rendering_driver, DisplayServer::WindowMode p_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) { + rendering_driver = p_rendering_driver; + + // TODO: rendering_driver is broken, change when different drivers are supported again + rendering_driver = "vulkan"; + + keep_screen_on = GLOBAL_GET("display/window/energy_saving/keep_screen_on"); + +#if defined(OPENGL_ENABLED) + if (rendering_driver == "opengl") { + bool gl_initialization_error = false; + + if (RasterizerGLES2::is_viable() == OK) { + RasterizerGLES2::register_config(); + RasterizerGLES2::make_current(); + } else { + gl_initialization_error = true; + } + + if (gl_initialization_error) { + OS::get_singleton()->alert("Your device does not support any of the supported OpenGL versions.\n" + "Please try updating your Android version.", + "Unable to initialize video driver"); + return; + } + } +#endif + +#if defined(VULKAN_ENABLED) + context_vulkan = nullptr; + rendering_device_vulkan = nullptr; + + if (rendering_driver == "vulkan") { + ANativeWindow *native_window = OS_Android::get_singleton()->get_native_window(); + ERR_FAIL_COND(!native_window); + + context_vulkan = memnew(VulkanContextAndroid); + if (context_vulkan->initialize() != OK) { + memdelete(context_vulkan); + context_vulkan = nullptr; + ERR_FAIL_MSG("Failed to initialize Vulkan context"); + } + + Size2i display_size = OS_Android::get_singleton()->get_display_size(); + if (context_vulkan->window_create(native_window, display_size.width, display_size.height) == -1) { + memdelete(context_vulkan); + context_vulkan = nullptr; + ERR_FAIL_MSG("Failed to create Vulkan window."); + } + + rendering_device_vulkan = memnew(RenderingDeviceVulkan); + rendering_device_vulkan->initialize(context_vulkan); + + RasterizerRD::make_current(); + } +#endif + + InputFilter::get_singleton()->set_event_dispatch_function(_dispatch_input_events); +} + +DisplayServerAndroid::~DisplayServerAndroid() { +#if defined(VULKAN_ENABLED) + if (rendering_driver == "vulkan") { + if (rendering_device_vulkan) { + rendering_device_vulkan->finalize(); + memdelete(rendering_device_vulkan); + } + + if (context_vulkan) { + memdelete(context_vulkan); + } + } +#endif +} + +void DisplayServerAndroid::process_joy_event(DisplayServerAndroid::JoypadEvent p_event) { + switch (p_event.type) { + case JOY_EVENT_BUTTON: + InputFilter::get_singleton()->joy_button(p_event.device, p_event.index, p_event.pressed); + break; + case JOY_EVENT_AXIS: + InputFilter::JoyAxis value; + value.min = -1; + value.value = p_event.value; + InputFilter::get_singleton()->joy_axis(p_event.device, p_event.index, value); + break; + case JOY_EVENT_HAT: + InputFilter::get_singleton()->joy_hat(p_event.device, p_event.hat); + break; + default: + return; + } +} + +void DisplayServerAndroid::process_key_event(int p_keycode, int p_scancode, int p_unicode_char, bool p_pressed) { + Ref<InputEventKey> ev; + ev.instance(); + int val = p_unicode_char; + int keycode = android_get_keysym(p_keycode); + int phy_keycode = android_get_keysym(p_scancode); + ev->set_keycode(keycode); + ev->set_physical_keycode(phy_keycode); + ev->set_unicode(val); + ev->set_pressed(p_pressed); + + if (val == '\n') { + ev->set_keycode(KEY_ENTER); + } else if (val == 61448) { + ev->set_keycode(KEY_BACKSPACE); + ev->set_unicode(KEY_BACKSPACE); + } else if (val == 61453) { + ev->set_keycode(KEY_ENTER); + ev->set_unicode(KEY_ENTER); + } else if (p_keycode == 4) { + OS_Android::get_singleton()->main_loop_request_go_back(); + } + + InputFilter::get_singleton()->parse_input_event(ev); +} + +void DisplayServerAndroid::process_touch(int p_what, int p_pointer, const Vector<DisplayServerAndroid::TouchPos> &p_points) { + switch (p_what) { + case 0: { //gesture begin + if (touch.size()) { + //end all if exist + for (int i = 0; i < touch.size(); i++) { + + Ref<InputEventScreenTouch> ev; + ev.instance(); + ev->set_index(touch[i].id); + ev->set_pressed(false); + ev->set_position(touch[i].pos); + InputFilter::get_singleton()->parse_input_event(ev); + } + } + + touch.resize(p_points.size()); + for (int i = 0; i < p_points.size(); i++) { + touch.write[i].id = p_points[i].id; + touch.write[i].pos = p_points[i].pos; + } + + //send touch + for (int i = 0; i < touch.size(); i++) { + + Ref<InputEventScreenTouch> ev; + ev.instance(); + ev->set_index(touch[i].id); + ev->set_pressed(true); + ev->set_position(touch[i].pos); + InputFilter::get_singleton()->parse_input_event(ev); + } + + } break; + case 1: { //motion + ERR_FAIL_COND(touch.size() != p_points.size()); + + for (int i = 0; i < touch.size(); i++) { + + int idx = -1; + for (int j = 0; j < p_points.size(); j++) { + + if (touch[i].id == p_points[j].id) { + idx = j; + break; + } + } + + ERR_CONTINUE(idx == -1); + + if (touch[i].pos == p_points[idx].pos) + continue; //no move unncesearily + + Ref<InputEventScreenDrag> ev; + ev.instance(); + ev->set_index(touch[i].id); + ev->set_position(p_points[idx].pos); + ev->set_relative(p_points[idx].pos - touch[i].pos); + InputFilter::get_singleton()->parse_input_event(ev); + touch.write[i].pos = p_points[idx].pos; + } + + } break; + case 2: { //release + if (touch.size()) { + //end all if exist + for (int i = 0; i < touch.size(); i++) { + + Ref<InputEventScreenTouch> ev; + ev.instance(); + ev->set_index(touch[i].id); + ev->set_pressed(false); + ev->set_position(touch[i].pos); + InputFilter::get_singleton()->parse_input_event(ev); + } + touch.clear(); + } + } break; + case 3: { // add touch + for (int i = 0; i < p_points.size(); i++) { + if (p_points[i].id == p_pointer) { + TouchPos tp = p_points[i]; + touch.push_back(tp); + + Ref<InputEventScreenTouch> ev; + ev.instance(); + + ev->set_index(tp.id); + ev->set_pressed(true); + ev->set_position(tp.pos); + InputFilter::get_singleton()->parse_input_event(ev); + + break; + } + } + } break; + case 4: { // remove touch + for (int i = 0; i < touch.size(); i++) { + if (touch[i].id == p_pointer) { + + Ref<InputEventScreenTouch> ev; + ev.instance(); + ev->set_index(touch[i].id); + ev->set_pressed(false); + ev->set_position(touch[i].pos); + InputFilter::get_singleton()->parse_input_event(ev); + touch.remove(i); + + break; + } + } + } break; + } +} + +void DisplayServerAndroid::process_hover(int p_type, Point2 p_pos) { + // https://developer.android.com/reference/android/view/MotionEvent.html#ACTION_HOVER_ENTER + switch (p_type) { + case 7: // hover move + case 9: // hover enter + case 10: { // hover exit + Ref<InputEventMouseMotion> ev; + ev.instance(); + ev->set_position(p_pos); + ev->set_global_position(p_pos); + ev->set_relative(p_pos - hover_prev_pos); + InputFilter::get_singleton()->parse_input_event(ev); + hover_prev_pos = p_pos; + } break; + } +} + +void DisplayServerAndroid::process_double_tap(Point2 p_pos) { + Ref<InputEventMouseButton> ev; + ev.instance(); + ev->set_position(p_pos); + ev->set_global_position(p_pos); + ev->set_pressed(false); + ev->set_doubleclick(true); + InputFilter::get_singleton()->parse_input_event(ev); +} + +void DisplayServerAndroid::process_scroll(Point2 p_pos) { + Ref<InputEventPanGesture> ev; + ev.instance(); + ev->set_position(p_pos); + ev->set_delta(p_pos - scroll_prev_pos); + InputFilter::get_singleton()->parse_input_event(ev); + scroll_prev_pos = p_pos; +} + +void DisplayServerAndroid::process_accelerometer(const Vector3 &p_accelerometer) { + InputFilter::get_singleton()->set_accelerometer(p_accelerometer); +} + +void DisplayServerAndroid::process_gravity(const Vector3 &p_gravity) { + InputFilter::get_singleton()->set_gravity(p_gravity); +} + +void DisplayServerAndroid::process_magnetometer(const Vector3 &p_magnetometer) { + InputFilter::get_singleton()->set_magnetometer(p_magnetometer); +} + +void DisplayServerAndroid::process_gyroscope(const Vector3 &p_gyroscope) { + InputFilter::get_singleton()->set_gyroscope(p_gyroscope); +} diff --git a/platform/android/display_server_android.h b/platform/android/display_server_android.h new file mode 100644 index 0000000000..2096ba68f1 --- /dev/null +++ b/platform/android/display_server_android.h @@ -0,0 +1,174 @@ +/*************************************************************************/ +/* display_server_android.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef DISPLAY_SERVER_ANDROID_H +#define DISPLAY_SERVER_ANDROID_H + +#include "servers/display_server.h" + +#if defined(VULKAN_ENABLED) +class VulkanContextAndroid; +class RenderingDeviceVulkan; +#endif + +class DisplayServerAndroid : public DisplayServer { +public: + struct TouchPos { + int id; + Point2 pos; + }; + + enum { + JOY_EVENT_BUTTON = 0, + JOY_EVENT_AXIS = 1, + JOY_EVENT_HAT = 2 + }; + + struct JoypadEvent { + + int device; + int type; + int index; + bool pressed; + float value; + int hat; + }; + +private: + String rendering_driver; + + bool keep_screen_on; + + Vector<TouchPos> touch; + Point2 hover_prev_pos; // needed to calculate the relative position on hover events + Point2 scroll_prev_pos; // needed to calculate the relative position on scroll events + +#if defined(VULKAN_ENABLED) + VulkanContextAndroid *context_vulkan; + RenderingDeviceVulkan *rendering_device_vulkan; +#endif + + ObjectID window_attached_instance_id; + + Callable window_event_callback; + Callable input_event_callback; + Callable input_text_callback; + + void _window_callback(const Callable &p_callable, const Variant &p_arg) const; + + static void _dispatch_input_events(const Ref<InputEvent> &p_event); + +public: + static DisplayServerAndroid *get_singleton(); + + virtual bool has_feature(Feature p_feature) const; + virtual String get_name() const; + + virtual void clipboard_set(const String &p_text); + virtual String clipboard_get() const; + + virtual void screen_set_keep_on(bool p_enable); + virtual bool screen_is_kept_on() const; + + virtual void screen_set_orientation(ScreenOrientation p_orientation, int p_screen = SCREEN_OF_MAIN_WINDOW); + virtual ScreenOrientation screen_get_orientation(int p_screen = SCREEN_OF_MAIN_WINDOW) const; + + virtual int get_screen_count() const; + virtual Point2i screen_get_position(int p_screen = SCREEN_OF_MAIN_WINDOW) const; + virtual Size2i screen_get_size(int p_screen = SCREEN_OF_MAIN_WINDOW) const; + virtual Rect2i screen_get_usable_rect(int p_screen = SCREEN_OF_MAIN_WINDOW) const; + virtual int screen_get_dpi(int p_screen = SCREEN_OF_MAIN_WINDOW) const; + virtual bool screen_is_touchscreen(int p_screen = SCREEN_OF_MAIN_WINDOW) const; + + virtual void virtual_keyboard_show(const String &p_existing_text, const Rect2 &p_screen_rect = Rect2(), int p_max_length = -1); + virtual void virtual_keyboard_hide(); + virtual int virtual_keyboard_get_height() const; + + virtual void window_set_window_event_callback(const Callable &p_callable, WindowID p_window = MAIN_WINDOW_ID); + virtual void window_set_input_event_callback(const Callable &p_callable, WindowID p_window = MAIN_WINDOW_ID); + virtual void window_set_input_text_callback(const Callable &p_callable, WindowID p_window = MAIN_WINDOW_ID); + virtual void window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window = MAIN_WINDOW_ID); + virtual void window_set_drop_files_callback(const Callable &p_callable, WindowID p_window = MAIN_WINDOW_ID); + + void send_window_event(WindowEvent p_event) const; + void send_input_event(const Ref<InputEvent> &p_event) const; + void send_input_text(const String &p_text) const; + + virtual Vector<WindowID> get_window_list() const; + virtual WindowID get_window_at_screen_position(const Point2i &p_position) const; + virtual void window_attach_instance_id(ObjectID p_instance, WindowID p_window = MAIN_WINDOW_ID); + virtual ObjectID window_get_attached_instance_id(WindowID p_window = MAIN_WINDOW_ID) const; + virtual void window_set_title(const String &p_title, WindowID p_window = MAIN_WINDOW_ID); + virtual int window_get_current_screen(WindowID p_window = MAIN_WINDOW_ID) const; + virtual void window_set_current_screen(int p_screen, WindowID p_window = MAIN_WINDOW_ID); + virtual Point2i window_get_position(WindowID p_window = MAIN_WINDOW_ID) const; + virtual void window_set_position(const Point2i &p_position, WindowID p_window = MAIN_WINDOW_ID); + virtual void window_set_transient(WindowID p_window, WindowID p_parent); + virtual void window_set_max_size(const Size2i p_size, WindowID p_window = MAIN_WINDOW_ID); + virtual Size2i window_get_max_size(WindowID p_window = MAIN_WINDOW_ID) const; + virtual void window_set_min_size(const Size2i p_size, WindowID p_window = MAIN_WINDOW_ID); + virtual Size2i window_get_min_size(WindowID p_window = MAIN_WINDOW_ID) const; + virtual void window_set_size(const Size2i p_size, WindowID p_window = MAIN_WINDOW_ID); + virtual Size2i window_get_size(WindowID p_window = MAIN_WINDOW_ID) const; + virtual Size2i window_get_real_size(WindowID p_window = MAIN_WINDOW_ID) const; + virtual void window_set_mode(WindowMode p_mode, WindowID p_window = MAIN_WINDOW_ID); + virtual WindowMode window_get_mode(WindowID p_window = MAIN_WINDOW_ID) const; + virtual bool window_is_maximize_allowed(WindowID p_window = MAIN_WINDOW_ID) const; + virtual void window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window = MAIN_WINDOW_ID); + virtual bool window_get_flag(WindowFlags p_flag, WindowID p_window = MAIN_WINDOW_ID) const; + virtual void window_request_attention(WindowID p_window = MAIN_WINDOW_ID); + virtual void window_move_to_foreground(WindowID p_window = MAIN_WINDOW_ID); + virtual bool window_can_draw(WindowID p_window = MAIN_WINDOW_ID) const; + virtual bool can_any_window_draw() const; + + virtual void alert(const String &p_alert, const String &p_title); + + virtual void process_events(); + + void process_accelerometer(const Vector3 &p_accelerometer); + void process_gravity(const Vector3 &p_gravity); + void process_magnetometer(const Vector3 &p_magnetometer); + void process_gyroscope(const Vector3 &p_gyroscope); + void process_touch(int p_what, int p_pointer, const Vector<TouchPos> &p_points); + void process_hover(int p_type, Point2 p_pos); + void process_double_tap(Point2 p_pos); + void process_scroll(Point2 p_pos); + void process_joy_event(JoypadEvent p_event); + void process_key_event(int p_keycode, int p_scancode, int p_unicode_char, bool p_pressed); + + static DisplayServer *create_func(const String &p_rendering_driver, WindowMode p_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error); + static Vector<String> get_rendering_drivers_func(); + static void register_android_driver(); + + DisplayServerAndroid(const String &p_rendering_driver, WindowMode p_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error); + ~DisplayServerAndroid(); +}; + +#endif // DISPLAY_SERVER_ANDROID_H diff --git a/platform/android/export/export.cpp b/platform/android/export/export.cpp index e7d4bc6c51..b6c30d120c 100644 --- a/platform/android/export/export.cpp +++ b/platform/android/export/export.cpp @@ -194,7 +194,7 @@ static const char *android_perms[] = { "WRITE_SOCIAL_STREAM", "WRITE_SYNC_SETTINGS", "WRITE_USER_DICTIONARY", - NULL + nullptr }; struct LauncherIcon { @@ -274,7 +274,7 @@ class EditorExportPlatformAndroid : public EditorExportPlatform { List<String> args; args.push_back("devices"); int ec; - OS::get_singleton()->execute(adb, args, true, NULL, &devices, &ec); + OS::get_singleton()->execute(adb, args, true, nullptr, &devices, &ec); Vector<String> ds = devices.split("\n"); Vector<String> ldevices; @@ -332,7 +332,7 @@ class EditorExportPlatformAndroid : public EditorExportPlatform { int ec2; String dp; - OS::get_singleton()->execute(adb, args, true, NULL, &dp, &ec2); + OS::get_singleton()->execute(adb, args, true, nullptr, &dp, &ec2); Vector<String> props = dp.split("\n"); String vendor; @@ -447,7 +447,7 @@ class EditorExportPlatformAndroid : public EditorExportPlatform { return pname; } - bool is_package_name_valid(const String &p_package, String *r_error = NULL) const { + bool is_package_name_valid(const String &p_package, String *r_error = nullptr) const { String pname = p_package; @@ -537,7 +537,7 @@ class EditorExportPlatformAndroid : public EditorExportPlatform { ".scn", // Binary scenes are usually already compressed ".stex", // Streamable textures are usually already compressed // Trailer for easier processing - NULL + nullptr }; for (const char **ext = unconditional_compress_ext; *ext; ++ext) { @@ -591,11 +591,11 @@ class EditorExportPlatformAndroid : public EditorExportPlatform { zipOpenNewFileInZip(ed->apk, p_path.utf8().get_data(), &zipfi, - NULL, + nullptr, 0, - NULL, + nullptr, 0, - NULL, + nullptr, compression_method, Z_DEFAULT_COMPRESSION); @@ -1530,7 +1530,7 @@ public: args.push_back("uninstall"); args.push_back(get_package_name(package_name)); - err = OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv); + err = OS::get_singleton()->execute(adb, args, true, nullptr, nullptr, &rv); } print_line("Installing to device (please wait...): " + devices[p_device].name); @@ -1545,7 +1545,7 @@ public: args.push_back("-r"); args.push_back(tmp_export_path); - err = OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv); + err = OS::get_singleton()->execute(adb, args, true, nullptr, nullptr, &rv); if (err || rv != 0) { EditorNode::add_io_error("Could not install to device."); CLEANUP_AND_RETURN(ERR_CANT_CREATE); @@ -1563,7 +1563,7 @@ public: args.push_back(devices[p_device].id); args.push_back("reverse"); args.push_back("--remove-all"); - OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv); + OS::get_singleton()->execute(adb, args, true, nullptr, nullptr, &rv); if (p_debug_flags & DEBUG_FLAG_REMOTE_DEBUG) { @@ -1575,7 +1575,7 @@ public: args.push_back("tcp:" + itos(dbg_port)); args.push_back("tcp:" + itos(dbg_port)); - OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv); + OS::get_singleton()->execute(adb, args, true, nullptr, nullptr, &rv); print_line("Reverse result: " + itos(rv)); } @@ -1590,7 +1590,7 @@ public: args.push_back("tcp:" + itos(fs_port)); args.push_back("tcp:" + itos(fs_port)); - err = OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv); + err = OS::get_singleton()->execute(adb, args, true, nullptr, nullptr, &rv); print_line("Reverse result2: " + itos(rv)); } } else { @@ -1619,7 +1619,7 @@ public: args.push_back("-n"); args.push_back(get_package_name(package_name) + "/com.godot.game.GodotApp"); - err = OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv); + err = OS::get_singleton()->execute(adb, args, true, nullptr, nullptr, &rv); if (err || rv != 0) { EditorNode::add_io_error("Could not execute on device."); CLEANUP_AND_RETURN(ERR_CANT_CREATE); @@ -1806,7 +1806,7 @@ public: /*{ used for debug int ec; String pipe; - OS::get_singleton()->execute(build_command, cmdline, true, NULL, NULL, &ec); + OS::get_singleton()->execute(build_command, cmdline, true, nullptr, nullptr, &ec); print_line("exit code: " + itos(ec)); } */ @@ -1851,7 +1851,7 @@ public: return ERR_FILE_BAD_PATH; } - FileAccess *src_f = NULL; + FileAccess *src_f = nullptr; zlib_filefunc_def io = zipio_create_io_from_file(&src_f); if (ep.step("Creating APK...", 0)) { @@ -1868,7 +1868,7 @@ public: int ret = unzGoToFirstFile(pkg); zlib_filefunc_def io2 = io; - FileAccess *dst_f = NULL; + FileAccess *dst_f = nullptr; io2.opaque = &dst_f; String tmp_unaligned_path = EditorSettings::get_singleton()->get_cache_dir().plus_file("tmpexport-unaligned.apk"); @@ -1879,7 +1879,7 @@ public: return m_err; \ } - zipFile unaligned_apk = zipOpen2(tmp_unaligned_path.utf8().get_data(), APPEND_STATUS_CREATE, NULL, &io2); + zipFile unaligned_apk = zipOpen2(tmp_unaligned_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io2); bool use_32_fb = p_preset->get("graphics/32_bits_framebuffer"); bool immersive = p_preset->get("screen/immersive_mode"); @@ -1937,7 +1937,7 @@ public: //get filename unz_file_info info; char fname[16384]; - ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0); + ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0); bool skip = false; @@ -2001,11 +2001,11 @@ public: zipOpenNewFileInZip(unaligned_apk, file.utf8().get_data(), &zipfi, - NULL, + nullptr, 0, - NULL, + nullptr, 0, - NULL, + nullptr, uncompressed ? 0 : Z_DEFLATED, Z_DEFAULT_COMPRESSION); @@ -2108,11 +2108,11 @@ public: zipOpenNewFileInZip(unaligned_apk, "assets/_cl_", &zipfi, - NULL, + nullptr, 0, - NULL, + nullptr, 0, - NULL, + nullptr, 0, // No compress (little size gain and potentially slower startup) Z_DEFAULT_COMPRESSION); @@ -2120,7 +2120,7 @@ public: zipCloseFileInZip(unaligned_apk); } - zipClose(unaligned_apk, NULL); + zipClose(unaligned_apk, nullptr); unzClose(pkg); if (err != OK) { @@ -2188,7 +2188,7 @@ public: args.push_back(tmp_unaligned_path); args.push_back(user); int retval; - OS::get_singleton()->execute(jarsigner, args, true, NULL, NULL, &retval); + OS::get_singleton()->execute(jarsigner, args, true, nullptr, nullptr, &retval); if (retval) { EditorNode::add_io_error("'jarsigner' returned with error #" + itos(retval)); CLEANUP_AND_RETURN(ERR_CANT_CREATE); @@ -2205,7 +2205,7 @@ public: args.push_back(tmp_unaligned_path); args.push_back("-verbose"); - OS::get_singleton()->execute(jarsigner, args, true, NULL, NULL, &retval); + OS::get_singleton()->execute(jarsigner, args, true, nullptr, nullptr, &retval); if (retval) { EditorNode::add_io_error("'jarsigner' verification of APK failed. Make sure to use a jarsigner from OpenJDK 8."); CLEANUP_AND_RETURN(ERR_CANT_CREATE); @@ -2230,9 +2230,9 @@ public: ret = unzGoToFirstFile(tmp_unaligned); io2 = io; - dst_f = NULL; + dst_f = nullptr; io2.opaque = &dst_f; - zipFile final_apk = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, NULL, &io2); + zipFile final_apk = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io2); // Take files from the unaligned APK and write them out to the aligned one // in raw mode, i.e. not uncompressing and recompressing, aligning them as needed, @@ -2245,7 +2245,7 @@ public: char fname[16384]; char extra[16384]; - ret = unzGetCurrentFileInfo(tmp_unaligned, &info, fname, 16384, extra, 16384 - ZIP_ALIGNMENT, NULL, 0); + ret = unzGetCurrentFileInfo(tmp_unaligned, &info, fname, 16384, extra, 16384 - ZIP_ALIGNMENT, nullptr, 0); String file = fname; @@ -2277,9 +2277,9 @@ public: &zipfi, extra, info.size_file_extra + padding, - NULL, + nullptr, 0, - NULL, + nullptr, method, level, 1); // raw write @@ -2291,7 +2291,7 @@ public: ret = unzGoToNextFile(tmp_unaligned); } - zipClose(final_apk, NULL); + zipClose(final_apk, nullptr); unzClose(tmp_unaligned); CLEANUP_AND_RETURN(OK); diff --git a/platform/android/file_access_android.cpp b/platform/android/file_access_android.cpp index 965342b364..fa805ec4f3 100644 --- a/platform/android/file_access_android.cpp +++ b/platform/android/file_access_android.cpp @@ -31,7 +31,7 @@ #include "file_access_android.h" #include "core/print_string.h" -AAssetManager *FileAccessAndroid::asset_manager = NULL; +AAssetManager *FileAccessAndroid::asset_manager = nullptr; /*void FileAccessAndroid::make_default() { @@ -68,12 +68,12 @@ void FileAccessAndroid::close() { if (!a) return; AAsset_close(a); - a = NULL; + a = nullptr; } bool FileAccessAndroid::is_open() const { - return a != NULL; + return a != nullptr; } void FileAccessAndroid::seek(size_t p_position) { @@ -175,7 +175,7 @@ bool FileAccessAndroid::file_exists(const String &p_path) { } FileAccessAndroid::FileAccessAndroid() { - a = NULL; + a = nullptr; eof = false; } diff --git a/platform/android/file_access_jandroid.cpp b/platform/android/file_access_jandroid.cpp index db3aa4255e..e088eca8ef 100644 --- a/platform/android/file_access_jandroid.cpp +++ b/platform/android/file_access_jandroid.cpp @@ -33,7 +33,7 @@ #include "thread_jandroid.h" #include <unistd.h> -jobject FileAccessJAndroid::io = NULL; +jobject FileAccessJAndroid::io = nullptr; jclass FileAccessJAndroid::cls; jmethodID FileAccessJAndroid::_file_open = 0; jmethodID FileAccessJAndroid::_file_get_size = 0; diff --git a/platform/android/java/app/config.gradle b/platform/android/java/app/config.gradle index eaaefcbccb..96cfd272f2 100644 --- a/platform/android/java/app/config.gradle +++ b/platform/android/java/app/config.gradle @@ -1,5 +1,5 @@ ext.versions = [ - androidGradlePlugin: '3.6.0', + androidGradlePlugin: '3.5.3', compileSdk : 29, minSdk : 18, targetSdk : 29, diff --git a/platform/android/java/lib/AndroidManifest.xml b/platform/android/java/lib/AndroidManifest.xml index b133585f99..fa39bc0f1d 100644 --- a/platform/android/java/lib/AndroidManifest.xml +++ b/platform/android/java/lib/AndroidManifest.xml @@ -13,7 +13,7 @@ <instrumentation android:icon="@mipmap/icon" android:label="@string/godot_project_name_string" - android:name=".GodotInstrumentation" + android:name="org.godotengine.godot.GodotInstrumentation" android:targetPackage="org.godotengine.godot" /> </manifest> diff --git a/platform/android/java/lib/build.gradle b/platform/android/java/lib/build.gradle index 062f91e08e..c69e19fbfa 100644 --- a/platform/android/java/lib/build.gradle +++ b/platform/android/java/lib/build.gradle @@ -1,4 +1,5 @@ apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' dependencies { implementation libraries.supportCoreUtils diff --git a/platform/android/java/lib/src/org/godotengine/godot/Godot.java b/platform/android/java/lib/src/org/godotengine/godot/Godot.java index 1798a1df3a..bf0d1c6273 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/Godot.java +++ b/platform/android/java/lib/src/org/godotengine/godot/Godot.java @@ -153,7 +153,7 @@ public abstract class Godot extends FragmentActivity implements SensorEventListe private String[] command_line; private boolean use_apk_expansion; - public GodotView mView; + public GodotRenderView mRenderView; private boolean godot_initialized = false; private SensorManager mSensorManager; @@ -213,34 +213,41 @@ public abstract class Godot extends FragmentActivity implements SensorEventListe setContentView(layout); // GodotEditText layout - GodotEditText edittext = new GodotEditText(this); - edittext.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); + GodotEditText editText = new GodotEditText(this); + editText.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); // ...add to FrameLayout - layout.addView(edittext); + layout.addView(editText); - mView = new GodotView(this, xrMode, use_32_bits, use_debug_opengl); - layout.addView(mView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); - edittext.setView(mView); - io.setEdit(edittext); + GodotLib.setup(command_line); - mView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { + final String videoDriver = GodotLib.getGlobal("rendering/quality/driver/driver_name"); + if (videoDriver.equals("Vulkan")) { + mRenderView = new GodotVulkanRenderView(this); + } else { + mRenderView = new GodotGLRenderView(this, xrMode, use_32_bits, use_debug_opengl); + } + + View view = mRenderView.getView(); + layout.addView(view, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); + editText.setView(mRenderView); + io.setEdit(editText); + + view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Point fullSize = new Point(); getWindowManager().getDefaultDisplay().getSize(fullSize); Rect gameSize = new Rect(); - mView.getWindowVisibleDisplayFrame(gameSize); + mRenderView.getView().getWindowVisibleDisplayFrame(gameSize); final int keyboardHeight = fullSize.y - gameSize.bottom; GodotLib.setVirtualKeyboardHeight(keyboardHeight); } }); - final String[] current_command_line = command_line; - mView.queueEvent(new Runnable() { + mRenderView.queueOnRenderThread(new Runnable() { @Override public void run() { - GodotLib.setup(current_command_line); // Must occur after GodotLib.setup has completed. for (GodotPlugin plugin : pluginRegistry.getAllPlugins()) { @@ -384,7 +391,7 @@ public abstract class Godot extends FragmentActivity implements SensorEventListe */ @Keep private Surface getSurface() { - return mView.getHolder().getSurface(); + return mRenderView.getView().getHolder().getSurface(); } /** @@ -617,7 +624,7 @@ public abstract class Godot extends FragmentActivity implements SensorEventListe } return; } - mView.onPause(); + mRenderView.onActivityPaused(); mSensorManager.unregisterListener(this); @@ -655,7 +662,7 @@ public abstract class Godot extends FragmentActivity implements SensorEventListe return; } - mView.onResume(); + mRenderView.onActivityResumed(); mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_GAME); mSensorManager.registerListener(this, mGravity, SensorManager.SENSOR_DELAY_GAME); @@ -721,8 +728,8 @@ public abstract class Godot extends FragmentActivity implements SensorEventListe final float z = adjustedValues[2]; final int typeOfSensor = event.sensor.getType(); - if (mView != null) { - mView.queueEvent(new Runnable() { + if (mRenderView != null) { + mRenderView.queueOnRenderThread(new Runnable() { @Override public void run() { if (typeOfSensor == Sensor.TYPE_ACCELEROMETER) { @@ -773,8 +780,8 @@ public abstract class Godot extends FragmentActivity implements SensorEventListe } } - if (shouldQuit && mView != null) { - mView.queueEvent(new Runnable() { + if (shouldQuit && mRenderView != null) { + mRenderView.queueOnRenderThread(new Runnable() { @Override public void run() { GodotLib.back(); @@ -789,8 +796,8 @@ public abstract class Godot extends FragmentActivity implements SensorEventListe * This must be called after the render thread has started. */ public final void runOnRenderThread(@NonNull Runnable action) { - if (mView != null) { - mView.queueEvent(action); + if (mRenderView != null) { + mRenderView.queueOnRenderThread(action); } } @@ -847,7 +854,7 @@ public abstract class Godot extends FragmentActivity implements SensorEventListe if (evcount == 0) return true; - if (mView != null) { + if (mRenderView != null) { final int[] arr = new int[event.getPointerCount() * 3]; for (int i = 0; i < event.getPointerCount(); i++) { @@ -860,7 +867,7 @@ public abstract class Godot extends FragmentActivity implements SensorEventListe //System.out.printf("gaction: %d\n",event.getAction()); final int action = event.getAction() & MotionEvent.ACTION_MASK; - mView.queueEvent(new Runnable() { + mRenderView.queueOnRenderThread(new Runnable() { @Override public void run() { switch (action) { @@ -911,7 +918,7 @@ public abstract class Godot extends FragmentActivity implements SensorEventListe for (int i = cc.length; --i >= 0; cnt += cc[i] != 0 ? 1 : 0) ; if (cnt == 0) return super.onKeyMultiple(inKeyCode, repeatCount, event); - mView.queueEvent(new Runnable() { + mRenderView.queueOnRenderThread(new Runnable() { // This method will be called on the rendering thread: public void run() { for (int i = 0, n = cc.length; i < n; i++) { @@ -1033,6 +1040,6 @@ public abstract class Godot extends FragmentActivity implements SensorEventListe progress.mOverallTotal)); } public void initInputDevices() { - mView.initInputDevices(); + mRenderView.initInputDevices(); } } diff --git a/platform/android/java/lib/src/org/godotengine/godot/GodotView.java b/platform/android/java/lib/src/org/godotengine/godot/GodotGLRenderView.java index 8d3c2ae319..9be93243b8 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/GodotView.java +++ b/platform/android/java/lib/src/org/godotengine/godot/GodotGLRenderView.java @@ -1,5 +1,5 @@ /*************************************************************************/ -/* GodotView.java */ +/* GodotGLRenderView.java */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -35,6 +35,7 @@ import android.opengl.GLSurfaceView; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.MotionEvent; +import android.view.SurfaceView; import org.godotengine.godot.input.GodotGestureHandler; import org.godotengine.godot.input.GodotInputHandler; import org.godotengine.godot.utils.GLUtils; @@ -64,16 +65,14 @@ import org.godotengine.godot.xr.regular.RegularFallbackConfigChooser; * that matches it exactly (with regards to red/green/blue/alpha channels * bit depths). Failure to do so would result in an EGL_BAD_MATCH error. */ -public class GodotView extends GLSurfaceView { - - private static String TAG = GodotView.class.getSimpleName(); +public class GodotGLRenderView extends GLSurfaceView implements GodotRenderView { private final Godot activity; private final GodotInputHandler inputHandler; private final GestureDetector detector; private final GodotRenderer godotRenderer; - public GodotView(Godot activity, XRMode xrMode, boolean p_use_32_bits, boolean p_use_debug_opengl) { + public GodotGLRenderView(Godot activity, XRMode xrMode, boolean p_use_32_bits, boolean p_use_debug_opengl) { super(activity); GLUtils.use_32 = p_use_32_bits; GLUtils.use_debug_opengl = p_use_debug_opengl; @@ -85,10 +84,36 @@ public class GodotView extends GLSurfaceView { init(xrMode, false, 16, 0); } + @Override + public SurfaceView getView() { + return this; + } + + @Override public void initInputDevices() { this.inputHandler.initInputDevices(); } + @Override + public void queueOnRenderThread(Runnable event) { + queueEvent(event); + } + + @Override + public void onActivityPaused() { + onPause(); + } + + @Override + public void onActivityResumed() { + onResume(); + } + + @Override + public void onBackPressed() { + activity.onBackPressed(); + } + @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent event) { @@ -170,10 +195,6 @@ public class GodotView extends GLSurfaceView { setRenderer(godotRenderer); } - public void onBackPressed() { - activity.onBackPressed(); - } - @Override public void onResume() { super.onResume(); diff --git a/platform/android/java/lib/src/org/godotengine/godot/GodotIO.java b/platform/android/java/lib/src/org/godotengine/godot/GodotIO.java index 68ce40ba10..016a3a8d18 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/GodotIO.java +++ b/platform/android/java/lib/src/org/godotengine/godot/GodotIO.java @@ -53,8 +53,6 @@ public class GodotIO { Godot activity; GodotEditText edit; - MediaPlayer mediaPlayer; - final int SCREEN_LANDSCAPE = 0; final int SCREEN_PORTRAIT = 1; final int SCREEN_REVERSE_LANDSCAPE = 2; @@ -530,44 +528,14 @@ public class GodotIO { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR); } break; } - }; - - public void setEdit(GodotEditText _edit) { - edit = _edit; - } - - public void playVideo(String p_path) { - Uri filePath = Uri.parse(p_path); - mediaPlayer = new MediaPlayer(); - - try { - mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); - mediaPlayer.setDataSource(activity.getApplicationContext(), filePath); - mediaPlayer.prepare(); - mediaPlayer.start(); - } catch (IOException e) { - System.out.println("IOError while playing video"); - } } - public boolean isVideoPlaying() { - if (mediaPlayer != null) { - return mediaPlayer.isPlaying(); - } - return false; + public int getScreenOrientation() { + return activity.getRequestedOrientation(); } - public void pauseVideo() { - if (mediaPlayer != null) { - mediaPlayer.pause(); - } - } - - public void stopVideo() { - if (mediaPlayer != null) { - mediaPlayer.release(); - mediaPlayer = null; - } + public void setEdit(GodotEditText _edit) { + edit = _edit; } public static final int SYSTEM_DIR_DESKTOP = 0; diff --git a/platform/android/java/lib/src/org/godotengine/godot/GodotLib.java b/platform/android/java/lib/src/org/godotengine/godot/GodotLib.java index 89a65aea24..71fe822233 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/GodotLib.java +++ b/platform/android/java/lib/src/org/godotengine/godot/GodotLib.java @@ -32,6 +32,7 @@ package org.godotengine.godot; import android.app.Activity; import android.hardware.SensorEvent; +import android.view.Surface; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; @@ -72,11 +73,11 @@ public class GodotLib { public static native void resize(int width, int height); /** - * Invoked on the GL thread when the underlying Android surface is created or recreated. + * Invoked on the render thread when the underlying Android surface is created or recreated. + * @param p_surface * @param p_32_bits - * @see android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(GL10, EGLConfig) */ - public static native void newcontext(boolean p_32_bits); + public static native void newcontext(Surface p_surface, boolean p_32_bits); /** * Forward {@link Activity#onBackPressed()} event from the main thread to the GL thread. diff --git a/platform/android/vulkan/vk_renderer_jni.h b/platform/android/java/lib/src/org/godotengine/godot/GodotRenderView.java index 017766fea2..170c433c9c 100644 --- a/platform/android/vulkan/vk_renderer_jni.h +++ b/platform/android/java/lib/src/org/godotengine/godot/GodotRenderView.java @@ -1,5 +1,5 @@ /*************************************************************************/ -/* vk_renderer_jni.h */ +/* GodotRenderView.java */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,19 +28,20 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef VK_RENDERER_JNI_H -#define VK_RENDERER_JNI_H +package org.godotengine.godot; -#include <android/log.h> -#include <jni.h> +import android.view.SurfaceView; -extern "C" { -JNIEXPORT void JNICALL Java_org_godotengine_godot_vulkan_VkRenderer_nativeOnVkSurfaceCreated(JNIEnv *env, jobject obj, jobject j_surface); -JNIEXPORT void JNICALL Java_org_godotengine_godot_vulkan_VkRenderer_nativeOnVkSurfaceChanged(JNIEnv *env, jobject object, jobject j_surface, jint width, jint height); -JNIEXPORT void JNICALL Java_org_godotengine_godot_vulkan_VkRenderer_nativeOnVkResume(JNIEnv *env, jobject obj); -JNIEXPORT void JNICALL Java_org_godotengine_godot_vulkan_VkRenderer_nativeOnVkDrawFrame(JNIEnv *env, jobject obj); -JNIEXPORT void JNICALL Java_org_godotengine_godot_vulkan_VkRenderer_nativeOnVkPause(JNIEnv *env, jobject obj); -JNIEXPORT void JNICALL Java_org_godotengine_godot_vulkan_VkRenderer_nativeOnVkDestroy(JNIEnv *env, jobject obj); -} +public interface GodotRenderView { + + abstract public SurfaceView getView(); + + abstract public void initInputDevices(); -#endif // VK_RENDERER_JNI_H + abstract public void queueOnRenderThread(Runnable event); + + abstract public void onActivityPaused(); + abstract public void onActivityResumed(); + + abstract public void onBackPressed(); +} diff --git a/platform/android/java/lib/src/org/godotengine/godot/GodotRenderer.java b/platform/android/java/lib/src/org/godotengine/godot/GodotRenderer.java index ee9a2aee4f..3e5bb4a4c9 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/GodotRenderer.java +++ b/platform/android/java/lib/src/org/godotengine/godot/GodotRenderer.java @@ -70,7 +70,7 @@ class GodotRenderer implements GLSurfaceView.Renderer { } public void onSurfaceCreated(GL10 gl, EGLConfig config) { - GodotLib.newcontext(GLUtils.use_32); + GodotLib.newcontext(null, GLUtils.use_32); for (GodotPlugin plugin : pluginRegistry.getAllPlugins()) { plugin.onGLSurfaceCreated(gl, config); } diff --git a/platform/android/java/lib/src/org/godotengine/godot/GodotVulkanRenderView.java b/platform/android/java/lib/src/org/godotengine/godot/GodotVulkanRenderView.java new file mode 100644 index 0000000000..30197d5729 --- /dev/null +++ b/platform/android/java/lib/src/org/godotengine/godot/GodotVulkanRenderView.java @@ -0,0 +1,142 @@ +/*************************************************************************/ +/* GodotVulkanRenderView.java */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +package org.godotengine.godot; + +import android.annotation.SuppressLint; +import android.view.GestureDetector; +import android.view.KeyEvent; +import android.view.MotionEvent; +import android.view.SurfaceView; +import org.godotengine.godot.input.GodotGestureHandler; +import org.godotengine.godot.input.GodotInputHandler; +import org.godotengine.godot.vulkan.VkRenderer; +import org.godotengine.godot.vulkan.VkSurfaceView; + +public class GodotVulkanRenderView extends VkSurfaceView implements GodotRenderView { + + private final Godot mActivity; + private final GodotInputHandler mInputHandler; + private final GestureDetector mGestureDetector; + private final VkRenderer mRenderer; + + public GodotVulkanRenderView(Godot activity) { + super(activity); + + mActivity = activity; + mInputHandler = new GodotInputHandler(this); + mGestureDetector = new GestureDetector(mActivity, new GodotGestureHandler(this)); + mRenderer = new VkRenderer(); + + setFocusableInTouchMode(true); + startRenderer(mRenderer); + } + + @Override + public SurfaceView getView() { + return this; + } + + @Override + public void initInputDevices() { + mInputHandler.initInputDevices(); + } + + @Override + public void queueOnRenderThread(Runnable event) { + queueOnVkThread(event); + } + + @Override + public void onActivityPaused() { + onPause(); + } + + @Override + public void onActivityResumed() { + onResume(); + } + + @Override + public void onBackPressed() { + mActivity.onBackPressed(); + } + + @SuppressLint("ClickableViewAccessibility") + @Override + public boolean onTouchEvent(MotionEvent event) { + super.onTouchEvent(event); + mGestureDetector.onTouchEvent(event); + return mActivity.gotTouchEvent(event); + } + + @Override + public boolean onKeyUp(final int keyCode, KeyEvent event) { + return mInputHandler.onKeyUp(keyCode, event) || super.onKeyUp(keyCode, event); + } + + @Override + public boolean onKeyDown(final int keyCode, KeyEvent event) { + return mInputHandler.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event); + } + + @Override + public boolean onGenericMotionEvent(MotionEvent event) { + return mInputHandler.onGenericMotionEvent(event) || super.onGenericMotionEvent(event); + } + + @Override + public void onResume() { + super.onResume(); + + queueOnVkThread(new Runnable() { + @Override + public void run() { + // Resume the renderer + mRenderer.onVkResume(); + GodotLib.focusin(); + } + }); + } + + @Override + public void onPause() { + super.onPause(); + + queueOnVkThread(new Runnable() { + @Override + public void run() { + GodotLib.focusout(); + // Pause the renderer + mRenderer.onVkPause(); + } + }); + } +} diff --git a/platform/android/java/lib/src/org/godotengine/godot/input/GodotEditText.java b/platform/android/java/lib/src/org/godotengine/godot/input/GodotEditText.java index e901b4b36d..92bb118e44 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/input/GodotEditText.java +++ b/platform/android/java/lib/src/org/godotengine/godot/input/GodotEditText.java @@ -51,7 +51,7 @@ public class GodotEditText extends EditText { // =========================================================== // Fields // =========================================================== - private GodotView mView; + private GodotRenderView mRenderView; private GodotTextInputWrapper mInputWrapper; private EditHandler sHandler = new EditHandler(this); private String mOriginText; @@ -76,22 +76,22 @@ public class GodotEditText extends EditText { // =========================================================== public GodotEditText(final Context context) { super(context); - this.initView(); + initView(); } public GodotEditText(final Context context, final AttributeSet attrs) { super(context, attrs); - this.initView(); + initView(); } public GodotEditText(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); - this.initView(); + initView(); } protected void initView() { - this.setPadding(0, 0, 0, 0); - this.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI); + setPadding(0, 0, 0, 0); + setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI); } private void handleMessage(final Message msg) { @@ -106,7 +106,7 @@ public class GodotEditText extends EditText { edit.mInputWrapper.setOriginText(text); edit.addTextChangedListener(edit.mInputWrapper); setMaxInputLength(edit, msg.arg1); - final InputMethodManager imm = (InputMethodManager)mView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + final InputMethodManager imm = (InputMethodManager)mRenderView.getView().getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(edit, 0); } } break; @@ -115,9 +115,9 @@ public class GodotEditText extends EditText { GodotEditText edit = (GodotEditText)msg.obj; edit.removeTextChangedListener(mInputWrapper); - final InputMethodManager imm = (InputMethodManager)mView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + final InputMethodManager imm = (InputMethodManager)mRenderView.getView().getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(edit.getWindowToken(), 0); - edit.mView.requestFocus(); + edit.mRenderView.getView().requestFocus(); } break; } } @@ -135,12 +135,12 @@ public class GodotEditText extends EditText { // =========================================================== // Getter & Setter // =========================================================== - public void setView(final GodotView view) { - this.mView = view; + public void setView(final GodotRenderView view) { + mRenderView = view; if (mInputWrapper == null) - mInputWrapper = new GodotTextInputWrapper(mView, this); - this.setOnEditorActionListener(mInputWrapper); - view.requestFocus(); + mInputWrapper = new GodotTextInputWrapper(mRenderView, this); + setOnEditorActionListener(mInputWrapper); + view.getView().requestFocus(); } // =========================================================== @@ -152,7 +152,7 @@ public class GodotEditText extends EditText { /* Let GlSurfaceView get focus if back key is input. */ if (keyCode == KeyEvent.KEYCODE_BACK) { - this.mView.requestFocus(); + mRenderView.getView().requestFocus(); } return true; @@ -162,7 +162,7 @@ public class GodotEditText extends EditText { // Methods // =========================================================== public void showKeyboard(String p_existing_text, int p_max_input_length) { - this.mOriginText = p_existing_text; + mOriginText = p_existing_text; final Message msg = new Message(); msg.what = HANDLER_OPEN_IME_KEYBOARD; diff --git a/platform/android/java/lib/src/org/godotengine/godot/input/GodotGestureHandler.java b/platform/android/java/lib/src/org/godotengine/godot/input/GodotGestureHandler.java index 1a38a9c3d2..b1e0f66373 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/input/GodotGestureHandler.java +++ b/platform/android/java/lib/src/org/godotengine/godot/input/GodotGestureHandler.java @@ -34,22 +34,22 @@ import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import org.godotengine.godot.GodotLib; -import org.godotengine.godot.GodotView; +import org.godotengine.godot.GodotRenderView; /** - * Handles gesture input related events for the {@link GodotView} view. + * Handles gesture input related events for the {@link GodotRenderView} view. * https://developer.android.com/reference/android/view/GestureDetector.SimpleOnGestureListener */ public class GodotGestureHandler extends GestureDetector.SimpleOnGestureListener { - private final GodotView godotView; + private final GodotRenderView mRenderView; - public GodotGestureHandler(GodotView godotView) { - this.godotView = godotView; + public GodotGestureHandler(GodotRenderView godotView) { + mRenderView = godotView; } private void queueEvent(Runnable task) { - godotView.queueEvent(task); + mRenderView.queueOnRenderThread(task); } @Override diff --git a/platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java b/platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java index e00ca86c41..0e4fc65119 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java +++ b/platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java @@ -42,27 +42,27 @@ import java.util.Collections; import java.util.Comparator; import java.util.List; import org.godotengine.godot.GodotLib; -import org.godotengine.godot.GodotView; +import org.godotengine.godot.GodotRenderView; import org.godotengine.godot.input.InputManagerCompat.InputDeviceListener; /** - * Handles input related events for the {@link GodotView} view. + * Handles input related events for the {@link GodotRenderView} view. */ public class GodotInputHandler implements InputDeviceListener { - private final ArrayList<Joystick> joysticksDevices = new ArrayList<Joystick>(); + private final ArrayList<Joystick> mJoysticksDevices = new ArrayList<Joystick>(); - private final GodotView godotView; - private final InputManagerCompat inputManager; + private final GodotRenderView mRenderView; + private final InputManagerCompat mInputManager; - public GodotInputHandler(GodotView godotView) { - this.godotView = godotView; - this.inputManager = InputManagerCompat.Factory.getInputManager(godotView.getContext()); - this.inputManager.registerInputDeviceListener(this, null); + public GodotInputHandler(GodotRenderView godotView) { + mRenderView = godotView; + mInputManager = InputManagerCompat.Factory.getInputManager(mRenderView.getView().getContext()); + mInputManager.registerInputDeviceListener(this, null); } private void queueEvent(Runnable task) { - godotView.queueEvent(task); + mRenderView.queueOnRenderThread(task); } private boolean isKeyEvent_GameDevice(int source) { @@ -113,7 +113,7 @@ public class GodotInputHandler implements InputDeviceListener { public boolean onKeyDown(final int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { - godotView.onBackPressed(); + mRenderView.onBackPressed(); // press 'back' button should not terminate program //normal handle 'back' event in game logic return true; @@ -164,7 +164,7 @@ public class GodotInputHandler implements InputDeviceListener { // Check if the device exists if (device_id > -1) { - Joystick joy = joysticksDevices.get(device_id); + Joystick joy = mJoysticksDevices.get(device_id); for (int i = 0; i < joy.axes.size(); i++) { InputDevice.MotionRange range = joy.axes.get(i); @@ -208,11 +208,11 @@ public class GodotInputHandler implements InputDeviceListener { public void initInputDevices() { /* initially add input devices*/ - int[] deviceIds = inputManager.getInputDeviceIds(); + int[] deviceIds = mInputManager.getInputDeviceIds(); for (int deviceId : deviceIds) { - InputDevice device = inputManager.getInputDevice(deviceId); + InputDevice device = mInputManager.getInputDevice(deviceId); if (DEBUG) { - Log.v("GodotView", String.format("init() deviceId:%d, Name:%s\n", deviceId, device.getName())); + Log.v("GodotInputHandler", String.format("init() deviceId:%d, Name:%s\n", deviceId, device.getName())); } onInputDeviceAdded(deviceId); } @@ -224,13 +224,13 @@ public class GodotInputHandler implements InputDeviceListener { // Check if the device has not been already added if (id < 0) { - InputDevice device = inputManager.getInputDevice(deviceId); + InputDevice device = mInputManager.getInputDevice(deviceId); //device can be null if deviceId is not found if (device != null) { int sources = device.getSources(); if (((sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) || ((sources & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK)) { - id = joysticksDevices.size(); + id = mJoysticksDevices.size(); Joystick joy = new Joystick(); joy.device_id = deviceId; @@ -249,7 +249,7 @@ public class GodotInputHandler implements InputDeviceListener { } } - joysticksDevices.add(joy); + mJoysticksDevices.add(joy); final int device_id = id; final String name = joy.name; @@ -270,7 +270,7 @@ public class GodotInputHandler implements InputDeviceListener { // Check if the evice has not been already removed if (device_id > -1) { - joysticksDevices.remove(device_id); + mJoysticksDevices.remove(device_id); queueEvent(new Runnable() { @Override @@ -360,8 +360,8 @@ public class GodotInputHandler implements InputDeviceListener { } private int findJoystickDevice(int device_id) { - for (int i = 0; i < joysticksDevices.size(); i++) { - if (joysticksDevices.get(i).device_id == device_id) { + for (int i = 0; i < mJoysticksDevices.size(); i++) { + if (mJoysticksDevices.get(i).device_id == device_id) { return i; } } diff --git a/platform/android/java/lib/src/org/godotengine/godot/input/GodotTextInputWrapper.java b/platform/android/java/lib/src/org/godotengine/godot/input/GodotTextInputWrapper.java index 18f2d57661..e12ff266bf 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/input/GodotTextInputWrapper.java +++ b/platform/android/java/lib/src/org/godotengine/godot/input/GodotTextInputWrapper.java @@ -48,7 +48,7 @@ public class GodotTextInputWrapper implements TextWatcher, OnEditorActionListene // =========================================================== // Fields // =========================================================== - private final GodotView mView; + private final GodotRenderView mRenderView; private final GodotEditText mEdit; private String mOriginText; @@ -56,9 +56,9 @@ public class GodotTextInputWrapper implements TextWatcher, OnEditorActionListene // Constructors // =========================================================== - public GodotTextInputWrapper(final GodotView view, final GodotEditText edit) { - this.mView = view; - this.mEdit = edit; + public GodotTextInputWrapper(final GodotRenderView view, final GodotEditText edit) { + mRenderView = view; + mEdit = edit; } // =========================================================== @@ -66,13 +66,13 @@ public class GodotTextInputWrapper implements TextWatcher, OnEditorActionListene // =========================================================== private boolean isFullScreenEdit() { - final TextView textField = this.mEdit; + final TextView textField = mEdit; final InputMethodManager imm = (InputMethodManager)textField.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); return imm.isFullscreenMode(); } public void setOriginText(final String originText) { - this.mOriginText = originText; + mOriginText = originText; } // =========================================================== @@ -87,7 +87,7 @@ public class GodotTextInputWrapper implements TextWatcher, OnEditorActionListene public void beforeTextChanged(final CharSequence pCharSequence, final int start, final int count, final int after) { //Log.d(TAG, "beforeTextChanged(" + pCharSequence + ")start: " + start + ",count: " + count + ",after: " + after); - mView.queueEvent(new Runnable() { + mRenderView.queueOnRenderThread(new Runnable() { @Override public void run() { for (int i = 0; i < count; ++i) { @@ -106,7 +106,7 @@ public class GodotTextInputWrapper implements TextWatcher, OnEditorActionListene for (int i = start; i < start + count; ++i) { newChars[i - start] = pCharSequence.charAt(i); } - mView.queueEvent(new Runnable() { + mRenderView.queueOnRenderThread(new Runnable() { @Override public void run() { for (int i = 0; i < count; ++i) { @@ -124,10 +124,10 @@ public class GodotTextInputWrapper implements TextWatcher, OnEditorActionListene @Override public boolean onEditorAction(final TextView pTextView, final int pActionID, final KeyEvent pKeyEvent) { - if (this.mEdit == pTextView && this.isFullScreenEdit()) { + if (mEdit == pTextView && isFullScreenEdit()) { final String characters = pKeyEvent.getCharacters(); - mView.queueEvent(new Runnable() { + mRenderView.queueOnRenderThread(new Runnable() { @Override public void run() { for (int i = 0; i < characters.length(); i++) { @@ -144,7 +144,7 @@ public class GodotTextInputWrapper implements TextWatcher, OnEditorActionListene GodotLib.key(KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_ENTER, 0, true); GodotLib.key(KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_ENTER, 0, false); - this.mView.requestFocus(); + mRenderView.getView().requestFocus(); return true; } return false; diff --git a/platform/android/java/lib/src/org/godotengine/godot/plugin/GodotPlugin.java b/platform/android/java/lib/src/org/godotengine/godot/plugin/GodotPlugin.java index e745cdd0a5..e3683704e1 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/plugin/GodotPlugin.java +++ b/platform/android/java/lib/src/org/godotengine/godot/plugin/GodotPlugin.java @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/platform/android/java/lib/src/org/godotengine/godot/plugin/GodotPluginRegistry.java b/platform/android/java/lib/src/org/godotengine/godot/plugin/GodotPluginRegistry.java index b6d949b7bf..e13a9c15d8 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/plugin/GodotPluginRegistry.java +++ b/platform/android/java/lib/src/org/godotengine/godot/plugin/GodotPluginRegistry.java @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ diff --git a/platform/android/java/lib/src/org/godotengine/godot/vulkan/VkRenderer.kt b/platform/android/java/lib/src/org/godotengine/godot/vulkan/VkRenderer.kt index 67faad8ddd..608ad48df9 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/vulkan/VkRenderer.kt +++ b/platform/android/java/lib/src/org/godotengine/godot/vulkan/VkRenderer.kt @@ -33,6 +33,11 @@ package org.godotengine.godot.vulkan import android.view.Surface +import org.godotengine.godot.Godot +import org.godotengine.godot.GodotLib +import org.godotengine.godot.plugin.GodotPlugin +import org.godotengine.godot.plugin.GodotPluginRegistry + /** * Responsible to setting up and driving the Vulkan rendering logic. * @@ -48,52 +53,64 @@ import android.view.Surface */ internal class VkRenderer { + private val pluginRegistry: GodotPluginRegistry = GodotPluginRegistry.getPluginRegistry() + /** * Called when the surface is created and signals the beginning of rendering. */ fun onVkSurfaceCreated(surface: Surface) { - nativeOnVkSurfaceCreated(surface) + // TODO: properly implement surface re-creation: + // GodotLib.newcontext should be called here once it's done. + //GodotLib.newcontext(surface, false) + + for (plugin in pluginRegistry.getAllPlugins()) { + plugin.onVkSurfaceCreated(surface) + } } /** * Called after the surface is created and whenever its size changes. */ fun onVkSurfaceChanged(surface: Surface, width: Int, height: Int) { - nativeOnVkSurfaceChanged(surface, width, height) + GodotLib.resize(width, height) + + // TODO: properly implement surface re-creation: + // Update the native renderer instead of restarting the app. + // GodotLib.newcontext should not be called here once it's done. + GodotLib.newcontext(surface, false) + + for (plugin in pluginRegistry.getAllPlugins()) { + plugin.onVkSurfaceChanged(surface, width, height) + } } /** * Called to draw the current frame. */ fun onVkDrawFrame() { - nativeOnVkDrawFrame() + GodotLib.step() + for (plugin in pluginRegistry.getAllPlugins()) { + plugin.onVkDrawFrame() + } } /** * Called when the rendering thread is resumed. */ fun onVkResume() { - nativeOnVkResume() + GodotLib.onRendererResumed() } /** * Called when the rendering thread is paused. */ fun onVkPause() { - nativeOnVkPause() + GodotLib.onRendererPaused() } /** * Called when the rendering thread is destroyed and used as signal to tear down the Vulkan logic. */ fun onVkDestroy() { - nativeOnVkDestroy() } - - private external fun nativeOnVkSurfaceCreated(surface: Surface) - private external fun nativeOnVkSurfaceChanged(surface: Surface, width: Int, height: Int) - private external fun nativeOnVkResume() - private external fun nativeOnVkDrawFrame() - private external fun nativeOnVkPause() - private external fun nativeOnVkDestroy() } diff --git a/platform/android/java/lib/src/org/godotengine/godot/vulkan/VkSurfaceView.kt b/platform/android/java/lib/src/org/godotengine/godot/vulkan/VkSurfaceView.kt index 1c594f3201..6b0e12b21a 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/vulkan/VkSurfaceView.kt +++ b/platform/android/java/lib/src/org/godotengine/godot/vulkan/VkSurfaceView.kt @@ -49,7 +49,7 @@ import android.view.SurfaceView * UI thread. * </ul> */ -internal class VkSurfaceView(context: Context) : SurfaceView(context), SurfaceHolder.Callback { +open internal class VkSurfaceView(context: Context) : SurfaceView(context), SurfaceHolder.Callback { companion object { fun checkState(expression: Boolean, errorMessage: Any) { @@ -100,7 +100,7 @@ internal class VkSurfaceView(context: Context) : SurfaceView(context), SurfaceHo * * Must not be called before a [VkRenderer] has been set. */ - fun onResume() { + open fun onResume() { vkThread.onResume() } @@ -109,7 +109,7 @@ internal class VkSurfaceView(context: Context) : SurfaceView(context), SurfaceHo * * Must not be called before a [VkRenderer] has been set. */ - fun onPause() { + open fun onPause() { vkThread.onPause() } diff --git a/platform/android/java/lib/src/org/godotengine/godot/vulkan/VkThread.kt b/platform/android/java/lib/src/org/godotengine/godot/vulkan/VkThread.kt index 2e332840bf..7557c8aa22 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/vulkan/VkThread.kt +++ b/platform/android/java/lib/src/org/godotengine/godot/vulkan/VkThread.kt @@ -219,9 +219,9 @@ internal class VkThread(private val vkSurfaceView: VkSurfaceView, private val vk vkRenderer.onVkDrawFrame() } } catch (ex: InterruptedException) { - Log.i(TAG, ex.message) + Log.i(TAG, "InterruptedException", ex) } catch (ex: IllegalStateException) { - Log.i(TAG, ex.message) + Log.i(TAG, "IllegalStateException", ex) } finally { threadExiting() } diff --git a/platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularContextFactory.java b/platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularContextFactory.java index f2b4c95a2c..31cf696195 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularContextFactory.java +++ b/platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularContextFactory.java @@ -51,7 +51,6 @@ public class RegularContextFactory implements GLSurfaceView.EGLContextFactory { private static int EGL_CONTEXT_CLIENT_VERSION = 0x3098; public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig) { - String driver_name = GodotLib.getGlobal("rendering/quality/driver/driver_name"); // FIXME: Add support for Vulkan. Log.w(TAG, "creating OpenGL ES 2.0 context :"); diff --git a/platform/android/java_class_wrapper.cpp b/platform/android/java_class_wrapper.cpp index 13550c4b11..6b9105b8e5 100644 --- a/platform/android/java_class_wrapper.cpp +++ b/platform/android/java_class_wrapper.cpp @@ -40,7 +40,7 @@ bool JavaClass::_call_method(JavaObject *p_instance, const StringName &p_method, JNIEnv *env = ThreadAndroid::get_env(); - MethodInfo *method = NULL; + MethodInfo *method = nullptr; for (List<MethodInfo>::Element *E = M->get().front(); E; E = E->next()) { if (!p_instance && !E->get()._static) { @@ -160,7 +160,7 @@ bool JavaClass::_call_method(JavaObject *p_instance, const StringName &p_method, r_error.error = Callable::CallError::CALL_OK; - jvalue *argv = NULL; + jvalue *argv = nullptr; if (method->param_types.size()) { @@ -173,7 +173,7 @@ bool JavaClass::_call_method(JavaObject *p_instance, const StringName &p_method, switch (method->param_types[i]) { case ARG_TYPE_VOID: { //can't happen - argv[i].l = NULL; //I hope this works + argv[i].l = nullptr; //I hope this works } break; case ARG_TYPE_BOOLEAN: { @@ -285,7 +285,7 @@ bool JavaClass::_call_method(JavaObject *p_instance, const StringName &p_method, argv[i].l = jo->instance; } else { - argv[i].l = NULL; //I hope this works + argv[i].l = nullptr; //I hope this works } } break; @@ -386,7 +386,7 @@ bool JavaClass::_call_method(JavaObject *p_instance, const StringName &p_method, case ARG_ARRAY_BIT | ARG_TYPE_STRING: { Array arr = *p_args[i]; - jobjectArray a = env->NewObjectArray(arr.size(), env->FindClass("java/lang/String"), NULL); + jobjectArray a = env->NewObjectArray(arr.size(), env->FindClass("java/lang/String"), nullptr); for (int j = 0; j < arr.size(); j++) { String s = arr[j]; @@ -400,7 +400,7 @@ bool JavaClass::_call_method(JavaObject *p_instance, const StringName &p_method, } break; case ARG_ARRAY_BIT | ARG_TYPE_CLASS: { - argv[i].l = NULL; + argv[i].l = nullptr; } break; } } @@ -520,7 +520,7 @@ bool JavaClass::_call_method(JavaObject *p_instance, const StringName &p_method, Variant JavaClass::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) { Variant ret; - bool found = _call_method(NULL, p_method, p_args, p_argcount, r_error, ret); + bool found = _call_method(nullptr, p_method, p_args, p_argcount, r_error, ret); if (found) { return ret; } @@ -1205,7 +1205,7 @@ Ref<JavaClass> JavaClassWrapper::wrap(const String &p_class) { int mods = env->CallIntMethod(obj, Field_getModifiers); if ((mods & 0x8) && (mods & 0x10) && (mods & 0x1)) { //static final public! - jobject objc = env->CallObjectMethod(obj, Field_get, NULL); + jobject objc = env->CallObjectMethod(obj, Field_get, nullptr); if (objc) { uint32_t sig; @@ -1236,7 +1236,7 @@ Ref<JavaClass> JavaClassWrapper::wrap(const String &p_class) { return Ref<JavaClass>(); } -JavaClassWrapper *JavaClassWrapper::singleton = NULL; +JavaClassWrapper *JavaClassWrapper::singleton = nullptr; JavaClassWrapper::JavaClassWrapper(jobject p_activity) { diff --git a/platform/android/java_godot_io_wrapper.cpp b/platform/android/java_godot_io_wrapper.cpp index 8d075f8e97..0da0bd6387 100644 --- a/platform/android/java_godot_io_wrapper.cpp +++ b/platform/android/java_godot_io_wrapper.cpp @@ -56,11 +56,8 @@ GodotIOJavaWrapper::GodotIOJavaWrapper(JNIEnv *p_env, jobject p_godot_io_instanc _show_keyboard = p_env->GetMethodID(cls, "showKeyboard", "(Ljava/lang/String;I)V"); _hide_keyboard = p_env->GetMethodID(cls, "hideKeyboard", "()V"); _set_screen_orientation = p_env->GetMethodID(cls, "setScreenOrientation", "(I)V"); + _get_screen_orientation = p_env->GetMethodID(cls, "getScreenOrientation", "()I"); _get_system_dir = p_env->GetMethodID(cls, "getSystemDir", "(I)Ljava/lang/String;"); - _play_video = p_env->GetMethodID(cls, "playVideo", "(Ljava/lang/String;)V"); - _is_video_playing = p_env->GetMethodID(cls, "isVideoPlaying", "()Z"); - _pause_video = p_env->GetMethodID(cls, "pauseVideo", "()V"); - _stop_video = p_env->GetMethodID(cls, "stopVideo", "()V"); } } @@ -157,40 +154,22 @@ void GodotIOJavaWrapper::set_screen_orientation(int p_orient) { } } -String GodotIOJavaWrapper::get_system_dir(int p_dir) { - if (_get_system_dir) { +int GodotIOJavaWrapper::get_screen_orientation() { + if (_get_screen_orientation) { JNIEnv *env = ThreadAndroid::get_env(); - jstring s = (jstring)env->CallObjectMethod(godot_io_instance, _get_system_dir, p_dir); - return jstring_to_string(s, env); + return env->CallIntMethod(godot_io_instance, _get_screen_orientation); } else { - return String("."); + return 0; } } -void GodotIOJavaWrapper::play_video(const String &p_path) { - // Why is this not here?!?! -} - -bool GodotIOJavaWrapper::is_video_playing() { - if (_is_video_playing) { +String GodotIOJavaWrapper::get_system_dir(int p_dir) { + if (_get_system_dir) { JNIEnv *env = ThreadAndroid::get_env(); - return env->CallBooleanMethod(godot_io_instance, _is_video_playing); + jstring s = (jstring)env->CallObjectMethod(godot_io_instance, _get_system_dir, p_dir); + return jstring_to_string(s, env); } else { - return false; - } -} - -void GodotIOJavaWrapper::pause_video() { - if (_pause_video) { - JNIEnv *env = ThreadAndroid::get_env(); - env->CallVoidMethod(godot_io_instance, _pause_video); - } -} - -void GodotIOJavaWrapper::stop_video() { - if (_stop_video) { - JNIEnv *env = ThreadAndroid::get_env(); - env->CallVoidMethod(godot_io_instance, _stop_video); + return String("."); } } diff --git a/platform/android/java_godot_io_wrapper.h b/platform/android/java_godot_io_wrapper.h index 7dfed52187..dbb3b564f6 100644 --- a/platform/android/java_godot_io_wrapper.h +++ b/platform/android/java_godot_io_wrapper.h @@ -54,11 +54,8 @@ private: jmethodID _show_keyboard = 0; jmethodID _hide_keyboard = 0; jmethodID _set_screen_orientation = 0; + jmethodID _get_screen_orientation = 0; jmethodID _get_system_dir = 0; - jmethodID _play_video = 0; - jmethodID _is_video_playing = 0; - jmethodID _pause_video = 0; - jmethodID _stop_video = 0; public: GodotIOJavaWrapper(JNIEnv *p_env, jobject p_godot_io_instance); @@ -78,11 +75,8 @@ public: int get_vk_height(); void set_vk_height(int p_height); void set_screen_orientation(int p_orient); + int get_screen_orientation(); String get_system_dir(int p_dir); - void play_video(const String &p_path); - bool is_video_playing(); - void pause_video(); - void stop_video(); }; #endif /* !JAVA_GODOT_IO_WRAPPER_H */ diff --git a/platform/android/java_godot_lib_jni.cpp b/platform/android/java_godot_lib_jni.cpp index e018ee69f0..c103e74222 100644 --- a/platform/android/java_godot_lib_jni.cpp +++ b/platform/android/java_godot_lib_jni.cpp @@ -34,13 +34,13 @@ #include "java_godot_wrapper.h" #include "android/asset_manager_jni.h" -#include "android_keys_utils.h" #include "api/java_class_wrapper.h" #include "audio_driver_jandroid.h" #include "core/engine.h" #include "core/input/input_filter.h" #include "core/project_settings.h" #include "dir_access_jandroid.h" +#include "display_server_android.h" #include "file_access_android.h" #include "file_access_jandroid.h" #include "jni_utils.h" @@ -52,10 +52,12 @@ #include <unistd.h> -static JavaClassWrapper *java_class_wrapper = NULL; -static OS_Android *os_android = NULL; -static GodotJavaWrapper *godot_java = NULL; -static GodotIOJavaWrapper *godot_io_java = NULL; +#include <android/native_window_jni.h> + +static JavaClassWrapper *java_class_wrapper = nullptr; +static OS_Android *os_android = nullptr; +static GodotJavaWrapper *godot_java = nullptr; +static GodotIOJavaWrapper *godot_io_java = nullptr; static bool initialized = false; static int step = 0; @@ -123,14 +125,14 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_ondestroy(JNIEnv *env JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_setup(JNIEnv *env, jclass clazz, jobjectArray p_cmdline) { ThreadAndroid::setup_thread(); - const char **cmdline = NULL; - jstring *j_cmdline = NULL; + const char **cmdline = nullptr; + jstring *j_cmdline = nullptr; int cmdlen = 0; if (p_cmdline) { cmdlen = env->GetArrayLength(p_cmdline); if (cmdlen) { cmdline = (const char **)malloc((cmdlen + 1) * sizeof(const char *)); - cmdline[cmdlen] = NULL; + cmdline[cmdlen] = nullptr; j_cmdline = (jstring *)malloc(cmdlen * sizeof(jstring)); for (int i = 0; i < cmdlen; i++) { @@ -165,17 +167,20 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_setup(JNIEnv *env, jc JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_resize(JNIEnv *env, jclass clazz, jint width, jint height) { if (os_android) - os_android->set_display_size(Size2(width, height)); + os_android->set_display_size(Size2i(width, height)); } -JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_newcontext(JNIEnv *env, jclass clazz, jboolean p_32_bits) { - +JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_newcontext(JNIEnv *env, jclass clazz, jobject p_surface, jboolean p_32_bits) { if (os_android) { if (step == 0) { // During startup os_android->set_context_is_16_bits(!p_32_bits); + if (p_surface) { + ANativeWindow *native_window = ANativeWindow_fromSurface(env, p_surface); + os_android->set_native_window(native_window); + } } else { - // GL context recreated because it was lost; restart app to let it reload everything + // Rendering context recreated because it was lost; restart app to let it reload everything os_android->main_loop_end(); godot_java->restart(env); step = -1; // Ensure no further steps are attempted @@ -195,7 +200,6 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_step(JNIEnv *env, jcl return; if (step == 0) { - // Since Godot is initialized on the UI thread, _main_thread_id was set to that thread's id, // but for Godot purposes, the main thread is the one running the game loop Main::setup2(Thread::get_caller_id()); @@ -213,10 +217,10 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_step(JNIEnv *env, jcl ++step; } - os_android->process_accelerometer(accelerometer); - os_android->process_gravity(gravity); - os_android->process_magnetometer(magnetometer); - os_android->process_gyroscope(gyroscope); + DisplayServerAndroid::get_singleton()->process_accelerometer(accelerometer); + DisplayServerAndroid::get_singleton()->process_gravity(gravity); + DisplayServerAndroid::get_singleton()->process_magnetometer(magnetometer); + DisplayServerAndroid::get_singleton()->process_gyroscope(gyroscope); if (os_android->main_loop_iterate()) { @@ -229,18 +233,18 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_touch(JNIEnv *env, jc if (step == 0) return; - Vector<OS_Android::TouchPos> points; + Vector<DisplayServerAndroid::TouchPos> points; for (int i = 0; i < count; i++) { jint p[3]; env->GetIntArrayRegion(positions, i * 3, 3, p); - OS_Android::TouchPos tp; + DisplayServerAndroid::TouchPos tp; tp.pos = Point2(p[1], p[2]); tp.id = p[0]; points.push_back(tp); } - os_android->process_touch(ev, pointer, points); + DisplayServerAndroid::get_singleton()->process_touch(ev, pointer, points); /* if (os_android) @@ -252,78 +256,78 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_hover(JNIEnv *env, jc if (step == 0) return; - os_android->process_hover(p_type, Point2(p_x, p_y)); + DisplayServerAndroid::get_singleton()->process_hover(p_type, Point2(p_x, p_y)); } JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_doubletap(JNIEnv *env, jclass clazz, jint p_x, jint p_y) { if (step == 0) return; - os_android->process_double_tap(Point2(p_x, p_y)); + DisplayServerAndroid::get_singleton()->process_double_tap(Point2(p_x, p_y)); } JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_scroll(JNIEnv *env, jclass clazz, jint p_x, jint p_y) { if (step == 0) return; - os_android->process_scroll(Point2(p_x, p_y)); + DisplayServerAndroid::get_singleton()->process_scroll(Point2(p_x, p_y)); } JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joybutton(JNIEnv *env, jclass clazz, jint p_device, jint p_button, jboolean p_pressed) { if (step == 0) return; - OS_Android::JoypadEvent jevent; + DisplayServerAndroid::JoypadEvent jevent; jevent.device = p_device; - jevent.type = OS_Android::JOY_EVENT_BUTTON; + jevent.type = DisplayServerAndroid::JOY_EVENT_BUTTON; jevent.index = p_button; jevent.pressed = p_pressed; - os_android->process_joy_event(jevent); + DisplayServerAndroid::get_singleton()->process_joy_event(jevent); } JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyaxis(JNIEnv *env, jclass clazz, jint p_device, jint p_axis, jfloat p_value) { if (step == 0) return; - OS_Android::JoypadEvent jevent; + DisplayServerAndroid::JoypadEvent jevent; jevent.device = p_device; - jevent.type = OS_Android::JOY_EVENT_AXIS; + jevent.type = DisplayServerAndroid::JOY_EVENT_AXIS; jevent.index = p_axis; jevent.value = p_value; - os_android->process_joy_event(jevent); + DisplayServerAndroid::get_singleton()->process_joy_event(jevent); } JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyhat(JNIEnv *env, jclass clazz, jint p_device, jint p_hat_x, jint p_hat_y) { if (step == 0) return; - OS_Android::JoypadEvent jevent; + DisplayServerAndroid::JoypadEvent jevent; jevent.device = p_device; - jevent.type = OS_Android::JOY_EVENT_HAT; + jevent.type = DisplayServerAndroid::JOY_EVENT_HAT; int hat = 0; if (p_hat_x != 0) { if (p_hat_x < 0) - hat |= InputDefault::HAT_MASK_LEFT; + hat |= InputFilter::HAT_MASK_LEFT; else - hat |= InputDefault::HAT_MASK_RIGHT; + hat |= InputFilter::HAT_MASK_RIGHT; } if (p_hat_y != 0) { if (p_hat_y < 0) - hat |= InputDefault::HAT_MASK_UP; + hat |= InputFilter::HAT_MASK_UP; else - hat |= InputDefault::HAT_MASK_DOWN; + hat |= InputFilter::HAT_MASK_DOWN; } jevent.hat = hat; - os_android->process_joy_event(jevent); + DisplayServerAndroid::get_singleton()->process_joy_event(jevent); } JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyconnectionchanged(JNIEnv *env, jclass clazz, jint p_device, jboolean p_connected, jstring p_name) { if (os_android) { String name = jstring_to_string(p_name, env); - os_android->joy_connection_changed(p_device, p_connected, name); + InputFilter::get_singleton()->joy_connection_changed(p_device, p_connected, name); } } @@ -331,29 +335,7 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_key(JNIEnv *env, jcla if (step == 0) return; - Ref<InputEventKey> ievent; - ievent.instance(); - int val = p_unicode_char; - int keycode = android_get_keysym(p_keycode); - int phy_keycode = android_get_keysym(p_scancode); - ievent->set_keycode(keycode); - ievent->set_physical_keycode(phy_keycode); - ievent->set_unicode(val); - ievent->set_pressed(p_pressed); - - if (val == '\n') { - ievent->set_keycode(KEY_ENTER); - } else if (val == 61448) { - ievent->set_keycode(KEY_BACKSPACE); - ievent->set_unicode(KEY_BACKSPACE); - } else if (val == 61453) { - ievent->set_keycode(KEY_ENTER); - ievent->set_unicode(KEY_ENTER); - } else if (p_keycode == 4) { - os_android->main_loop_request_go_back(); - } - - os_android->process_event(ievent); + DisplayServerAndroid::get_singleton()->process_key_event(p_keycode, p_scancode, p_unicode_char, p_pressed); } JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_accelerometer(JNIEnv *env, jclass clazz, jfloat x, jfloat y, jfloat z) { @@ -430,7 +412,7 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_callobject(JNIEnv *en obj->call(str_method, (const Variant **)vptr, count, err); // something - env->PopLocalFrame(NULL); + env->PopLocalFrame(nullptr); } JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_calldeferred(JNIEnv *env, jclass clazz, jint ID, jstring method, jobjectArray params) { @@ -456,7 +438,7 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_calldeferred(JNIEnv * obj->call_deferred(str_method, args[0], args[1], args[2], args[3], args[4]); // something - env->PopLocalFrame(NULL); + env->PopLocalFrame(nullptr); } JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_requestPermissionResult(JNIEnv *env, jclass clazz, jstring p_permission, jboolean p_result) { diff --git a/platform/android/java_godot_lib_jni.h b/platform/android/java_godot_lib_jni.h index a7a5970440..221d701e2b 100644 --- a/platform/android/java_godot_lib_jni.h +++ b/platform/android/java_godot_lib_jni.h @@ -41,7 +41,7 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_initialize(JNIEnv *en JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_ondestroy(JNIEnv *env, jclass clazz, jobject activity); JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_setup(JNIEnv *env, jclass clazz, jobjectArray p_cmdline); JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_resize(JNIEnv *env, jclass clazz, jint width, jint height); -JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_newcontext(JNIEnv *env, jclass clazz, jboolean p_32_bits); +JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_newcontext(JNIEnv *env, jclass clazz, jobject p_surface, jboolean p_32_bits); JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_step(JNIEnv *env, jclass clazz); JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_back(JNIEnv *env, jclass clazz); JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_touch(JNIEnv *env, jclass clazz, jint ev, jint pointer, jint count, jintArray positions); diff --git a/platform/android/java_godot_wrapper.cpp b/platform/android/java_godot_wrapper.cpp index 2a540bb4a9..8ef99dfab0 100644 --- a/platform/android/java_godot_wrapper.cpp +++ b/platform/android/java_godot_wrapper.cpp @@ -80,13 +80,13 @@ jobject GodotJavaWrapper::get_activity() { jobject GodotJavaWrapper::get_member_object(const char *p_name, const char *p_class, JNIEnv *p_env) { if (cls) { - if (p_env == NULL) + if (p_env == nullptr) p_env = ThreadAndroid::get_env(); jfieldID fid = p_env->GetStaticFieldID(cls, p_name, p_class); return p_env->GetStaticObjectField(cls, fid); } else { - return NULL; + return nullptr; } } @@ -96,13 +96,13 @@ jobject GodotJavaWrapper::get_class_loader() { jmethodID getClassLoader = env->GetMethodID(cls, "getClassLoader", "()Ljava/lang/ClassLoader;"); return env->CallObjectMethod(godot_instance, getClassLoader); } else { - return NULL; + return nullptr; } } void GodotJavaWrapper::on_video_init(JNIEnv *p_env) { if (_on_video_init) - if (p_env == NULL) + if (p_env == nullptr) p_env = ThreadAndroid::get_env(); p_env->CallVoidMethod(godot_instance, _on_video_init); @@ -110,7 +110,7 @@ void GodotJavaWrapper::on_video_init(JNIEnv *p_env) { void GodotJavaWrapper::on_godot_main_loop_started(JNIEnv *p_env) { if (_on_godot_main_loop_started) { - if (p_env == NULL) { + if (p_env == nullptr) { p_env = ThreadAndroid::get_env(); } } @@ -119,7 +119,7 @@ void GodotJavaWrapper::on_godot_main_loop_started(JNIEnv *p_env) { void GodotJavaWrapper::restart(JNIEnv *p_env) { if (_restart) - if (p_env == NULL) + if (p_env == nullptr) p_env = ThreadAndroid::get_env(); p_env->CallVoidMethod(godot_instance, _restart); @@ -127,7 +127,7 @@ void GodotJavaWrapper::restart(JNIEnv *p_env) { void GodotJavaWrapper::force_quit(JNIEnv *p_env) { if (_finish) - if (p_env == NULL) + if (p_env == nullptr) p_env = ThreadAndroid::get_env(); p_env->CallVoidMethod(godot_instance, _finish); @@ -244,7 +244,7 @@ jobject GodotJavaWrapper::get_surface() { JNIEnv *env = ThreadAndroid::get_env(); return env->CallObjectMethod(godot_instance, _get_surface); } else { - return NULL; + return nullptr; } } diff --git a/platform/android/java_godot_wrapper.h b/platform/android/java_godot_wrapper.h index fb77c8ba6a..89d6b6db46 100644 --- a/platform/android/java_godot_wrapper.h +++ b/platform/android/java_godot_wrapper.h @@ -68,14 +68,14 @@ public: ~GodotJavaWrapper(); jobject get_activity(); - jobject get_member_object(const char *p_name, const char *p_class, JNIEnv *p_env = NULL); + jobject get_member_object(const char *p_name, const char *p_class, JNIEnv *p_env = nullptr); jobject get_class_loader(); - void on_video_init(JNIEnv *p_env = NULL); - void on_godot_main_loop_started(JNIEnv *p_env = NULL); - void restart(JNIEnv *p_env = NULL); - void force_quit(JNIEnv *p_env = NULL); + void on_video_init(JNIEnv *p_env = nullptr); + void on_godot_main_loop_started(JNIEnv *p_env = nullptr); + void restart(JNIEnv *p_env = nullptr); + void force_quit(JNIEnv *p_env = nullptr); void set_keep_screen_on(bool p_enabled); void alert(const String &p_message, const String &p_title); int get_gles_version_code(); diff --git a/platform/android/jni_utils.cpp b/platform/android/jni_utils.cpp index 3fa4e80884..ded79a668f 100644 --- a/platform/android/jni_utils.cpp +++ b/platform/android/jni_utils.cpp @@ -130,7 +130,7 @@ jvalret _variant_to_jvalue(JNIEnv *env, Variant::Type p_type, const Variant *p_a env->CallVoidMethodA(jdict, set_keys, &val); env->DeleteLocalRef(jkeys); - jobjectArray jvalues = env->NewObjectArray(keys.size(), env->FindClass("java/lang/Object"), NULL); + jobjectArray jvalues = env->NewObjectArray(keys.size(), env->FindClass("java/lang/Object"), nullptr); for (int j = 0; j < keys.size(); j++) { Variant var = dict[keys[j]]; @@ -211,7 +211,7 @@ String _get_class_name(JNIEnv *env, jclass cls, bool *array) { Variant _jobject_to_variant(JNIEnv *env, jobject obj) { - if (obj == NULL) { + if (obj == nullptr) { return Variant(); } @@ -384,7 +384,7 @@ Variant::Type get_jni_type(const String &p_type) { { "[F", Variant::PACKED_FLOAT32_ARRAY }, { "[Ljava.lang.String;", Variant::PACKED_STRING_ARRAY }, { "org.godotengine.godot.Dictionary", Variant::DICTIONARY }, - { NULL, Variant::NIL } + { nullptr, Variant::NIL } }; int idx = 0; @@ -417,7 +417,7 @@ const char *get_jni_sig(const String &p_type) { { "[B", "[B" }, { "[F", "[F" }, { "[Ljava.lang.String;", "[Ljava/lang/String;" }, - { NULL, "V" } + { nullptr, "V" } }; int idx = 0; diff --git a/platform/android/jni_utils.h b/platform/android/jni_utils.h index 925340a680..b9ee243308 100644 --- a/platform/android/jni_utils.h +++ b/platform/android/jni_utils.h @@ -40,7 +40,7 @@ struct jvalret { jobject obj; jvalue val; - jvalret() { obj = NULL; } + jvalret() { obj = nullptr; } }; jvalret _variant_to_jvalue(JNIEnv *env, Variant::Type p_type, const Variant *p_arg, bool force_jobject = false); @@ -106,7 +106,7 @@ public: } } - jvalue *v = NULL; + jvalue *v = nullptr; if (p_argcount) { @@ -201,7 +201,7 @@ public: } break; default: { - env->PopLocalFrame(NULL); + env->PopLocalFrame(nullptr); ERR_FAIL_V(Variant()); } break; } @@ -211,7 +211,7 @@ public: to_erase.pop_front(); } - env->PopLocalFrame(NULL); + env->PopLocalFrame(nullptr); return ret; } @@ -235,7 +235,7 @@ public: } JNISingleton() { - instance = NULL; + instance = nullptr; } }; diff --git a/platform/android/os_android.cpp b/platform/android/os_android.cpp index e3792b1f31..760157595c 100644 --- a/platform/android/os_android.cpp +++ b/platform/android/os_android.cpp @@ -32,15 +32,11 @@ #include "core/io/file_access_buffered_fa.h" #include "core/project_settings.h" -#if defined(OPENGL_ENABLED) -#include "drivers/gles2/rasterizer_gles2.h" -#endif #include "drivers/unix/dir_access_unix.h" #include "drivers/unix/file_access_unix.h" #include "file_access_android.h" #include "main/main.h" -#include "servers/visual/visual_server_raster.h" -#include "servers/visual/visual_server_wrap_mt.h" +#include "platform/android/display_server_android.h" #include "dir_access_jandroid.h" #include "file_access_jandroid.h" @@ -60,29 +56,6 @@ public: virtual ~AndroidLogger() {} }; -int OS_Android::get_video_driver_count() const { - - return 2; -} - -const char *OS_Android::get_video_driver_name(int p_driver) const { - - switch (p_driver) { - case VIDEO_DRIVER_GLES2: - return "GLES2"; - } - ERR_FAIL_V_MSG(NULL, "Invalid video driver index: " + itos(p_driver) + "."); -} -int OS_Android::get_audio_driver_count() const { - - return 1; -} - -const char *OS_Android::get_audio_driver_name(int p_driver) const { - - return "Android"; -} - void OS_Android::initialize_core() { OS_Unix::initialize_core(); @@ -110,71 +83,33 @@ void OS_Android::initialize_core() { NetSocketAndroid::make_default(); } -void OS_Android::set_opengl_extensions(const char *p_gl_extensions) { - - ERR_FAIL_COND(!p_gl_extensions); - gl_extensions = p_gl_extensions; -} - -int OS_Android::get_current_video_driver() const { - return video_driver_index; +void OS_Android::initialize() { + initialize_core(); } -Error OS_Android::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { +void OS_Android::initialize_joypads() { + InputFilter::get_singleton()->set_fallback_mapping(godot_java->get_input_fallback_mapping()); - // FIXME: Add Vulkan support. Readd fallback code from Vulkan to GLES2? - -#if defined(OPENGL_ENABLED) - if (video_driver_index == VIDEO_DRIVER_GLES2) { - bool gl_initialization_error = false; - - if (RasterizerGLES2::is_viable() == OK) { - RasterizerGLES2::register_config(); - RasterizerGLES2::make_current(); - } else { - gl_initialization_error = true; - } - - if (gl_initialization_error) { - OS::get_singleton()->alert("Your device does not support any of the supported OpenGL versions.\n" - "Please try updating your Android version.", - "Unable to initialize video driver"); - return ERR_UNAVAILABLE; - } - } -#endif - - video_driver_index = p_video_driver; - - visual_server = memnew(VisualServerRaster); - if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { - visual_server = memnew(VisualServerWrapMT(visual_server, false)); - } - - visual_server->init(); - - AudioDriverManager::initialize(p_audio_driver); - - input = memnew(InputDefault); - input->set_fallback_mapping(godot_java->get_input_fallback_mapping()); - - return OK; + // This queries/updates the currently connected devices/joypads. + godot_java->init_input_devices(); } void OS_Android::set_main_loop(MainLoop *p_main_loop) { - main_loop = p_main_loop; - input->set_main_loop(p_main_loop); } void OS_Android::delete_main_loop() { - - memdelete(main_loop); + if (main_loop) { + memdelete(main_loop); + main_loop = nullptr; + } } void OS_Android::finalize() { +} - memdelete(input); +OS_Android *OS_Android::get_singleton() { + return (OS_Android *)OS::get_singleton(); } GodotJavaWrapper *OS_Android::get_godot_java() { @@ -185,12 +120,6 @@ GodotIOJavaWrapper *OS_Android::get_godot_io_java() { return godot_io_java; } -void OS_Android::alert(const String &p_alert, const String &p_title) { - - //print("ALERT: %s\n", p_alert.utf8().get_data()); - godot_java->alert(p_alert, p_title); -} - bool OS_Android::request_permission(const String &p_name) { return godot_java->request_permission(p_name); @@ -212,63 +141,6 @@ Error OS_Android::open_dynamic_library(const String p_path, void *&p_library_han return OK; } -void OS_Android::set_mouse_show(bool p_show) { - - //android has no mouse... -} - -void OS_Android::set_mouse_grab(bool p_grab) { - - //it really has no mouse...! -} - -bool OS_Android::is_mouse_grab_enabled() const { - - //*sigh* technology has evolved so much since i was a kid.. - return false; -} - -Point2 OS_Android::get_mouse_position() const { - - return Point2(); -} - -int OS_Android::get_mouse_button_state() const { - - return 0; -} - -void OS_Android::set_window_title(const String &p_title) { - //This queries/updates the currently connected devices/joypads - //Set_window_title is called when initializing the main loop (main.cpp) - //therefore this place is found to be suitable (I found no better). - godot_java->init_input_devices(); -} - -void OS_Android::set_video_mode(const VideoMode &p_video_mode, int p_screen) { -} - -OS::VideoMode OS_Android::get_video_mode(int p_screen) const { - - return default_videomode; -} - -void OS_Android::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const { - - p_list->push_back(default_videomode); -} - -void OS_Android::set_keep_screen_on(bool p_enabled) { - OS::set_keep_screen_on(p_enabled); - - godot_java->set_keep_screen_on(p_enabled); -} - -Size2 OS_Android::get_window_size() const { - - return Vector2(default_videomode.width, default_videomode.height); -} - String OS_Android::get_name() const { return "Android"; @@ -279,11 +151,6 @@ MainLoop *OS_Android::get_main_loop() const { return main_loop; } -bool OS_Android::can_draw() const { - - return true; //always? -} - void OS_Android::main_loop_begin() { if (main_loop) @@ -304,277 +171,17 @@ void OS_Android::main_loop_end() { } void OS_Android::main_loop_focusout() { - - if (main_loop) - main_loop->notification(NOTIFICATION_WM_FOCUS_OUT); + DisplayServerAndroid::get_singleton()->send_window_event(DisplayServer::WINDOW_EVENT_FOCUS_OUT); audio_driver_android.set_pause(true); } void OS_Android::main_loop_focusin() { - - if (main_loop) - main_loop->notification(NOTIFICATION_WM_FOCUS_IN); + DisplayServerAndroid::get_singleton()->send_window_event(DisplayServer::WINDOW_EVENT_FOCUS_IN); audio_driver_android.set_pause(false); } -void OS_Android::process_joy_event(OS_Android::JoypadEvent p_event) { - - switch (p_event.type) { - case JOY_EVENT_BUTTON: - input->joy_button(p_event.device, p_event.index, p_event.pressed); - break; - case JOY_EVENT_AXIS: - InputDefault::JoyAxis value; - value.min = -1; - value.value = p_event.value; - input->joy_axis(p_event.device, p_event.index, value); - break; - case JOY_EVENT_HAT: - input->joy_hat(p_event.device, p_event.hat); - break; - default: - return; - } -} - -void OS_Android::process_event(Ref<InputEvent> p_event) { - - input->parse_input_event(p_event); -} - -void OS_Android::process_touch(int p_what, int p_pointer, const Vector<TouchPos> &p_points) { - - switch (p_what) { - case 0: { //gesture begin - - if (touch.size()) { - //end all if exist - for (int i = 0; i < touch.size(); i++) { - - Ref<InputEventScreenTouch> ev; - ev.instance(); - ev->set_index(touch[i].id); - ev->set_pressed(false); - ev->set_position(touch[i].pos); - input->parse_input_event(ev); - } - } - - touch.resize(p_points.size()); - for (int i = 0; i < p_points.size(); i++) { - touch.write[i].id = p_points[i].id; - touch.write[i].pos = p_points[i].pos; - } - - //send touch - for (int i = 0; i < touch.size(); i++) { - - Ref<InputEventScreenTouch> ev; - ev.instance(); - ev->set_index(touch[i].id); - ev->set_pressed(true); - ev->set_position(touch[i].pos); - input->parse_input_event(ev); - } - - } break; - case 1: { //motion - - ERR_FAIL_COND(touch.size() != p_points.size()); - - for (int i = 0; i < touch.size(); i++) { - - int idx = -1; - for (int j = 0; j < p_points.size(); j++) { - - if (touch[i].id == p_points[j].id) { - idx = j; - break; - } - } - - ERR_CONTINUE(idx == -1); - - if (touch[i].pos == p_points[idx].pos) - continue; //no move unncesearily - - Ref<InputEventScreenDrag> ev; - ev.instance(); - ev->set_index(touch[i].id); - ev->set_position(p_points[idx].pos); - ev->set_relative(p_points[idx].pos - touch[i].pos); - input->parse_input_event(ev); - touch.write[i].pos = p_points[idx].pos; - } - - } break; - case 2: { //release - - if (touch.size()) { - //end all if exist - for (int i = 0; i < touch.size(); i++) { - - Ref<InputEventScreenTouch> ev; - ev.instance(); - ev->set_index(touch[i].id); - ev->set_pressed(false); - ev->set_position(touch[i].pos); - input->parse_input_event(ev); - } - touch.clear(); - } - } break; - case 3: { // add touch - - for (int i = 0; i < p_points.size(); i++) { - if (p_points[i].id == p_pointer) { - TouchPos tp = p_points[i]; - touch.push_back(tp); - - Ref<InputEventScreenTouch> ev; - ev.instance(); - - ev->set_index(tp.id); - ev->set_pressed(true); - ev->set_position(tp.pos); - input->parse_input_event(ev); - - break; - } - } - } break; - case 4: { // remove touch - - for (int i = 0; i < touch.size(); i++) { - if (touch[i].id == p_pointer) { - - Ref<InputEventScreenTouch> ev; - ev.instance(); - ev->set_index(touch[i].id); - ev->set_pressed(false); - ev->set_position(touch[i].pos); - input->parse_input_event(ev); - touch.remove(i); - - break; - } - } - } break; - } -} - -void OS_Android::process_hover(int p_type, Point2 p_pos) { - // https://developer.android.com/reference/android/view/MotionEvent.html#ACTION_HOVER_ENTER - switch (p_type) { - case 7: // hover move - case 9: // hover enter - case 10: { // hover exit - Ref<InputEventMouseMotion> ev; - ev.instance(); - ev->set_position(p_pos); - ev->set_global_position(p_pos); - ev->set_relative(p_pos - hover_prev_pos); - input->parse_input_event(ev); - hover_prev_pos = p_pos; - } break; - } -} - -void OS_Android::process_double_tap(Point2 p_pos) { - Ref<InputEventMouseButton> ev; - ev.instance(); - ev->set_position(p_pos); - ev->set_global_position(p_pos); - ev->set_pressed(false); - ev->set_doubleclick(true); - input->parse_input_event(ev); -} - -void OS_Android::process_scroll(Point2 p_pos) { - Ref<InputEventPanGesture> ev; - ev.instance(); - ev->set_position(p_pos); - ev->set_delta(p_pos - scroll_prev_pos); - input->parse_input_event(ev); - scroll_prev_pos = p_pos; -} - -void OS_Android::process_accelerometer(const Vector3 &p_accelerometer) { - - input->set_accelerometer(p_accelerometer); -} - -void OS_Android::process_gravity(const Vector3 &p_gravity) { - - input->set_gravity(p_gravity); -} - -void OS_Android::process_magnetometer(const Vector3 &p_magnetometer) { - - input->set_magnetometer(p_magnetometer); -} - -void OS_Android::process_gyroscope(const Vector3 &p_gyroscope) { - - input->set_gyroscope(p_gyroscope); -} - -bool OS_Android::has_touchscreen_ui_hint() const { - - return true; -} - -bool OS_Android::has_virtual_keyboard() const { - - return true; -} - -int OS_Android::get_virtual_keyboard_height() const { - return godot_io_java->get_vk_height(); - - // ERR_PRINT("Cannot obtain virtual keyboard height."); - // return 0; -} - -void OS_Android::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect, int p_max_input_length) { - - if (godot_io_java->has_vk()) { - godot_io_java->show_vk(p_existing_text, p_max_input_length); - } else { - - ERR_PRINT("Virtual keyboard not available"); - }; -} - -void OS_Android::hide_virtual_keyboard() { - - if (godot_io_java->has_vk()) { - - godot_io_java->hide_vk(); - } else { - - ERR_PRINT("Virtual keyboard not available"); - }; -} - -void OS_Android::init_video_mode(int p_video_width, int p_video_height) { - - default_videomode.width = p_video_width; - default_videomode.height = p_video_height; - default_videomode.fullscreen = true; - default_videomode.resizable = false; -} - void OS_Android::main_loop_request_go_back() { - - if (main_loop) - main_loop->notification(NOTIFICATION_WM_GO_BACK_REQUEST); -} - -void OS_Android::set_display_size(Size2 p_size) { - - default_videomode.width = p_size.x; - default_videomode.height = p_size.y; + DisplayServerAndroid::get_singleton()->send_window_event(DisplayServer::WINDOW_EVENT_GO_BACK_REQUEST); } Error OS_Android::shell_open(String p_uri) { @@ -597,26 +204,6 @@ String OS_Android::get_locale() const { return OS_Unix::get_locale(); } -void OS_Android::set_clipboard(const String &p_text) { - - // DO we really need the fallback to OS_Unix here?! - if (godot_java->has_set_clipboard()) { - godot_java->set_clipboard(p_text); - } else { - OS_Unix::set_clipboard(p_text); - } -} - -String OS_Android::get_clipboard() const { - - // DO we really need the fallback to OS_Unix here?! - if (godot_java->has_get_clipboard()) { - return godot_java->get_clipboard(); - } - - return OS_Unix::get_clipboard(); -} - String OS_Android::get_model_name() const { String model = godot_io_java->get_model(); @@ -626,11 +213,6 @@ String OS_Android::get_model_name() const { return OS_Unix::get_model_name(); } -int OS_Android::get_screen_dpi(int p_screen) const { - - return godot_io_java->get_screen_dpi(); -} - String OS_Android::get_user_data_dir() const { if (data_dir_cache != String()) @@ -662,11 +244,6 @@ String OS_Android::get_user_data_dir() const { return "."; } -void OS_Android::set_screen_orientation(ScreenOrientation p_orientation) { - - godot_io_java->set_screen_orientation(p_orientation); -} - String OS_Android::get_unique_id() const { String unique_id = godot_io_java->get_unique_id(); @@ -676,50 +253,46 @@ String OS_Android::get_unique_id() const { return OS::get_unique_id(); } -Error OS_Android::native_video_play(String p_path, float p_volume, String p_audio_track, String p_subtitle_track) { - // FIXME: Add support for volume, audio and subtitle tracks - - godot_io_java->play_video(p_path); - return OK; -} - -bool OS_Android::native_video_is_playing() const { - - return godot_io_java->is_video_playing(); -} - -void OS_Android::native_video_pause() { - - godot_io_java->pause_video(); -} - String OS_Android::get_system_dir(SystemDir p_dir) const { return godot_io_java->get_system_dir(p_dir); } -void OS_Android::native_video_stop() { +void OS_Android::set_display_size(const Size2i &p_size) { + display_size = p_size; +} - godot_io_java->stop_video(); +Size2i OS_Android::get_display_size() const { + return display_size; } void OS_Android::set_context_is_16_bits(bool p_is_16) { - +#if defined(OPENGL_ENABLED) //use_16bits_fbo = p_is_16; //if (rasterizer) // rasterizer->set_force_16_bits_fbo(p_is_16); +#endif } -void OS_Android::joy_connection_changed(int p_device, bool p_connected, String p_name) { - return input->joy_connection_changed(p_device, p_connected, p_name, ""); +void OS_Android::set_opengl_extensions(const char *p_gl_extensions) { +#if defined(OPENGL_ENABLED) + ERR_FAIL_COND(!p_gl_extensions); + gl_extensions = p_gl_extensions; +#endif } -bool OS_Android::is_joy_known(int p_device) { - return input->is_joy_mapped(p_device); +void OS_Android::set_native_window(ANativeWindow *p_native_window) { +#if defined(VULKAN_ENABLED) + native_window = p_native_window; +#endif } -String OS_Android::get_joy_guid(int p_device) const { - return input->get_joy_guid_remapped(p_device); +ANativeWindow *OS_Android::get_native_window() const { +#if defined(VULKAN_ENABLED) + return native_window; +#else + return nullptr; +#endif } void OS_Android::vibrate_handheld(int p_duration_ms) { @@ -747,19 +320,21 @@ bool OS_Android::_check_internal_feature_support(const String &p_feature) { } OS_Android::OS_Android(GodotJavaWrapper *p_godot_java, GodotIOJavaWrapper *p_godot_io_java, bool p_use_apk_expansion) { + display_size.width = 800; + display_size.height = 600; use_apk_expansion = p_use_apk_expansion; - default_videomode.width = 800; - default_videomode.height = 600; - default_videomode.fullscreen = true; - default_videomode.resizable = false; - - main_loop = NULL; - gl_extensions = NULL; - //rasterizer = NULL; + + main_loop = nullptr; + +#if defined(OPENGL_ENABLED) + gl_extensions = nullptr; use_gl2 = false; +#endif - visual_server = NULL; +#if defined(VULKAN_ENABLED) + native_window = nullptr; +#endif godot_java = p_godot_java; godot_io_java = p_godot_io_java; @@ -769,6 +344,8 @@ OS_Android::OS_Android(GodotJavaWrapper *p_godot_java, GodotIOJavaWrapper *p_god _set_logger(memnew(CompositeLogger(loggers))); AudioDriverManager::add_driver(&audio_driver_android); + + DisplayServerAndroid::register_android_driver(); } OS_Android::~OS_Android() { diff --git a/platform/android/os_android.h b/platform/android/os_android.h index d09f4e10d6..cac7efaa88 100644 --- a/platform/android/os_android.h +++ b/platform/android/os_android.h @@ -33,78 +33,45 @@ #include "audio_driver_jandroid.h" #include "audio_driver_opensl.h" -#include "core/input/input_filter.h" #include "core/os/main_loop.h" #include "drivers/unix/os_unix.h" #include "servers/audio_server.h" -#include "servers/visual/rasterizer.h" class GodotJavaWrapper; class GodotIOJavaWrapper; -class OS_Android : public OS_Unix { -public: - struct TouchPos { - int id; - Point2 pos; - }; - - enum { - JOY_EVENT_BUTTON = 0, - JOY_EVENT_AXIS = 1, - JOY_EVENT_HAT = 2 - }; - - struct JoypadEvent { - - int device; - int type; - int index; - bool pressed; - float value; - int hat; - }; +struct ANativeWindow; +class OS_Android : public OS_Unix { private: - Vector<TouchPos> touch; - Point2 hover_prev_pos; // needed to calculate the relative position on hover events - Point2 scroll_prev_pos; // needed to calculate the relative position on scroll events + Size2i display_size; - bool use_gl2; bool use_apk_expansion; +#if defined(OPENGL_ENABLED) bool use_16bits_fbo; + const char *gl_extensions; +#endif - VisualServer *visual_server; +#if defined(VULKAN_ENABLED) + ANativeWindow *native_window; +#endif mutable String data_dir_cache; //AudioDriverAndroid audio_driver_android; AudioDriverOpenSL audio_driver_android; - const char *gl_extensions; - - InputDefault *input; - VideoMode default_videomode; MainLoop *main_loop; GodotJavaWrapper *godot_java; GodotIOJavaWrapper *godot_io_java; - int video_driver_index; - public: - // functions used by main to initialize/deinitialize the OS - virtual int get_video_driver_count() const; - virtual const char *get_video_driver_name(int p_driver) const; - - virtual int get_audio_driver_count() const; - virtual const char *get_audio_driver_name(int p_driver) const; - - virtual int get_current_video_driver() const; - virtual void initialize_core(); - virtual Error initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver); + virtual void initialize(); + + virtual void initialize_joypads(); virtual void set_main_loop(MainLoop *p_main_loop); virtual void delete_main_loop(); @@ -113,37 +80,19 @@ public: typedef int64_t ProcessID; - static OS *get_singleton(); + static OS_Android *get_singleton(); GodotJavaWrapper *get_godot_java(); GodotIOJavaWrapper *get_godot_io_java(); - virtual void alert(const String &p_alert, const String &p_title = "ALERT!"); virtual bool request_permission(const String &p_name); virtual bool request_permissions(); virtual Vector<String> get_granted_permissions() const; virtual Error open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path = false); - virtual void set_mouse_show(bool p_show); - virtual void set_mouse_grab(bool p_grab); - virtual bool is_mouse_grab_enabled() const; - virtual Point2 get_mouse_position() const; - virtual int get_mouse_button_state() const; - virtual void set_window_title(const String &p_title); - - virtual void set_video_mode(const VideoMode &p_video_mode, int p_screen = 0); - virtual VideoMode get_video_mode(int p_screen = 0) const; - virtual void get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen = 0) const; - - virtual void set_keep_screen_on(bool p_enabled); - - virtual Size2 get_window_size() const; - virtual String get_name() const; virtual MainLoop *get_main_loop() const; - virtual bool can_draw() const; - void main_loop_begin(); bool main_loop_iterate(); void main_loop_request_go_back(); @@ -151,53 +100,25 @@ public: void main_loop_focusout(); void main_loop_focusin(); - virtual bool has_touchscreen_ui_hint() const; - - virtual bool has_virtual_keyboard() const; - virtual void show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect = Rect2(), int p_max_input_length = -1); - virtual void hide_virtual_keyboard(); - virtual int get_virtual_keyboard_height() const; - - void set_opengl_extensions(const char *p_gl_extensions); - void set_display_size(Size2 p_size); + void set_display_size(const Size2i &p_size); + Size2i get_display_size() const; void set_context_is_16_bits(bool p_is_16); + void set_opengl_extensions(const char *p_gl_extensions); - virtual void set_screen_orientation(ScreenOrientation p_orientation); + void set_native_window(ANativeWindow *p_native_window); + ANativeWindow *get_native_window() const; virtual Error shell_open(String p_uri); virtual String get_user_data_dir() const; virtual String get_resource_dir() const; virtual String get_locale() const; - virtual void set_clipboard(const String &p_text); - virtual String get_clipboard() const; virtual String get_model_name() const; - virtual int get_screen_dpi(int p_screen = 0) const; virtual String get_unique_id() const; virtual String get_system_dir(SystemDir p_dir) const; - void process_accelerometer(const Vector3 &p_accelerometer); - void process_gravity(const Vector3 &p_gravity); - void process_magnetometer(const Vector3 &p_magnetometer); - void process_gyroscope(const Vector3 &p_gyroscope); - void process_touch(int p_what, int p_pointer, const Vector<TouchPos> &p_points); - void process_hover(int p_type, Point2 p_pos); - void process_double_tap(Point2 p_pos); - void process_scroll(Point2 p_pos); - void process_joy_event(JoypadEvent p_event); - void process_event(Ref<InputEvent> p_event); - void init_video_mode(int p_video_width, int p_video_height); - - virtual Error native_video_play(String p_path, float p_volume, String p_audio_track, String p_subtitle_track); - virtual bool native_video_is_playing() const; - virtual void native_video_pause(); - virtual void native_video_stop(); - - virtual bool is_joy_known(int p_device); - virtual String get_joy_guid(int p_device) const; - void joy_connection_changed(int p_device, bool p_connected, String p_name); void vibrate_handheld(int p_duration_ms); virtual bool _check_internal_feature_support(const String &p_feature); diff --git a/platform/android/string_android.h b/platform/android/string_android.h index 51c488c8cc..88ccd3b652 100644 --- a/platform/android/string_android.h +++ b/platform/android/string_android.h @@ -40,13 +40,13 @@ * @param env JNI environment instance. If null obtained by ThreadAndroid::get_env(). * @return Godot string instance. */ -static inline String jstring_to_string(jstring source, JNIEnv *env = NULL) { +static inline String jstring_to_string(jstring source, JNIEnv *env = nullptr) { String result; if (source) { if (!env) { env = ThreadAndroid::get_env(); } - const char *const source_utf8 = env->GetStringUTFChars(source, NULL); + const char *const source_utf8 = env->GetStringUTFChars(source, nullptr); if (source_utf8) { result.parse_utf8(source_utf8); env->ReleaseStringUTFChars(source, source_utf8); diff --git a/platform/android/thread_jandroid.cpp b/platform/android/thread_jandroid.cpp index 98b61ad755..729327f6f0 100644 --- a/platform/android/thread_jandroid.cpp +++ b/platform/android/thread_jandroid.cpp @@ -66,7 +66,7 @@ void *ThreadAndroid::thread_callback(void *userdata) { pthread_setspecific(thread_id_key, (void *)memnew(ID(t->id))); t->callback(t->user); ScriptServer::thread_exit(); - return NULL; + return nullptr; } Thread *ThreadAndroid::create_func_jandroid(ThreadCreateCallback p_callback, void *p_user, const Settings &) { @@ -100,7 +100,7 @@ void ThreadAndroid::wait_to_finish_func_jandroid(Thread *p_thread) { ERR_FAIL_COND(!tp); ERR_FAIL_COND(tp->pthread == 0); - pthread_join(tp->pthread, NULL); + pthread_join(tp->pthread, nullptr); tp->pthread = 0; } @@ -108,21 +108,21 @@ void ThreadAndroid::_thread_destroyed(void *value) { /* The thread is being destroyed, detach it from the Java VM and set the mThreadKey value to NULL as required */ JNIEnv *env = (JNIEnv *)value; - if (env != NULL) { + if (env != nullptr) { java_vm->DetachCurrentThread(); - pthread_setspecific(jvm_key, NULL); + pthread_setspecific(jvm_key, nullptr); } } pthread_key_t ThreadAndroid::jvm_key; -JavaVM *ThreadAndroid::java_vm = NULL; +JavaVM *ThreadAndroid::java_vm = nullptr; void ThreadAndroid::setup_thread() { if (pthread_getspecific(jvm_key)) return; //already setup JNIEnv *env; - java_vm->AttachCurrentThread(&env, NULL); + java_vm->AttachCurrentThread(&env, nullptr); pthread_setspecific(jvm_key, (void *)env); } @@ -142,8 +142,8 @@ JNIEnv *ThreadAndroid::get_env() { setup_thread(); } - JNIEnv *env = NULL; - java_vm->AttachCurrentThread(&env, NULL); + JNIEnv *env = nullptr; + java_vm->AttachCurrentThread(&env, nullptr); return env; } diff --git a/platform/android/vulkan/vulkan_context_android.cpp b/platform/android/vulkan/vulkan_context_android.cpp new file mode 100644 index 0000000000..5fb7a83da4 --- /dev/null +++ b/platform/android/vulkan/vulkan_context_android.cpp @@ -0,0 +1,60 @@ +/*************************************************************************/ +/* vulkan_context_android.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "vulkan_context_android.h" +#include <vulkan/vulkan_android.h> + +const char *VulkanContextAndroid::_get_platform_surface_extension() const { + return VK_KHR_ANDROID_SURFACE_EXTENSION_NAME; +} + +int VulkanContextAndroid::window_create(ANativeWindow *p_window, int p_width, int p_height) { + VkAndroidSurfaceCreateInfoKHR createInfo; + createInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR; + createInfo.pNext = nullptr; + createInfo.flags = 0; + createInfo.window = p_window; + + VkSurfaceKHR surface; + VkResult err = vkCreateAndroidSurfaceKHR(_get_instance(), &createInfo, nullptr, &surface); + if (err != VK_SUCCESS) { + ERR_FAIL_V_MSG(-1, "vkCreateAndroidSurfaceKHR failed with error " + itos(err)); + } + + return _window_create(DisplayServer::MAIN_WINDOW_ID, surface, p_width, p_height); +} + +VulkanContextAndroid::VulkanContextAndroid() { + // TODO: fix validation layers + use_validation_layers = false; +} + +VulkanContextAndroid::~VulkanContextAndroid() { +} diff --git a/platform/android/vulkan/vk_renderer_jni.cpp b/platform/android/vulkan/vulkan_context_android.h index 3026e7daad..7e698ada4f 100644 --- a/platform/android/vulkan/vk_renderer_jni.cpp +++ b/platform/android/vulkan/vulkan_context_android.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* vk_renderer_jni.cpp */ +/* vulkan_context_android.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,31 +28,22 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "vk_renderer_jni.h" +#ifndef VULKAN_CONTEXT_ANDROID_H +#define VULKAN_CONTEXT_ANDROID_H -extern "C" { +#include "drivers/vulkan/vulkan_context.h" -JNIEXPORT void JNICALL Java_org_godotengine_godot_vulkan_VkRenderer_nativeOnVkSurfaceCreated(JNIEnv *env, jobject obj, jobject j_surface) { - // TODO: complete -} +struct ANativeWindow; -JNIEXPORT void JNICALL Java_org_godotengine_godot_vulkan_VkRenderer_nativeOnVkSurfaceChanged(JNIEnv *env, jobject object, jobject j_surface, jint width, jint height) { - // TODO: complete -} +class VulkanContextAndroid : public VulkanContext { -JNIEXPORT void JNICALL Java_org_godotengine_godot_vulkan_VkRenderer_nativeOnVkResume(JNIEnv *env, jobject obj) { - // TODO: complete -} + virtual const char *_get_platform_surface_extension() const; -JNIEXPORT void JNICALL Java_org_godotengine_godot_vulkan_VkRenderer_nativeOnVkDrawFrame(JNIEnv *env, jobject obj) { - // TODO: complete -} +public: + int window_create(ANativeWindow *p_window, int p_width, int p_height); -JNIEXPORT void JNICALL Java_org_godotengine_godot_vulkan_VkRenderer_nativeOnVkPause(JNIEnv *env, jobject obj) { - // TODO: complete -} + VulkanContextAndroid(); + ~VulkanContextAndroid(); +}; -JNIEXPORT void JNICALL Java_org_godotengine_godot_vulkan_VkRenderer_nativeOnVkDestroy(JNIEnv *env, jobject obj) { - // TODO: complete -} -} +#endif // VULKAN_CONTEXT_ANDROID_H diff --git a/platform/haiku/SCsub b/platform/haiku/SCsub index 592f56bbbf..dbff6c5ae9 100644 --- a/platform/haiku/SCsub +++ b/platform/haiku/SCsub @@ -1,28 +1,25 @@ #!/usr/bin/env python -Import('env') +Import("env") common_haiku = [ - 'os_haiku.cpp', - 'context_gl_haiku.cpp', - 'haiku_application.cpp', - 'haiku_direct_window.cpp', - 'haiku_gl_view.cpp', - 'key_mapping_haiku.cpp', - 'audio_driver_media_kit.cpp' + "os_haiku.cpp", + "context_gl_haiku.cpp", + "haiku_application.cpp", + "haiku_direct_window.cpp", + "haiku_gl_view.cpp", + "key_mapping_haiku.cpp", + "audio_driver_media_kit.cpp", ] -target = env.add_program( - '#bin/godot', - ['godot_haiku.cpp'] + common_haiku -) +target = env.add_program("#bin/godot", ["godot_haiku.cpp"] + common_haiku) -command = env.Command('#bin/godot.rsrc', '#platform/haiku/godot.rdef', - ['rc -o $TARGET $SOURCE']) +command = env.Command("#bin/godot.rsrc", "#platform/haiku/godot.rdef", ["rc -o $TARGET $SOURCE"]) def addResourcesAction(target=None, source=None, env=None): - return env.Execute('xres -o ' + File(target)[0].path + ' bin/godot.rsrc') + return env.Execute("xres -o " + File(target)[0].path + " bin/godot.rsrc") + env.AddPostAction(target, addResourcesAction) env.Depends(target, command) diff --git a/platform/haiku/audio_driver_media_kit.cpp b/platform/haiku/audio_driver_media_kit.cpp index 0a5df14743..94c9e83368 100644 --- a/platform/haiku/audio_driver_media_kit.cpp +++ b/platform/haiku/audio_driver_media_kit.cpp @@ -34,7 +34,7 @@ #include "core/project_settings.h" -int32_t *AudioDriverMediaKit::samples_in = NULL; +int32_t *AudioDriverMediaKit::samples_in = nullptr; Error AudioDriverMediaKit::init() { active = false; @@ -59,12 +59,12 @@ Error AudioDriverMediaKit::init() { &format, "godot_sound_server", AudioDriverMediaKit::PlayBuffer, - NULL, + nullptr, this); if (player->InitCheck() != B_OK) { fprintf(stderr, "MediaKit ERR: can not create a BSoundPlayer instance\n"); - ERR_FAIL_COND_V(player == NULL, ERR_CANT_OPEN); + ERR_FAIL_COND_V(player == nullptr, ERR_CANT_OPEN); } player->Start(); @@ -126,7 +126,7 @@ void AudioDriverMediaKit::finish() { } AudioDriverMediaKit::AudioDriverMediaKit() { - player = NULL; + player = nullptr; } AudioDriverMediaKit::~AudioDriverMediaKit() { diff --git a/platform/haiku/detect.py b/platform/haiku/detect.py index dd72294816..0b84df8f9b 100644 --- a/platform/haiku/detect.py +++ b/platform/haiku/detect.py @@ -12,7 +12,7 @@ def get_name(): def can_build(): - if (os.name != "posix" or sys.platform == "darwin"): + if os.name != "posix" or sys.platform == "darwin": return False return True @@ -22,41 +22,40 @@ def get_opts(): from SCons.Variables import EnumVariable return [ - EnumVariable('debug_symbols', 'Add debugging symbols to release builds', 'yes', ('yes', 'no', 'full')), + EnumVariable("debug_symbols", "Add debugging symbols to release builds", "yes", ("yes", "no", "full")), ] def get_flags(): - return [ - ] + return [] def configure(env): ## Build type - if (env["target"] == "release"): - env.Prepend(CCFLAGS=['-O3']) - if (env["debug_symbols"] == "yes"): - env.Prepend(CCFLAGS=['-g1']) - if (env["debug_symbols"] == "full"): - env.Prepend(CCFLAGS=['-g2']) + if env["target"] == "release": + env.Prepend(CCFLAGS=["-O3"]) + if env["debug_symbols"] == "yes": + env.Prepend(CCFLAGS=["-g1"]) + if env["debug_symbols"] == "full": + env.Prepend(CCFLAGS=["-g2"]) - elif (env["target"] == "release_debug"): - env.Prepend(CCFLAGS=['-O2', '-DDEBUG_ENABLED']) - if (env["debug_symbols"] == "yes"): - env.Prepend(CCFLAGS=['-g1']) - if (env["debug_symbols"] == "full"): - env.Prepend(CCFLAGS=['-g2']) + elif env["target"] == "release_debug": + env.Prepend(CCFLAGS=["-O2", "-DDEBUG_ENABLED"]) + if env["debug_symbols"] == "yes": + env.Prepend(CCFLAGS=["-g1"]) + if env["debug_symbols"] == "full": + env.Prepend(CCFLAGS=["-g2"]) - elif (env["target"] == "debug"): - env.Prepend(CCFLAGS=['-g3', '-DDEBUG_ENABLED', '-DDEBUG_MEMORY_ENABLED']) + elif env["target"] == "debug": + env.Prepend(CCFLAGS=["-g3", "-DDEBUG_ENABLED", "-DDEBUG_MEMORY_ENABLED"]) ## Architecture - is64 = sys.maxsize > 2**32 - if (env["bits"] == "default"): + is64 = sys.maxsize > 2 ** 32 + if env["bits"] == "default": env["bits"] = "64" if is64 else "32" ## Compiler configuration @@ -66,89 +65,94 @@ def configure(env): ## Dependencies - if not env['builtin_libwebp']: - env.ParseConfig('pkg-config libwebp --cflags --libs') + if not env["builtin_libwebp"]: + env.ParseConfig("pkg-config libwebp --cflags --libs") # freetype depends on libpng and zlib, so bundling one of them while keeping others # as shared libraries leads to weird issues - if env['builtin_freetype'] or env['builtin_libpng'] or env['builtin_zlib']: - env['builtin_freetype'] = True - env['builtin_libpng'] = True - env['builtin_zlib'] = True + if env["builtin_freetype"] or env["builtin_libpng"] or env["builtin_zlib"]: + env["builtin_freetype"] = True + env["builtin_libpng"] = True + env["builtin_zlib"] = True - if not env['builtin_freetype']: - env.ParseConfig('pkg-config freetype2 --cflags --libs') + if not env["builtin_freetype"]: + env.ParseConfig("pkg-config freetype2 --cflags --libs") - if not env['builtin_libpng']: - env.ParseConfig('pkg-config libpng16 --cflags --libs') + if not env["builtin_libpng"]: + env.ParseConfig("pkg-config libpng16 --cflags --libs") - if not env['builtin_bullet']: + if not env["builtin_bullet"]: # We need at least version 2.88 import subprocess - bullet_version = subprocess.check_output(['pkg-config', 'bullet', '--modversion']).strip() + + bullet_version = subprocess.check_output(["pkg-config", "bullet", "--modversion"]).strip() if bullet_version < "2.88": # Abort as system bullet was requested but too old - print("Bullet: System version {0} does not match minimal requirements ({1}). Aborting.".format(bullet_version, "2.88")) + print( + "Bullet: System version {0} does not match minimal requirements ({1}). Aborting.".format( + bullet_version, "2.88" + ) + ) sys.exit(255) - env.ParseConfig('pkg-config bullet --cflags --libs') + env.ParseConfig("pkg-config bullet --cflags --libs") - if not env['builtin_enet']: - env.ParseConfig('pkg-config libenet --cflags --libs') + if not env["builtin_enet"]: + env.ParseConfig("pkg-config libenet --cflags --libs") - if not env['builtin_squish']: - env.ParseConfig('pkg-config libsquish --cflags --libs') + if not env["builtin_squish"]: + env.ParseConfig("pkg-config libsquish --cflags --libs") - if not env['builtin_zstd']: - env.ParseConfig('pkg-config libzstd --cflags --libs') + if not env["builtin_zstd"]: + env.ParseConfig("pkg-config libzstd --cflags --libs") # Sound and video libraries # Keep the order as it triggers chained dependencies (ogg needed by others, etc.) - if not env['builtin_libtheora']: - env['builtin_libogg'] = False # Needed to link against system libtheora - env['builtin_libvorbis'] = False # Needed to link against system libtheora - env.ParseConfig('pkg-config theora theoradec --cflags --libs') + if not env["builtin_libtheora"]: + env["builtin_libogg"] = False # Needed to link against system libtheora + env["builtin_libvorbis"] = False # Needed to link against system libtheora + env.ParseConfig("pkg-config theora theoradec --cflags --libs") - if not env['builtin_libvpx']: - env.ParseConfig('pkg-config vpx --cflags --libs') + if not env["builtin_libvpx"]: + env.ParseConfig("pkg-config vpx --cflags --libs") - if not env['builtin_libvorbis']: - env['builtin_libogg'] = False # Needed to link against system libvorbis - env.ParseConfig('pkg-config vorbis vorbisfile --cflags --libs') + if not env["builtin_libvorbis"]: + env["builtin_libogg"] = False # Needed to link against system libvorbis + env.ParseConfig("pkg-config vorbis vorbisfile --cflags --libs") - if not env['builtin_opus']: - env['builtin_libogg'] = False # Needed to link against system opus - env.ParseConfig('pkg-config opus opusfile --cflags --libs') + if not env["builtin_opus"]: + env["builtin_libogg"] = False # Needed to link against system opus + env.ParseConfig("pkg-config opus opusfile --cflags --libs") - if not env['builtin_libogg']: - env.ParseConfig('pkg-config ogg --cflags --libs') + if not env["builtin_libogg"]: + env.ParseConfig("pkg-config ogg --cflags --libs") - if env['builtin_libtheora']: - list_of_x86 = ['x86_64', 'x86', 'i386', 'i586'] + if env["builtin_libtheora"]: + list_of_x86 = ["x86_64", "x86", "i386", "i586"] if any(platform.machine() in s for s in list_of_x86): env["x86_libtheora_opt_gcc"] = True - if not env['builtin_wslay']: - env.ParseConfig('pkg-config libwslay --cflags --libs') + if not env["builtin_wslay"]: + env.ParseConfig("pkg-config libwslay --cflags --libs") - if not env['builtin_mbedtls']: + if not env["builtin_mbedtls"]: # mbedTLS does not provide a pkgconfig config yet. See https://github.com/ARMmbed/mbedtls/issues/228 - env.Append(LIBS=['mbedtls', 'mbedcrypto', 'mbedx509']) + env.Append(LIBS=["mbedtls", "mbedcrypto", "mbedx509"]) - if not env['builtin_miniupnpc']: + if not env["builtin_miniupnpc"]: # No pkgconfig file so far, hardcode default paths. env.Prepend(CPPPATH=["/system/develop/headers/x86/miniupnpc"]) env.Append(LIBS=["miniupnpc"]) # On Linux wchar_t should be 32-bits # 16-bit library shouldn't be required due to compiler optimisations - if not env['builtin_pcre2']: - env.ParseConfig('pkg-config libpcre2-32 --cflags --libs') + if not env["builtin_pcre2"]: + env.ParseConfig("pkg-config libpcre2-32 --cflags --libs") ## Flags - env.Prepend(CPPPATH=['#platform/haiku']) - env.Append(CPPDEFINES=['UNIX_ENABLED', 'OPENGL_ENABLED', 'GLES_ENABLED']) - env.Append(CPPDEFINES=['MEDIA_KIT_ENABLED']) - env.Append(CPPDEFINES=['PTHREAD_NO_RENAME']) # TODO: enable when we have pthread_setname_np - env.Append(LIBS=['be', 'game', 'media', 'network', 'bnetapi', 'z', 'GL']) + env.Prepend(CPPPATH=["#platform/haiku"]) + env.Append(CPPDEFINES=["UNIX_ENABLED", "OPENGL_ENABLED", "GLES_ENABLED"]) + env.Append(CPPDEFINES=["MEDIA_KIT_ENABLED"]) + env.Append(CPPDEFINES=["PTHREAD_NO_RENAME"]) # TODO: enable when we have pthread_setname_np + env.Append(LIBS=["be", "game", "media", "network", "bnetapi", "z", "GL"]) diff --git a/platform/haiku/haiku_direct_window.cpp b/platform/haiku/haiku_direct_window.cpp index 18e1862d33..0a40f847f4 100644 --- a/platform/haiku/haiku_direct_window.cpp +++ b/platform/haiku/haiku_direct_window.cpp @@ -42,10 +42,10 @@ HaikuDirectWindow::HaikuDirectWindow(BRect p_frame) : last_button_mask = 0; last_key_modifier_state = 0; - view = NULL; - update_runner = NULL; - input = NULL; - main_loop = NULL; + view = nullptr; + update_runner = nullptr; + input = nullptr; + main_loop = nullptr; } HaikuDirectWindow::~HaikuDirectWindow() { @@ -278,7 +278,7 @@ void HaikuDirectWindow::HandleKeyboardEvent(BMessage *message) { event->set_echo(message->HasInt32("be:key_repeat")); event->set_unicode(0); - const char *bytes = NULL; + const char *bytes = nullptr; if (message->FindString("bytes", &bytes) == B_OK) { event->set_unicode(BUnicodeChar::FromUTF8(&bytes)); } diff --git a/platform/haiku/os_haiku.cpp b/platform/haiku/os_haiku.cpp index a082ba53f9..07cb18d7cd 100644 --- a/platform/haiku/os_haiku.cpp +++ b/platform/haiku/os_haiku.cpp @@ -32,9 +32,9 @@ #include "drivers/gles2/rasterizer_gles2.h" #include "main/main.h" -#include "servers/physics/physics_server_sw.h" -#include "servers/visual/visual_server_raster.h" -#include "servers/visual/visual_server_wrap_mt.h" +#include "servers/physics_3d/physics_server_3d_sw.h" +#include "servers/rendering/rendering_server_raster.h" +#include "servers/rendering/rendering_server_wrap_mt.h" #include <Screen.h> @@ -85,7 +85,7 @@ int OS_Haiku::get_current_video_driver() const { } Error OS_Haiku::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { - main_loop = NULL; + main_loop = nullptr; current_video_mode = p_desired; app = new HaikuApplication(); @@ -116,13 +116,13 @@ Error OS_Haiku::initialize(const VideoMode &p_desired, int p_video_driver, int p RasterizerGLES2::make_current(); #endif - visual_server = memnew(VisualServerRaster); + rendering_server = memnew(RenderingServerRaster); // FIXME: Reimplement threaded rendering if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { - visual_server = memnew(VisualServerWrapMT(visual_server, false)); + rendering_server = memnew(RenderingServerWrapMT(rendering_server, false)); } - ERR_FAIL_COND_V(!visual_server, ERR_UNAVAILABLE); + ERR_FAIL_COND_V(!rendering_server, ERR_UNAVAILABLE); video_driver_index = p_video_driver; @@ -130,7 +130,7 @@ Error OS_Haiku::initialize(const VideoMode &p_desired, int p_video_driver, int p window->SetInput(input); window->Show(); - visual_server->init(); + rendering_server->init(); AudioDriverManager::initialize(p_audio_driver); @@ -142,10 +142,10 @@ void OS_Haiku::finalize() { memdelete(main_loop); } - main_loop = NULL; + main_loop = nullptr; - visual_server->finish(); - memdelete(visual_server); + rendering_server->finish(); + memdelete(rendering_server); memdelete(input); @@ -169,8 +169,8 @@ void OS_Haiku::delete_main_loop() { memdelete(main_loop); } - main_loop = NULL; - window->SetMainLoop(NULL); + main_loop = nullptr; + window->SetMainLoop(nullptr); } void OS_Haiku::release_rendering_thread() { @@ -267,7 +267,7 @@ void OS_Haiku::set_window_position(const Point2 &p_position) { void OS_Haiku::set_window_fullscreen(bool p_enabled) { window->SetFullScreen(p_enabled); current_video_mode.fullscreen = p_enabled; - visual_server->init(); + rendering_server->init(); } bool OS_Haiku::is_window_fullscreen() const { diff --git a/platform/haiku/os_haiku.h b/platform/haiku/os_haiku.h index 90c0abc3ef..64f5690dd1 100644 --- a/platform/haiku/os_haiku.h +++ b/platform/haiku/os_haiku.h @@ -38,7 +38,7 @@ #include "haiku_application.h" #include "haiku_direct_window.h" #include "servers/audio_server.h" -#include "servers/visual_server.h" +#include "servers/rendering_server.h" class OS_Haiku : public OS_Unix { private: @@ -46,7 +46,7 @@ private: HaikuDirectWindow *window; MainLoop *main_loop; InputDefault *input; - VisualServer *visual_server; + RenderingServer *rendering_server; VideoMode current_video_mode; int video_driver_index; diff --git a/platform/iphone/SCsub b/platform/iphone/SCsub index 1f82f51888..a48629f720 100644 --- a/platform/iphone/SCsub +++ b/platform/iphone/SCsub @@ -1,31 +1,35 @@ #!/usr/bin/env python -Import('env') +Import("env") iphone_lib = [ - 'godot_iphone.cpp', - 'os_iphone.cpp', - 'semaphore_iphone.cpp', - 'gl_view.mm', - 'main.m', - 'app_delegate.mm', - 'view_controller.mm', - 'game_center.mm', - 'in_app_store.mm', - 'icloud.mm', - 'ios.mm', - 'vulkan_context_iphone.mm', + "godot_iphone.cpp", + "os_iphone.cpp", + "semaphore_iphone.cpp", + "gl_view.mm", + "main.m", + "app_delegate.mm", + "view_controller.mm", + "game_center.mm", + "in_app_store.mm", + "icloud.mm", + "ios.mm", + "vulkan_context_iphone.mm", ] env_ios = env.Clone() -ios_lib = env_ios.add_library('iphone', iphone_lib) +ios_lib = env_ios.add_library("iphone", iphone_lib) + def combine_libs(target=None, source=None, env=None): lib_path = target[0].srcnode().abspath if "osxcross" in env: - libtool = '$IPHONEPATH/usr/bin/${ios_triple}libtool' + libtool = "$IPHONEPATH/usr/bin/${ios_triple}libtool" else: libtool = "$IPHONEPATH/usr/bin/libtool" - env.Execute(libtool + ' -static -o "' + lib_path + '" ' + ' '.join([('"' + lib.srcnode().abspath + '"') for lib in source])) + env.Execute( + libtool + ' -static -o "' + lib_path + '" ' + " ".join([('"' + lib.srcnode().abspath + '"') for lib in source]) + ) + -combine_command = env_ios.Command('#bin/libgodot' + env_ios['LIBSUFFIX'], [ios_lib] + env_ios['LIBS'], combine_libs) +combine_command = env_ios.Command("#bin/libgodot" + env_ios["LIBSUFFIX"], [ios_lib] + env_ios["LIBS"], combine_libs) diff --git a/platform/iphone/detect.py b/platform/iphone/detect.py index e01950c1db..3e6c2f0ecf 100644 --- a/platform/iphone/detect.py +++ b/platform/iphone/detect.py @@ -2,6 +2,7 @@ import os import sys from methods import detect_darwin_sdk_path + def is_active(): return True @@ -12,7 +13,7 @@ def get_name(): def can_build(): - if sys.platform == 'darwin' or ("OSXCROSS_IOS" in os.environ): + if sys.platform == "darwin" or ("OSXCROSS_IOS" in os.environ): return True return False @@ -20,22 +21,31 @@ def can_build(): def get_opts(): from SCons.Variables import BoolVariable + return [ - ('IPHONEPATH', 'Path to iPhone toolchain', '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain'), - ('IPHONESDK', 'Path to the iPhone SDK', ''), - BoolVariable('use_static_mvk', 'Link MoltenVK statically as Level-0 driver (better portability) or use Vulkan ICD loader (enables validation layers)', False), - BoolVariable('game_center', 'Support for game center', True), - BoolVariable('store_kit', 'Support for in-app store', True), - BoolVariable('icloud', 'Support for iCloud', True), - BoolVariable('ios_exceptions', 'Enable exceptions', False), - ('ios_triple', 'Triple for ios toolchain', ''), + ( + "IPHONEPATH", + "Path to iPhone toolchain", + "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain", + ), + ("IPHONESDK", "Path to the iPhone SDK", ""), + BoolVariable( + "use_static_mvk", + "Link MoltenVK statically as Level-0 driver (better portability) or use Vulkan ICD loader (enables validation layers)", + False, + ), + BoolVariable("game_center", "Support for game center", True), + BoolVariable("store_kit", "Support for in-app store", True), + BoolVariable("icloud", "Support for iCloud", True), + BoolVariable("ios_exceptions", "Enable exceptions", False), + ("ios_triple", "Triple for ios toolchain", ""), ] def get_flags(): return [ - ('tools', False), + ("tools", False), ] @@ -43,32 +53,32 @@ def configure(env): ## Build type - if (env["target"].startswith("release")): - env.Append(CPPDEFINES=['NDEBUG', ('NS_BLOCK_ASSERTIONS', 1)]) - if (env["optimize"] == "speed"): #optimize for speed (default) - env.Append(CCFLAGS=['-O2', '-ftree-vectorize', '-fomit-frame-pointer']) - env.Append(LINKFLAGS=['-O2']) - else: #optimize for size - env.Append(CCFLAGS=['-Os', '-ftree-vectorize']) - env.Append(LINKFLAGS=['-Os']) + if env["target"].startswith("release"): + env.Append(CPPDEFINES=["NDEBUG", ("NS_BLOCK_ASSERTIONS", 1)]) + if env["optimize"] == "speed": # optimize for speed (default) + env.Append(CCFLAGS=["-O2", "-ftree-vectorize", "-fomit-frame-pointer"]) + env.Append(LINKFLAGS=["-O2"]) + else: # optimize for size + env.Append(CCFLAGS=["-Os", "-ftree-vectorize"]) + env.Append(LINKFLAGS=["-Os"]) if env["target"] == "release_debug": - env.Append(CPPDEFINES=['DEBUG_ENABLED']) + env.Append(CPPDEFINES=["DEBUG_ENABLED"]) - elif (env["target"] == "debug"): - env.Append(CCFLAGS=['-gdwarf-2', '-O0']) - env.Append(CPPDEFINES=['_DEBUG', ('DEBUG', 1), 'DEBUG_ENABLED', 'DEBUG_MEMORY_ENABLED']) + elif env["target"] == "debug": + env.Append(CCFLAGS=["-gdwarf-2", "-O0"]) + env.Append(CPPDEFINES=["_DEBUG", ("DEBUG", 1), "DEBUG_ENABLED", "DEBUG_MEMORY_ENABLED"]) - if (env["use_lto"]): - env.Append(CCFLAGS=['-flto']) - env.Append(LINKFLAGS=['-flto']) + if env["use_lto"]: + env.Append(CCFLAGS=["-flto"]) + env.Append(LINKFLAGS=["-flto"]) ## Architecture if env["arch"] == "x86": # i386 env["bits"] = "32" elif env["arch"] == "x86_64": env["bits"] = "64" - elif (env["arch"] == "arm" or env["arch"] == "arm32" or env["arch"] == "armv7" or env["bits"] == "32"): # arm + elif env["arch"] == "arm" or env["arch"] == "arm32" or env["arch"] == "armv7" or env["bits"] == "32": # arm env["arch"] = "arm" env["bits"] = "32" else: # armv64 @@ -81,108 +91,145 @@ def configure(env): if "OSXCROSS_IOS" in os.environ: env["osxcross"] = True - env['ENV']['PATH'] = env['IPHONEPATH'] + "/Developer/usr/bin/:" + env['ENV']['PATH'] + env["ENV"]["PATH"] = env["IPHONEPATH"] + "/Developer/usr/bin/:" + env["ENV"]["PATH"] - compiler_path = '$IPHONEPATH/usr/bin/${ios_triple}' - s_compiler_path = '$IPHONEPATH/Developer/usr/bin/' + compiler_path = "$IPHONEPATH/usr/bin/${ios_triple}" + s_compiler_path = "$IPHONEPATH/Developer/usr/bin/" ccache_path = os.environ.get("CCACHE") if ccache_path is None: - env['CC'] = compiler_path + 'clang' - env['CXX'] = compiler_path + 'clang++' - env['S_compiler'] = s_compiler_path + 'gcc' + env["CC"] = compiler_path + "clang" + env["CXX"] = compiler_path + "clang++" + env["S_compiler"] = s_compiler_path + "gcc" else: # there aren't any ccache wrappers available for iOS, # to enable caching we need to prepend the path to the ccache binary - env['CC'] = ccache_path + ' ' + compiler_path + 'clang' - env['CXX'] = ccache_path + ' ' + compiler_path + 'clang++' - env['S_compiler'] = ccache_path + ' ' + s_compiler_path + 'gcc' - env['AR'] = compiler_path + 'ar' - env['RANLIB'] = compiler_path + 'ranlib' + env["CC"] = ccache_path + " " + compiler_path + "clang" + env["CXX"] = ccache_path + " " + compiler_path + "clang++" + env["S_compiler"] = ccache_path + " " + s_compiler_path + "gcc" + env["AR"] = compiler_path + "ar" + env["RANLIB"] = compiler_path + "ranlib" ## Compile flags - if (env["arch"] == "x86" or env["arch"] == "x86_64"): - detect_darwin_sdk_path('iphonesimulator', env) - env['ENV']['MACOSX_DEPLOYMENT_TARGET'] = '10.9' + if env["arch"] == "x86" or env["arch"] == "x86_64": + detect_darwin_sdk_path("iphonesimulator", env) + env["ENV"]["MACOSX_DEPLOYMENT_TARGET"] = "10.9" arch_flag = "i386" if env["arch"] == "x86" else env["arch"] - env.Append(CCFLAGS=('-arch ' + arch_flag + ' -fobjc-abi-version=2 -fobjc-legacy-dispatch -fmessage-length=0 -fpascal-strings -fblocks -fasm-blocks -isysroot $IPHONESDK -mios-simulator-version-min=10.0').split()) - elif (env["arch"] == "arm"): - detect_darwin_sdk_path('iphone', env) - env.Append(CCFLAGS='-fno-objc-arc -arch armv7 -fmessage-length=0 -fno-strict-aliasing -fdiagnostics-print-source-range-info -fdiagnostics-show-category=id -fdiagnostics-parseable-fixits -fpascal-strings -fblocks -isysroot $IPHONESDK -fvisibility=hidden -mthumb "-DIBOutlet=__attribute__((iboutlet))" "-DIBOutletCollection(ClassName)=__attribute__((iboutletcollection(ClassName)))" "-DIBAction=void)__attribute__((ibaction)" -miphoneos-version-min=10.0 -MMD -MT dependencies'.split()) - elif (env["arch"] == "arm64"): - detect_darwin_sdk_path('iphone', env) - env.Append(CCFLAGS='-fno-objc-arc -arch arm64 -fmessage-length=0 -fno-strict-aliasing -fdiagnostics-print-source-range-info -fdiagnostics-show-category=id -fdiagnostics-parseable-fixits -fpascal-strings -fblocks -fvisibility=hidden -MMD -MT dependencies -miphoneos-version-min=10.0 -isysroot $IPHONESDK'.split()) - env.Append(CPPDEFINES=['NEED_LONG_INT']) - env.Append(CPPDEFINES=['LIBYUV_DISABLE_NEON']) + env.Append( + CCFLAGS=( + "-arch " + + arch_flag + + " -fobjc-abi-version=2 -fobjc-legacy-dispatch -fmessage-length=0 -fpascal-strings -fblocks -fasm-blocks -isysroot $IPHONESDK -mios-simulator-version-min=10.0" + ).split() + ) + elif env["arch"] == "arm": + detect_darwin_sdk_path("iphone", env) + env.Append( + CCFLAGS='-fno-objc-arc -arch armv7 -fmessage-length=0 -fno-strict-aliasing -fdiagnostics-print-source-range-info -fdiagnostics-show-category=id -fdiagnostics-parseable-fixits -fpascal-strings -fblocks -isysroot $IPHONESDK -fvisibility=hidden -mthumb "-DIBOutlet=__attribute__((iboutlet))" "-DIBOutletCollection(ClassName)=__attribute__((iboutletcollection(ClassName)))" "-DIBAction=void)__attribute__((ibaction)" -miphoneos-version-min=10.0 -MMD -MT dependencies'.split() + ) + elif env["arch"] == "arm64": + detect_darwin_sdk_path("iphone", env) + env.Append( + CCFLAGS="-fno-objc-arc -arch arm64 -fmessage-length=0 -fno-strict-aliasing -fdiagnostics-print-source-range-info -fdiagnostics-show-category=id -fdiagnostics-parseable-fixits -fpascal-strings -fblocks -fvisibility=hidden -MMD -MT dependencies -miphoneos-version-min=10.0 -isysroot $IPHONESDK".split() + ) + env.Append(CPPDEFINES=["NEED_LONG_INT"]) + env.Append(CPPDEFINES=["LIBYUV_DISABLE_NEON"]) # Disable exceptions on non-tools (template) builds - if not env['tools']: - if env['ios_exceptions']: - env.Append(CCFLAGS=['-fexceptions']) + if not env["tools"]: + if env["ios_exceptions"]: + env.Append(CCFLAGS=["-fexceptions"]) else: - env.Append(CCFLAGS=['-fno-exceptions']) + env.Append(CCFLAGS=["-fno-exceptions"]) ## Link flags - if (env["arch"] == "x86" or env["arch"] == "x86_64"): + if env["arch"] == "x86" or env["arch"] == "x86_64": arch_flag = "i386" if env["arch"] == "x86" else env["arch"] - env.Append(LINKFLAGS=['-arch', arch_flag, '-mios-simulator-version-min=10.0', - '-isysroot', '$IPHONESDK', - '-Xlinker', - '-objc_abi_version', - '-Xlinker', '2', - '-F$IPHONESDK', - ]) - elif (env["arch"] == "arm"): - env.Append(LINKFLAGS=['-arch', 'armv7', '-Wl,-dead_strip', '-miphoneos-version-min=10.0']) - if (env["arch"] == "arm64"): - env.Append(LINKFLAGS=['-arch', 'arm64', '-Wl,-dead_strip', '-miphoneos-version-min=10.0']) - - env.Append(LINKFLAGS=['-isysroot', '$IPHONESDK', - '-framework', 'AudioToolbox', - '-framework', 'AVFoundation', - '-framework', 'CoreAudio', - '-framework', 'CoreGraphics', - '-framework', 'CoreMedia', - '-framework', 'CoreVideo', - '-framework', 'CoreMotion', - '-framework', 'Foundation', - '-framework', 'GameController', - '-framework', 'MediaPlayer', - '-framework', 'Metal', - '-framework', 'QuartzCore', - '-framework', 'Security', - '-framework', 'SystemConfiguration', - '-framework', 'UIKit', - '-framework', 'ARKit', - ]) + env.Append( + LINKFLAGS=[ + "-arch", + arch_flag, + "-mios-simulator-version-min=10.0", + "-isysroot", + "$IPHONESDK", + "-Xlinker", + "-objc_abi_version", + "-Xlinker", + "2", + "-F$IPHONESDK", + ] + ) + elif env["arch"] == "arm": + env.Append(LINKFLAGS=["-arch", "armv7", "-Wl,-dead_strip", "-miphoneos-version-min=10.0"]) + if env["arch"] == "arm64": + env.Append(LINKFLAGS=["-arch", "arm64", "-Wl,-dead_strip", "-miphoneos-version-min=10.0"]) + + env.Append( + LINKFLAGS=[ + "-isysroot", + "$IPHONESDK", + "-framework", + "AudioToolbox", + "-framework", + "AVFoundation", + "-framework", + "CoreAudio", + "-framework", + "CoreGraphics", + "-framework", + "CoreMedia", + "-framework", + "CoreVideo", + "-framework", + "CoreMotion", + "-framework", + "Foundation", + "-framework", + "GameController", + "-framework", + "MediaPlayer", + "-framework", + "Metal", + "-framework", + "QuartzCore", + "-framework", + "Security", + "-framework", + "SystemConfiguration", + "-framework", + "UIKit", + "-framework", + "ARKit", + ] + ) # Feature options - if env['game_center']: - env.Append(CPPDEFINES=['GAME_CENTER_ENABLED']) - env.Append(LINKFLAGS=['-framework', 'GameKit']) + if env["game_center"]: + env.Append(CPPDEFINES=["GAME_CENTER_ENABLED"]) + env.Append(LINKFLAGS=["-framework", "GameKit"]) - if env['store_kit']: - env.Append(CPPDEFINES=['STOREKIT_ENABLED']) - env.Append(LINKFLAGS=['-framework', 'StoreKit']) + if env["store_kit"]: + env.Append(CPPDEFINES=["STOREKIT_ENABLED"]) + env.Append(LINKFLAGS=["-framework", "StoreKit"]) - if env['icloud']: - env.Append(CPPDEFINES=['ICLOUD_ENABLED']) + if env["icloud"]: + env.Append(CPPDEFINES=["ICLOUD_ENABLED"]) - env.Prepend(CPPPATH=['$IPHONESDK/usr/include', - '$IPHONESDK/System/Library/Frameworks/AudioUnit.framework/Headers', - ]) + env.Prepend( + CPPPATH=["$IPHONESDK/usr/include", "$IPHONESDK/System/Library/Frameworks/AudioUnit.framework/Headers",] + ) - env['ENV']['CODESIGN_ALLOCATE'] = '/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/codesign_allocate' + env["ENV"]["CODESIGN_ALLOCATE"] = "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/codesign_allocate" - env.Prepend(CPPPATH=['#platform/iphone']) - env.Append(CPPDEFINES=['IPHONE_ENABLED', 'UNIX_ENABLED', 'COREAUDIO_ENABLED']) + env.Prepend(CPPPATH=["#platform/iphone"]) + env.Append(CPPDEFINES=["IPHONE_ENABLED", "UNIX_ENABLED", "COREAUDIO_ENABLED"]) - env.Append(CPPDEFINES=['VULKAN_ENABLED']) - env.Append(LINKFLAGS=['-framework', 'IOSurface']) - if (env['use_static_mvk']): - env.Append(LINKFLAGS=['-framework', 'MoltenVK']) - env['builtin_vulkan'] = False - elif not env['builtin_vulkan']: - env.Append(LIBS=['vulkan']) + env.Append(CPPDEFINES=["VULKAN_ENABLED"]) + env.Append(LINKFLAGS=["-framework", "IOSurface"]) + if env["use_static_mvk"]: + env.Append(LINKFLAGS=["-framework", "MoltenVK"]) + env["builtin_vulkan"] = False + elif not env["builtin_vulkan"]: + env.Append(LIBS=["vulkan"]) diff --git a/platform/iphone/export/export.cpp b/platform/iphone/export/export.cpp index 08f3c3f91f..3efe338ac7 100644 --- a/platform/iphone/export/export.cpp +++ b/platform/iphone/export/export.cpp @@ -71,8 +71,8 @@ class EditorExportPlatformIOS : public EditorExportPlatform { String modules_buildphase; String modules_buildgrp; }; - struct ExportArchitecture { + String name; bool is_default; @@ -106,7 +106,7 @@ class EditorExportPlatformIOS : public EditorExportPlatform { Error _export_additional_assets(const String &p_out_dir, const Vector<String> &p_assets, bool p_is_framework, Vector<IOSExportAsset> &r_exported_assets); Error _export_additional_assets(const String &p_out_dir, const Vector<SharedObject> &p_libraries, Vector<IOSExportAsset> &r_exported_assets); - bool is_package_name_valid(const String &p_package, String *r_error = NULL) const { + bool is_package_name_valid(const String &p_package, String *r_error = nullptr) const { String pname = p_package; @@ -795,7 +795,7 @@ void EditorExportPlatformIOS::_add_assets_to_project(const Ref<EditorExportPrese String pbx_resources_refs; const String file_info_format = String("$build_id = {isa = PBXBuildFile; fileRef = $ref_id; };\n") + - "$ref_id = {isa = PBXFileReference; lastKnownFileType = $file_type; name = $name; path = \"$file_path\"; sourceTree = \"<group>\"; };\n"; + "$ref_id = {isa = PBXFileReference; lastKnownFileType = $file_type; name = \"$name\"; path = \"$file_path\"; sourceTree = \"<group>\"; };\n"; for (int i = 0; i < p_additional_assets.size(); ++i) { String build_id = (++current_id).str(); String ref_id = (++current_id).str(); @@ -925,6 +925,13 @@ Error EditorExportPlatformIOS::_export_additional_assets(const String &p_out_dir Vector<String> frameworks = export_plugins[i]->get_ios_frameworks(); Error err = _export_additional_assets(p_out_dir, frameworks, true, r_exported_assets); ERR_FAIL_COND_V(err, err); + + Vector<String> project_static_libs = export_plugins[i]->get_ios_project_static_libs(); + for (int j = 0; j < project_static_libs.size(); j++) + project_static_libs.write[j] = project_static_libs[j].get_file(); // Only the file name as it's copied to the project + err = _export_additional_assets(p_out_dir, project_static_libs, true, r_exported_assets); + ERR_FAIL_COND_V(err, err); + Vector<String> ios_bundle_files = export_plugins[i]->get_ios_bundle_files(); err = _export_additional_assets(p_out_dir, ios_bundle_files, false, r_exported_assets); ERR_FAIL_COND_V(err, err); @@ -1076,7 +1083,7 @@ Error EditorExportPlatformIOS::export_project(const Ref<EditorExportPreset> &p_p ERR_FAIL_COND_V(!tmp_app_path, ERR_CANT_CREATE); print_line("Unzipping..."); - FileAccess *src_f = NULL; + FileAccess *src_f = nullptr; zlib_filefunc_def io = zipio_create_io_from_file(&src_f); unzFile src_pkg_zip = unzOpen2(src_pkg_name.utf8().get_data(), &io); if (!src_pkg_zip) { @@ -1098,7 +1105,7 @@ Error EditorExportPlatformIOS::export_project(const Ref<EditorExportPreset> &p_p //get filename unz_file_info info; char fname[16384]; - ret = unzGetCurrentFileInfo(src_pkg_zip, &info, fname, 16384, NULL, 0, NULL, 0); + ret = unzGetCurrentFileInfo(src_pkg_zip, &info, fname, 16384, nullptr, 0, nullptr, 0); String file = fname; @@ -1202,6 +1209,22 @@ Error EditorExportPlatformIOS::export_project(const Ref<EditorExportPreset> &p_p return ERR_FILE_NOT_FOUND; } + // Copy project static libs to the project + Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins(); + for (int i = 0; i < export_plugins.size(); i++) { + Vector<String> project_static_libs = export_plugins[i]->get_ios_project_static_libs(); + for (int j = 0; j < project_static_libs.size(); j++) { + const String &static_lib_path = project_static_libs[j]; + String dest_lib_file_path = dest_dir + static_lib_path.get_file(); + Error lib_copy_err = tmp_app_path->copy(static_lib_path, dest_lib_file_path); + if (lib_copy_err != OK) { + ERR_PRINT("Can't copy '" + static_lib_path + "'."); + memdelete(tmp_app_path); + return lib_copy_err; + } + } + } + String iconset_dir = dest_dir + binary_name + "/Images.xcassets/AppIcon.appiconset/"; err = OK; if (!tmp_app_path->dir_exists(iconset_dir)) { diff --git a/platform/iphone/godot_iphone.cpp b/platform/iphone/godot_iphone.cpp index 8c3eddc5f7..3e67362e16 100644 --- a/platform/iphone/godot_iphone.cpp +++ b/platform/iphone/godot_iphone.cpp @@ -36,7 +36,7 @@ #include <string.h> #include <unistd.h> -static OSIPhone *os = NULL; +static OSIPhone *os = nullptr; extern "C" { int add_path(int p_argc, char **p_args); @@ -71,7 +71,7 @@ int iphone_main(int width, int height, int argc, char **argv, String data_dir) { for (int i = 0; i < argc; i++) { fargv[i] = argv[i]; }; - fargv[argc] = NULL; + fargv[argc] = nullptr; argc = add_path(argc, fargv); argc = add_cmdline(argc, fargv); diff --git a/platform/iphone/os_iphone.cpp b/platform/iphone/os_iphone.cpp index 497f2f747d..3ef521a61a 100644 --- a/platform/iphone/os_iphone.cpp +++ b/platform/iphone/os_iphone.cpp @@ -37,13 +37,13 @@ #endif #if defined(VULKAN_ENABLED) -#include "servers/visual/rasterizer_rd/rasterizer_rd.h" +#include "servers/rendering/rasterizer_rd/rasterizer_rd.h" // #import <QuartzCore/CAMetalLayer.h> #include <vulkan/vulkan_metal.h> #endif -#include "servers/visual/visual_server_raster.h" -#include "servers/visual/visual_server_wrap_mt.h" +#include "servers/rendering/rendering_server_raster.h" +#include "servers/rendering/rendering_server_wrap_mt.h" #include "main/main.h" @@ -68,7 +68,7 @@ const char *OSIPhone::get_video_driver_name(int p_driver) const { case VIDEO_DRIVER_GLES2: return "GLES2"; } - ERR_FAIL_V_MSG(NULL, "Invalid video driver index: " + itos(p_driver) + "."); + ERR_FAIL_V_MSG(nullptr, "Invalid video driver index: " + itos(p_driver) + "."); }; OSIPhone *OSIPhone::get_singleton() { @@ -134,16 +134,16 @@ Error OSIPhone::initialize(const VideoMode &p_desired, int p_video_driver, int p RasterizerRD::make_current(); #endif - visual_server = memnew(VisualServerRaster); + rendering_server = memnew(RenderingServerRaster); // FIXME: Reimplement threaded rendering if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { - visual_server = memnew(VisualServerWrapMT(visual_server, false)); + rendering_server = memnew(RenderingServerWrapMT(rendering_server, false)); } - visual_server->init(); - //visual_server->cursor_set_visible(false, 0); + rendering_server->init(); + //rendering_server->cursor_set_visible(false, 0); #if defined(OPENGL_ENABLED) - // reset this to what it should be, it will have been set to 0 after visual_server->init() is called + // reset this to what it should be, it will have been set to 0 after rendering_server->init() is called RasterizerStorageGLES2::system_fbo = gl_view_base_fb; #endif @@ -339,7 +339,7 @@ void OSIPhone::delete_main_loop() { memdelete(main_loop); }; - main_loop = NULL; + main_loop = nullptr; }; void OSIPhone::finalize() { @@ -361,8 +361,8 @@ void OSIPhone::finalize() { memdelete(icloud); #endif - visual_server->finish(); - memdelete(visual_server); + rendering_server->finish(); + memdelete(rendering_server); // memdelete(rasterizer); // Free unhandled events before close @@ -608,7 +608,7 @@ bool OSIPhone::_check_internal_feature_support(const String &p_feature) { // so we use this as a hack to ensure certain code is called before // everything else, but after all units are initialized. typedef void (*init_callback)(); -static init_callback *ios_init_callbacks = NULL; +static init_callback *ios_init_callbacks = nullptr; static int ios_init_callbacks_count = 0; static int ios_init_callbacks_capacity = 0; @@ -631,12 +631,12 @@ OSIPhone::OSIPhone(int width, int height, String p_data_dir) { ios_init_callbacks[i](); } free(ios_init_callbacks); - ios_init_callbacks = NULL; + ios_init_callbacks = nullptr; ios_init_callbacks_count = 0; ios_init_callbacks_capacity = 0; - main_loop = NULL; - visual_server = NULL; + main_loop = nullptr; + rendering_server = nullptr; VideoMode vm; vm.fullscreen = true; diff --git a/platform/iphone/os_iphone.h b/platform/iphone/os_iphone.h index 2efb7af7c2..96cf041c37 100644 --- a/platform/iphone/os_iphone.h +++ b/platform/iphone/os_iphone.h @@ -41,8 +41,8 @@ #include "in_app_store.h" #include "ios.h" #include "servers/audio_server.h" -#include "servers/visual/rasterizer.h" -#include "servers/visual_server.h" +#include "servers/rendering/rasterizer.h" +#include "servers/rendering_server.h" #if defined(VULKAN_ENABLED) #include "drivers/vulkan/rendering_device_vulkan.h" @@ -60,7 +60,7 @@ private: static HashMap<String, void *> dynamic_symbol_lookup_table; friend void register_dynamic_symbol(char *name, void *address); - VisualServer *visual_server; + RenderingServer *rendering_server; AudioDriverCoreAudio audio_driver; diff --git a/platform/iphone/vulkan_context_iphone.h b/platform/iphone/vulkan_context_iphone.h index 200057e14d..625e41f4b9 100644 --- a/platform/iphone/vulkan_context_iphone.h +++ b/platform/iphone/vulkan_context_iphone.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* vulkan_context_osx.h */ +/* vulkan_context_iphone.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ diff --git a/platform/iphone/vulkan_context_iphone.mm b/platform/iphone/vulkan_context_iphone.mm index f49b85c097..701ac0d9bb 100644 --- a/platform/iphone/vulkan_context_iphone.mm +++ b/platform/iphone/vulkan_context_iphone.mm @@ -1,5 +1,5 @@ /*************************************************************************/ -/* vulkan_context_osx.mm */ +/* vulkan_context_iphone.mm */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ diff --git a/platform/javascript/SCsub b/platform/javascript/SCsub index d3cd8f76b7..7239648937 100644 --- a/platform/javascript/SCsub +++ b/platform/javascript/SCsub @@ -1,67 +1,63 @@ #!/usr/bin/env python -Import('env') +Import("env") javascript_files = [ - 'audio_driver_javascript.cpp', - 'http_client_javascript.cpp', - 'javascript_eval.cpp', - 'javascript_main.cpp', - 'os_javascript.cpp', + "audio_driver_javascript.cpp", + "http_client_javascript.cpp", + "javascript_eval.cpp", + "javascript_main.cpp", + "os_javascript.cpp", ] -build_targets = ['#bin/godot${PROGSUFFIX}.js', '#bin/godot${PROGSUFFIX}.wasm'] -if env['threads_enabled']: - build_targets.append('#bin/godot${PROGSUFFIX}.worker.js') +build_targets = ["#bin/godot${PROGSUFFIX}.js", "#bin/godot${PROGSUFFIX}.wasm"] +if env["threads_enabled"]: + build_targets.append("#bin/godot${PROGSUFFIX}.worker.js") build = env.add_program(build_targets, javascript_files) js_libraries = [ - 'http_request.js', + "http_request.js", ] for lib in js_libraries: - env.Append(LINKFLAGS=['--js-library', env.File(lib).path]) + env.Append(LINKFLAGS=["--js-library", env.File(lib).path]) env.Depends(build, js_libraries) js_modules = [ - 'id_handler.js', + "id_handler.js", ] for module in js_modules: - env.Append(LINKFLAGS=['--pre-js', env.File(module).path]) + env.Append(LINKFLAGS=["--pre-js", env.File(module).path]) env.Depends(build, js_modules) engine = [ - 'engine/preloader.js', - 'engine/loader.js', - 'engine/utils.js', - 'engine/engine.js', + "engine/preloader.js", + "engine/loader.js", + "engine/utils.js", + "engine/engine.js", ] -externs = [ - env.File('#platform/javascript/engine/externs.js') -] -js_engine = env.CreateEngineFile('#bin/godot${PROGSUFFIX}.engine.js', engine, externs) +externs = [env.File("#platform/javascript/engine/externs.js")] +js_engine = env.CreateEngineFile("#bin/godot${PROGSUFFIX}.engine.js", engine, externs) env.Depends(js_engine, externs) wrap_list = [ build[0], js_engine, ] -js_wrapped = env.Textfile('#bin/godot', [env.File(f) for f in wrap_list], TEXTFILESUFFIX='${PROGSUFFIX}.wrapped.js') +js_wrapped = env.Textfile("#bin/godot", [env.File(f) for f in wrap_list], TEXTFILESUFFIX="${PROGSUFFIX}.wrapped.js") -zip_dir = env.Dir('#bin/.javascript_zip') -out_files = [ - zip_dir.File('godot.js'), - zip_dir.File('godot.wasm'), - zip_dir.File('godot.html') -] -in_files = [ - js_wrapped, - build[1], - '#misc/dist/html/full-size.html' -] -if env['threads_enabled']: +zip_dir = env.Dir("#bin/.javascript_zip") +out_files = [zip_dir.File("godot.js"), zip_dir.File("godot.wasm"), zip_dir.File("godot.html")] +in_files = [js_wrapped, build[1], "#misc/dist/html/full-size.html"] +if env["threads_enabled"]: in_files.append(build[2]) - out_files.append(zip_dir.File('godot.worker.js')) + out_files.append(zip_dir.File("godot.worker.js")) zip_files = env.InstallAs(out_files, in_files) -env.Zip('#bin/godot', zip_files, ZIPROOT=zip_dir, ZIPSUFFIX='${PROGSUFFIX}${ZIPSUFFIX}', ZIPCOMSTR='Archving $SOURCES as $TARGET') +env.Zip( + "#bin/godot", + zip_files, + ZIPROOT=zip_dir, + ZIPSUFFIX="${PROGSUFFIX}${ZIPSUFFIX}", + ZIPCOMSTR="Archving $SOURCES as $TARGET", +) diff --git a/platform/javascript/api/api.cpp b/platform/javascript/api/api.cpp index 88de13d771..45cb82b351 100644 --- a/platform/javascript/api/api.cpp +++ b/platform/javascript/api/api.cpp @@ -46,7 +46,7 @@ void unregister_javascript_api() { memdelete(javascript_eval); } -JavaScript *JavaScript::singleton = NULL; +JavaScript *JavaScript::singleton = nullptr; JavaScript *JavaScript::get_singleton() { @@ -55,7 +55,7 @@ JavaScript *JavaScript::get_singleton() { JavaScript::JavaScript() { - ERR_FAIL_COND_MSG(singleton != NULL, "JavaScript singleton already exist."); + ERR_FAIL_COND_MSG(singleton != nullptr, "JavaScript singleton already exist."); singleton = this; } diff --git a/platform/javascript/audio_driver_javascript.cpp b/platform/javascript/audio_driver_javascript.cpp index d63c6a40a5..8f857478e5 100644 --- a/platform/javascript/audio_driver_javascript.cpp +++ b/platform/javascript/audio_driver_javascript.cpp @@ -32,7 +32,7 @@ #include <emscripten.h> -AudioDriverJavaScript *AudioDriverJavaScript::singleton = NULL; +AudioDriverJavaScript *AudioDriverJavaScript::singleton = nullptr; const char *AudioDriverJavaScript::get_name() const { @@ -200,7 +200,7 @@ void AudioDriverJavaScript::finish() { if (internal_buffer) { memdelete_arr(internal_buffer); - internal_buffer = NULL; + internal_buffer = nullptr; } _driver_id = 0; } @@ -264,7 +264,7 @@ Error AudioDriverJavaScript::capture_stop() { AudioDriverJavaScript::AudioDriverJavaScript() { _driver_id = 0; - internal_buffer = NULL; + internal_buffer = nullptr; buffer_length = 0; singleton = this; diff --git a/platform/javascript/detect.py b/platform/javascript/detect.py index fb02752aa7..9486e10717 100644 --- a/platform/javascript/detect.py +++ b/platform/javascript/detect.py @@ -2,37 +2,39 @@ import os from emscripten_helpers import parse_config, run_closure_compiler, create_engine_file + def is_active(): return True def get_name(): - return 'JavaScript' + return "JavaScript" def can_build(): - return 'EM_CONFIG' in os.environ or os.path.exists(os.path.expanduser('~/.emscripten')) + return "EM_CONFIG" in os.environ or os.path.exists(os.path.expanduser("~/.emscripten")) def get_opts(): from SCons.Variables import BoolVariable + return [ # eval() can be a security concern, so it can be disabled. - BoolVariable('javascript_eval', 'Enable JavaScript eval interface', True), - BoolVariable('threads_enabled', 'Enable WebAssembly Threads support (limited browser support)', False), - BoolVariable('use_closure_compiler', 'Use closure compiler to minimize Javascript code', False), + BoolVariable("javascript_eval", "Enable JavaScript eval interface", True), + BoolVariable("threads_enabled", "Enable WebAssembly Threads support (limited browser support)", False), + BoolVariable("use_closure_compiler", "Use closure compiler to minimize Javascript code", False), ] def get_flags(): return [ - ('tools', False), - ('builtin_pcre2_with_jit', False), + ("tools", False), + ("builtin_pcre2_with_jit", False), # Disabling the mbedtls module reduces file size. # The module has little use due to the limited networking functionality # in this platform. For the available networking methods, the browser # manages TLS. - ('module_mbedtls_enabled', False), + ("module_mbedtls_enabled", False), ] @@ -40,125 +42,125 @@ def configure(env): ## Build type - if env['target'] == 'release': + if env["target"] == "release": # Use -Os to prioritize optimizing for reduced file size. This is # particularly valuable for the web platform because it directly # decreases download time. # -Os reduces file size by around 5 MiB over -O3. -Oz only saves about # 100 KiB over -Os, which does not justify the negative impact on # run-time performance. - env.Append(CCFLAGS=['-Os']) - env.Append(LINKFLAGS=['-Os']) - elif env['target'] == 'release_debug': - env.Append(CCFLAGS=['-Os']) - env.Append(LINKFLAGS=['-Os']) - env.Append(CPPDEFINES=['DEBUG_ENABLED']) + env.Append(CCFLAGS=["-Os"]) + env.Append(LINKFLAGS=["-Os"]) + elif env["target"] == "release_debug": + env.Append(CCFLAGS=["-Os"]) + env.Append(LINKFLAGS=["-Os"]) + env.Append(CPPDEFINES=["DEBUG_ENABLED"]) # Retain function names for backtraces at the cost of file size. - env.Append(LINKFLAGS=['--profiling-funcs']) - else: # 'debug' - env.Append(CPPDEFINES=['DEBUG_ENABLED']) - env.Append(CCFLAGS=['-O1', '-g']) - env.Append(LINKFLAGS=['-O1', '-g']) - env.Append(LINKFLAGS=['-s', 'ASSERTIONS=1']) - - if env['tools']: - if not env['threads_enabled']: - raise RuntimeError("Threads must be enabled to build the editor. Please add the 'threads_enabled=yes' option") + env.Append(LINKFLAGS=["--profiling-funcs"]) + else: # 'debug' + env.Append(CPPDEFINES=["DEBUG_ENABLED"]) + env.Append(CCFLAGS=["-O1", "-g"]) + env.Append(LINKFLAGS=["-O1", "-g"]) + env.Append(LINKFLAGS=["-s", "ASSERTIONS=1"]) + + if env["tools"]: + if not env["threads_enabled"]: + raise RuntimeError( + "Threads must be enabled to build the editor. Please add the 'threads_enabled=yes' option" + ) # Tools need more memory. Initial stack memory in bytes. See `src/settings.js` in emscripten repository (will be renamed to INITIAL_MEMORY). - env.Append(LINKFLAGS=['-s', 'TOTAL_MEMORY=33554432']) + env.Append(LINKFLAGS=["-s", "TOTAL_MEMORY=33554432"]) else: # Disable exceptions and rtti on non-tools (template) builds # These flags help keep the file size down. - env.Append(CCFLAGS=['-fno-exceptions', '-fno-rtti']) + env.Append(CCFLAGS=["-fno-exceptions", "-fno-rtti"]) # Don't use dynamic_cast, necessary with no-rtti. - env.Append(CPPDEFINES=['NO_SAFE_CAST']) + env.Append(CPPDEFINES=["NO_SAFE_CAST"]) ## Copy env variables. - env['ENV'] = os.environ + env["ENV"] = os.environ # LTO - if env['use_lto']: - env.Append(CCFLAGS=['-s', 'WASM_OBJECT_FILES=0']) - env.Append(LINKFLAGS=['-s', 'WASM_OBJECT_FILES=0']) - env.Append(LINKFLAGS=['--llvm-lto', '1']) + if env["use_lto"]: + env.Append(CCFLAGS=["-s", "WASM_OBJECT_FILES=0"]) + env.Append(LINKFLAGS=["-s", "WASM_OBJECT_FILES=0"]) + env.Append(LINKFLAGS=["--llvm-lto", "1"]) # Closure compiler - if env['use_closure_compiler']: + if env["use_closure_compiler"]: # For emscripten support code. - env.Append(LINKFLAGS=['--closure', '1']) + env.Append(LINKFLAGS=["--closure", "1"]) # Register builder for our Engine files - jscc = env.Builder(generator=run_closure_compiler, suffix='.cc.js', src_suffix='.js') - env.Append(BUILDERS = {'BuildJS' : jscc}) + jscc = env.Builder(generator=run_closure_compiler, suffix=".cc.js", src_suffix=".js") + env.Append(BUILDERS={"BuildJS": jscc}) # Add method that joins/compiles our Engine files. env.AddMethod(create_engine_file, "CreateEngineFile") # Closure compiler extern and support for ecmascript specs (const, let, etc). - env['ENV']['EMCC_CLOSURE_ARGS'] = '--language_in ECMASCRIPT6' + env["ENV"]["EMCC_CLOSURE_ARGS"] = "--language_in ECMASCRIPT6" em_config = parse_config() - env.PrependENVPath('PATH', em_config['EMCC_ROOT']) + env.PrependENVPath("PATH", em_config["EMCC_ROOT"]) - env['CC'] = 'emcc' - env['CXX'] = 'em++' - env['LINK'] = 'emcc' + env["CC"] = "emcc" + env["CXX"] = "em++" + env["LINK"] = "emcc" - env['AR'] = 'emar' - env['RANLIB'] = 'emranlib' + env["AR"] = "emar" + env["RANLIB"] = "emranlib" # Use TempFileMunge since some AR invocations are too long for cmd.exe. # Use POSIX-style paths, required with TempFileMunge. - env['ARCOM_POSIX'] = env['ARCOM'].replace( - '$TARGET', '$TARGET.posix').replace( - '$SOURCES', '$SOURCES.posix') - env['ARCOM'] = '${TEMPFILE(ARCOM_POSIX)}' + env["ARCOM_POSIX"] = env["ARCOM"].replace("$TARGET", "$TARGET.posix").replace("$SOURCES", "$SOURCES.posix") + env["ARCOM"] = "${TEMPFILE(ARCOM_POSIX)}" # All intermediate files are just LLVM bitcode. - env['OBJPREFIX'] = '' - env['OBJSUFFIX'] = '.bc' - env['PROGPREFIX'] = '' + env["OBJPREFIX"] = "" + env["OBJSUFFIX"] = ".bc" + env["PROGPREFIX"] = "" # Program() output consists of multiple files, so specify suffixes manually at builder. - env['PROGSUFFIX'] = '' - env['LIBPREFIX'] = 'lib' - env['LIBSUFFIX'] = '.bc' - env['LIBPREFIXES'] = ['$LIBPREFIX'] - env['LIBSUFFIXES'] = ['$LIBSUFFIX'] + env["PROGSUFFIX"] = "" + env["LIBPREFIX"] = "lib" + env["LIBSUFFIX"] = ".bc" + env["LIBPREFIXES"] = ["$LIBPREFIX"] + env["LIBSUFFIXES"] = ["$LIBSUFFIX"] - env.Prepend(CPPPATH=['#platform/javascript']) - env.Append(CPPDEFINES=['JAVASCRIPT_ENABLED', 'UNIX_ENABLED']) + env.Prepend(CPPPATH=["#platform/javascript"]) + env.Append(CPPDEFINES=["JAVASCRIPT_ENABLED", "UNIX_ENABLED"]) - if env['javascript_eval']: - env.Append(CPPDEFINES=['JAVASCRIPT_EVAL_ENABLED']) + if env["javascript_eval"]: + env.Append(CPPDEFINES=["JAVASCRIPT_EVAL_ENABLED"]) # Thread support (via SharedArrayBuffer). - if env['threads_enabled']: - env.Append(CPPDEFINES=['PTHREAD_NO_RENAME']) - env.Append(CCFLAGS=['-s', 'USE_PTHREADS=1']) - env.Append(LINKFLAGS=['-s', 'USE_PTHREADS=1']) - env.Append(LINKFLAGS=['-s', 'PTHREAD_POOL_SIZE=4']) - env.Append(LINKFLAGS=['-s', 'WASM_MEM_MAX=2048MB']) + if env["threads_enabled"]: + env.Append(CPPDEFINES=["PTHREAD_NO_RENAME"]) + env.Append(CCFLAGS=["-s", "USE_PTHREADS=1"]) + env.Append(LINKFLAGS=["-s", "USE_PTHREADS=1"]) + env.Append(LINKFLAGS=["-s", "PTHREAD_POOL_SIZE=4"]) + env.Append(LINKFLAGS=["-s", "WASM_MEM_MAX=2048MB"]) else: - env.Append(CPPDEFINES=['NO_THREADS']) + env.Append(CPPDEFINES=["NO_THREADS"]) # Reduce code size by generating less support code (e.g. skip NodeJS support). - env.Append(LINKFLAGS=['-s', 'ENVIRONMENT=web,worker']) + env.Append(LINKFLAGS=["-s", "ENVIRONMENT=web,worker"]) # We use IDBFS in javascript_main.cpp. Since Emscripten 1.39.1 it needs to # be linked explicitly. - env.Append(LIBS=['idbfs.js']) + env.Append(LIBS=["idbfs.js"]) - env.Append(LINKFLAGS=['-s', 'BINARYEN=1']) - env.Append(LINKFLAGS=['-s', 'MODULARIZE=1', '-s', 'EXPORT_NAME="Godot"']) + env.Append(LINKFLAGS=["-s", "BINARYEN=1"]) + env.Append(LINKFLAGS=["-s", "MODULARIZE=1", "-s", 'EXPORT_NAME="Godot"']) # Allow increasing memory buffer size during runtime. This is efficient # when using WebAssembly (in comparison to asm.js) and works well for # us since we don't know requirements at compile-time. - env.Append(LINKFLAGS=['-s', 'ALLOW_MEMORY_GROWTH=1']) + env.Append(LINKFLAGS=["-s", "ALLOW_MEMORY_GROWTH=1"]) # This setting just makes WebGL 2 APIs available, it does NOT disable WebGL 1. - env.Append(LINKFLAGS=['-s', 'USE_WEBGL2=1']) + env.Append(LINKFLAGS=["-s", "USE_WEBGL2=1"]) - env.Append(LINKFLAGS=['-s', 'INVOKE_RUN=0']) + env.Append(LINKFLAGS=["-s", "INVOKE_RUN=0"]) # callMain for manual start, FS for preloading. - env.Append(LINKFLAGS=['-s', 'EXTRA_EXPORTED_RUNTIME_METHODS=["callMain", "FS"]']) + env.Append(LINKFLAGS=["-s", 'EXTRA_EXPORTED_RUNTIME_METHODS=["callMain", "FS"]']) diff --git a/platform/javascript/emscripten_helpers.py b/platform/javascript/emscripten_helpers.py index bda5b40a74..a55c9d3f48 100644 --- a/platform/javascript/emscripten_helpers.py +++ b/platform/javascript/emscripten_helpers.py @@ -1,7 +1,8 @@ import os + def parse_config(): - em_config_file = os.getenv('EM_CONFIG') or os.path.expanduser('~/.emscripten') + em_config_file = os.getenv("EM_CONFIG") or os.path.expanduser("~/.emscripten") if not os.path.exists(em_config_file): raise RuntimeError("Emscripten configuration file '%s' does not exist" % em_config_file) @@ -13,25 +14,25 @@ def parse_config(): exec(f.read(), em_config) except StandardError as e: raise RuntimeError("Emscripten configuration file '%s' is invalid:\n%s" % (em_config_file, e)) - normalized['EMCC_ROOT'] = em_config.get('EMSCRIPTEN_ROOT') - normalized['NODE_JS'] = em_config.get('NODE_JS') - normalized['CLOSURE_BIN'] = os.path.join(normalized['EMCC_ROOT'], 'node_modules', '.bin', 'google-closure-compiler') + normalized["EMCC_ROOT"] = em_config.get("EMSCRIPTEN_ROOT") + normalized["NODE_JS"] = em_config.get("NODE_JS") + normalized["CLOSURE_BIN"] = os.path.join(normalized["EMCC_ROOT"], "node_modules", ".bin", "google-closure-compiler") return normalized def run_closure_compiler(target, source, env, for_signature): cfg = parse_config() - cmd = [cfg['NODE_JS'], cfg['CLOSURE_BIN']] - cmd.extend(['--compilation_level', 'ADVANCED_OPTIMIZATIONS']) - for f in env['JSEXTERNS']: - cmd.extend(['--externs', f.get_abspath()]) + cmd = [cfg["NODE_JS"], cfg["CLOSURE_BIN"]] + cmd.extend(["--compilation_level", "ADVANCED_OPTIMIZATIONS"]) + for f in env["JSEXTERNS"]: + cmd.extend(["--externs", f.get_abspath()]) for f in source: - cmd.extend(['--js', f.get_abspath()]) - cmd.extend(['--js_output_file', target[0].get_abspath()]) - return ' '.join(cmd) + cmd.extend(["--js", f.get_abspath()]) + cmd.extend(["--js_output_file", target[0].get_abspath()]) + return " ".join(cmd) def create_engine_file(env, target, source, externs): - if env['use_closure_compiler']: + if env["use_closure_compiler"]: return env.BuildJS(target, source, JSEXTERNS=externs) return env.Textfile(target, [env.File(s) for s in source]) diff --git a/platform/javascript/export/export.cpp b/platform/javascript/export/export.cpp index da61425747..39faae2d17 100644 --- a/platform/javascript/export/export.cpp +++ b/platform/javascript/export/export.cpp @@ -390,7 +390,7 @@ Error EditorExportPlatformJavaScript::export_project(const Ref<EditorExportPrese return error; } - FileAccess *src_f = NULL; + FileAccess *src_f = nullptr; zlib_filefunc_def io = zipio_create_io_from_file(&src_f); unzFile pkg = unzOpen2(template_path.utf8().get_data(), &io); @@ -410,7 +410,7 @@ Error EditorExportPlatformJavaScript::export_project(const Ref<EditorExportPrese //get filename unz_file_info info; char fname[16384]; - unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0); + unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0); String file = fname; diff --git a/platform/javascript/http_client_javascript.cpp b/platform/javascript/http_client_javascript.cpp index 472384cf30..863c207896 100644 --- a/platform/javascript/http_client_javascript.cpp +++ b/platform/javascript/http_client_javascript.cpp @@ -88,8 +88,8 @@ Error HTTPClient::prepare_request(Method p_method, const String &p_url, const Ve String url = (use_tls ? "https://" : "http://") + host + ":" + itos(port) + p_url; godot_xhr_reset(xhr_id); godot_xhr_open(xhr_id, _methods[p_method], url.utf8().get_data(), - username.empty() ? NULL : username.utf8().get_data(), - password.empty() ? NULL : password.utf8().get_data()); + username.empty() ? nullptr : username.utf8().get_data(), + password.empty() ? nullptr : password.utf8().get_data()); for (int i = 0; i < p_headers.size(); i++) { int header_separator = p_headers[i].find(": "); diff --git a/platform/javascript/http_request.h b/platform/javascript/http_request.h index 57dc4f0d9f..54e98c1927 100644 --- a/platform/javascript/http_request.h +++ b/platform/javascript/http_request.h @@ -49,7 +49,7 @@ extern int godot_xhr_new(); extern void godot_xhr_reset(int p_xhr_id); extern bool godot_xhr_free(int p_xhr_id); -extern int godot_xhr_open(int p_xhr_id, const char *p_method, const char *p_url, const char *p_user = NULL, const char *p_password = NULL); +extern int godot_xhr_open(int p_xhr_id, const char *p_method, const char *p_url, const char *p_user = nullptr, const char *p_password = nullptr); extern void godot_xhr_set_request_header(int p_xhr_id, const char *p_header, const char *p_value); diff --git a/platform/javascript/os_javascript.cpp b/platform/javascript/os_javascript.cpp index b7feb5bfbd..ad06aef86e 100644 --- a/platform/javascript/os_javascript.cpp +++ b/platform/javascript/os_javascript.cpp @@ -36,7 +36,7 @@ #include "drivers/unix/dir_access_unix.h" #include "drivers/unix/file_access_unix.h" #include "main/main.h" -#include "servers/visual/visual_server_raster.h" +#include "servers/rendering/rendering_server_raster.h" #include <emscripten.h> #include <png.h> @@ -167,7 +167,7 @@ void OS_JavaScript::set_window_maximized(bool p_enabled) { strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH; strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF; strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT; - strategy.canvasResizedCallback = NULL; + strategy.canvasResizedCallback = nullptr; emscripten_enter_soft_fullscreen(GODOT_CANVAS_SELECTOR, &strategy); window_maximized = p_enabled; } @@ -196,7 +196,7 @@ void OS_JavaScript::set_window_fullscreen(bool p_enabled) { strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH; strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF; strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT; - strategy.canvasResizedCallback = NULL; + strategy.canvasResizedCallback = nullptr; EMSCRIPTEN_RESULT result = emscripten_request_fullscreen_strategy(GODOT_CANVAS_SELECTOR, false, &strategy); ERR_FAIL_COND_MSG(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED, "Enabling fullscreen is only possible from an input callback for the HTML5 platform."); ERR_FAIL_COND_MSG(result != EMSCRIPTEN_RESULT_SUCCESS, "Enabling fullscreen is only possible from an input callback for the HTML5 platform."); @@ -541,10 +541,10 @@ void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_s PackedByteArray png; size_t len; PackedByteArray data = image->get_data(); - ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, data.ptr(), 0, NULL)); + ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, data.ptr(), 0, nullptr)); png.resize(len); - ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, png.ptrw(), &len, 0, data.ptr(), 0, NULL)); + ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, png.ptrw(), &len, 0, data.ptr(), 0, nullptr)); char *object_url; /* clang-format off */ @@ -824,7 +824,7 @@ const char *OS_JavaScript::get_video_driver_name(int p_driver) const { case VIDEO_DRIVER_GLES2: return "GLES2"; } - ERR_FAIL_V_MSG(NULL, "Invalid video driver index: " + itos(p_driver) + "."); + ERR_FAIL_V_MSG(nullptr, "Invalid video driver index: " + itos(p_driver) + "."); } // Audio @@ -962,18 +962,18 @@ Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, setenv("LANG", locale_ptr, true); AudioDriverManager::initialize(p_audio_driver); - VisualServer *visual_server = memnew(VisualServerRaster()); + RenderingServer *rendering_server = memnew(RenderingServerRaster()); input = memnew(InputDefault); EMSCRIPTEN_RESULT result; #define EM_CHECK(ev) \ if (result != EMSCRIPTEN_RESULT_SUCCESS) \ ERR_PRINT("Error while setting " #ev " callback: Code " + itos(result)); -#define SET_EM_CALLBACK(target, ev, cb) \ - result = emscripten_set_##ev##_callback(target, NULL, true, &cb); \ +#define SET_EM_CALLBACK(target, ev, cb) \ + result = emscripten_set_##ev##_callback(target, nullptr, true, &cb); \ EM_CHECK(ev) -#define SET_EM_CALLBACK_NOTARGET(ev, cb) \ - result = emscripten_set_##ev##_callback(NULL, true, &cb); \ +#define SET_EM_CALLBACK_NOTARGET(ev, cb) \ + result = emscripten_set_##ev##_callback(nullptr, true, &cb); \ EM_CHECK(ev) // These callbacks from Emscripten's html5.h suffice to access most // JavaScript APIs. For APIs that are not (sufficiently) exposed, EM_ASM @@ -1016,7 +1016,7 @@ Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, ); /* clang-format on */ - visual_server->init(); + rendering_server->init(); return OK; } @@ -1072,7 +1072,7 @@ bool OS_JavaScript::main_loop_iterate() { strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH; strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF; strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT; - strategy.canvasResizedCallback = NULL; + strategy.canvasResizedCallback = nullptr; emscripten_enter_soft_fullscreen(GODOT_CANVAS_SELECTOR, &strategy); } else { emscripten_set_canvas_element_size(GODOT_CANVAS_SELECTOR, windowed_size.width, windowed_size.height); @@ -1182,10 +1182,10 @@ void OS_JavaScript::set_icon(const Ref<Image> &p_icon) { PackedByteArray png; size_t len; PackedByteArray data = icon->get_data(); - ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, data.ptr(), 0, NULL)); + ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, data.ptr(), 0, nullptr)); png.resize(len); - ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, png.ptrw(), &len, 0, data.ptr(), 0, NULL)); + ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, png.ptrw(), &len, 0, data.ptr(), 0, nullptr)); /* clang-format off */ EM_ASM_ARGS({ @@ -1284,7 +1284,7 @@ OS_JavaScript::OS_JavaScript(int p_argc, char *p_argv[]) { just_exited_fullscreen = false; transparency_enabled = false; - main_loop = NULL; + main_loop = nullptr; idb_available = false; sync_wait_time = -1; diff --git a/platform/javascript/os_javascript.h b/platform/javascript/os_javascript.h index 1a3a6616b0..81fe4cf0cc 100644 --- a/platform/javascript/os_javascript.h +++ b/platform/javascript/os_javascript.h @@ -35,7 +35,7 @@ #include "core/input/input_filter.h" #include "drivers/unix/os_unix.h" #include "servers/audio_server.h" -#include "servers/visual/rasterizer.h" +#include "servers/rendering/rasterizer.h" #include <emscripten/html5.h> @@ -145,7 +145,7 @@ public: void run_async(); bool main_loop_iterate(); - virtual Error execute(const String &p_path, const List<String> &p_arguments, bool p_blocking = true, ProcessID *r_child_id = NULL, String *r_pipe = NULL, int *r_exitcode = NULL, bool read_stderr = false, Mutex *p_pipe_mutex = NULL); + virtual Error execute(const String &p_path, const List<String> &p_arguments, bool p_blocking = true, ProcessID *r_child_id = nullptr, String *r_pipe = nullptr, int *r_exitcode = nullptr, bool read_stderr = false, Mutex *p_pipe_mutex = nullptr); virtual Error kill(const ProcessID &p_pid); virtual int get_process_id() const; diff --git a/platform/linuxbsd/SCsub b/platform/linuxbsd/SCsub index f3f65e216e..ae75a75830 100644 --- a/platform/linuxbsd/SCsub +++ b/platform/linuxbsd/SCsub @@ -1,6 +1,6 @@ #!/usr/bin/env python -Import('env') +Import("env") from platform_methods import run_in_subprocess import platform_linuxbsd_builders @@ -14,10 +14,9 @@ common_x11 = [ "display_server_x11.cpp", "vulkan_context_x11.cpp", "key_mapping_x11.cpp", - ] -prog = env.add_program('#bin/godot', ['godot_linuxbsd.cpp'] + common_x11) +prog = env.add_program("#bin/godot", ["godot_linuxbsd.cpp"] + common_x11) if (env["debug_symbols"] == "full" or env["debug_symbols"] == "yes") and env["separate_debug_symbols"]: env.AddPostAction(prog, run_in_subprocess(platform_linuxbsd_builders.make_debug_linuxbsd)) diff --git a/platform/linuxbsd/context_gl_x11.cpp b/platform/linuxbsd/context_gl_x11.cpp index 5442af3bef..308d68521a 100644 --- a/platform/linuxbsd/context_gl_x11.cpp +++ b/platform/linuxbsd/context_gl_x11.cpp @@ -52,7 +52,7 @@ struct ContextGL_X11_Private { void ContextGL_X11::release_current() { - glXMakeCurrent(x11_display, None, NULL); + glXMakeCurrent(x11_display, None, nullptr); } void ContextGL_X11::make_current() { @@ -117,7 +117,7 @@ Error ContextGL_X11::initialize() { int fbcount; GLXFBConfig fbconfig = 0; - XVisualInfo *vi = NULL; + XVisualInfo *vi = nullptr; XSetWindowAttributes swa; swa.event_mask = StructureNotifyMask; @@ -136,7 +136,7 @@ Error ContextGL_X11::initialize() { XRenderPictFormat *pict_format = XRenderFindVisualFormat(x11_display, vi->visual); if (!pict_format) { XFree(vi); - vi = NULL; + vi = nullptr; continue; } @@ -208,9 +208,9 @@ int ContextGL_X11::get_window_height() { void ContextGL_X11::set_use_vsync(bool p_use) { static bool setup = false; - static PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT = NULL; - static PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalMESA = NULL; - static PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = NULL; + static PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT = nullptr; + static PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalMESA = nullptr; + static PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = nullptr; if (!setup) { setup = true; diff --git a/platform/linuxbsd/crash_handler_linuxbsd.cpp b/platform/linuxbsd/crash_handler_linuxbsd.cpp index 1b3804e3ed..dbdb15918e 100644 --- a/platform/linuxbsd/crash_handler_linuxbsd.cpp +++ b/platform/linuxbsd/crash_handler_linuxbsd.cpp @@ -46,7 +46,7 @@ #include <stdlib.h> static void handle_crash(int sig) { - if (OS::get_singleton() == NULL) { + if (OS::get_singleton() == nullptr) { abort(); } @@ -79,7 +79,7 @@ static void handle_crash(int sig) { if (dladdr(bt_buffer[i], &info) && info.dli_sname) { if (info.dli_sname[0] == '_') { int status; - char *demangled = abi::__cxa_demangle(info.dli_sname, NULL, 0, &status); + char *demangled = abi::__cxa_demangle(info.dli_sname, nullptr, nullptr, &status); if (status == 0 && demangled) { snprintf(fname, 1024, "%s", demangled); @@ -102,7 +102,7 @@ static void handle_crash(int sig) { // Try to get the file/line number using addr2line int ret; - Error err = OS::get_singleton()->execute(String("addr2line"), args, true, NULL, &output, &ret); + Error err = OS::get_singleton()->execute(String("addr2line"), args, true, nullptr, &output, &ret); if (err == OK) { output.erase(output.length() - 1, 1); } @@ -132,9 +132,9 @@ void CrashHandler::disable() { return; #ifdef CRASH_HANDLER_ENABLED - signal(SIGSEGV, NULL); - signal(SIGFPE, NULL); - signal(SIGILL, NULL); + signal(SIGSEGV, nullptr); + signal(SIGFPE, nullptr); + signal(SIGILL, nullptr); #endif disabled = true; diff --git a/platform/linuxbsd/detect.py b/platform/linuxbsd/detect.py index 1a395efffe..5d8b4fba48 100644 --- a/platform/linuxbsd/detect.py +++ b/platform/linuxbsd/detect.py @@ -13,64 +13,65 @@ def get_name(): def can_build(): - if (os.name != "posix" or sys.platform == "darwin"): + if os.name != "posix" or sys.platform == "darwin": return False # Check the minimal dependencies x11_error = os.system("pkg-config --version > /dev/null") - if (x11_error): + if x11_error: return False x11_error = os.system("pkg-config x11 --modversion > /dev/null ") - if (x11_error): + if x11_error: return False x11_error = os.system("pkg-config xcursor --modversion > /dev/null ") - if (x11_error): + if x11_error: print("xcursor not found.. x11 disabled.") return False x11_error = os.system("pkg-config xinerama --modversion > /dev/null ") - if (x11_error): + if x11_error: print("xinerama not found.. x11 disabled.") return False x11_error = os.system("pkg-config xrandr --modversion > /dev/null ") - if (x11_error): + if x11_error: print("xrandr not found.. x11 disabled.") return False x11_error = os.system("pkg-config xrender --modversion > /dev/null ") - if (x11_error): + if x11_error: print("xrender not found.. x11 disabled.") return False x11_error = os.system("pkg-config xi --modversion > /dev/null ") - if (x11_error): + if x11_error: print("xi not found.. Aborting.") return False return True + def get_opts(): from SCons.Variables import BoolVariable, EnumVariable return [ - BoolVariable('use_llvm', 'Use the LLVM compiler', False), - BoolVariable('use_lld', 'Use the LLD linker', False), - BoolVariable('use_thinlto', 'Use ThinLTO', False), - BoolVariable('use_static_cpp', 'Link libgcc and libstdc++ statically for better portability', False), - BoolVariable('use_coverage', 'Test Godot coverage', False), - BoolVariable('use_ubsan', 'Use LLVM/GCC compiler undefined behavior sanitizer (UBSAN)', False), - BoolVariable('use_asan', 'Use LLVM/GCC compiler address sanitizer (ASAN))', False), - BoolVariable('use_lsan', 'Use LLVM/GCC compiler leak sanitizer (LSAN))', False), - BoolVariable('use_tsan', 'Use LLVM/GCC compiler thread sanitizer (TSAN))', False), - BoolVariable('pulseaudio', 'Detect and use PulseAudio', True), - BoolVariable('udev', 'Use udev for gamepad connection callbacks', False), - EnumVariable('debug_symbols', 'Add debugging symbols to release builds', 'yes', ('yes', 'no', 'full')), - BoolVariable('separate_debug_symbols', 'Create a separate file containing debugging symbols', False), - BoolVariable('touch', 'Enable touch events', True), - BoolVariable('execinfo', 'Use libexecinfo on systems where glibc is not available', False), + BoolVariable("use_llvm", "Use the LLVM compiler", False), + BoolVariable("use_lld", "Use the LLD linker", False), + BoolVariable("use_thinlto", "Use ThinLTO", False), + BoolVariable("use_static_cpp", "Link libgcc and libstdc++ statically for better portability", False), + BoolVariable("use_coverage", "Test Godot coverage", False), + BoolVariable("use_ubsan", "Use LLVM/GCC compiler undefined behavior sanitizer (UBSAN)", False), + BoolVariable("use_asan", "Use LLVM/GCC compiler address sanitizer (ASAN))", False), + BoolVariable("use_lsan", "Use LLVM/GCC compiler leak sanitizer (LSAN))", False), + BoolVariable("use_tsan", "Use LLVM/GCC compiler thread sanitizer (TSAN))", False), + BoolVariable("pulseaudio", "Detect and use PulseAudio", True), + BoolVariable("udev", "Use udev for gamepad connection callbacks", False), + EnumVariable("debug_symbols", "Add debugging symbols to release builds", "yes", ("yes", "no", "full")), + BoolVariable("separate_debug_symbols", "Create a separate file containing debugging symbols", False), + BoolVariable("touch", "Enable touch events", True), + BoolVariable("execinfo", "Use libexecinfo on systems where glibc is not available", False), ] @@ -83,286 +84,294 @@ def configure(env): ## Build type - if (env["target"] == "release"): - if (env["optimize"] == "speed"): #optimize for speed (default) - env.Prepend(CCFLAGS=['-O3']) - else: #optimize for size - env.Prepend(CCFLAGS=['-Os']) - - if (env["debug_symbols"] == "yes"): - env.Prepend(CCFLAGS=['-g1']) - if (env["debug_symbols"] == "full"): - env.Prepend(CCFLAGS=['-g2']) - - elif (env["target"] == "release_debug"): - if (env["optimize"] == "speed"): #optimize for speed (default) - env.Prepend(CCFLAGS=['-O2']) - else: #optimize for size - env.Prepend(CCFLAGS=['-Os']) - env.Prepend(CPPDEFINES=['DEBUG_ENABLED']) - - if (env["debug_symbols"] == "yes"): - env.Prepend(CCFLAGS=['-g1']) - if (env["debug_symbols"] == "full"): - env.Prepend(CCFLAGS=['-g2']) - - elif (env["target"] == "debug"): - env.Prepend(CCFLAGS=['-g3']) - env.Prepend(CPPDEFINES=['DEBUG_ENABLED', 'DEBUG_MEMORY_ENABLED']) - env.Append(LINKFLAGS=['-rdynamic']) + if env["target"] == "release": + if env["optimize"] == "speed": # optimize for speed (default) + env.Prepend(CCFLAGS=["-O3"]) + else: # optimize for size + env.Prepend(CCFLAGS=["-Os"]) + + if env["debug_symbols"] == "yes": + env.Prepend(CCFLAGS=["-g1"]) + if env["debug_symbols"] == "full": + env.Prepend(CCFLAGS=["-g2"]) + + elif env["target"] == "release_debug": + if env["optimize"] == "speed": # optimize for speed (default) + env.Prepend(CCFLAGS=["-O2"]) + else: # optimize for size + env.Prepend(CCFLAGS=["-Os"]) + env.Prepend(CPPDEFINES=["DEBUG_ENABLED"]) + + if env["debug_symbols"] == "yes": + env.Prepend(CCFLAGS=["-g1"]) + if env["debug_symbols"] == "full": + env.Prepend(CCFLAGS=["-g2"]) + + elif env["target"] == "debug": + env.Prepend(CCFLAGS=["-g3"]) + env.Prepend(CPPDEFINES=["DEBUG_ENABLED", "DEBUG_MEMORY_ENABLED"]) + env.Append(LINKFLAGS=["-rdynamic"]) ## Architecture - is64 = sys.maxsize > 2**32 - if (env["bits"] == "default"): + is64 = sys.maxsize > 2 ** 32 + if env["bits"] == "default": env["bits"] = "64" if is64 else "32" ## Compiler configuration - if 'CXX' in env and 'clang' in os.path.basename(env['CXX']): + if "CXX" in env and "clang" in os.path.basename(env["CXX"]): # Convenience check to enforce the use_llvm overrides when CXX is clang(++) - env['use_llvm'] = True + env["use_llvm"] = True - if env['use_llvm']: - if ('clang++' not in os.path.basename(env['CXX'])): + if env["use_llvm"]: + if "clang++" not in os.path.basename(env["CXX"]): env["CC"] = "clang" env["CXX"] = "clang++" env["LINK"] = "clang++" - env.Append(CPPDEFINES=['TYPED_METHOD_BIND']) + env.Append(CPPDEFINES=["TYPED_METHOD_BIND"]) env.extra_suffix = ".llvm" + env.extra_suffix - if env['use_lld']: - if env['use_llvm']: - env.Append(LINKFLAGS=['-fuse-ld=lld']) - if env['use_thinlto']: + if env["use_lld"]: + if env["use_llvm"]: + env.Append(LINKFLAGS=["-fuse-ld=lld"]) + if env["use_thinlto"]: # A convenience so you don't need to write use_lto too when using SCons - env['use_lto'] = True + env["use_lto"] = True else: print("Using LLD with GCC is not supported yet, try compiling with 'use_llvm=yes'.") sys.exit(255) - if env['use_coverage']: - env.Append(CCFLAGS=['-ftest-coverage', '-fprofile-arcs']) - env.Append(LINKFLAGS=['-ftest-coverage', '-fprofile-arcs']) + if env["use_coverage"]: + env.Append(CCFLAGS=["-ftest-coverage", "-fprofile-arcs"]) + env.Append(LINKFLAGS=["-ftest-coverage", "-fprofile-arcs"]) - if env['use_ubsan'] or env['use_asan'] or env['use_lsan'] or env['use_tsan']: + if env["use_ubsan"] or env["use_asan"] or env["use_lsan"] or env["use_tsan"]: env.extra_suffix += "s" - if env['use_ubsan']: - env.Append(CCFLAGS=['-fsanitize=undefined']) - env.Append(LINKFLAGS=['-fsanitize=undefined']) + if env["use_ubsan"]: + env.Append(CCFLAGS=["-fsanitize=undefined"]) + env.Append(LINKFLAGS=["-fsanitize=undefined"]) - if env['use_asan']: - env.Append(CCFLAGS=['-fsanitize=address']) - env.Append(LINKFLAGS=['-fsanitize=address']) + if env["use_asan"]: + env.Append(CCFLAGS=["-fsanitize=address"]) + env.Append(LINKFLAGS=["-fsanitize=address"]) - if env['use_lsan']: - env.Append(CCFLAGS=['-fsanitize=leak']) - env.Append(LINKFLAGS=['-fsanitize=leak']) + if env["use_lsan"]: + env.Append(CCFLAGS=["-fsanitize=leak"]) + env.Append(LINKFLAGS=["-fsanitize=leak"]) - if env['use_tsan']: - env.Append(CCFLAGS=['-fsanitize=thread']) - env.Append(LINKFLAGS=['-fsanitize=thread']) + if env["use_tsan"]: + env.Append(CCFLAGS=["-fsanitize=thread"]) + env.Append(LINKFLAGS=["-fsanitize=thread"]) - if env['use_lto']: - if not env['use_llvm'] and env.GetOption("num_jobs") > 1: - env.Append(CCFLAGS=['-flto']) - env.Append(LINKFLAGS=['-flto=' + str(env.GetOption("num_jobs"))]) + if env["use_lto"]: + if not env["use_llvm"] and env.GetOption("num_jobs") > 1: + env.Append(CCFLAGS=["-flto"]) + env.Append(LINKFLAGS=["-flto=" + str(env.GetOption("num_jobs"))]) else: - if env['use_lld'] and env['use_thinlto']: - env.Append(CCFLAGS=['-flto=thin']) - env.Append(LINKFLAGS=['-flto=thin']) + if env["use_lld"] and env["use_thinlto"]: + env.Append(CCFLAGS=["-flto=thin"]) + env.Append(LINKFLAGS=["-flto=thin"]) else: - env.Append(CCFLAGS=['-flto']) - env.Append(LINKFLAGS=['-flto']) + env.Append(CCFLAGS=["-flto"]) + env.Append(LINKFLAGS=["-flto"]) - if not env['use_llvm']: - env['RANLIB'] = 'gcc-ranlib' - env['AR'] = 'gcc-ar' + if not env["use_llvm"]: + env["RANLIB"] = "gcc-ranlib" + env["AR"] = "gcc-ar" - env.Append(CCFLAGS=['-pipe']) - env.Append(LINKFLAGS=['-pipe']) + env.Append(CCFLAGS=["-pipe"]) + env.Append(LINKFLAGS=["-pipe"]) # -fpie and -no-pie is supported on GCC 6+ and Clang 4+, both below our # minimal requirements. - env.Append(CCFLAGS=['-fpie']) - env.Append(LINKFLAGS=['-no-pie']) + env.Append(CCFLAGS=["-fpie"]) + env.Append(LINKFLAGS=["-no-pie"]) ## Dependencies - env.ParseConfig('pkg-config x11 --cflags --libs') - env.ParseConfig('pkg-config xcursor --cflags --libs') - env.ParseConfig('pkg-config xinerama --cflags --libs') - env.ParseConfig('pkg-config xrandr --cflags --libs') - env.ParseConfig('pkg-config xrender --cflags --libs') - env.ParseConfig('pkg-config xi --cflags --libs') + env.ParseConfig("pkg-config x11 --cflags --libs") + env.ParseConfig("pkg-config xcursor --cflags --libs") + env.ParseConfig("pkg-config xinerama --cflags --libs") + env.ParseConfig("pkg-config xrandr --cflags --libs") + env.ParseConfig("pkg-config xrender --cflags --libs") + env.ParseConfig("pkg-config xi --cflags --libs") - if (env['touch']): - env.Append(CPPDEFINES=['TOUCH_ENABLED']) + if env["touch"]: + env.Append(CPPDEFINES=["TOUCH_ENABLED"]) # FIXME: Check for existence of the libs before parsing their flags with pkg-config # freetype depends on libpng and zlib, so bundling one of them while keeping others # as shared libraries leads to weird issues - if env['builtin_freetype'] or env['builtin_libpng'] or env['builtin_zlib']: - env['builtin_freetype'] = True - env['builtin_libpng'] = True - env['builtin_zlib'] = True + if env["builtin_freetype"] or env["builtin_libpng"] or env["builtin_zlib"]: + env["builtin_freetype"] = True + env["builtin_libpng"] = True + env["builtin_zlib"] = True - if not env['builtin_freetype']: - env.ParseConfig('pkg-config freetype2 --cflags --libs') + if not env["builtin_freetype"]: + env.ParseConfig("pkg-config freetype2 --cflags --libs") - if not env['builtin_libpng']: - env.ParseConfig('pkg-config libpng16 --cflags --libs') + if not env["builtin_libpng"]: + env.ParseConfig("pkg-config libpng16 --cflags --libs") - if not env['builtin_bullet']: + if not env["builtin_bullet"]: # We need at least version 2.89 import subprocess - bullet_version = subprocess.check_output(['pkg-config', 'bullet', '--modversion']).strip() + + bullet_version = subprocess.check_output(["pkg-config", "bullet", "--modversion"]).strip() if str(bullet_version) < "2.89": # Abort as system bullet was requested but too old - print("Bullet: System version {0} does not match minimal requirements ({1}). Aborting.".format(bullet_version, "2.89")) + print( + "Bullet: System version {0} does not match minimal requirements ({1}). Aborting.".format( + bullet_version, "2.89" + ) + ) sys.exit(255) - env.ParseConfig('pkg-config bullet --cflags --libs') + env.ParseConfig("pkg-config bullet --cflags --libs") if False: # not env['builtin_assimp']: # FIXME: Add min version check - env.ParseConfig('pkg-config assimp --cflags --libs') + env.ParseConfig("pkg-config assimp --cflags --libs") - if not env['builtin_enet']: - env.ParseConfig('pkg-config libenet --cflags --libs') + if not env["builtin_enet"]: + env.ParseConfig("pkg-config libenet --cflags --libs") - if not env['builtin_squish']: - env.ParseConfig('pkg-config libsquish --cflags --libs') + if not env["builtin_squish"]: + env.ParseConfig("pkg-config libsquish --cflags --libs") - if not env['builtin_zstd']: - env.ParseConfig('pkg-config libzstd --cflags --libs') + if not env["builtin_zstd"]: + env.ParseConfig("pkg-config libzstd --cflags --libs") # Sound and video libraries # Keep the order as it triggers chained dependencies (ogg needed by others, etc.) - if not env['builtin_libtheora']: - env['builtin_libogg'] = False # Needed to link against system libtheora - env['builtin_libvorbis'] = False # Needed to link against system libtheora - env.ParseConfig('pkg-config theora theoradec --cflags --libs') + if not env["builtin_libtheora"]: + env["builtin_libogg"] = False # Needed to link against system libtheora + env["builtin_libvorbis"] = False # Needed to link against system libtheora + env.ParseConfig("pkg-config theora theoradec --cflags --libs") else: - list_of_x86 = ['x86_64', 'x86', 'i386', 'i586'] + list_of_x86 = ["x86_64", "x86", "i386", "i586"] if any(platform.machine() in s for s in list_of_x86): env["x86_libtheora_opt_gcc"] = True - if not env['builtin_libvpx']: - env.ParseConfig('pkg-config vpx --cflags --libs') + if not env["builtin_libvpx"]: + env.ParseConfig("pkg-config vpx --cflags --libs") - if not env['builtin_libvorbis']: - env['builtin_libogg'] = False # Needed to link against system libvorbis - env.ParseConfig('pkg-config vorbis vorbisfile --cflags --libs') + if not env["builtin_libvorbis"]: + env["builtin_libogg"] = False # Needed to link against system libvorbis + env.ParseConfig("pkg-config vorbis vorbisfile --cflags --libs") - if not env['builtin_opus']: - env['builtin_libogg'] = False # Needed to link against system opus - env.ParseConfig('pkg-config opus opusfile --cflags --libs') + if not env["builtin_opus"]: + env["builtin_libogg"] = False # Needed to link against system opus + env.ParseConfig("pkg-config opus opusfile --cflags --libs") - if not env['builtin_libogg']: - env.ParseConfig('pkg-config ogg --cflags --libs') + if not env["builtin_libogg"]: + env.ParseConfig("pkg-config ogg --cflags --libs") - if not env['builtin_libwebp']: - env.ParseConfig('pkg-config libwebp --cflags --libs') + if not env["builtin_libwebp"]: + env.ParseConfig("pkg-config libwebp --cflags --libs") - if not env['builtin_mbedtls']: + if not env["builtin_mbedtls"]: # mbedTLS does not provide a pkgconfig config yet. See https://github.com/ARMmbed/mbedtls/issues/228 - env.Append(LIBS=['mbedtls', 'mbedcrypto', 'mbedx509']) + env.Append(LIBS=["mbedtls", "mbedcrypto", "mbedx509"]) - if not env['builtin_wslay']: - env.ParseConfig('pkg-config libwslay --cflags --libs') + if not env["builtin_wslay"]: + env.ParseConfig("pkg-config libwslay --cflags --libs") - if not env['builtin_miniupnpc']: + if not env["builtin_miniupnpc"]: # No pkgconfig file so far, hardcode default paths. env.Prepend(CPPPATH=["/usr/include/miniupnpc"]) env.Append(LIBS=["miniupnpc"]) # On Linux wchar_t should be 32-bits # 16-bit library shouldn't be required due to compiler optimisations - if not env['builtin_pcre2']: - env.ParseConfig('pkg-config libpcre2-32 --cflags --libs') + if not env["builtin_pcre2"]: + env.ParseConfig("pkg-config libpcre2-32 --cflags --libs") ## Flags - if (os.system("pkg-config --exists alsa") == 0): # 0 means found + if os.system("pkg-config --exists alsa") == 0: # 0 means found print("Enabling ALSA") env.Append(CPPDEFINES=["ALSA_ENABLED", "ALSAMIDI_ENABLED"]) - # Don't parse --cflags, we don't need to add /usr/include/alsa to include path - env.ParseConfig('pkg-config alsa --libs') + # Don't parse --cflags, we don't need to add /usr/include/alsa to include path + env.ParseConfig("pkg-config alsa --libs") else: print("ALSA libraries not found, disabling driver") - if env['pulseaudio']: - if (os.system("pkg-config --exists libpulse") == 0): # 0 means found + if env["pulseaudio"]: + if os.system("pkg-config --exists libpulse") == 0: # 0 means found print("Enabling PulseAudio") env.Append(CPPDEFINES=["PULSEAUDIO_ENABLED"]) - env.ParseConfig('pkg-config --cflags --libs libpulse') + env.ParseConfig("pkg-config --cflags --libs libpulse") else: print("PulseAudio development libraries not found, disabling driver") - if (platform.system() == "Linux"): + if platform.system() == "Linux": env.Append(CPPDEFINES=["JOYDEV_ENABLED"]) - if env['udev']: - if (os.system("pkg-config --exists libudev") == 0): # 0 means found + if env["udev"]: + if os.system("pkg-config --exists libudev") == 0: # 0 means found print("Enabling udev support") env.Append(CPPDEFINES=["UDEV_ENABLED"]) - env.ParseConfig('pkg-config libudev --cflags --libs') + env.ParseConfig("pkg-config libudev --cflags --libs") else: print("libudev development libraries not found, disabling udev support") # Linkflags below this line should typically stay the last ones - if not env['builtin_zlib']: - env.ParseConfig('pkg-config zlib --cflags --libs') + if not env["builtin_zlib"]: + env.ParseConfig("pkg-config zlib --cflags --libs") - env.Prepend(CPPPATH=['#platform/linuxbsd']) - env.Append(CPPDEFINES=['X11_ENABLED', 'UNIX_ENABLED']) + env.Prepend(CPPPATH=["#platform/linuxbsd"]) + env.Append(CPPDEFINES=["X11_ENABLED", "UNIX_ENABLED"]) - env.Append(CPPDEFINES=['VULKAN_ENABLED']) - if not env['builtin_vulkan']: - env.ParseConfig('pkg-config vulkan --cflags --libs') - if not env['builtin_glslang']: + env.Append(CPPDEFINES=["VULKAN_ENABLED"]) + if not env["builtin_vulkan"]: + env.ParseConfig("pkg-config vulkan --cflags --libs") + if not env["builtin_glslang"]: # No pkgconfig file for glslang so far - env.Append(LIBS=['glslang', 'SPIRV']) + env.Append(LIBS=["glslang", "SPIRV"]) - #env.Append(CPPDEFINES=['OPENGL_ENABLED']) - env.Append(LIBS=['GL']) + # env.Append(CPPDEFINES=['OPENGL_ENABLED']) + env.Append(LIBS=["GL"]) - env.Append(LIBS=['pthread']) + env.Append(LIBS=["pthread"]) - if (platform.system() == "Linux"): - env.Append(LIBS=['dl']) + if platform.system() == "Linux": + env.Append(LIBS=["dl"]) - if (platform.system().find("BSD") >= 0): + if platform.system().find("BSD") >= 0: env["execinfo"] = True if env["execinfo"]: - env.Append(LIBS=['execinfo']) + env.Append(LIBS=["execinfo"]) - if not env['tools']: + if not env["tools"]: import subprocess import re - linker_version_str = subprocess.check_output([env.subst(env["LINK"]), '-Wl,--version']).decode("utf-8") - gnu_ld_version = re.search('^GNU ld [^$]*(\d+\.\d+)$', linker_version_str, re.MULTILINE) + + linker_version_str = subprocess.check_output([env.subst(env["LINK"]), "-Wl,--version"]).decode("utf-8") + gnu_ld_version = re.search("^GNU ld [^$]*(\d+\.\d+)$", linker_version_str, re.MULTILINE) if not gnu_ld_version: - print("Warning: Creating template binaries enabled for PCK embedding is currently only supported with GNU ld") + print( + "Warning: Creating template binaries enabled for PCK embedding is currently only supported with GNU ld" + ) else: if float(gnu_ld_version.group(1)) >= 2.30: - env.Append(LINKFLAGS=['-T', 'platform/linuxbsd/pck_embed.ld']) + env.Append(LINKFLAGS=["-T", "platform/linuxbsd/pck_embed.ld"]) else: - env.Append(LINKFLAGS=['-T', 'platform/linuxbsd/pck_embed.legacy.ld']) + env.Append(LINKFLAGS=["-T", "platform/linuxbsd/pck_embed.legacy.ld"]) ## Cross-compilation - if (is64 and env["bits"] == "32"): - env.Append(CCFLAGS=['-m32']) - env.Append(LINKFLAGS=['-m32', '-L/usr/lib/i386-linux-gnu']) - elif (not is64 and env["bits"] == "64"): - env.Append(CCFLAGS=['-m64']) - env.Append(LINKFLAGS=['-m64', '-L/usr/lib/i686-linux-gnu']) + if is64 and env["bits"] == "32": + env.Append(CCFLAGS=["-m32"]) + env.Append(LINKFLAGS=["-m32", "-L/usr/lib/i386-linux-gnu"]) + elif not is64 and env["bits"] == "64": + env.Append(CCFLAGS=["-m64"]) + env.Append(LINKFLAGS=["-m64", "-L/usr/lib/i686-linux-gnu"]) # Link those statically for portability - if env['use_static_cpp']: - env.Append(LINKFLAGS=['-static-libgcc', '-static-libstdc++']) + if env["use_static_cpp"]: + env.Append(LINKFLAGS=["-static-libgcc", "-static-libstdc++"]) diff --git a/platform/linuxbsd/detect_prime_x11.cpp b/platform/linuxbsd/detect_prime_x11.cpp index 69b0837e6c..1bec65ff04 100644 --- a/platform/linuxbsd/detect_prime_x11.cpp +++ b/platform/linuxbsd/detect_prime_x11.cpp @@ -67,12 +67,12 @@ vendor vendormap[] = { { "Intel", 20 }, { "nouveau", 10 }, { "Mesa Project", 0 }, - { NULL, 0 } + { nullptr, 0 } }; // Runs inside a child. Exiting will not quit the engine. void create_context() { - Display *x11_display = XOpenDisplay(NULL); + Display *x11_display = XOpenDisplay(nullptr); Window x11_window; GLXContext glx_context; @@ -91,7 +91,7 @@ void create_context() { int fbcount; GLXFBConfig fbconfig = 0; - XVisualInfo *vi = NULL; + XVisualInfo *vi = nullptr; XSetWindowAttributes swa; swa.event_mask = StructureNotifyMask; @@ -114,7 +114,7 @@ void create_context() { None }; - glx_context = glXCreateContextAttribsARB(x11_display, fbconfig, NULL, true, context_attribs); + glx_context = glXCreateContextAttribsARB(x11_display, fbconfig, nullptr, true, context_attribs); swa.colormap = XCreateColormap(x11_display, RootWindow(x11_display, vi->screen), vi->visual, AllocNone); x11_window = XCreateWindow(x11_display, RootWindow(x11_display, vi->screen), 0, 0, 10, 10, 0, vi->depth, InputOutput, vi->visual, valuemask, &swa); diff --git a/platform/linuxbsd/display_server_x11.cpp b/platform/linuxbsd/display_server_x11.cpp index 4bea458187..6049dbf4d6 100644 --- a/platform/linuxbsd/display_server_x11.cpp +++ b/platform/linuxbsd/display_server_x11.cpp @@ -44,7 +44,7 @@ #endif #if defined(VULKAN_ENABLED) -#include "servers/visual/rasterizer_rd/rasterizer_rd.h" +#include "servers/rendering/rasterizer_rd/rasterizer_rd.h" #endif #include "scene/resources/texture.h" @@ -254,10 +254,10 @@ bool DisplayServerX11::_refresh_device_info() { bool absolute_mode = false; int resolution_x = 0; int resolution_y = 0; - int range_min_x = 0; - int range_min_y = 0; - int range_max_x = 0; - int range_max_y = 0; + double range_min_x = 0; + double range_min_y = 0; + double range_max_x = 0; + double range_max_y = 0; int pressure_resolution = 0; int tilt_resolution_x = 0; int tilt_resolution_y = 0; @@ -902,7 +902,7 @@ void DisplayServerX11::window_set_position(const Point2i &p_position, WindowID p int format; unsigned long len; unsigned long remaining; - unsigned char *data = NULL; + unsigned char *data = nullptr; if (XGetWindowProperty(x11_display, wd.x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) { if (format == 32 && len == 4 && data) { long *extents = (long *)data; @@ -1091,7 +1091,7 @@ Size2i DisplayServerX11::window_get_real_size(WindowID p_window) const { int format; unsigned long len; unsigned long remaining; - unsigned char *data = NULL; + unsigned char *data = nullptr; if (XGetWindowProperty(x11_display, wd.x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) { if (format == 32 && len == 4 && data) { long *extents = (long *)data; @@ -1116,7 +1116,7 @@ bool DisplayServerX11::window_is_maximize_allowed(WindowID p_window) const { int format; unsigned long len; unsigned long remaining; - unsigned char *data = NULL; + unsigned char *data = nullptr; int result = XGetWindowProperty( x11_display, @@ -1402,7 +1402,7 @@ DisplayServer::WindowMode DisplayServerX11::window_get_mode(WindowID p_window) c int format; unsigned long len; unsigned long remaining; - unsigned char *data = NULL; + unsigned char *data = nullptr; bool retval = false; int result = XGetWindowProperty( @@ -1453,7 +1453,7 @@ DisplayServer::WindowMode DisplayServerX11::window_get_mode(WindowID p_window) c int format; unsigned long len; unsigned long remaining; - unsigned char *data = NULL; + unsigned char *data = nullptr; int result = XGetWindowProperty( x11_display, @@ -1592,7 +1592,7 @@ bool DisplayServerX11::window_get_flag(WindowFlags p_flag, WindowID p_window) co int format; unsigned long len; unsigned long remaining; - unsigned char *data = NULL; + unsigned char *data = nullptr; if (XGetWindowProperty(x11_display, wd.x11_window, prop, 0, sizeof(Hints), False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) { if (data && (format == 32) && (len >= 5)) { borderless = !((Hints *)data)->decorations; @@ -1719,8 +1719,8 @@ void DisplayServerX11::window_set_ime_position(const Point2i &p_pos, WindowID p_ ::XPoint spot; spot.x = short(p_pos.x); spot.y = short(p_pos.y); - XVaNestedList preedit_attr = XVaCreateNestedList(0, XNSpotLocation, &spot, NULL); - XSetICValues(wd.xic, XNPreeditAttributes, preedit_attr, NULL); + XVaNestedList preedit_attr = XVaCreateNestedList(0, XNSpotLocation, &spot, nullptr); + XSetICValues(wd.xic, XNPreeditAttributes, preedit_attr, nullptr); XFree(preedit_attr); } @@ -1827,7 +1827,7 @@ void DisplayServerX11::cursor_set_custom_image(const RES &p_cursor, CursorShape *(cursor_image->pixels + index) = image->get_pixel(column_index, row_index).to_argb32(); } - ERR_FAIL_COND(cursor_image->pixels == NULL); + ERR_FAIL_COND(cursor_image->pixels == nullptr); // Save it for a further usage cursors[p_shape] = XcursorImageLoadCursor(x11_display, cursor_image); @@ -1900,14 +1900,14 @@ DisplayServerX11::Property DisplayServerX11::_read_property(Display *p_display, int actual_format; unsigned long nitems; unsigned long bytes_after; - unsigned char *ret = 0; + unsigned char *ret = nullptr; int read_bytes = 1024; //Keep trying to read the property until there are no //bytes unread. do { - if (ret != 0) + if (ret != nullptr) XFree(ret); XGetWindowProperty(p_display, p_window, p_property, 0, read_bytes, False, AnyPropertyType, @@ -2006,8 +2006,8 @@ void DisplayServerX11::_handle_key_event(WindowID p_window, XKeyEvent *p_event, XKeyEvent xkeyevent_no_mod = *xkeyevent; xkeyevent_no_mod.state &= ~ShiftMask; xkeyevent_no_mod.state &= ~ControlMask; - XLookupString(xkeyevent, str, 256, &keysym_unicode, NULL); - XLookupString(&xkeyevent_no_mod, NULL, 0, &keysym_keycode, NULL); + XLookupString(xkeyevent, str, 256, &keysym_unicode, nullptr); + XLookupString(&xkeyevent_no_mod, nullptr, 0, &keysym_keycode, nullptr); // Meanwhile, XLookupString returns keysyms useful for unicode. @@ -2170,7 +2170,7 @@ void DisplayServerX11::_handle_key_event(WindowID p_window, XKeyEvent *p_event, #undef ABSDIFF if (peek_event.type == KeyPress && threshold < 5) { KeySym rk; - XLookupString((XKeyEvent *)&peek_event, str, 256, &rk, NULL); + XLookupString((XKeyEvent *)&peek_event, str, 256, &rk, nullptr); if (rk == keysym_keycode) { XEvent event; XNextEvent(x11_display, &event); //erase next event @@ -2232,10 +2232,10 @@ void DisplayServerX11::_xim_destroy_callback(::XIM im, ::XPointer client_data, WARN_PRINT("Input method stopped"); DisplayServerX11 *ds = reinterpret_cast<DisplayServerX11 *>(client_data); - ds->xim = NULL; + ds->xim = nullptr; for (Map<WindowID, WindowData>::Element *E = ds->windows.front(); E; E = E->next()) { - E->get().xic = NULL; + E->get().xic = nullptr; } } @@ -3222,11 +3222,11 @@ DisplayServerX11::WindowID DisplayServerX11::_create_window(WindowMode p_mode, u if (xim && xim_style) { - wd.xic = XCreateIC(xim, XNInputStyle, xim_style, XNClientWindow, wd.x11_window, XNFocusWindow, wd.x11_window, (char *)NULL); - if (XGetICValues(wd.xic, XNFilterEvents, &im_event_mask, NULL) != NULL) { + wd.xic = XCreateIC(xim, XNInputStyle, xim_style, XNClientWindow, wd.x11_window, XNFocusWindow, wd.x11_window, (char *)nullptr); + if (XGetICValues(wd.xic, XNFilterEvents, &im_event_mask, nullptr) != nullptr) { WARN_PRINT("XGetICValues couldn't obtain XNFilterEvents value"); XDestroyIC(wd.xic); - wd.xic = NULL; + wd.xic = nullptr; } if (wd.xic) { XUnsetICFocus(wd.xic); @@ -3235,7 +3235,7 @@ DisplayServerX11::WindowID DisplayServerX11::_create_window(WindowMode p_mode, u } } else { - wd.xic = NULL; + wd.xic = nullptr; WARN_PRINT("XCreateIC couldn't create wd.xic"); } @@ -3374,9 +3374,18 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode r_error = OK; + current_cursor = CURSOR_ARROW; + mouse_mode = MOUSE_MODE_VISIBLE; + + for (int i = 0; i < CURSOR_MAX; i++) { + + cursors[i] = None; + img[i] = nullptr; + } + last_button_state = 0; - xmbstring = NULL; + xmbstring = nullptr; last_click_ms = 0; last_click_button_index = -1; @@ -3389,7 +3398,7 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode XInitThreads(); //always use threads /** XLIB INITIALIZATION **/ - x11_display = XOpenDisplay(NULL); + x11_display = XOpenDisplay(nullptr); if (!x11_display) { ERR_PRINT("X11 Display is not available"); @@ -3397,10 +3406,10 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode return; } - char *modifiers = NULL; + char *modifiers = nullptr; Bool xkb_dar = False; XAutoRepeatOn(x11_display); - xkb_dar = XkbSetDetectableAutoRepeat(x11_display, True, NULL); + xkb_dar = XkbSetDetectableAutoRepeat(x11_display, True, nullptr); // Try to support IME if detectable auto-repeat is supported if (xkb_dar == True) { @@ -3412,7 +3421,7 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode #endif } - if (modifiers == NULL) { + if (modifiers == nullptr) { if (OS::get_singleton()->is_stdout_verbose()) { WARN_PRINT("IME is disabled"); } @@ -3421,8 +3430,8 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode } const char *err; - xrr_get_monitors = NULL; - xrr_free_monitors = NULL; + xrr_get_monitors = nullptr; + xrr_free_monitors = nullptr; int xrandr_major = 0; int xrandr_minor = 0; int event_base, error_base; @@ -3443,7 +3452,7 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode if (!xrr_free_monitors) { err = dlerror(); fprintf(stderr, "could not find XRRFreeMonitors\nError: %s\n", err); - xrr_get_monitors = NULL; + xrr_get_monitors = nullptr; } } } @@ -3457,9 +3466,9 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode return; } - xim = XOpenIM(x11_display, NULL, NULL, NULL); + xim = XOpenIM(x11_display, nullptr, nullptr, nullptr); - if (xim == NULL) { + if (xim == nullptr) { WARN_PRINT("XOpenIM failed"); xim_style = 0L; } else { @@ -3467,14 +3476,14 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode im_destroy_callback.client_data = (::XPointer)(this); im_destroy_callback.callback = (::XIMProc)(_xim_destroy_callback); if (XSetIMValues(xim, XNDestroyCallback, &im_destroy_callback, - NULL) != NULL) { + nullptr) != nullptr) { WARN_PRINT("Error setting XIM destroy callback"); } - ::XIMStyles *xim_styles = NULL; + ::XIMStyles *xim_styles = nullptr; xim_style = 0L; - char *imvalret = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL); - if (imvalret != NULL || xim_styles == NULL) { + char *imvalret = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, nullptr); + if (imvalret != nullptr || xim_styles == nullptr) { fprintf(stderr, "Input method doesn't support any styles\n"); } @@ -3523,7 +3532,7 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode context_vulkan = memnew(VulkanContextX11); if (context_vulkan->initialize() != OK) { memdelete(context_vulkan); - context_vulkan = NULL; + context_vulkan = nullptr; r_error = ERR_CANT_CREATE; ERR_FAIL_MSG("Could not initialize Vulkan"); } @@ -3532,7 +3541,7 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode // Init context and rendering device #if defined(OPENGL_ENABLED) if (rendering_driver == "opengl_es") { - if (getenv("DRI_PRIME") == NULL) { + if (getenv("DRI_PRIME") == nullptr) { int use_prime = -1; if (getenv("PRIMUS_DISPLAY") || @@ -3578,7 +3587,7 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode if (context_gles2->initialize() != OK) { memdelete(context_gles2); - context_gles2 = NULL; + context_gles2 = nullptr; ERR_FAIL_V(ERR_UNAVAILABLE); } @@ -3589,7 +3598,7 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode RasterizerGLES2::make_current(); } else { memdelete(context_gles2); - context_gles2 = NULL; + context_gles2 = nullptr; ERR_FAIL_V(ERR_UNAVAILABLE); } } @@ -3615,9 +3624,9 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode #endif /* - visual_server = memnew(VisualServerRaster); + rendering_server = memnew(RenderingServerRaster); if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { - visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD)); + rendering_server = memnew(RenderingServerWrapMT(rendering_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD)); } */ @@ -3652,14 +3661,6 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode for (int i = 0; i < CURSOR_MAX; i++) { - cursors[i] = None; - img[i] = NULL; - } - - current_cursor = CURSOR_ARROW; - - for (int i = 0; i < CURSOR_MAX; i++) { - static const char *cursor_file[] = { "left_ptr", "xterm", @@ -3682,7 +3683,7 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode img[i] = XcursorLibraryLoadImage(cursor_file[i], cursor_theme, cursor_size); if (!img[i]) { - const char *fallback = NULL; + const char *fallback = nullptr; switch (i) { case CURSOR_POINTING_HAND: @@ -3731,7 +3732,7 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode fallback = "help"; break; } - if (fallback != NULL) { + if (fallback != nullptr) { img[i] = XcursorLibraryLoadImage(fallback, cursor_theme, cursor_size); } } @@ -3831,7 +3832,7 @@ DisplayServerX11::~DisplayServerX11() { for (int i = 0; i < CURSOR_MAX; i++) { if (cursors[i] != None) XFreeCursor(x11_display, cursors[i]); - if (img[i] != NULL) + if (img[i] != nullptr) XcursorImageDestroy(img[i]); }; diff --git a/platform/linuxbsd/display_server_x11.h b/platform/linuxbsd/display_server_x11.h index d1680b0508..113e504e9b 100644 --- a/platform/linuxbsd/display_server_x11.h +++ b/platform/linuxbsd/display_server_x11.h @@ -43,8 +43,8 @@ #include "drivers/unix/os_unix.h" #include "joypad_linux.h" #include "servers/audio_server.h" -#include "servers/visual/rasterizer.h" -#include "servers/visual_server.h" +#include "servers/rendering/rasterizer.h" +#include "servers/rendering_server.h" #if defined(OPENGL_ENABLED) #include "context_gl_x11.h" @@ -193,7 +193,6 @@ class DisplayServerX11 : public DisplayServer { void _handle_key_event(WindowID p_window, XKeyEvent *p_event, bool p_echo = false); - bool force_quit; bool minimized; bool window_has_focus; bool do_mouse_warp; diff --git a/platform/linuxbsd/joypad_linux.cpp b/platform/linuxbsd/joypad_linux.cpp index c4c793093d..381eb909ba 100644 --- a/platform/linuxbsd/joypad_linux.cpp +++ b/platform/linuxbsd/joypad_linux.cpp @@ -54,7 +54,7 @@ JoypadLinux::Joypad::Joypad() { dpad = 0; devpath = ""; for (int i = 0; i < MAX_ABS; i++) { - abs_info[i] = NULL; + abs_info[i] = nullptr; } } @@ -146,9 +146,9 @@ void JoypadLinux::enumerate_joypads(udev *p_udev) { void JoypadLinux::monitor_joypads(udev *p_udev) { - udev_device *dev = NULL; + udev_device *dev = nullptr; udev_monitor *mon = udev_monitor_new_from_netlink(p_udev, "udev"); - udev_monitor_filter_add_match_subsystem_devtype(mon, "input", NULL); + udev_monitor_filter_add_match_subsystem_devtype(mon, "input", nullptr); udev_monitor_enable_receiving(mon); int fd = udev_monitor_get_fd(mon); @@ -163,7 +163,7 @@ void JoypadLinux::monitor_joypads(udev *p_udev) { tv.tv_sec = 0; tv.tv_usec = 0; - ret = select(fd + 1, &fds, NULL, NULL, &tv); + ret = select(fd + 1, &fds, nullptr, nullptr, &tv); /* Check if our file descriptor has received data. */ if (ret > 0 && FD_ISSET(fd, &fds)) { @@ -299,7 +299,7 @@ void JoypadLinux::setup_joypad_properties(int p_id) { joy->abs_info[i] = memnew(input_absinfo); if (ioctl(joy->fd, EVIOCGABS(i), joy->abs_info[i]) < 0) { memdelete(joy->abs_info[i]); - joy->abs_info[i] = NULL; + joy->abs_info[i] = nullptr; } } } diff --git a/platform/linuxbsd/os_linuxbsd.cpp b/platform/linuxbsd/os_linuxbsd.cpp index 084453bdc6..5b9a25bd8b 100644 --- a/platform/linuxbsd/os_linuxbsd.cpp +++ b/platform/linuxbsd/os_linuxbsd.cpp @@ -87,7 +87,7 @@ void OS_LinuxBSD::finalize() { if (main_loop) memdelete(main_loop); - main_loop = NULL; + main_loop = nullptr; #ifdef ALSAMIDI_ENABLED driver_alsamidi.close(); @@ -107,7 +107,7 @@ void OS_LinuxBSD::delete_main_loop() { if (main_loop) memdelete(main_loop); - main_loop = NULL; + main_loop = nullptr; } void OS_LinuxBSD::set_main_loop(MainLoop *p_main_loop) { @@ -230,7 +230,7 @@ String OS_LinuxBSD::get_system_dir(SystemDir p_dir) const { String pipe; List<String> arg; arg.push_back(xdgparam); - Error err = const_cast<OS_LinuxBSD *>(this)->execute("xdg-user-dir", arg, true, NULL, &pipe); + Error err = const_cast<OS_LinuxBSD *>(this)->execute("xdg-user-dir", arg, true, nullptr, &pipe); if (err != OK) return "."; return pipe.strip_edges(); @@ -351,7 +351,7 @@ Error OS_LinuxBSD::move_to_trash(const String &p_path) { mv_args.push_back(p_path); mv_args.push_back(trash_can); int retval; - err = execute("mv", mv_args, true, NULL, NULL, &retval); + err = execute("mv", mv_args, true, nullptr, nullptr, &retval); // Issue an error if "mv" failed to move the given resource to the trash can. if (err != OK || retval != 0) { @@ -364,7 +364,7 @@ Error OS_LinuxBSD::move_to_trash(const String &p_path) { OS_LinuxBSD::OS_LinuxBSD() { - main_loop = NULL; + main_loop = nullptr; force_quit = false; #ifdef PULSEAUDIO_ENABLED diff --git a/platform/linuxbsd/os_linuxbsd.h b/platform/linuxbsd/os_linuxbsd.h index 6c656c1945..100cb53ba3 100644 --- a/platform/linuxbsd/os_linuxbsd.h +++ b/platform/linuxbsd/os_linuxbsd.h @@ -39,8 +39,8 @@ #include "drivers/unix/os_unix.h" #include "joypad_linux.h" #include "servers/audio_server.h" -#include "servers/visual/rasterizer.h" -#include "servers/visual_server.h" +#include "servers/rendering/rasterizer.h" +#include "servers/rendering_server.h" class OS_LinuxBSD : public OS_Unix { diff --git a/platform/linuxbsd/platform_linuxbsd_builders.py b/platform/linuxbsd/platform_linuxbsd_builders.py index a72306a9c0..58234f3748 100644 --- a/platform/linuxbsd/platform_linuxbsd_builders.py +++ b/platform/linuxbsd/platform_linuxbsd_builders.py @@ -8,10 +8,10 @@ from platform_methods import subprocess_main def make_debug_linuxbsd(target, source, env): - os.system('objcopy --only-keep-debug {0} {0}.debugsymbols'.format(target[0])) - os.system('strip --strip-debug --strip-unneeded {0}'.format(target[0])) - os.system('objcopy --add-gnu-debuglink={0}.debugsymbols {0}'.format(target[0])) + os.system("objcopy --only-keep-debug {0} {0}.debugsymbols".format(target[0])) + os.system("strip --strip-debug --strip-unneeded {0}".format(target[0])) + os.system("objcopy --add-gnu-debuglink={0}.debugsymbols {0}".format(target[0])) -if __name__ == '__main__': +if __name__ == "__main__": subprocess_main(globals()) diff --git a/platform/linuxbsd/vulkan_context_x11.cpp b/platform/linuxbsd/vulkan_context_x11.cpp index d0e1b1678c..1798a7026e 100644 --- a/platform/linuxbsd/vulkan_context_x11.cpp +++ b/platform/linuxbsd/vulkan_context_x11.cpp @@ -39,13 +39,13 @@ Error VulkanContextX11::window_create(DisplayServer::WindowID p_window_id, ::Win VkXlibSurfaceCreateInfoKHR createInfo; createInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR; - createInfo.pNext = NULL; + createInfo.pNext = nullptr; createInfo.flags = 0; createInfo.dpy = p_display; createInfo.window = p_window; VkSurfaceKHR surface; - VkResult err = vkCreateXlibSurfaceKHR(_get_instance(), &createInfo, NULL, &surface); + VkResult err = vkCreateXlibSurfaceKHR(_get_instance(), &createInfo, nullptr, &surface); ERR_FAIL_COND_V(err, ERR_CANT_CREATE); return _window_create(p_window_id, surface, p_width, p_height); } diff --git a/platform/osx/SCsub b/platform/osx/SCsub index 4ec8aeab6d..ad62db358b 100644 --- a/platform/osx/SCsub +++ b/platform/osx/SCsub @@ -1,23 +1,22 @@ #!/usr/bin/env python -Import('env') +Import("env") from platform_methods import run_in_subprocess import platform_osx_builders files = [ - 'crash_handler_osx.mm', - 'os_osx.mm', - 'display_server_osx.mm', - 'godot_main_osx.mm', - 'dir_access_osx.mm', - 'joypad_osx.cpp', - 'vulkan_context_osx.mm', - 'context_gl_osx.mm' + "crash_handler_osx.mm", + "os_osx.mm", + "display_server_osx.mm", + "godot_main_osx.mm", + "dir_access_osx.mm", + "joypad_osx.cpp", + "vulkan_context_osx.mm", + "context_gl_osx.mm", ] -prog = env.add_program('#bin/godot', files) +prog = env.add_program("#bin/godot", files) if (env["debug_symbols"] == "full" or env["debug_symbols"] == "yes") and env["separate_debug_symbols"]: env.AddPostAction(prog, run_in_subprocess(platform_osx_builders.make_debug_osx)) - diff --git a/platform/osx/detect.py b/platform/osx/detect.py index 12ca5c10dc..29aa8ece19 100644 --- a/platform/osx/detect.py +++ b/platform/osx/detect.py @@ -14,7 +14,7 @@ def get_name(): def can_build(): - if (sys.platform == "darwin" or ("OSXCROSS_ROOT" in os.environ)): + if sys.platform == "darwin" or ("OSXCROSS_ROOT" in os.environ): return True return False @@ -24,52 +24,55 @@ def get_opts(): from SCons.Variables import BoolVariable, EnumVariable return [ - ('osxcross_sdk', 'OSXCross SDK version', 'darwin14'), - ('MACOS_SDK_PATH', 'Path to the macOS SDK', ''), - BoolVariable('use_static_mvk', 'Link MoltenVK statically as Level-0 driver (better portability) or use Vulkan ICD loader (enables validation layers)', False), - EnumVariable('debug_symbols', 'Add debugging symbols to release builds', 'yes', ('yes', 'no', 'full')), - BoolVariable('separate_debug_symbols', 'Create a separate file containing debugging symbols', False), - BoolVariable('use_ubsan', 'Use LLVM/GCC compiler undefined behavior sanitizer (UBSAN)', False), - BoolVariable('use_asan', 'Use LLVM/GCC compiler address sanitizer (ASAN))', False), - BoolVariable('use_tsan', 'Use LLVM/GCC compiler thread sanitizer (TSAN))', False), + ("osxcross_sdk", "OSXCross SDK version", "darwin14"), + ("MACOS_SDK_PATH", "Path to the macOS SDK", ""), + BoolVariable( + "use_static_mvk", + "Link MoltenVK statically as Level-0 driver (better portability) or use Vulkan ICD loader (enables validation layers)", + False, + ), + EnumVariable("debug_symbols", "Add debugging symbols to release builds", "yes", ("yes", "no", "full")), + BoolVariable("separate_debug_symbols", "Create a separate file containing debugging symbols", False), + BoolVariable("use_ubsan", "Use LLVM/GCC compiler undefined behavior sanitizer (UBSAN)", False), + BoolVariable("use_asan", "Use LLVM/GCC compiler address sanitizer (ASAN))", False), + BoolVariable("use_tsan", "Use LLVM/GCC compiler thread sanitizer (TSAN))", False), ] def get_flags(): - return [ - ] + return [] def configure(env): - ## Build type - - if (env["target"] == "release"): - if (env["optimize"] == "speed"): #optimize for speed (default) - env.Prepend(CCFLAGS=['-O3', '-fomit-frame-pointer', '-ftree-vectorize', '-msse2']) - else: #optimize for size - env.Prepend(CCFLAGS=['-Os','-ftree-vectorize', '-msse2']) - - if (env["debug_symbols"] == "yes"): - env.Prepend(CCFLAGS=['-g1']) - if (env["debug_symbols"] == "full"): - env.Prepend(CCFLAGS=['-g2']) - - elif (env["target"] == "release_debug"): - if (env["optimize"] == "speed"): #optimize for speed (default) - env.Prepend(CCFLAGS=['-O2']) - else: #optimize for size - env.Prepend(CCFLAGS=['-Os']) - env.Prepend(CPPDEFINES=['DEBUG_ENABLED']) - if (env["debug_symbols"] == "yes"): - env.Prepend(CCFLAGS=['-g1']) - if (env["debug_symbols"] == "full"): - env.Prepend(CCFLAGS=['-g2']) - - elif (env["target"] == "debug"): - env.Prepend(CCFLAGS=['-g3']) - env.Prepend(CPPDEFINES=['DEBUG_ENABLED', 'DEBUG_MEMORY_ENABLED']) + ## Build type + + if env["target"] == "release": + if env["optimize"] == "speed": # optimize for speed (default) + env.Prepend(CCFLAGS=["-O3", "-fomit-frame-pointer", "-ftree-vectorize", "-msse2"]) + else: # optimize for size + env.Prepend(CCFLAGS=["-Os", "-ftree-vectorize", "-msse2"]) + + if env["debug_symbols"] == "yes": + env.Prepend(CCFLAGS=["-g1"]) + if env["debug_symbols"] == "full": + env.Prepend(CCFLAGS=["-g2"]) + + elif env["target"] == "release_debug": + if env["optimize"] == "speed": # optimize for speed (default) + env.Prepend(CCFLAGS=["-O2"]) + else: # optimize for size + env.Prepend(CCFLAGS=["-Os"]) + env.Prepend(CPPDEFINES=["DEBUG_ENABLED"]) + if env["debug_symbols"] == "yes": + env.Prepend(CCFLAGS=["-g1"]) + if env["debug_symbols"] == "full": + env.Prepend(CCFLAGS=["-g2"]) + + elif env["target"] == "debug": + env.Prepend(CCFLAGS=["-g3"]) + env.Prepend(CPPDEFINES=["DEBUG_ENABLED", "DEBUG_MEMORY_ENABLED"]) ## Architecture @@ -83,86 +86,109 @@ def configure(env): if "OSXCROSS_ROOT" in os.environ: env["osxcross"] = True - if not "osxcross" in env: # regular native build - env.Append(CCFLAGS=['-arch', 'x86_64']) - env.Append(LINKFLAGS=['-arch', 'x86_64']) - if (env["macports_clang"] != 'no'): + if not "osxcross" in env: # regular native build + env.Append(CCFLAGS=["-arch", "x86_64"]) + env.Append(LINKFLAGS=["-arch", "x86_64"]) + if env["macports_clang"] != "no": mpprefix = os.environ.get("MACPORTS_PREFIX", "/opt/local") mpclangver = env["macports_clang"] env["CC"] = mpprefix + "/libexec/llvm-" + mpclangver + "/bin/clang" env["LINK"] = mpprefix + "/libexec/llvm-" + mpclangver + "/bin/clang++" env["CXX"] = mpprefix + "/libexec/llvm-" + mpclangver + "/bin/clang++" - env['AR'] = mpprefix + "/libexec/llvm-" + mpclangver + "/bin/llvm-ar" - env['RANLIB'] = mpprefix + "/libexec/llvm-" + mpclangver + "/bin/llvm-ranlib" - env['AS'] = mpprefix + "/libexec/llvm-" + mpclangver + "/bin/llvm-as" - env.Append(CPPDEFINES=['__MACPORTS__']) #hack to fix libvpx MM256_BROADCASTSI128_SI256 define + env["AR"] = mpprefix + "/libexec/llvm-" + mpclangver + "/bin/llvm-ar" + env["RANLIB"] = mpprefix + "/libexec/llvm-" + mpclangver + "/bin/llvm-ranlib" + env["AS"] = mpprefix + "/libexec/llvm-" + mpclangver + "/bin/llvm-as" + env.Append(CPPDEFINES=["__MACPORTS__"]) # hack to fix libvpx MM256_BROADCASTSI128_SI256 define else: - env['CC'] = 'clang' - env['CXX'] = 'clang++' + env["CC"] = "clang" + env["CXX"] = "clang++" - detect_darwin_sdk_path('osx', env) - env.Append(CCFLAGS=['-isysroot', '$MACOS_SDK_PATH']) - env.Append(LINKFLAGS=['-isysroot', '$MACOS_SDK_PATH']) + detect_darwin_sdk_path("osx", env) + env.Append(CCFLAGS=["-isysroot", "$MACOS_SDK_PATH"]) + env.Append(LINKFLAGS=["-isysroot", "$MACOS_SDK_PATH"]) - else: # osxcross build + else: # osxcross build root = os.environ.get("OSXCROSS_ROOT", 0) basecmd = root + "/target/bin/x86_64-apple-" + env["osxcross_sdk"] + "-" ccache_path = os.environ.get("CCACHE") if ccache_path is None: - env['CC'] = basecmd + "cc" - env['CXX'] = basecmd + "c++" + env["CC"] = basecmd + "cc" + env["CXX"] = basecmd + "c++" else: # there aren't any ccache wrappers available for OS X cross-compile, # to enable caching we need to prepend the path to the ccache binary - env['CC'] = ccache_path + ' ' + basecmd + "cc" - env['CXX'] = ccache_path + ' ' + basecmd + "c++" - env['AR'] = basecmd + "ar" - env['RANLIB'] = basecmd + "ranlib" - env['AS'] = basecmd + "as" - env.Append(CPPDEFINES=['__MACPORTS__']) #hack to fix libvpx MM256_BROADCASTSI128_SI256 define - - if (env["CXX"] == "clang++"): - env.Append(CPPDEFINES=['TYPED_METHOD_BIND']) + env["CC"] = ccache_path + " " + basecmd + "cc" + env["CXX"] = ccache_path + " " + basecmd + "c++" + env["AR"] = basecmd + "ar" + env["RANLIB"] = basecmd + "ranlib" + env["AS"] = basecmd + "as" + env.Append(CPPDEFINES=["__MACPORTS__"]) # hack to fix libvpx MM256_BROADCASTSI128_SI256 define + + if env["CXX"] == "clang++": + env.Append(CPPDEFINES=["TYPED_METHOD_BIND"]) env["CC"] = "clang" env["LINK"] = "clang++" - if env['use_ubsan'] or env['use_asan'] or env['use_tsan']: + if env["use_ubsan"] or env["use_asan"] or env["use_tsan"]: env.extra_suffix += "s" - if env['use_ubsan']: - env.Append(CCFLAGS=['-fsanitize=undefined']) - env.Append(LINKFLAGS=['-fsanitize=undefined']) + if env["use_ubsan"]: + env.Append(CCFLAGS=["-fsanitize=undefined"]) + env.Append(LINKFLAGS=["-fsanitize=undefined"]) - if env['use_asan']: - env.Append(CCFLAGS=['-fsanitize=address']) - env.Append(LINKFLAGS=['-fsanitize=address']) + if env["use_asan"]: + env.Append(CCFLAGS=["-fsanitize=address"]) + env.Append(LINKFLAGS=["-fsanitize=address"]) - if env['use_tsan']: - env.Append(CCFLAGS=['-fsanitize=thread']) - env.Append(LINKFLAGS=['-fsanitize=thread']) + if env["use_tsan"]: + env.Append(CCFLAGS=["-fsanitize=thread"]) + env.Append(LINKFLAGS=["-fsanitize=thread"]) ## Dependencies - if env['builtin_libtheora']: + if env["builtin_libtheora"]: env["x86_libtheora_opt_gcc"] = True ## Flags - env.Prepend(CPPPATH=['#platform/osx']) - env.Append(CPPDEFINES=['OSX_ENABLED', 'UNIX_ENABLED', 'APPLE_STYLE_KEYS', 'COREAUDIO_ENABLED', 'COREMIDI_ENABLED']) - env.Append(LINKFLAGS=['-framework', 'Cocoa', '-framework', 'Carbon', '-framework', 'AudioUnit', '-framework', 'CoreAudio', '-framework', 'CoreMIDI', '-framework', 'IOKit', '-framework', 'ForceFeedback', '-framework', 'CoreVideo', '-framework', 'AVFoundation', '-framework', 'CoreMedia']) - env.Append(LIBS=['pthread', 'z']) - - env.Append(CPPDEFINES=['VULKAN_ENABLED']) - env.Append(LINKFLAGS=['-framework', 'Metal', '-framework', 'QuartzCore', '-framework', 'IOSurface']) - if (env['use_static_mvk']): - env.Append(LINKFLAGS=['-framework', 'MoltenVK']) - env['builtin_vulkan'] = False - elif not env['builtin_vulkan']: - env.Append(LIBS=['vulkan']) - - #env.Append(CPPDEFINES=['GLES_ENABLED', 'OPENGL_ENABLED']) - - env.Append(CCFLAGS=['-mmacosx-version-min=10.12']) - env.Append(LINKFLAGS=['-mmacosx-version-min=10.12']) + env.Prepend(CPPPATH=["#platform/osx"]) + env.Append(CPPDEFINES=["OSX_ENABLED", "UNIX_ENABLED", "APPLE_STYLE_KEYS", "COREAUDIO_ENABLED", "COREMIDI_ENABLED"]) + env.Append( + LINKFLAGS=[ + "-framework", + "Cocoa", + "-framework", + "Carbon", + "-framework", + "AudioUnit", + "-framework", + "CoreAudio", + "-framework", + "CoreMIDI", + "-framework", + "IOKit", + "-framework", + "ForceFeedback", + "-framework", + "CoreVideo", + "-framework", + "AVFoundation", + "-framework", + "CoreMedia", + ] + ) + env.Append(LIBS=["pthread", "z"]) + + env.Append(CPPDEFINES=["VULKAN_ENABLED"]) + env.Append(LINKFLAGS=["-framework", "Metal", "-framework", "QuartzCore", "-framework", "IOSurface"]) + if env["use_static_mvk"]: + env.Append(LINKFLAGS=["-framework", "MoltenVK"]) + env["builtin_vulkan"] = False + elif not env["builtin_vulkan"]: + env.Append(LIBS=["vulkan"]) + + # env.Append(CPPDEFINES=['GLES_ENABLED', 'OPENGL_ENABLED']) + + env.Append(CCFLAGS=["-mmacosx-version-min=10.12"]) + env.Append(LINKFLAGS=["-mmacosx-version-min=10.12"]) diff --git a/platform/osx/display_server_osx.h b/platform/osx/display_server_osx.h index d0e2babd06..86ceb51763 100644 --- a/platform/osx/display_server_osx.h +++ b/platform/osx/display_server_osx.h @@ -71,8 +71,8 @@ public: const NSMenu *_get_menu_root(const String &p_menu_root) const; NSMenu *_get_menu_root(const String &p_menu_root); - NSMenu *apple_menu = NULL; - NSMenu *dock_menu = NULL; + NSMenu *apple_menu = nullptr; + NSMenu *dock_menu = nullptr; Map<String, NSMenu *> submenu; struct KeyEvent { @@ -95,7 +95,7 @@ public: id window_view; #if defined(OPENGL_ENABLED) - ContextGL_OSX *context_gles2 = NULL; + ContextGL_OSX *context_gles2 = nullptr; #endif Point2i mouse_pos; @@ -148,6 +148,7 @@ public: void _push_input(const Ref<InputEvent> &p_event); void _process_key_events(); + void _release_pressed_events(); String rendering_driver; @@ -165,6 +166,7 @@ public: bool window_focused; bool drop_events; + bool in_dispatch_input_event = false; public: virtual bool has_feature(Feature p_feature) const; diff --git a/platform/osx/display_server_osx.mm b/platform/osx/display_server_osx.mm index a7099c1207..074fc3be0d 100644 --- a/platform/osx/display_server_osx.mm +++ b/platform/osx/display_server_osx.mm @@ -50,7 +50,7 @@ #endif #if defined(VULKAN_ENABLED) -#include "servers/visual/rasterizer_rd/rasterizer_rd.h" +#include "servers/rendering/rasterizer_rd/rasterizer_rd.h" #include <QuartzCore/CAMetalLayer.h> #endif @@ -286,8 +286,15 @@ static NSCursor *_cursorFromSelector(SEL selector, SEL fallback = nil) { DS_OSX->window_set_transient(wd.transient_children.front()->get(), DisplayServerOSX::INVALID_WINDOW_ID); } + DS_OSX->windows.erase(window_id); + if (wd.transient_parent != DisplayServerOSX::INVALID_WINDOW_ID) { + DisplayServerOSX::WindowData &pwd = DS_OSX->windows[wd.transient_parent]; + [pwd.window_object makeKeyAndOrderFront:nil]; // Move focus back to parent. DS_OSX->window_set_transient(window_id, DisplayServerOSX::INVALID_WINDOW_ID); + } else if ((window_id != DisplayServerOSX::MAIN_WINDOW_ID) && (DS_OSX->windows.size() == 1)) { + DisplayServerOSX::WindowData &pwd = DS_OSX->windows[DisplayServerOSX::MAIN_WINDOW_ID]; + [pwd.window_object makeKeyAndOrderFront:nil]; // Move focus back to main window if there is no parent or other windows left. } #ifdef VULKAN_ENABLED @@ -295,7 +302,6 @@ static NSCursor *_cursorFromSelector(SEL selector, SEL fallback = nil) { DS_OSX->context_vulkan->window_destroy(window_id); } #endif - DS_OSX->windows.erase(window_id); } - (void)windowDidEnterFullScreen:(NSNotification *)notification { @@ -414,9 +420,7 @@ static NSCursor *_cursorFromSelector(SEL selector, SEL fallback = nil) { } - (void)windowDidMove:(NSNotification *)notification { - if (InputFilter::get_singleton()) { - InputFilter::get_singleton()->release_pressed_events(); - } + DS_OSX->_release_pressed_events(); } - (void)windowDidBecomeKey:(NSNotification *)notification { @@ -437,7 +441,7 @@ static NSCursor *_cursorFromSelector(SEL selector, SEL fallback = nil) { DS_OSX->window_focused = false; - InputFilter::get_singleton()->release_pressed_events(); + DS_OSX->_release_pressed_events(); DS_OSX->_send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_FOCUS_OUT); } @@ -447,7 +451,7 @@ static NSCursor *_cursorFromSelector(SEL selector, SEL fallback = nil) { DS_OSX->window_focused = false; - InputFilter::get_singleton()->release_pressed_events(); + DS_OSX->_release_pressed_events(); DS_OSX->_send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_FOCUS_OUT); } @@ -2139,7 +2143,7 @@ Rect2i DisplayServerOSX::screen_get_usable_rect(int p_screen) const { Point2i position = Point2i(nsrect.origin.x, nsrect.origin.y + nsrect.size.height) * displayScale - _get_screens_origin(); position.y *= -1; - Size2i size = Size2i(nsrect.size.width, nsrect.size.height) * displayScale; + Size2i size = Size2i(nsrect.size.width, nsrect.size.height) / displayScale; return Rect2i(position, size); } @@ -2172,6 +2176,8 @@ DisplayServer::WindowID DisplayServerOSX::create_sub_window(WindowMode p_mode, u } void DisplayServerOSX::_send_window_event(const WindowData &wd, WindowEvent p_event) { + _THREAD_SAFE_METHOD_ + if (!wd.event_callback.is_null()) { Variant event = int(p_event); Variant *eventp = &event; @@ -2222,20 +2228,8 @@ void DisplayServerOSX::delete_sub_window(WindowID p_id) { WindowData &wd = windows[p_id]; - while (wd.transient_children.size()) { - window_set_transient(wd.transient_children.front()->get(), INVALID_WINDOW_ID); - } - - if (wd.transient_parent != INVALID_WINDOW_ID) { - WindowData &pwd = windows[wd.transient_parent]; - [pwd.window_object makeKeyAndOrderFront:nil]; // Move focus back to parent. - window_set_transient(p_id, INVALID_WINDOW_ID); - } - [wd.window_object setContentView:nil]; [wd.window_object close]; - - windows.erase(p_id); } void DisplayServerOSX::window_set_title(const String &p_title, WindowID p_window) { @@ -3011,6 +3005,13 @@ void DisplayServerOSX::_push_input(const Ref<InputEvent> &p_event) { InputFilter::get_singleton()->accumulate_input_event(ev); } +void DisplayServerOSX::_release_pressed_events() { + _THREAD_SAFE_METHOD_ + if (InputFilter::get_singleton()) { + InputFilter::get_singleton()->release_pressed_events(); + } +} + void DisplayServerOSX::_process_key_events() { Ref<InputEventKey> k; for (int i = 0; i < key_event_pos; i++) { @@ -3337,30 +3338,37 @@ void DisplayServerOSX::_dispatch_input_events(const Ref<InputEvent> &p_event) { } void DisplayServerOSX::_dispatch_input_event(const Ref<InputEvent> &p_event) { - Variant ev = p_event; - Variant *evp = &ev; - Variant ret; - Callable::CallError ce; - - Ref<InputEventFromWindow> event_from_window = p_event; - if (event_from_window.is_valid() && event_from_window->get_window_id() != INVALID_WINDOW_ID) { - //send to a window - if (windows.has(event_from_window->get_window_id())) { - Callable callable = windows[event_from_window->get_window_id()].input_event_callback; - if (callable.is_null()) { - return; + _THREAD_SAFE_METHOD_ + if (!in_dispatch_input_event) { + in_dispatch_input_event = true; + + Variant ev = p_event; + Variant *evp = &ev; + Variant ret; + Callable::CallError ce; + + Ref<InputEventFromWindow> event_from_window = p_event; + if (event_from_window.is_valid() && event_from_window->get_window_id() != INVALID_WINDOW_ID) { + //send to a window + if (windows.has(event_from_window->get_window_id())) { + Callable callable = windows[event_from_window->get_window_id()].input_event_callback; + if (callable.is_null()) { + return; + } + callable.call((const Variant **)&evp, 1, ret, ce); } - callable.call((const Variant **)&evp, 1, ret, ce); - } - } else { - //send to all windows - for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) { - Callable callable = E->get().input_event_callback; - if (callable.is_null()) { - continue; + } else { + //send to all windows + for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) { + Callable callable = E->get().input_event_callback; + if (callable.is_null()) { + continue; + } + callable.call((const Variant **)&evp, 1, ret, ce); } - callable.call((const Variant **)&evp, 1, ret, ce); } + + in_dispatch_input_event = false; } } diff --git a/platform/osx/export/export.cpp b/platform/osx/export/export.cpp index dbe52da912..c2df9c7082 100644 --- a/platform/osx/export/export.cpp +++ b/platform/osx/export/export.cpp @@ -402,7 +402,7 @@ Error EditorExportPlatformOSX::_code_sign(const Ref<EditorExportPreset> &p_prese args.push_back(p_path); String str; - Error err = OS::get_singleton()->execute("codesign", args, true, NULL, &str, NULL, true); + Error err = OS::get_singleton()->execute("codesign", args, true, nullptr, &str, nullptr, true); ERR_FAIL_COND_V(err != OK, err); print_line("codesign (" + p_path + "): " + str); @@ -435,7 +435,7 @@ Error EditorExportPlatformOSX::_create_dmg(const String &p_dmg_path, const Strin args.push_back(p_app_path_name); String str; - Error err = OS::get_singleton()->execute("hdiutil", args, true, NULL, &str, NULL, true); + Error err = OS::get_singleton()->execute("hdiutil", args, true, nullptr, &str, nullptr, true); ERR_FAIL_COND_V(err != OK, err); print_line("hdiutil returned: " + str); @@ -476,7 +476,7 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p return ERR_FILE_BAD_PATH; } - FileAccess *src_f = NULL; + FileAccess *src_f = nullptr; zlib_filefunc_def io = zipio_create_io_from_file(&src_f); if (ep.step("Creating app", 0)) { @@ -507,11 +507,11 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p Error err = OK; String tmp_app_path_name = ""; zlib_filefunc_def io2 = io; - FileAccess *dst_f = NULL; + FileAccess *dst_f = nullptr; io2.opaque = &dst_f; - zipFile dst_pkg_zip = NULL; + zipFile dst_pkg_zip = nullptr; - DirAccess *tmp_app_path = NULL; + DirAccess *tmp_app_path = nullptr; String export_format = use_dmg() && p_path.ends_with("dmg") ? "dmg" : "zip"; if (export_format == "dmg") { // We're on OSX so we can export to DMG, but first we create our application bundle @@ -539,7 +539,7 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p } } else { // Open our destination zip file - dst_pkg_zip = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, NULL, &io2); + dst_pkg_zip = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io2); if (!dst_pkg_zip) { err = ERR_CANT_CREATE; } @@ -555,7 +555,7 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p //get filename unz_file_info info; char fname[16384]; - ret = unzGetCurrentFileInfo(src_pkg_zip, &info, fname, 16384, NULL, 0, NULL, 0); + ret = unzGetCurrentFileInfo(src_pkg_zip, &info, fname, 16384, nullptr, 0, nullptr, 0); String file = fname; @@ -672,11 +672,11 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p zipOpenNewFileInZip(dst_pkg_zip, file.utf8().get_data(), &fi, - NULL, + nullptr, 0, - NULL, + nullptr, 0, - NULL, + nullptr, Z_DEFLATED, Z_DEFAULT_COMPRESSION); @@ -754,12 +754,12 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p if (err == OK) { zipOpenNewFileInZip(dst_pkg_zip, (pkg_name + ".app/Contents/Resources/" + pkg_name + ".pck").utf8().get_data(), - NULL, - NULL, + nullptr, + nullptr, 0, - NULL, + nullptr, 0, - NULL, + nullptr, Z_DEFLATED, Z_DEFAULT_COMPRESSION); @@ -791,12 +791,12 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p zipOpenNewFileInZip(dst_pkg_zip, (pkg_name + ".app/Contents/Frameworks/").plus_file(shared_objects[i].path.get_file()).utf8().get_data(), - NULL, - NULL, + nullptr, + nullptr, 0, - NULL, + nullptr, 0, - NULL, + nullptr, Z_DEFLATED, Z_DEFAULT_COMPRESSION); @@ -811,7 +811,7 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p } if (dst_pkg_zip) { - zipClose(dst_pkg_zip, NULL); + zipClose(dst_pkg_zip, nullptr); } return err; diff --git a/platform/osx/joypad_osx.cpp b/platform/osx/joypad_osx.cpp index f2d9de6fbd..643acd8944 100644 --- a/platform/osx/joypad_osx.cpp +++ b/platform/osx/joypad_osx.cpp @@ -34,13 +34,13 @@ #define GODOT_JOY_LOOP_RUN_MODE CFSTR("GodotJoypad") -static JoypadOSX *self = NULL; +static JoypadOSX *self = nullptr; joypad::joypad() { - device_ref = NULL; - ff_device = NULL; - ff_axes = NULL; - ff_directions = NULL; + device_ref = nullptr; + ff_device = nullptr; + ff_axes = nullptr; + ff_directions = nullptr; ffservice = 0; ff_timestamp = 0; id = 0; @@ -53,7 +53,7 @@ joypad::joypad() { ff_effect.dwTriggerButton = FFEB_NOTRIGGER; ff_effect.dwStartDelay = 0; ff_effect.dwTriggerRepeatInterval = 0; - ff_effect.lpEnvelope = NULL; + ff_effect.lpEnvelope = nullptr; ff_effect.cbTypeSpecificParams = sizeof(FFCONSTANTFORCE); ff_effect.lpvTypeSpecificParams = &ff_constant_force; ff_effect.dwSize = sizeof(ff_effect); @@ -105,7 +105,7 @@ void joypad::add_hid_element(IOHIDElementRef p_element) { const IOHIDElementCookie cookie = IOHIDElementGetCookie(p_element); const uint32_t usagePage = IOHIDElementGetUsagePage(p_element); const uint32_t usage = IOHIDElementGetUsage(p_element); - Vector<rec_element> *list = NULL; + Vector<rec_element> *list = nullptr; switch (IOHIDElementGetType(p_element)) { case kIOHIDElementTypeInput_Misc: @@ -249,7 +249,7 @@ void JoypadOSX::_device_added(IOReturn p_res, IOHIDDeviceRef p_device) { if (is_joypad(p_device)) { configure_joypad(p_device, &new_joypad); #if MAC_OS_X_VERSION_MIN_REQUIRED < 1060 - if (IOHIDDeviceGetService != NULL) { + if (IOHIDDeviceGetService != nullptr) { #endif const io_service_t ioservice = IOHIDDeviceGetService(p_device); if ((ioservice) && (FFIsForceFeedback(ioservice) == FF_OK) && new_joypad.config_force_feedback(ioservice)) { @@ -330,7 +330,7 @@ bool JoypadOSX::configure_joypad(IOHIDDeviceRef p_device_ref, joypad *p_joy) { input->joy_connection_changed(id, true, name, guid); } - CFArrayRef array = IOHIDDeviceCopyMatchingElements(p_device_ref, NULL, kIOHIDOptionsTypeNone); + CFArrayRef array = IOHIDDeviceCopyMatchingElements(p_device_ref, nullptr, kIOHIDOptionsTypeNone); if (array) { p_joy->add_hid_elements(array); CFRelease(array); @@ -531,7 +531,7 @@ bool JoypadOSX::have_device(IOHIDDeviceRef p_device) const { } static CFDictionaryRef create_match_dictionary(const UInt32 page, const UInt32 usage, int *okay) { - CFDictionaryRef retval = NULL; + CFDictionaryRef retval = nullptr; CFNumberRef pageNumRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &page); CFNumberRef usageNumRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage); const void *keys[2] = { (void *)CFSTR(kIOHIDDeviceUsagePageKey), (void *)CFSTR(kIOHIDDeviceUsageKey) }; @@ -562,8 +562,8 @@ void JoypadOSX::config_hid_manager(CFArrayRef p_matching_array) const { ERR_FAIL_COND(ret != kIOReturnSuccess); IOHIDManagerSetDeviceMatchingMultiple(hid_manager, p_matching_array); - IOHIDManagerRegisterDeviceMatchingCallback(hid_manager, joypad_added_callback, NULL); - IOHIDManagerRegisterDeviceRemovalCallback(hid_manager, joypad_removed_callback, NULL); + IOHIDManagerRegisterDeviceMatchingCallback(hid_manager, joypad_added_callback, nullptr); + IOHIDManagerRegisterDeviceRemovalCallback(hid_manager, joypad_removed_callback, nullptr); IOHIDManagerScheduleWithRunLoop(hid_manager, runloop, GODOT_JOY_LOOP_RUN_MODE); while (CFRunLoopRunInMode(GODOT_JOY_LOOP_RUN_MODE, 0, TRUE) == kCFRunLoopRunHandledSource) { @@ -582,7 +582,7 @@ JoypadOSX::JoypadOSX(InputFilter *in) { (void *)create_match_dictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_MultiAxisController, &okay), }; const size_t n_elements = sizeof(vals) / sizeof(vals[0]); - CFArrayRef array = okay ? CFArrayCreate(kCFAllocatorDefault, vals, n_elements, &kCFTypeArrayCallBacks) : NULL; + CFArrayRef array = okay ? CFArrayCreate(kCFAllocatorDefault, vals, n_elements, &kCFTypeArrayCallBacks) : nullptr; for (size_t i = 0; i < n_elements; i++) { if (vals[i]) { @@ -592,7 +592,7 @@ JoypadOSX::JoypadOSX(InputFilter *in) { if (array) { hid_manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); - if (hid_manager != NULL) { + if (hid_manager != nullptr) { config_hid_manager(array); } CFRelease(array); @@ -608,5 +608,5 @@ JoypadOSX::~JoypadOSX() { IOHIDManagerUnscheduleFromRunLoop(hid_manager, CFRunLoopGetCurrent(), GODOT_JOY_LOOP_RUN_MODE); IOHIDManagerClose(hid_manager, kIOHIDOptionsTypeNone); CFRelease(hid_manager); - hid_manager = NULL; + hid_manager = nullptr; } diff --git a/platform/osx/platform_osx_builders.py b/platform/osx/platform_osx_builders.py index 81997f674b..953ed479db 100644 --- a/platform/osx/platform_osx_builders.py +++ b/platform/osx/platform_osx_builders.py @@ -8,14 +8,14 @@ from platform_methods import subprocess_main def make_debug_osx(target, source, env): - if (env["macports_clang"] != 'no'): + if env["macports_clang"] != "no": mpprefix = os.environ.get("MACPORTS_PREFIX", "/opt/local") mpclangver = env["macports_clang"] - os.system(mpprefix + '/libexec/llvm-' + mpclangver + '/bin/llvm-dsymutil {0} -o {0}.dSYM'.format(target[0])) + os.system(mpprefix + "/libexec/llvm-" + mpclangver + "/bin/llvm-dsymutil {0} -o {0}.dSYM".format(target[0])) else: - os.system('dsymutil {0} -o {0}.dSYM'.format(target[0])) - os.system('strip -u -r {0}'.format(target[0])) + os.system("dsymutil {0} -o {0}.dSYM".format(target[0])) + os.system("strip -u -r {0}".format(target[0])) -if __name__ == '__main__': +if __name__ == "__main__": subprocess_main(globals()) diff --git a/platform/server/SCsub b/platform/server/SCsub index 8364164114..15b9af4d25 100644 --- a/platform/server/SCsub +++ b/platform/server/SCsub @@ -2,15 +2,15 @@ import sys -Import('env') +Import("env") -common_server = [\ - "os_server.cpp",\ +common_server = [ + "os_server.cpp", ] if sys.platform == "darwin": - common_server.append("#platform/osx/crash_handler_osx.mm") + common_server.append("#platform/osx/crash_handler_osx.mm") else: - common_server.append("#platform/x11/crash_handler_x11.cpp") + common_server.append("#platform/x11/crash_handler_x11.cpp") -prog = env.add_program('#bin/godot_server', ['godot_server.cpp'] + common_server) +prog = env.add_program("#bin/godot_server", ["godot_server.cpp"] + common_server) diff --git a/platform/server/detect.py b/platform/server/detect.py index 4ea4bddddd..a73810cdf4 100644 --- a/platform/server/detect.py +++ b/platform/server/detect.py @@ -5,6 +5,7 @@ import sys # This file is mostly based on platform/x11/detect.py. # If editing this file, make sure to apply relevant changes here too. + def is_active(): return True @@ -14,14 +15,14 @@ def get_name(): def get_program_suffix(): - if (sys.platform == "darwin"): + if sys.platform == "darwin": return "osx" return "linuxbsd" def can_build(): - if (os.name != "posix"): + if os.name != "posix": return False return True @@ -29,17 +30,18 @@ def can_build(): def get_opts(): from SCons.Variables import BoolVariable, EnumVariable + return [ - BoolVariable('use_llvm', 'Use the LLVM compiler', False), - BoolVariable('use_static_cpp', 'Link libgcc and libstdc++ statically for better portability', False), - BoolVariable('use_coverage', 'Test Godot coverage', False), - BoolVariable('use_ubsan', 'Use LLVM/GCC compiler undefined behavior sanitizer (UBSAN)', False), - BoolVariable('use_asan', 'Use LLVM/GCC compiler address sanitizer (ASAN))', False), - BoolVariable('use_lsan', 'Use LLVM/GCC compiler leak sanitizer (LSAN))', False), - BoolVariable('use_tsan', 'Use LLVM/GCC compiler thread sanitizer (TSAN))', False), - EnumVariable('debug_symbols', 'Add debugging symbols to release builds', 'yes', ('yes', 'no', 'full')), - BoolVariable('separate_debug_symbols', 'Create a separate file containing debugging symbols', False), - BoolVariable('execinfo', 'Use libexecinfo on systems where glibc is not available', False), + BoolVariable("use_llvm", "Use the LLVM compiler", False), + BoolVariable("use_static_cpp", "Link libgcc and libstdc++ statically for better portability", False), + BoolVariable("use_coverage", "Test Godot coverage", False), + BoolVariable("use_ubsan", "Use LLVM/GCC compiler undefined behavior sanitizer (UBSAN)", False), + BoolVariable("use_asan", "Use LLVM/GCC compiler address sanitizer (ASAN))", False), + BoolVariable("use_lsan", "Use LLVM/GCC compiler leak sanitizer (LSAN))", False), + BoolVariable("use_tsan", "Use LLVM/GCC compiler thread sanitizer (TSAN))", False), + EnumVariable("debug_symbols", "Add debugging symbols to release builds", "yes", ("yes", "no", "full")), + BoolVariable("separate_debug_symbols", "Create a separate file containing debugging symbols", False), + BoolVariable("execinfo", "Use libexecinfo on systems where glibc is not available", False), ] @@ -52,89 +54,89 @@ def configure(env): ## Build type - if (env["target"] == "release"): - if (env["optimize"] == "speed"): #optimize for speed (default) - env.Prepend(CCFLAGS=['-O3']) - else: #optimize for size - env.Prepend(CCFLAGS=['-Os']) - - if (env["debug_symbols"] == "yes"): - env.Prepend(CCFLAGS=['-g1']) - if (env["debug_symbols"] == "full"): - env.Prepend(CCFLAGS=['-g2']) - - elif (env["target"] == "release_debug"): - if (env["optimize"] == "speed"): #optimize for speed (default) - env.Prepend(CCFLAGS=['-O2']) - else: #optimize for size - env.Prepend(CCFLAGS=['-Os']) - env.Prepend(CPPDEFINES=['DEBUG_ENABLED']) - - if (env["debug_symbols"] == "yes"): - env.Prepend(CCFLAGS=['-g1']) - if (env["debug_symbols"] == "full"): - env.Prepend(CCFLAGS=['-g2']) - - elif (env["target"] == "debug"): - env.Prepend(CCFLAGS=['-g3']) - env.Prepend(CPPDEFINES=['DEBUG_ENABLED', 'DEBUG_MEMORY_ENABLED']) - env.Append(LINKFLAGS=['-rdynamic']) + if env["target"] == "release": + if env["optimize"] == "speed": # optimize for speed (default) + env.Prepend(CCFLAGS=["-O3"]) + else: # optimize for size + env.Prepend(CCFLAGS=["-Os"]) + + if env["debug_symbols"] == "yes": + env.Prepend(CCFLAGS=["-g1"]) + if env["debug_symbols"] == "full": + env.Prepend(CCFLAGS=["-g2"]) + + elif env["target"] == "release_debug": + if env["optimize"] == "speed": # optimize for speed (default) + env.Prepend(CCFLAGS=["-O2"]) + else: # optimize for size + env.Prepend(CCFLAGS=["-Os"]) + env.Prepend(CPPDEFINES=["DEBUG_ENABLED"]) + + if env["debug_symbols"] == "yes": + env.Prepend(CCFLAGS=["-g1"]) + if env["debug_symbols"] == "full": + env.Prepend(CCFLAGS=["-g2"]) + + elif env["target"] == "debug": + env.Prepend(CCFLAGS=["-g3"]) + env.Prepend(CPPDEFINES=["DEBUG_ENABLED", "DEBUG_MEMORY_ENABLED"]) + env.Append(LINKFLAGS=["-rdynamic"]) ## Architecture - is64 = sys.maxsize > 2**32 - if (env["bits"] == "default"): + is64 = sys.maxsize > 2 ** 32 + if env["bits"] == "default": env["bits"] = "64" if is64 else "32" ## Compiler configuration - if 'CXX' in env and 'clang' in os.path.basename(env['CXX']): + if "CXX" in env and "clang" in os.path.basename(env["CXX"]): # Convenience check to enforce the use_llvm overrides when CXX is clang(++) - env['use_llvm'] = True + env["use_llvm"] = True - if env['use_llvm']: - if ('clang++' not in os.path.basename(env['CXX'])): + if env["use_llvm"]: + if "clang++" not in os.path.basename(env["CXX"]): env["CC"] = "clang" env["CXX"] = "clang++" env["LINK"] = "clang++" - env.Append(CPPDEFINES=['TYPED_METHOD_BIND']) + env.Append(CPPDEFINES=["TYPED_METHOD_BIND"]) env.extra_suffix = ".llvm" + env.extra_suffix - if env['use_coverage']: - env.Append(CCFLAGS=['-ftest-coverage', '-fprofile-arcs']) - env.Append(LINKFLAGS=['-ftest-coverage', '-fprofile-arcs']) + if env["use_coverage"]: + env.Append(CCFLAGS=["-ftest-coverage", "-fprofile-arcs"]) + env.Append(LINKFLAGS=["-ftest-coverage", "-fprofile-arcs"]) - if env['use_ubsan'] or env['use_asan'] or env['use_lsan'] or env['use_tsan']: + if env["use_ubsan"] or env["use_asan"] or env["use_lsan"] or env["use_tsan"]: env.extra_suffix += "s" - if env['use_ubsan']: - env.Append(CCFLAGS=['-fsanitize=undefined']) - env.Append(LINKFLAGS=['-fsanitize=undefined']) + if env["use_ubsan"]: + env.Append(CCFLAGS=["-fsanitize=undefined"]) + env.Append(LINKFLAGS=["-fsanitize=undefined"]) - if env['use_asan']: - env.Append(CCFLAGS=['-fsanitize=address']) - env.Append(LINKFLAGS=['-fsanitize=address']) + if env["use_asan"]: + env.Append(CCFLAGS=["-fsanitize=address"]) + env.Append(LINKFLAGS=["-fsanitize=address"]) - if env['use_lsan']: - env.Append(CCFLAGS=['-fsanitize=leak']) - env.Append(LINKFLAGS=['-fsanitize=leak']) + if env["use_lsan"]: + env.Append(CCFLAGS=["-fsanitize=leak"]) + env.Append(LINKFLAGS=["-fsanitize=leak"]) - if env['use_tsan']: - env.Append(CCFLAGS=['-fsanitize=thread']) - env.Append(LINKFLAGS=['-fsanitize=thread']) + if env["use_tsan"]: + env.Append(CCFLAGS=["-fsanitize=thread"]) + env.Append(LINKFLAGS=["-fsanitize=thread"]) - if env['use_lto']: - env.Append(CCFLAGS=['-flto']) - if not env['use_llvm'] and env.GetOption("num_jobs") > 1: - env.Append(LINKFLAGS=['-flto=' + str(env.GetOption("num_jobs"))]) + if env["use_lto"]: + env.Append(CCFLAGS=["-flto"]) + if not env["use_llvm"] and env.GetOption("num_jobs") > 1: + env.Append(LINKFLAGS=["-flto=" + str(env.GetOption("num_jobs"))]) else: - env.Append(LINKFLAGS=['-flto']) - if not env['use_llvm']: - env['RANLIB'] = 'gcc-ranlib' - env['AR'] = 'gcc-ar' + env.Append(LINKFLAGS=["-flto"]) + if not env["use_llvm"]: + env["RANLIB"] = "gcc-ranlib" + env["AR"] = "gcc-ar" - env.Append(CCFLAGS=['-pipe']) - env.Append(LINKFLAGS=['-pipe']) + env.Append(CCFLAGS=["-pipe"]) + env.Append(LINKFLAGS=["-pipe"]) ## Dependencies @@ -142,109 +144,114 @@ def configure(env): # freetype depends on libpng and zlib, so bundling one of them while keeping others # as shared libraries leads to weird issues - if env['builtin_freetype'] or env['builtin_libpng'] or env['builtin_zlib']: - env['builtin_freetype'] = True - env['builtin_libpng'] = True - env['builtin_zlib'] = True + if env["builtin_freetype"] or env["builtin_libpng"] or env["builtin_zlib"]: + env["builtin_freetype"] = True + env["builtin_libpng"] = True + env["builtin_zlib"] = True - if not env['builtin_freetype']: - env.ParseConfig('pkg-config freetype2 --cflags --libs') + if not env["builtin_freetype"]: + env.ParseConfig("pkg-config freetype2 --cflags --libs") - if not env['builtin_libpng']: - env.ParseConfig('pkg-config libpng16 --cflags --libs') + if not env["builtin_libpng"]: + env.ParseConfig("pkg-config libpng16 --cflags --libs") - if not env['builtin_bullet']: + if not env["builtin_bullet"]: # We need at least version 2.89 import subprocess - bullet_version = subprocess.check_output(['pkg-config', 'bullet', '--modversion']).strip() + + bullet_version = subprocess.check_output(["pkg-config", "bullet", "--modversion"]).strip() if str(bullet_version) < "2.89": # Abort as system bullet was requested but too old - print("Bullet: System version {0} does not match minimal requirements ({1}). Aborting.".format(bullet_version, "2.89")) + print( + "Bullet: System version {0} does not match minimal requirements ({1}). Aborting.".format( + bullet_version, "2.89" + ) + ) sys.exit(255) - env.ParseConfig('pkg-config bullet --cflags --libs') + env.ParseConfig("pkg-config bullet --cflags --libs") if False: # not env['builtin_assimp']: # FIXME: Add min version check - env.ParseConfig('pkg-config assimp --cflags --libs') + env.ParseConfig("pkg-config assimp --cflags --libs") - if not env['builtin_enet']: - env.ParseConfig('pkg-config libenet --cflags --libs') + if not env["builtin_enet"]: + env.ParseConfig("pkg-config libenet --cflags --libs") - if not env['builtin_squish']: - env.ParseConfig('pkg-config libsquish --cflags --libs') + if not env["builtin_squish"]: + env.ParseConfig("pkg-config libsquish --cflags --libs") - if not env['builtin_zstd']: - env.ParseConfig('pkg-config libzstd --cflags --libs') + if not env["builtin_zstd"]: + env.ParseConfig("pkg-config libzstd --cflags --libs") # Sound and video libraries # Keep the order as it triggers chained dependencies (ogg needed by others, etc.) - if not env['builtin_libtheora']: - env['builtin_libogg'] = False # Needed to link against system libtheora - env['builtin_libvorbis'] = False # Needed to link against system libtheora - env.ParseConfig('pkg-config theora theoradec --cflags --libs') + if not env["builtin_libtheora"]: + env["builtin_libogg"] = False # Needed to link against system libtheora + env["builtin_libvorbis"] = False # Needed to link against system libtheora + env.ParseConfig("pkg-config theora theoradec --cflags --libs") else: - list_of_x86 = ['x86_64', 'x86', 'i386', 'i586'] + list_of_x86 = ["x86_64", "x86", "i386", "i586"] if any(platform.machine() in s for s in list_of_x86): env["x86_libtheora_opt_gcc"] = True - if not env['builtin_libvpx']: - env.ParseConfig('pkg-config vpx --cflags --libs') + if not env["builtin_libvpx"]: + env.ParseConfig("pkg-config vpx --cflags --libs") - if not env['builtin_libvorbis']: - env['builtin_libogg'] = False # Needed to link against system libvorbis - env.ParseConfig('pkg-config vorbis vorbisfile --cflags --libs') + if not env["builtin_libvorbis"]: + env["builtin_libogg"] = False # Needed to link against system libvorbis + env.ParseConfig("pkg-config vorbis vorbisfile --cflags --libs") - if not env['builtin_opus']: - env['builtin_libogg'] = False # Needed to link against system opus - env.ParseConfig('pkg-config opus opusfile --cflags --libs') + if not env["builtin_opus"]: + env["builtin_libogg"] = False # Needed to link against system opus + env.ParseConfig("pkg-config opus opusfile --cflags --libs") - if not env['builtin_libogg']: - env.ParseConfig('pkg-config ogg --cflags --libs') + if not env["builtin_libogg"]: + env.ParseConfig("pkg-config ogg --cflags --libs") - if not env['builtin_libwebp']: - env.ParseConfig('pkg-config libwebp --cflags --libs') + if not env["builtin_libwebp"]: + env.ParseConfig("pkg-config libwebp --cflags --libs") - if not env['builtin_mbedtls']: + if not env["builtin_mbedtls"]: # mbedTLS does not provide a pkgconfig config yet. See https://github.com/ARMmbed/mbedtls/issues/228 - env.Append(LIBS=['mbedtls', 'mbedcrypto', 'mbedx509']) + env.Append(LIBS=["mbedtls", "mbedcrypto", "mbedx509"]) - if not env['builtin_wslay']: - env.ParseConfig('pkg-config libwslay --cflags --libs') + if not env["builtin_wslay"]: + env.ParseConfig("pkg-config libwslay --cflags --libs") - if not env['builtin_miniupnpc']: + if not env["builtin_miniupnpc"]: # No pkgconfig file so far, hardcode default paths. env.Prepend(CPPPATH=["/usr/include/miniupnpc"]) env.Append(LIBS=["miniupnpc"]) # On Linux wchar_t should be 32-bits # 16-bit library shouldn't be required due to compiler optimisations - if not env['builtin_pcre2']: - env.ParseConfig('pkg-config libpcre2-32 --cflags --libs') + if not env["builtin_pcre2"]: + env.ParseConfig("pkg-config libpcre2-32 --cflags --libs") ## Flags # Linkflags below this line should typically stay the last ones - if not env['builtin_zlib']: - env.ParseConfig('pkg-config zlib --cflags --libs') + if not env["builtin_zlib"]: + env.ParseConfig("pkg-config zlib --cflags --libs") - env.Prepend(CPPPATH=['#platform/server']) - env.Append(CPPDEFINES=['SERVER_ENABLED', 'UNIX_ENABLED']) + env.Prepend(CPPPATH=["#platform/server"]) + env.Append(CPPDEFINES=["SERVER_ENABLED", "UNIX_ENABLED"]) - if (platform.system() == "Darwin"): - env.Append(LINKFLAGS=['-framework', 'Cocoa', '-framework', 'Carbon', '-lz', '-framework', 'IOKit']) + if platform.system() == "Darwin": + env.Append(LINKFLAGS=["-framework", "Cocoa", "-framework", "Carbon", "-lz", "-framework", "IOKit"]) - env.Append(LIBS=['pthread']) + env.Append(LIBS=["pthread"]) - if (platform.system() == "Linux"): - env.Append(LIBS=['dl']) + if platform.system() == "Linux": + env.Append(LIBS=["dl"]) - if (platform.system().find("BSD") >= 0): + if platform.system().find("BSD") >= 0: env["execinfo"] = True if env["execinfo"]: - env.Append(LIBS=['execinfo']) + env.Append(LIBS=["execinfo"]) # Link those statically for portability - if env['use_static_cpp']: - env.Append(LINKFLAGS=['-static-libgcc', '-static-libstdc++']) + if env["use_static_cpp"]: + env.Append(LINKFLAGS=["-static-libgcc", "-static-libstdc++"]) diff --git a/platform/server/os_server.cpp b/platform/server/os_server.cpp index 3257ec261c..0fda0663a2 100644 --- a/platform/server/os_server.cpp +++ b/platform/server/os_server.cpp @@ -33,7 +33,7 @@ #include "core/print_string.h" #include "drivers/dummy/rasterizer_dummy.h" #include "drivers/dummy/texture_loader_dummy.h" -#include "servers/visual/visual_server_raster.h" +#include "servers/rendering/rendering_server_raster.h" #include "main/main.h" @@ -74,14 +74,14 @@ Error OS_Server::initialize(const VideoMode &p_desired, int p_video_driver, int args = OS::get_singleton()->get_cmdline_args(); current_videomode = p_desired; - main_loop = NULL; + main_loop = nullptr; RasterizerDummy::make_current(); video_driver_index = p_video_driver; // unused in server platform, but should still be initialized - visual_server = memnew(VisualServerRaster); - visual_server->init(); + rendering_server = memnew(RenderingServerRaster); + rendering_server->init(); AudioDriverManager::initialize(p_audio_driver); @@ -99,10 +99,10 @@ void OS_Server::finalize() { if (main_loop) memdelete(main_loop); - main_loop = NULL; + main_loop = nullptr; - visual_server->finish(); - memdelete(visual_server); + rendering_server->finish(); + memdelete(rendering_server); memdelete(input); @@ -163,7 +163,7 @@ void OS_Server::delete_main_loop() { if (main_loop) memdelete(main_loop); - main_loop = NULL; + main_loop = nullptr; } void OS_Server::set_main_loop(MainLoop *p_main_loop) { @@ -289,7 +289,7 @@ String OS_Server::get_system_dir(SystemDir p_dir) const { String pipe; List<String> arg; arg.push_back(xdgparam); - Error err = const_cast<OS_Server *>(this)->execute("xdg-user-dir", arg, true, NULL, &pipe); + Error err = const_cast<OS_Server *>(this)->execute("xdg-user-dir", arg, true, nullptr, &pipe); if (err != OK) return "."; return pipe.strip_edges(); diff --git a/platform/server/os_server.h b/platform/server/os_server.h index d40905718e..62028b26e4 100644 --- a/platform/server/os_server.h +++ b/platform/server/os_server.h @@ -41,14 +41,14 @@ #include "platform/x11/crash_handler_linuxbsd.h" #endif #include "servers/audio_server.h" -#include "servers/visual/rasterizer.h" -#include "servers/visual_server.h" +#include "servers/rendering/rasterizer.h" +#include "servers/rendering_server.h" #undef CursorShape class OS_Server : public OS_Unix { - VisualServer *visual_server; + RenderingServer *rendering_server; VideoMode current_videomode; List<String> args; MainLoop *main_loop; diff --git a/platform/uwp/SCsub b/platform/uwp/SCsub index 620d8c3c3a..4358b0eead 100644 --- a/platform/uwp/SCsub +++ b/platform/uwp/SCsub @@ -1,21 +1,21 @@ #!/usr/bin/env python -Import('env') +Import("env") files = [ - 'thread_uwp.cpp', - '#platform/windows/key_mapping_windows.cpp', - '#platform/windows/windows_terminal_logger.cpp', - 'joypad_uwp.cpp', - 'context_egl_uwp.cpp', - 'app.cpp', - 'os_uwp.cpp', + "thread_uwp.cpp", + "#platform/windows/key_mapping_windows.cpp", + "#platform/windows/windows_terminal_logger.cpp", + "joypad_uwp.cpp", + "context_egl_uwp.cpp", + "app.cpp", + "os_uwp.cpp", ] if "build_angle" in env and env["build_angle"]: - cmd = env.AlwaysBuild(env.ANGLE('libANGLE.lib', None)) + cmd = env.AlwaysBuild(env.ANGLE("libANGLE.lib", None)) -prog = env.add_program('#bin/godot', files) +prog = env.add_program("#bin/godot", files) if "build_angle" in env and env["build_angle"]: env.Depends(prog, [cmd]) diff --git a/platform/uwp/app.cpp b/platform/uwp/app.cpp index ccb4b43373..d3870b0b6c 100644 --- a/platform/uwp/app.cpp +++ b/platform/uwp/app.cpp @@ -507,12 +507,12 @@ void App::UpdateWindowSize(Size size) { char **App::get_command_line(unsigned int *out_argc) { - static char *fail_cl[] = { "--path", "game", NULL }; + static char *fail_cl[] = { "--path", "game", nullptr }; *out_argc = 2; FILE *f = _wfopen(L"__cl__.cl", L"rb"); - if (f == NULL) { + if (f == nullptr) { wprintf(L"Couldn't open command line file.\n"); return fail_cl; @@ -558,7 +558,7 @@ char **App::get_command_line(unsigned int *out_argc) { if (r == strlen) { - int warg_size = MultiByteToWideChar(CP_UTF8, 0, arg, -1, NULL, 0); + int warg_size = MultiByteToWideChar(CP_UTF8, 0, arg, -1, nullptr, 0); wchar_t *warg = new wchar_t[warg_size]; MultiByteToWideChar(CP_UTF8, 0, arg, -1, warg, warg_size); @@ -583,14 +583,14 @@ char **App::get_command_line(unsigned int *out_argc) { for (int i = 0; i < cl.Size; i++) { - int arg_size = WideCharToMultiByte(CP_UTF8, 0, cl.GetAt(i)->Data(), -1, NULL, 0, NULL, NULL); + int arg_size = WideCharToMultiByte(CP_UTF8, 0, cl.GetAt(i)->Data(), -1, nullptr, 0, nullptr, nullptr); char *arg = new char[arg_size]; - WideCharToMultiByte(CP_UTF8, 0, cl.GetAt(i)->Data(), -1, arg, arg_size, NULL, NULL); + WideCharToMultiByte(CP_UTF8, 0, cl.GetAt(i)->Data(), -1, arg, arg_size, nullptr, nullptr); ret[i] = arg; } - ret[cl.Size] = NULL; + ret[cl.Size] = nullptr; *out_argc = cl.Size; return ret; diff --git a/platform/uwp/context_egl_uwp.cpp b/platform/uwp/context_egl_uwp.cpp index 7ac9489bb4..bc8ca2e36c 100644 --- a/platform/uwp/context_egl_uwp.cpp +++ b/platform/uwp/context_egl_uwp.cpp @@ -155,7 +155,7 @@ Error ContextEGL_UWP::initialize() { throw Exception::CreateException(E_FAIL, L"Failed to initialize EGL"); } - if (eglGetConfigs(display, NULL, 0, &numConfigs) == EGL_FALSE) { + if (eglGetConfigs(display, nullptr, 0, &numConfigs) == EGL_FALSE) { throw Exception::CreateException(E_FAIL, L"Failed to get EGLConfig count"); } diff --git a/platform/uwp/detect.py b/platform/uwp/detect.py index 000bd18e7d..669bfe6814 100644 --- a/platform/uwp/detect.py +++ b/platform/uwp/detect.py @@ -12,11 +12,11 @@ def get_name(): def can_build(): - if (os.name == "nt"): + if os.name == "nt": # building natively on windows! - if (os.getenv("VSINSTALLDIR")): + if os.getenv("VSINSTALLDIR"): - if (os.getenv("ANGLE_SRC_PATH") is None): + if os.getenv("ANGLE_SRC_PATH") is None: return False return True @@ -25,16 +25,16 @@ def can_build(): def get_opts(): return [ - ('msvc_version', 'MSVC version to use (ignored if the VCINSTALLDIR environment variable is set)', None), + ("msvc_version", "MSVC version to use (ignored if the VCINSTALLDIR environment variable is set)", None), ] def get_flags(): return [ - ('tools', False), - ('xaudio2', True), - ('builtin_pcre2_with_jit', False), + ("tools", False), + ("xaudio2", True), + ("builtin_pcre2_with_jit", False), ] @@ -42,45 +42,53 @@ def configure(env): env.msvc = True - if (env["bits"] != "default"): + if env["bits"] != "default": print("Error: bits argument is disabled for MSVC") - print(""" + print( + """ Bits argument is not supported for MSVC compilation. Architecture depends on the Native/Cross Compile Tools Prompt/Developer Console (or Visual Studio settings) that is being used to run SCons. As a consequence, bits argument is disabled. Run scons again without bits argument (example: scons p=uwp) and SCons will attempt to detect what MSVC compiler will be executed and inform you. - """) + """ + ) sys.exit() ## Build type - if (env["target"] == "release"): - env.Append(CCFLAGS=['/O2', '/GL']) - env.Append(CCFLAGS=['/MD']) - env.Append(LINKFLAGS=['/SUBSYSTEM:WINDOWS', '/LTCG']) + if env["target"] == "release": + env.Append(CCFLAGS=["/O2", "/GL"]) + env.Append(CCFLAGS=["/MD"]) + env.Append(LINKFLAGS=["/SUBSYSTEM:WINDOWS", "/LTCG"]) - elif (env["target"] == "release_debug"): - env.Append(CCFLAGS=['/O2', '/Zi']) - env.Append(CCFLAGS=['/MD']) - env.Append(CPPDEFINES=['DEBUG_ENABLED']) - env.Append(LINKFLAGS=['/SUBSYSTEM:CONSOLE']) + elif env["target"] == "release_debug": + env.Append(CCFLAGS=["/O2", "/Zi"]) + env.Append(CCFLAGS=["/MD"]) + env.Append(CPPDEFINES=["DEBUG_ENABLED"]) + env.Append(LINKFLAGS=["/SUBSYSTEM:CONSOLE"]) - elif (env["target"] == "debug"): - env.Append(CCFLAGS=['/Zi']) - env.Append(CCFLAGS=['/MDd']) - env.Append(CPPDEFINES=['DEBUG_ENABLED', 'DEBUG_MEMORY_ENABLED']) - env.Append(LINKFLAGS=['/SUBSYSTEM:CONSOLE']) - env.Append(LINKFLAGS=['/DEBUG']) + elif env["target"] == "debug": + env.Append(CCFLAGS=["/Zi"]) + env.Append(CCFLAGS=["/MDd"]) + env.Append(CPPDEFINES=["DEBUG_ENABLED", "DEBUG_MEMORY_ENABLED"]) + env.Append(LINKFLAGS=["/SUBSYSTEM:CONSOLE"]) + env.Append(LINKFLAGS=["/DEBUG"]) ## Compiler configuration - env['ENV'] = os.environ - vc_base_path = os.environ['VCTOOLSINSTALLDIR'] if "VCTOOLSINSTALLDIR" in os.environ else os.environ['VCINSTALLDIR'] + env["ENV"] = os.environ + vc_base_path = os.environ["VCTOOLSINSTALLDIR"] if "VCTOOLSINSTALLDIR" in os.environ else os.environ["VCINSTALLDIR"] # ANGLE angle_root = os.getenv("ANGLE_SRC_PATH") - env.Prepend(CPPPATH=[angle_root + '/include']) + env.Prepend(CPPPATH=[angle_root + "/include"]) jobs = str(env.GetOption("num_jobs")) - angle_build_cmd = "msbuild.exe " + angle_root + "/winrt/10/src/angle.sln /nologo /v:m /m:" + jobs + " /p:Configuration=Release /p:Platform=" + angle_build_cmd = ( + "msbuild.exe " + + angle_root + + "/winrt/10/src/angle.sln /nologo /v:m /m:" + + jobs + + " /p:Configuration=Release /p:Platform=" + ) if os.path.isfile(str(os.getenv("ANGLE_SRC_PATH")) + "/winrt/10/src/angle.sln"): env["build_angle"] = True @@ -88,49 +96,51 @@ def configure(env): ## Architecture arch = "" - if str(os.getenv('Platform')).lower() == "arm": + if str(os.getenv("Platform")).lower() == "arm": print("Compiled program architecture will be an ARM executable. (forcing bits=32).") arch = "arm" env["bits"] = "32" - env.Append(LINKFLAGS=['/MACHINE:ARM']) - env.Append(LIBPATH=[vc_base_path + 'lib/store/arm']) + env.Append(LINKFLAGS=["/MACHINE:ARM"]) + env.Append(LIBPATH=[vc_base_path + "lib/store/arm"]) angle_build_cmd += "ARM" - env.Append(LIBPATH=[angle_root + '/winrt/10/src/Release_ARM/lib']) + env.Append(LIBPATH=[angle_root + "/winrt/10/src/Release_ARM/lib"]) else: - compiler_version_str = methods.detect_visual_c_compiler_version(env['ENV']) + compiler_version_str = methods.detect_visual_c_compiler_version(env["ENV"]) - if(compiler_version_str == "amd64" or compiler_version_str == "x86_amd64"): + if compiler_version_str == "amd64" or compiler_version_str == "x86_amd64": env["bits"] = "64" print("Compiled program architecture will be a x64 executable (forcing bits=64).") - elif (compiler_version_str == "x86" or compiler_version_str == "amd64_x86"): + elif compiler_version_str == "x86" or compiler_version_str == "amd64_x86": env["bits"] = "32" print("Compiled program architecture will be a x86 executable. (forcing bits=32).") else: - print("Failed to detect MSVC compiler architecture version... Defaulting to 32-bit executable settings (forcing bits=32). Compilation attempt will continue, but SCons can not detect for what architecture this build is compiled for. You should check your settings/compilation setup.") + print( + "Failed to detect MSVC compiler architecture version... Defaulting to 32-bit executable settings (forcing bits=32). Compilation attempt will continue, but SCons can not detect for what architecture this build is compiled for. You should check your settings/compilation setup." + ) env["bits"] = "32" - if (env["bits"] == "32"): + if env["bits"] == "32": arch = "x86" angle_build_cmd += "Win32" - env.Append(LINKFLAGS=['/MACHINE:X86']) - env.Append(LIBPATH=[vc_base_path + 'lib/store']) - env.Append(LIBPATH=[angle_root + '/winrt/10/src/Release_Win32/lib']) + env.Append(LINKFLAGS=["/MACHINE:X86"]) + env.Append(LIBPATH=[vc_base_path + "lib/store"]) + env.Append(LIBPATH=[angle_root + "/winrt/10/src/Release_Win32/lib"]) else: arch = "x64" angle_build_cmd += "x64" - env.Append(LINKFLAGS=['/MACHINE:X64']) - env.Append(LIBPATH=[os.environ['VCINSTALLDIR'] + 'lib/store/amd64']) - env.Append(LIBPATH=[angle_root + '/winrt/10/src/Release_x64/lib']) + env.Append(LINKFLAGS=["/MACHINE:X64"]) + env.Append(LIBPATH=[os.environ["VCINSTALLDIR"] + "lib/store/amd64"]) + env.Append(LIBPATH=[angle_root + "/winrt/10/src/Release_x64/lib"]) env["PROGSUFFIX"] = "." + arch + env["PROGSUFFIX"] env["OBJSUFFIX"] = "." + arch + env["OBJSUFFIX"] @@ -138,39 +148,61 @@ def configure(env): ## Compile flags - env.Prepend(CPPPATH=['#platform/uwp', '#drivers/windows']) - env.Append(CPPDEFINES=['UWP_ENABLED', 'WINDOWS_ENABLED', 'TYPED_METHOD_BIND']) - env.Append(CPPDEFINES=['GLES_ENABLED', 'GL_GLEXT_PROTOTYPES', 'EGL_EGLEXT_PROTOTYPES', 'ANGLE_ENABLED']) - winver = "0x0602" # Windows 8 is the minimum target for UWP build - env.Append(CPPDEFINES=[('WINVER', winver), ('_WIN32_WINNT', winver), 'WIN32']) - - env.Append(CPPDEFINES=['__WRL_NO_DEFAULT_LIB__', ('PNG_ABORT', 'abort')]) - - env.Append(CPPFLAGS=['/AI', vc_base_path + 'lib/store/references']) - env.Append(CPPFLAGS=['/AI', vc_base_path + 'lib/x86/store/references']) - - env.Append(CCFLAGS='/FS /MP /GS /wd"4453" /wd"28204" /wd"4291" /Zc:wchar_t /Gm- /fp:precise /errorReport:prompt /WX- /Zc:forScope /Gd /EHsc /nologo'.split()) - env.Append(CPPDEFINES=['_UNICODE', 'UNICODE', ('WINAPI_FAMILY', 'WINAPI_FAMILY_APP')]) - env.Append(CXXFLAGS=['/ZW']) - env.Append(CCFLAGS=['/AI', vc_base_path + '\\vcpackages', '/AI', os.environ['WINDOWSSDKDIR'] + '\\References\\CommonConfiguration\\Neutral']) + env.Prepend(CPPPATH=["#platform/uwp", "#drivers/windows"]) + env.Append(CPPDEFINES=["UWP_ENABLED", "WINDOWS_ENABLED", "TYPED_METHOD_BIND"]) + env.Append(CPPDEFINES=["GLES_ENABLED", "GL_GLEXT_PROTOTYPES", "EGL_EGLEXT_PROTOTYPES", "ANGLE_ENABLED"]) + winver = "0x0602" # Windows 8 is the minimum target for UWP build + env.Append(CPPDEFINES=[("WINVER", winver), ("_WIN32_WINNT", winver), "WIN32"]) + + env.Append(CPPDEFINES=["__WRL_NO_DEFAULT_LIB__", ("PNG_ABORT", "abort")]) + + env.Append(CPPFLAGS=["/AI", vc_base_path + "lib/store/references"]) + env.Append(CPPFLAGS=["/AI", vc_base_path + "lib/x86/store/references"]) + + env.Append( + CCFLAGS='/FS /MP /GS /wd"4453" /wd"28204" /wd"4291" /Zc:wchar_t /Gm- /fp:precise /errorReport:prompt /WX- /Zc:forScope /Gd /EHsc /nologo'.split() + ) + env.Append(CPPDEFINES=["_UNICODE", "UNICODE", ("WINAPI_FAMILY", "WINAPI_FAMILY_APP")]) + env.Append(CXXFLAGS=["/ZW"]) + env.Append( + CCFLAGS=[ + "/AI", + vc_base_path + "\\vcpackages", + "/AI", + os.environ["WINDOWSSDKDIR"] + "\\References\\CommonConfiguration\\Neutral", + ] + ) ## Link flags - env.Append(LINKFLAGS=['/MANIFEST:NO', '/NXCOMPAT', '/DYNAMICBASE', '/WINMD', '/APPCONTAINER', '/ERRORREPORT:PROMPT', '/NOLOGO', '/TLBID:1', '/NODEFAULTLIB:"kernel32.lib"', '/NODEFAULTLIB:"ole32.lib"']) + env.Append( + LINKFLAGS=[ + "/MANIFEST:NO", + "/NXCOMPAT", + "/DYNAMICBASE", + "/WINMD", + "/APPCONTAINER", + "/ERRORREPORT:PROMPT", + "/NOLOGO", + "/TLBID:1", + '/NODEFAULTLIB:"kernel32.lib"', + '/NODEFAULTLIB:"ole32.lib"', + ] + ) LIBS = [ - 'WindowsApp', - 'mincore', - 'ws2_32', - 'libANGLE', - 'libEGL', - 'libGLESv2', - 'bcrypt', + "WindowsApp", + "mincore", + "ws2_32", + "libANGLE", + "libEGL", + "libGLESv2", + "bcrypt", ] env.Append(LINKFLAGS=[p + ".lib" for p in LIBS]) # Incremental linking fix - env['BUILDERS']['ProgramOriginal'] = env['BUILDERS']['Program'] - env['BUILDERS']['Program'] = methods.precious_program + env["BUILDERS"]["ProgramOriginal"] = env["BUILDERS"]["Program"] + env["BUILDERS"]["Program"] = methods.precious_program - env.Append(BUILDERS={'ANGLE': env.Builder(action=angle_build_cmd)}) + env.Append(BUILDERS={"ANGLE": env.Builder(action=angle_build_cmd)}) diff --git a/platform/uwp/export/export.cpp b/platform/uwp/export/export.cpp index 533293387d..06bf738dc1 100644 --- a/platform/uwp/export/export.cpp +++ b/platform/uwp/export/export.cpp @@ -54,7 +54,7 @@ static const char *uwp_capabilities[] = { "internetClient", "internetClientServer", "privateNetworkClientServer", - NULL + nullptr }; static const char *uwp_uap_capabilities[] = { "appointments", @@ -71,7 +71,7 @@ static const char *uwp_uap_capabilities[] = { "userAccountInformation", "videosLibrary", "voipCall", - NULL + nullptr }; static const char *uwp_device_capabilities[] = { "bluetooth", @@ -79,7 +79,7 @@ static const char *uwp_device_capabilities[] = { "microphone", "proximity", "webcam", - NULL + nullptr }; class AppxPackager { @@ -478,7 +478,7 @@ Error AppxPackager::add_file(String p_file_name, const uint8_t *p_buffer, size_t // Data for compression z_stream strm; - FileAccess *strm_f = NULL; + FileAccess *strm_f = nullptr; Vector<uint8_t> strm_in; strm_in.resize(BLOCK_SIZE); Vector<uint8_t> strm_out; @@ -641,7 +641,7 @@ void AppxPackager::finish() { package->close(); memdelete(package); - package = NULL; + package = nullptr; } AppxPackager::AppxPackager() {} @@ -670,7 +670,7 @@ class EditorExportPlatformUWP : public EditorExportPlatform { static const char *invalid_names[] = { "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", - NULL + nullptr }; const char **t = invalid_names; @@ -726,7 +726,7 @@ class EditorExportPlatformUWP : public EditorExportPlatform { "snow", "springGreen", "steelBlue", "tan", "teal", "thistle", "tomato", "transparent", "turquoise", "violet", "wheat", "white", "whiteSmoke", "yellow", "yellowGreen", - NULL + nullptr }; const char **color = valid_colors; @@ -876,22 +876,22 @@ class EditorExportPlatformUWP : public EditorExportPlatform { Vector<uint8_t> _get_image_data(const Ref<EditorExportPreset> &p_preset, const String &p_path) { Vector<uint8_t> data; - StreamTexture *image = NULL; + StreamTexture *image = nullptr; if (p_path.find("StoreLogo") != -1) { - image = p_preset->get("images/store_logo").is_zero() ? NULL : Object::cast_to<StreamTexture>(((Object *)p_preset->get("images/store_logo"))); + image = p_preset->get("images/store_logo").is_zero() ? nullptr : Object::cast_to<StreamTexture>(((Object *)p_preset->get("images/store_logo"))); } else if (p_path.find("Square44x44Logo") != -1) { - image = p_preset->get("images/square44x44_logo").is_zero() ? NULL : Object::cast_to<StreamTexture>(((Object *)p_preset->get("images/square44x44_logo"))); + image = p_preset->get("images/square44x44_logo").is_zero() ? nullptr : Object::cast_to<StreamTexture>(((Object *)p_preset->get("images/square44x44_logo"))); } else if (p_path.find("Square71x71Logo") != -1) { - image = p_preset->get("images/square71x71_logo").is_zero() ? NULL : Object::cast_to<StreamTexture>(((Object *)p_preset->get("images/square71x71_logo"))); + image = p_preset->get("images/square71x71_logo").is_zero() ? nullptr : Object::cast_to<StreamTexture>(((Object *)p_preset->get("images/square71x71_logo"))); } else if (p_path.find("Square150x150Logo") != -1) { - image = p_preset->get("images/square150x150_logo").is_zero() ? NULL : Object::cast_to<StreamTexture>(((Object *)p_preset->get("images/square150x150_logo"))); + image = p_preset->get("images/square150x150_logo").is_zero() ? nullptr : Object::cast_to<StreamTexture>(((Object *)p_preset->get("images/square150x150_logo"))); } else if (p_path.find("Square310x310Logo") != -1) { - image = p_preset->get("images/square310x310_logo").is_zero() ? NULL : Object::cast_to<StreamTexture>(((Object *)p_preset->get("images/square310x310_logo"))); + image = p_preset->get("images/square310x310_logo").is_zero() ? nullptr : Object::cast_to<StreamTexture>(((Object *)p_preset->get("images/square310x310_logo"))); } else if (p_path.find("Wide310x150Logo") != -1) { - image = p_preset->get("images/wide310x150_logo").is_zero() ? NULL : Object::cast_to<StreamTexture>(((Object *)p_preset->get("images/wide310x150_logo"))); + image = p_preset->get("images/wide310x150_logo").is_zero() ? nullptr : Object::cast_to<StreamTexture>(((Object *)p_preset->get("images/wide310x150_logo"))); } else if (p_path.find("SplashScreen") != -1) { - image = p_preset->get("images/splash_screen").is_zero() ? NULL : Object::cast_to<StreamTexture>(((Object *)p_preset->get("images/splash_screen"))); + image = p_preset->get("images/splash_screen").is_zero() ? nullptr : Object::cast_to<StreamTexture>(((Object *)p_preset->get("images/splash_screen"))); } else { ERR_PRINT("Unable to load logo"); } @@ -961,7 +961,7 @@ class EditorExportPlatformUWP : public EditorExportPlatform { ".scn", // Binary scenes are usually already compressed ".stex", // Streamable textures are usually already compressed // Trailer for easier processing - NULL + nullptr }; for (const char **ext = unconditional_compress_ext; *ext; ++ext) { @@ -1251,7 +1251,7 @@ public: AppxPackager packager; packager.init(fa_pack); - FileAccess *src_f = NULL; + FileAccess *src_f = nullptr; zlib_filefunc_def io = zipio_create_io_from_file(&src_f); if (ep.step("Creating package...", 0)) { @@ -1283,7 +1283,7 @@ public: // get file name unz_file_info info; char fname[16834]; - ret = unzGetCurrentFileInfo(pkg, &info, fname, 16834, NULL, 0, NULL, 0); + ret = unzGetCurrentFileInfo(pkg, &info, fname, 16834, nullptr, 0, nullptr, 0); String path = fname; diff --git a/platform/uwp/os_uwp.cpp b/platform/uwp/os_uwp.cpp index 4ddb5463d0..f5e989b370 100644 --- a/platform/uwp/os_uwp.cpp +++ b/platform/uwp/os_uwp.cpp @@ -45,8 +45,8 @@ #include "main/main.h" #include "platform/windows/windows_terminal_logger.h" #include "servers/audio_server.h" -#include "servers/visual/visual_server_raster.h" -#include "servers/visual/visual_server_wrap_mt.h" +#include "servers/rendering/rendering_server_raster.h" +#include "servers/rendering/rendering_server_wrap_mt.h" #include "thread_uwp.h" #include <ppltasks.h> @@ -180,7 +180,7 @@ void OS_UWP::screen_size_changed() { Error OS_UWP::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { - main_loop = NULL; + main_loop = nullptr; outside = true; // FIXME: Hardcoded for now, add Vulkan support. @@ -193,7 +193,7 @@ Error OS_UWP::initialize(const VideoMode &p_desired, int p_video_driver, int p_a if (gl_context->initialize() != OK) { memdelete(gl_context); - gl_context = NULL; + gl_context = nullptr; gl_initialization_error = true; } @@ -254,13 +254,13 @@ Error OS_UWP::initialize(const VideoMode &p_desired, int p_video_driver, int p_a set_video_mode(vm); - visual_server = memnew(VisualServerRaster); + rendering_server = memnew(RenderingServerRaster); // FIXME: Reimplement threaded rendering if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { - visual_server = memnew(VisualServerWrapMT(visual_server, false)); + rendering_server = memnew(RenderingServerWrapMT(rendering_server, false)); } - visual_server->init(); + rendering_server->init(); input = memnew(InputDefault); @@ -333,7 +333,7 @@ void OS_UWP::delete_main_loop() { if (main_loop) memdelete(main_loop); - main_loop = NULL; + main_loop = nullptr; } void OS_UWP::set_main_loop(MainLoop *p_main_loop) { @@ -347,10 +347,10 @@ void OS_UWP::finalize() { if (main_loop) memdelete(main_loop); - main_loop = NULL; + main_loop = nullptr; - visual_server->finish(); - memdelete(visual_server); + rendering_server->finish(); + memdelete(rendering_server); #ifdef OPENGL_ENABLED if (gl_context) memdelete(gl_context); @@ -773,9 +773,9 @@ void OS_UWP::hide_virtual_keyboard() { static String format_error_message(DWORD id) { - LPWSTR messageBuffer = NULL; + LPWSTR messageBuffer = nullptr; size_t size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0, NULL); + nullptr, id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0, nullptr); String msg = "Error " + itos(id) + ": " + String(messageBuffer, size); @@ -869,14 +869,14 @@ OS_UWP::OS_UWP() { stdo = fopen("stdout.txt", "wb"); #endif - gl_context = NULL; + gl_context = nullptr; display_request = ref new Windows::System::Display::DisplayRequest(); managed_object = ref new ManagedType; managed_object->os = this; - mouse_mode_changed = CreateEvent(NULL, TRUE, FALSE, L"os_mouse_mode_changed"); + mouse_mode_changed = CreateEvent(nullptr, TRUE, FALSE, L"os_mouse_mode_changed"); AudioDriverManager::add_driver(&audio_driver); diff --git a/platform/uwp/os_uwp.h b/platform/uwp/os_uwp.h index cc4dfcc79f..ad0efa1d03 100644 --- a/platform/uwp/os_uwp.h +++ b/platform/uwp/os_uwp.h @@ -39,8 +39,8 @@ #include "drivers/xaudio2/audio_driver_xaudio2.h" #include "joypad_uwp.h" #include "servers/audio_server.h" -#include "servers/visual/rasterizer.h" -#include "servers/visual_server.h" +#include "servers/rendering/rasterizer.h" +#include "servers/rendering_server.h" #include <fcntl.h> #include <io.h> @@ -88,7 +88,7 @@ private: bool outside; int old_x, old_y; Point2i center; - VisualServer *visual_server; + RenderingServer *rendering_server; int pressrc; ContextEGL_UWP *gl_context; @@ -202,7 +202,7 @@ public: virtual void delay_usec(uint32_t p_usec) const; virtual uint64_t get_ticks_usec() const; - virtual Error execute(const String &p_path, const List<String> &p_arguments, bool p_blocking = true, ProcessID *r_child_id = NULL, String *r_pipe = NULL, int *r_exitcode = NULL, bool read_stderr = false, Mutex *p_pipe_mutex = NULL); + virtual Error execute(const String &p_path, const List<String> &p_arguments, bool p_blocking = true, ProcessID *r_child_id = nullptr, String *r_pipe = nullptr, int *r_exitcode = nullptr, bool read_stderr = false, Mutex *p_pipe_mutex = nullptr); virtual Error kill(const ProcessID &p_pid); virtual bool has_environment(const String &p_var) const; diff --git a/platform/windows/SCsub b/platform/windows/SCsub index 89ee4dfa7a..daffe59f34 100644 --- a/platform/windows/SCsub +++ b/platform/windows/SCsub @@ -1,6 +1,6 @@ #!/usr/bin/env python -Import('env') +Import("env") import os from platform_methods import run_in_subprocess @@ -15,17 +15,17 @@ common_win = [ "joypad_windows.cpp", "windows_terminal_logger.cpp", "vulkan_context_win.cpp", - "context_gl_windows.cpp" + "context_gl_windows.cpp", ] -res_file = 'godot_res.rc' +res_file = "godot_res.rc" res_target = "godot_res" + env["OBJSUFFIX"] res_obj = env.RES(res_target, res_file) -prog = env.add_program('#bin/godot', common_win + res_obj, PROGSUFFIX=env["PROGSUFFIX"]) +prog = env.add_program("#bin/godot", common_win + res_obj, PROGSUFFIX=env["PROGSUFFIX"]) # Microsoft Visual Studio Project Generation -if env['vsproj']: +if env["vsproj"]: env.vs_srcs = env.vs_srcs + ["platform/windows/" + res_file] env.vs_srcs = env.vs_srcs + ["platform/windows/godot.natvis"] for x in common_win: diff --git a/platform/windows/context_gl_windows.cpp b/platform/windows/context_gl_windows.cpp index ad62e3a306..5a36b5546d 100644 --- a/platform/windows/context_gl_windows.cpp +++ b/platform/windows/context_gl_windows.cpp @@ -52,7 +52,7 @@ typedef HGLRC(APIENTRY *PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC, HGLRC, const int void ContextGL_Windows::release_current() { - wglMakeCurrent(hDC, NULL); + wglMakeCurrent(hDC, nullptr); } void ContextGL_Windows::make_current() { @@ -185,10 +185,10 @@ Error ContextGL_Windows::initialize() { 0 }; //zero indicates the end of the array - PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = NULL; //pointer to the method + PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = nullptr; //pointer to the method wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); - if (wglCreateContextAttribsARB == NULL) //OpenGL 3.0 is not supported + if (wglCreateContextAttribsARB == nullptr) //OpenGL 3.0 is not supported { wglDeleteContext(hRC); return ERR_CANT_CREATE; @@ -199,7 +199,7 @@ Error ContextGL_Windows::initialize() { wglDeleteContext(hRC); return ERR_CANT_CREATE; // Return false } - wglMakeCurrent(hDC, NULL); + wglMakeCurrent(hDC, nullptr); wglDeleteContext(hRC); hRC = new_hRC; diff --git a/platform/windows/crash_handler_windows.cpp b/platform/windows/crash_handler_windows.cpp index 6145751e00..1d9eba22d8 100644 --- a/platform/windows/crash_handler_windows.cpp +++ b/platform/windows/crash_handler_windows.cpp @@ -121,7 +121,7 @@ DWORD CrashHandlerException(EXCEPTION_POINTERS *ep) { DWORD cbNeeded; std::vector<HMODULE> module_handles(1); - if (OS::get_singleton() == NULL || OS::get_singleton()->is_disable_crash_handler() || IsDebuggerPresent()) { + if (OS::get_singleton() == nullptr || OS::get_singleton()->is_disable_crash_handler() || IsDebuggerPresent()) { return EXCEPTION_CONTINUE_SEARCH; } @@ -131,7 +131,7 @@ DWORD CrashHandlerException(EXCEPTION_POINTERS *ep) { OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_CRASH); // Load the symbols: - if (!SymInitialize(process, NULL, false)) + if (!SymInitialize(process, nullptr, false)) return EXCEPTION_CONTINUE_SEARCH; SymSetOptions(SymGetOptions() | SYMOPT_LOAD_LINES | SYMOPT_UNDNAME); @@ -193,7 +193,7 @@ DWORD CrashHandlerException(EXCEPTION_POINTERS *ep) { n++; } - if (!StackWalk64(image_type, process, hThread, &frame, context, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL)) + if (!StackWalk64(image_type, process, hThread, &frame, context, nullptr, SymFunctionTableAccess64, SymGetModuleBase64, nullptr)) break; } while (frame.AddrReturn.Offset != 0 && n < 256); diff --git a/platform/windows/detect.py b/platform/windows/detect.py index cc859c0339..9f79e92dcb 100644 --- a/platform/windows/detect.py +++ b/platform/windows/detect.py @@ -14,10 +14,10 @@ def get_name(): def can_build(): - if (os.name == "nt"): + if os.name == "nt": # Building natively on Windows # If VCINSTALLDIR is set in the OS environ, use traditional Godot logic to set up MSVC - if (os.getenv("VCINSTALLDIR")): # MSVC, manual setup + if os.getenv("VCINSTALLDIR"): # MSVC, manual setup return True # Otherwise, let SCons find MSVC if installed, or else Mingw. @@ -26,18 +26,18 @@ def can_build(): # null compiler. return True - if (os.name == "posix"): + if os.name == "posix": # Cross-compiling with MinGW-w64 (old MinGW32 is not supported) mingw32 = "i686-w64-mingw32-" mingw64 = "x86_64-w64-mingw32-" - if (os.getenv("MINGW32_PREFIX")): + if os.getenv("MINGW32_PREFIX"): mingw32 = os.getenv("MINGW32_PREFIX") - if (os.getenv("MINGW64_PREFIX")): + if os.getenv("MINGW64_PREFIX"): mingw64 = os.getenv("MINGW64_PREFIX") test = "gcc --version > /dev/null 2>&1" - if (os.system(mingw64 + test) == 0 or os.system(mingw32 + test) == 0): + if os.system(mingw64 + test) == 0 or os.system(mingw32 + test) == 0: return True return False @@ -48,47 +48,47 @@ def get_opts(): mingw32 = "" mingw64 = "" - if (os.name == "posix"): + if os.name == "posix": mingw32 = "i686-w64-mingw32-" mingw64 = "x86_64-w64-mingw32-" - if (os.getenv("MINGW32_PREFIX")): + if os.getenv("MINGW32_PREFIX"): mingw32 = os.getenv("MINGW32_PREFIX") - if (os.getenv("MINGW64_PREFIX")): + if os.getenv("MINGW64_PREFIX"): mingw64 = os.getenv("MINGW64_PREFIX") return [ - ('mingw_prefix_32', 'MinGW prefix (Win32)', mingw32), - ('mingw_prefix_64', 'MinGW prefix (Win64)', mingw64), + ("mingw_prefix_32", "MinGW prefix (Win32)", mingw32), + ("mingw_prefix_64", "MinGW prefix (Win64)", mingw64), # Targeted Windows version: 7 (and later), minimum supported version # XP support dropped after EOL due to missing API for IPv6 and other issues # Vista support dropped after EOL due to GH-10243 - ('target_win_version', 'Targeted Windows version, >= 0x0601 (Windows 7)', '0x0601'), - EnumVariable('debug_symbols', 'Add debugging symbols to release builds', 'yes', ('yes', 'no', 'full')), - BoolVariable('separate_debug_symbols', 'Create a separate file containing debugging symbols', False), - ('msvc_version', 'MSVC version to use. Ignored if VCINSTALLDIR is set in shell env.', None), - BoolVariable('use_mingw', 'Use the Mingw compiler, even if MSVC is installed. Only used on Windows.', False), - BoolVariable('use_llvm', 'Use the LLVM compiler', False), - BoolVariable('use_thinlto', 'Use ThinLTO', False), + ("target_win_version", "Targeted Windows version, >= 0x0601 (Windows 7)", "0x0601"), + EnumVariable("debug_symbols", "Add debugging symbols to release builds", "yes", ("yes", "no", "full")), + BoolVariable("separate_debug_symbols", "Create a separate file containing debugging symbols", False), + ("msvc_version", "MSVC version to use. Ignored if VCINSTALLDIR is set in shell env.", None), + BoolVariable("use_mingw", "Use the Mingw compiler, even if MSVC is installed. Only used on Windows.", False), + BoolVariable("use_llvm", "Use the LLVM compiler", False), + BoolVariable("use_thinlto", "Use ThinLTO", False), ] def get_flags(): - return [ - ] + return [] def build_res_file(target, source, env): - if (env["bits"] == "32"): - cmdbase = env['mingw_prefix_32'] + if env["bits"] == "32": + cmdbase = env["mingw_prefix_32"] else: - cmdbase = env['mingw_prefix_64'] - cmdbase = cmdbase + 'windres --include-dir . ' + cmdbase = env["mingw_prefix_64"] + cmdbase = cmdbase + "windres --include-dir . " import subprocess + for x in range(len(source)): - cmd = cmdbase + '-i ' + str(source[x]) + ' -o ' + str(target[x]) + cmd = cmdbase + "-i " + str(source[x]) + " -o " + str(target[x]) try: out = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE).communicate() if len(out[1]): @@ -100,12 +100,14 @@ def build_res_file(target, source, env): def setup_msvc_manual(env): """Set up env to use MSVC manually, using VCINSTALLDIR""" - if (env["bits"] != "default"): - print(""" + if env["bits"] != "default": + print( + """ Bits argument is not supported for MSVC compilation. Architecture depends on the Native/Cross Compile Tools Prompt/Developer Console (or Visual Studio settings) that is being used to run SCons. As a consequence, bits argument is disabled. Run scons again without bits argument (example: scons p=windows) and SCons will attempt to detect what MSVC compiler will be executed and inform you. - """) + """ + ) raise SCons.Errors.UserError("Bits argument should not be used when using VCINSTALLDIR") # Force bits arg @@ -114,18 +116,21 @@ def setup_msvc_manual(env): env["x86_libtheora_opt_vc"] = True # find compiler manually - compiler_version_str = methods.detect_visual_c_compiler_version(env['ENV']) + compiler_version_str = methods.detect_visual_c_compiler_version(env["ENV"]) print("Found MSVC compiler: " + compiler_version_str) # If building for 64bit architecture, disable assembly optimisations for 32 bit builds (theora as of writing)... vc compiler for 64bit can not compile _asm - if(compiler_version_str == "amd64" or compiler_version_str == "x86_amd64"): + if compiler_version_str == "amd64" or compiler_version_str == "x86_amd64": env["bits"] = "64" env["x86_libtheora_opt_vc"] = False print("Compiled program architecture will be a 64 bit executable (forcing bits=64).") - elif (compiler_version_str == "x86" or compiler_version_str == "amd64_x86"): + elif compiler_version_str == "x86" or compiler_version_str == "amd64_x86": print("Compiled program architecture will be a 32 bit executable. (forcing bits=32).") else: - print("Failed to manually detect MSVC compiler architecture version... Defaulting to 32bit executable settings (forcing bits=32). Compilation attempt will continue, but SCons can not detect for what architecture this build is compiled for. You should check your settings/compilation setup, or avoid setting VCINSTALLDIR.") + print( + "Failed to manually detect MSVC compiler architecture version... Defaulting to 32bit executable settings (forcing bits=32). Compilation attempt will continue, but SCons can not detect for what architecture this build is compiled for. You should check your settings/compilation setup, or avoid setting VCINSTALLDIR." + ) + def setup_msvc_auto(env): """Set up MSVC using SCons's auto-detection logic""" @@ -138,103 +143,127 @@ def setup_msvc_auto(env): # (Ideally we'd decide on the tool config before configuring any # environment, and just set the env up once, but this function runs # on an existing env so this is the simplest way.) - env['MSVC_SETUP_RUN'] = False # Need to set this to re-run the tool - env['MSVS_VERSION'] = None - env['MSVC_VERSION'] = None - env['TARGET_ARCH'] = None - if env['bits'] != 'default': - env['TARGET_ARCH'] = {'32': 'x86', '64': 'x86_64'}[env['bits']] - if env.has_key('msvc_version'): - env['MSVC_VERSION'] = env['msvc_version'] - env.Tool('msvc') - env.Tool('mssdk') # we want the MS SDK + env["MSVC_SETUP_RUN"] = False # Need to set this to re-run the tool + env["MSVS_VERSION"] = None + env["MSVC_VERSION"] = None + env["TARGET_ARCH"] = None + if env["bits"] != "default": + env["TARGET_ARCH"] = {"32": "x86", "64": "x86_64"}[env["bits"]] + if env.has_key("msvc_version"): + env["MSVC_VERSION"] = env["msvc_version"] + env.Tool("msvc") + env.Tool("mssdk") # we want the MS SDK # Note: actual compiler version can be found in env['MSVC_VERSION'], e.g. "14.1" for VS2015 # Get actual target arch into bits (it may be "default" at this point): - if env['TARGET_ARCH'] in ('amd64', 'x86_64'): - env['bits'] = '64' + if env["TARGET_ARCH"] in ("amd64", "x86_64"): + env["bits"] = "64" else: - env['bits'] = '32' - print("Found MSVC version %s, arch %s, bits=%s" % (env['MSVC_VERSION'], env['TARGET_ARCH'], env['bits'])) - if env['TARGET_ARCH'] in ('amd64', 'x86_64'): + env["bits"] = "32" + print("Found MSVC version %s, arch %s, bits=%s" % (env["MSVC_VERSION"], env["TARGET_ARCH"], env["bits"])) + if env["TARGET_ARCH"] in ("amd64", "x86_64"): env["x86_libtheora_opt_vc"] = False + def setup_mingw(env): """Set up env for use with mingw""" # Nothing to do here print("Using MinGW") pass + def configure_msvc(env, manual_msvc_config): """Configure env to work with MSVC""" # Build type - if (env["target"] == "release"): - if (env["optimize"] == "speed"): #optimize for speed (default) - env.Append(CCFLAGS=['/O2']) - else: # optimize for size - env.Append(CCFLAGS=['/O1']) - env.Append(LINKFLAGS=['/SUBSYSTEM:WINDOWS']) - env.Append(LINKFLAGS=['/ENTRY:mainCRTStartup']) - env.Append(LINKFLAGS=['/OPT:REF']) - - elif (env["target"] == "release_debug"): - if (env["optimize"] == "speed"): #optimize for speed (default) - env.Append(CCFLAGS=['/O2']) - else: # optimize for size - env.Append(CCFLAGS=['/O1']) - env.AppendUnique(CPPDEFINES = ['DEBUG_ENABLED']) - env.Append(LINKFLAGS=['/SUBSYSTEM:CONSOLE']) - env.Append(LINKFLAGS=['/OPT:REF']) - - elif (env["target"] == "debug"): - env.AppendUnique(CCFLAGS=['/Z7', '/Od', '/EHsc']) - env.AppendUnique(CPPDEFINES = ['DEBUG_ENABLED', 'DEBUG_MEMORY_ENABLED', - 'D3D_DEBUG_INFO']) - env.Append(LINKFLAGS=['/SUBSYSTEM:CONSOLE']) - env.Append(LINKFLAGS=['/DEBUG']) - - if (env["debug_symbols"] == "full" or env["debug_symbols"] == "yes"): - env.AppendUnique(CCFLAGS=['/Z7']) - env.AppendUnique(LINKFLAGS=['/DEBUG']) + if env["target"] == "release": + if env["optimize"] == "speed": # optimize for speed (default) + env.Append(CCFLAGS=["/O2"]) + else: # optimize for size + env.Append(CCFLAGS=["/O1"]) + env.Append(LINKFLAGS=["/SUBSYSTEM:WINDOWS"]) + env.Append(LINKFLAGS=["/ENTRY:mainCRTStartup"]) + env.Append(LINKFLAGS=["/OPT:REF"]) + + elif env["target"] == "release_debug": + if env["optimize"] == "speed": # optimize for speed (default) + env.Append(CCFLAGS=["/O2"]) + else: # optimize for size + env.Append(CCFLAGS=["/O1"]) + env.AppendUnique(CPPDEFINES=["DEBUG_ENABLED"]) + env.Append(LINKFLAGS=["/SUBSYSTEM:CONSOLE"]) + env.Append(LINKFLAGS=["/OPT:REF"]) + + elif env["target"] == "debug": + env.AppendUnique(CCFLAGS=["/Z7", "/Od", "/EHsc"]) + env.AppendUnique(CPPDEFINES=["DEBUG_ENABLED", "DEBUG_MEMORY_ENABLED", "D3D_DEBUG_INFO"]) + env.Append(LINKFLAGS=["/SUBSYSTEM:CONSOLE"]) + env.Append(LINKFLAGS=["/DEBUG"]) + + if env["debug_symbols"] == "full" or env["debug_symbols"] == "yes": + env.AppendUnique(CCFLAGS=["/Z7"]) + env.AppendUnique(LINKFLAGS=["/DEBUG"]) ## Compile/link flags - env.AppendUnique(CCFLAGS=['/MT', '/Gd', '/GR', '/nologo']) - if int(env['MSVC_VERSION'].split('.')[0]) >= 14: #vs2015 and later - env.AppendUnique(CCFLAGS=['/utf-8']) - env.AppendUnique(CXXFLAGS=['/TP']) # assume all sources are C++ - if manual_msvc_config: # should be automatic if SCons found it + env.AppendUnique(CCFLAGS=["/MT", "/Gd", "/GR", "/nologo"]) + if int(env["MSVC_VERSION"].split(".")[0]) >= 14: # vs2015 and later + env.AppendUnique(CCFLAGS=["/utf-8"]) + env.AppendUnique(CXXFLAGS=["/TP"]) # assume all sources are C++ + if manual_msvc_config: # should be automatic if SCons found it if os.getenv("WindowsSdkDir") is not None: env.Prepend(CPPPATH=[os.getenv("WindowsSdkDir") + "/Include"]) else: print("Missing environment variable: WindowsSdkDir") - env.AppendUnique(CPPDEFINES = ['WINDOWS_ENABLED', - 'WASAPI_ENABLED', 'WINMIDI_ENABLED', - 'TYPED_METHOD_BIND', - 'WIN32', 'MSVC', - 'WINVER=%s' % env["target_win_version"], - '_WIN32_WINNT=%s' % env["target_win_version"]]) - env.AppendUnique(CPPDEFINES=['NOMINMAX']) # disable bogus min/max WinDef.h macros + env.AppendUnique( + CPPDEFINES=[ + "WINDOWS_ENABLED", + "WASAPI_ENABLED", + "WINMIDI_ENABLED", + "TYPED_METHOD_BIND", + "WIN32", + "MSVC", + "WINVER=%s" % env["target_win_version"], + "_WIN32_WINNT=%s" % env["target_win_version"], + ] + ) + env.AppendUnique(CPPDEFINES=["NOMINMAX"]) # disable bogus min/max WinDef.h macros if env["bits"] == "64": - env.AppendUnique(CPPDEFINES=['_WIN64']) + env.AppendUnique(CPPDEFINES=["_WIN64"]) ## Libs - LIBS = ['winmm', 'dsound', 'kernel32', 'ole32', 'oleaut32', - 'user32', 'gdi32', 'IPHLPAPI', 'Shlwapi', 'wsock32', 'Ws2_32', - 'shell32', 'advapi32', 'dinput8', 'dxguid', 'imm32', 'bcrypt', 'Avrt', - 'dwmapi'] + LIBS = [ + "winmm", + "dsound", + "kernel32", + "ole32", + "oleaut32", + "user32", + "gdi32", + "IPHLPAPI", + "Shlwapi", + "wsock32", + "Ws2_32", + "shell32", + "advapi32", + "dinput8", + "dxguid", + "imm32", + "bcrypt", + "Avrt", + "dwmapi", + ] - env.AppendUnique(CPPDEFINES=['VULKAN_ENABLED']) - if not env['builtin_vulkan']: - LIBS += ['vulkan'] + env.AppendUnique(CPPDEFINES=["VULKAN_ENABLED"]) + if not env["builtin_vulkan"]: + LIBS += ["vulkan"] else: - LIBS += ['cfgmgr32'] + LIBS += ["cfgmgr32"] - #env.AppendUnique(CPPDEFINES = ['OPENGL_ENABLED']) - LIBS += ['opengl32'] + # env.AppendUnique(CPPDEFINES = ['OPENGL_ENABLED']) + LIBS += ["opengl32"] env.Append(LINKFLAGS=[p + env["LIBSUFFIX"] for p in LIBS]) @@ -246,23 +275,24 @@ def configure_msvc(env, manual_msvc_config): ## LTO - if (env["use_lto"]): - env.AppendUnique(CCFLAGS=['/GL']) - env.AppendUnique(ARFLAGS=['/LTCG']) + if env["use_lto"]: + env.AppendUnique(CCFLAGS=["/GL"]) + env.AppendUnique(ARFLAGS=["/LTCG"]) if env["progress"]: - env.AppendUnique(LINKFLAGS=['/LTCG:STATUS']) + env.AppendUnique(LINKFLAGS=["/LTCG:STATUS"]) else: - env.AppendUnique(LINKFLAGS=['/LTCG']) + env.AppendUnique(LINKFLAGS=["/LTCG"]) if manual_msvc_config: env.Prepend(CPPPATH=[p for p in os.getenv("INCLUDE").split(";")]) env.Append(LIBPATH=[p for p in os.getenv("LIB").split(";")]) # Incremental linking fix - env['BUILDERS']['ProgramOriginal'] = env['BUILDERS']['Program'] - env['BUILDERS']['Program'] = methods.precious_program + env["BUILDERS"]["ProgramOriginal"] = env["BUILDERS"]["Program"] + env["BUILDERS"]["Program"] = methods.precious_program + + env.AppendUnique(LINKFLAGS=["/STACK:" + str(STACK_SIZE)]) - env.AppendUnique(LINKFLAGS=['/STACK:' + str(STACK_SIZE)]) def configure_mingw(env): # Workaround for MinGW. See: @@ -271,125 +301,148 @@ def configure_mingw(env): ## Build type - if (env["target"] == "release"): - env.Append(CCFLAGS=['-msse2']) + if env["target"] == "release": + env.Append(CCFLAGS=["-msse2"]) - if (env["optimize"] == "speed"): #optimize for speed (default) - if (env["bits"] == "64"): - env.Append(CCFLAGS=['-O3']) + if env["optimize"] == "speed": # optimize for speed (default) + if env["bits"] == "64": + env.Append(CCFLAGS=["-O3"]) else: - env.Append(CCFLAGS=['-O2']) - else: #optimize for size - env.Prepend(CCFLAGS=['-Os']) - - - env.Append(LINKFLAGS=['-Wl,--subsystem,windows']) - - if (env["debug_symbols"] == "yes"): - env.Prepend(CCFLAGS=['-g1']) - if (env["debug_symbols"] == "full"): - env.Prepend(CCFLAGS=['-g2']) - - elif (env["target"] == "release_debug"): - env.Append(CCFLAGS=['-O2']) - env.Append(CPPDEFINES=['DEBUG_ENABLED']) - if (env["debug_symbols"] == "yes"): - env.Prepend(CCFLAGS=['-g1']) - if (env["debug_symbols"] == "full"): - env.Prepend(CCFLAGS=['-g2']) - if (env["optimize"] == "speed"): #optimize for speed (default) - env.Append(CCFLAGS=['-O2']) - else: #optimize for size - env.Prepend(CCFLAGS=['-Os']) - - elif (env["target"] == "debug"): - env.Append(CCFLAGS=['-g3']) - env.Append(CPPDEFINES=['DEBUG_ENABLED', 'DEBUG_MEMORY_ENABLED']) + env.Append(CCFLAGS=["-O2"]) + else: # optimize for size + env.Prepend(CCFLAGS=["-Os"]) + + env.Append(LINKFLAGS=["-Wl,--subsystem,windows"]) + + if env["debug_symbols"] == "yes": + env.Prepend(CCFLAGS=["-g1"]) + if env["debug_symbols"] == "full": + env.Prepend(CCFLAGS=["-g2"]) + + elif env["target"] == "release_debug": + env.Append(CCFLAGS=["-O2"]) + env.Append(CPPDEFINES=["DEBUG_ENABLED"]) + if env["debug_symbols"] == "yes": + env.Prepend(CCFLAGS=["-g1"]) + if env["debug_symbols"] == "full": + env.Prepend(CCFLAGS=["-g2"]) + if env["optimize"] == "speed": # optimize for speed (default) + env.Append(CCFLAGS=["-O2"]) + else: # optimize for size + env.Prepend(CCFLAGS=["-Os"]) + + elif env["target"] == "debug": + env.Append(CCFLAGS=["-g3"]) + env.Append(CPPDEFINES=["DEBUG_ENABLED", "DEBUG_MEMORY_ENABLED"]) ## Compiler configuration if os.name != "nt": env["PROGSUFFIX"] = env["PROGSUFFIX"] + ".exe" # for linux cross-compilation - if (env["bits"] == "default"): - if (os.name == "nt"): + if env["bits"] == "default": + if os.name == "nt": env["bits"] = "64" if "PROGRAMFILES(X86)" in os.environ else "32" - else: # default to 64-bit on Linux + else: # default to 64-bit on Linux env["bits"] = "64" mingw_prefix = "" - if (env["bits"] == "32"): - env.Append(LINKFLAGS=['-static']) - env.Append(LINKFLAGS=['-static-libgcc']) - env.Append(LINKFLAGS=['-static-libstdc++']) + if env["bits"] == "32": + env.Append(LINKFLAGS=["-static"]) + env.Append(LINKFLAGS=["-static-libgcc"]) + env.Append(LINKFLAGS=["-static-libstdc++"]) mingw_prefix = env["mingw_prefix_32"] else: - env.Append(LINKFLAGS=['-static']) + env.Append(LINKFLAGS=["-static"]) mingw_prefix = env["mingw_prefix_64"] - if env['use_llvm']: + if env["use_llvm"]: env["CC"] = mingw_prefix + "clang" - env['AS'] = mingw_prefix + "as" + env["AS"] = mingw_prefix + "as" env["CXX"] = mingw_prefix + "clang++" - env['AR'] = mingw_prefix + "ar" - env['RANLIB'] = mingw_prefix + "ranlib" + env["AR"] = mingw_prefix + "ar" + env["RANLIB"] = mingw_prefix + "ranlib" env["LINK"] = mingw_prefix + "clang++" else: env["CC"] = mingw_prefix + "gcc" - env['AS'] = mingw_prefix + "as" - env['CXX'] = mingw_prefix + "g++" - env['AR'] = mingw_prefix + "gcc-ar" - env['RANLIB'] = mingw_prefix + "gcc-ranlib" - env['LINK'] = mingw_prefix + "g++" + env["AS"] = mingw_prefix + "as" + env["CXX"] = mingw_prefix + "g++" + env["AR"] = mingw_prefix + "gcc-ar" + env["RANLIB"] = mingw_prefix + "gcc-ranlib" + env["LINK"] = mingw_prefix + "g++" env["x86_libtheora_opt_gcc"] = True - if env['use_lto']: - if not env['use_llvm'] and env.GetOption("num_jobs") > 1: - env.Append(CCFLAGS=['-flto']) - env.Append(LINKFLAGS=['-flto=' + str(env.GetOption("num_jobs"))]) + if env["use_lto"]: + if not env["use_llvm"] and env.GetOption("num_jobs") > 1: + env.Append(CCFLAGS=["-flto"]) + env.Append(LINKFLAGS=["-flto=" + str(env.GetOption("num_jobs"))]) else: - if env['use_thinlto']: - env.Append(CCFLAGS=['-flto=thin']) - env.Append(LINKFLAGS=['-flto=thin']) + if env["use_thinlto"]: + env.Append(CCFLAGS=["-flto=thin"]) + env.Append(LINKFLAGS=["-flto=thin"]) else: - env.Append(CCFLAGS=['-flto']) - env.Append(LINKFLAGS=['-flto']) + env.Append(CCFLAGS=["-flto"]) + env.Append(LINKFLAGS=["-flto"]) - env.Append(LINKFLAGS=['-Wl,--stack,' + str(STACK_SIZE)]) + env.Append(LINKFLAGS=["-Wl,--stack," + str(STACK_SIZE)]) ## Compile flags - env.Append(CCFLAGS=['-mwindows']) - - env.Append(CPPDEFINES=['WINDOWS_ENABLED', 'WASAPI_ENABLED', 'WINMIDI_ENABLED']) - env.Append(CPPDEFINES=[('WINVER', env['target_win_version']), ('_WIN32_WINNT', env['target_win_version'])]) - env.Append(LIBS=['mingw32', 'dsound', 'ole32', 'd3d9', 'winmm', 'gdi32', 'iphlpapi', 'shlwapi', 'wsock32', 'ws2_32', 'kernel32', 'oleaut32', 'dinput8', 'dxguid', 'ksuser', 'imm32', 'bcrypt', 'avrt', 'uuid', 'dwmapi']) - - env.Append(CPPDEFINES=['VULKAN_ENABLED']) - if not env['builtin_vulkan']: - env.Append(LIBS=['vulkan']) + env.Append(CCFLAGS=["-mwindows"]) + + env.Append(CPPDEFINES=["WINDOWS_ENABLED", "WASAPI_ENABLED", "WINMIDI_ENABLED"]) + env.Append(CPPDEFINES=[("WINVER", env["target_win_version"]), ("_WIN32_WINNT", env["target_win_version"])]) + env.Append( + LIBS=[ + "mingw32", + "dsound", + "ole32", + "d3d9", + "winmm", + "gdi32", + "iphlpapi", + "shlwapi", + "wsock32", + "ws2_32", + "kernel32", + "oleaut32", + "dinput8", + "dxguid", + "ksuser", + "imm32", + "bcrypt", + "avrt", + "uuid", + "dwmapi", + ] + ) + + env.Append(CPPDEFINES=["VULKAN_ENABLED"]) + if not env["builtin_vulkan"]: + env.Append(LIBS=["vulkan"]) else: - env.Append(LIBS=['cfgmgr32']) + env.Append(LIBS=["cfgmgr32"]) ## TODO !!! Reenable when OpenGLES Rendering Device is implemented !!! - #env.Append(CPPDEFINES=['OPENGL_ENABLED']) - env.Append(LIBS=['opengl32']) + # env.Append(CPPDEFINES=['OPENGL_ENABLED']) + env.Append(LIBS=["opengl32"]) - env.Append(CPPDEFINES=['MINGW_ENABLED', ('MINGW_HAS_SECURE_API', 1)]) + env.Append(CPPDEFINES=["MINGW_ENABLED", ("MINGW_HAS_SECURE_API", 1)]) # resrc - env.Append(BUILDERS={'RES': env.Builder(action=build_res_file, suffix='.o', src_suffix='.rc')}) + env.Append(BUILDERS={"RES": env.Builder(action=build_res_file, suffix=".o", src_suffix=".rc")}) + def configure(env): # At this point the env has been set up with basic tools/compilers. - env.Prepend(CPPPATH=['#platform/windows']) + env.Prepend(CPPPATH=["#platform/windows"]) - print("Configuring for Windows: target=%s, bits=%s" % (env['target'], env['bits'])) + print("Configuring for Windows: target=%s, bits=%s" % (env["target"], env["bits"])) - if (os.name == "nt"): - env['ENV'] = os.environ # this makes build less repeatable, but simplifies some things - env['ENV']['TMP'] = os.environ['TMP'] + if os.name == "nt": + env["ENV"] = os.environ # this makes build less repeatable, but simplifies some things + env["ENV"]["TMP"] = os.environ["TMP"] # First figure out which compiler, version, and target arch we're using if os.getenv("VCINSTALLDIR") and not env["use_mingw"]: @@ -397,7 +450,7 @@ def configure(env): setup_msvc_manual(env) env.msvc = True manual_msvc_config = True - elif env.get('MSVC_VERSION', '') and not env["use_mingw"]: + elif env.get("MSVC_VERSION", "") and not env["use_mingw"]: setup_msvc_auto(env) env.msvc = True manual_msvc_config = False @@ -409,5 +462,5 @@ def configure(env): if env.msvc: configure_msvc(env, manual_msvc_config) - else: # MinGW + else: # MinGW configure_mingw(env) diff --git a/platform/windows/display_server_windows.cpp b/platform/windows/display_server_windows.cpp index 707337bc8d..ebe9a7d27a 100644 --- a/platform/windows/display_server_windows.cpp +++ b/platform/windows/display_server_windows.cpp @@ -1,3 +1,33 @@ +/*************************************************************************/ +/* display_server_windows.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + #include "display_server_windows.h" #include "core/io/marshalls.h" #include "main/main.h" @@ -13,9 +43,9 @@ #ifdef DEBUG_ENABLED static String format_error_message(DWORD id) { - LPWSTR messageBuffer = NULL; + LPWSTR messageBuffer = nullptr; size_t size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0, NULL); + nullptr, id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0, nullptr); String msg = "Error " + itos(id) + ": " + String(messageBuffer, size); @@ -53,7 +83,7 @@ String DisplayServerWindows::get_name() const { } void DisplayServerWindows::alert(const String &p_alert, const String &p_title) { - MessageBoxW(NULL, p_alert.c_str(), p_title.c_str(), MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL); + MessageBoxW(nullptr, p_alert.c_str(), p_title.c_str(), MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL); } void DisplayServerWindows::_set_mouse_mode_impl(MouseMode p_mode) { @@ -76,11 +106,11 @@ void DisplayServerWindows::_set_mouse_mode_impl(MouseMode p_mode) { } } else { ReleaseCapture(); - ClipCursor(NULL); + ClipCursor(nullptr); } if (p_mode == MOUSE_MODE_CAPTURED || p_mode == MOUSE_MODE_HIDDEN) { - hCursor = SetCursor(NULL); + hCursor = SetCursor(nullptr); } else { CursorShape c = cursor_shape; cursor_shape = CURSOR_MAX; @@ -152,7 +182,7 @@ void DisplayServerWindows::clipboard_set(const String &p_text) { EmptyClipboard(); HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, (text.length() + 1) * sizeof(CharType)); - ERR_FAIL_COND_MSG(mem == NULL, "Unable to allocate memory for clipboard contents."); + ERR_FAIL_COND_MSG(mem == nullptr, "Unable to allocate memory for clipboard contents."); LPWSTR lptstrCopy = (LPWSTR)GlobalLock(mem); memcpy(lptstrCopy, text.c_str(), (text.length() + 1) * sizeof(CharType)); @@ -163,7 +193,7 @@ void DisplayServerWindows::clipboard_set(const String &p_text) { // set the CF_TEXT version (not needed?) CharString utf8 = text.utf8(); mem = GlobalAlloc(GMEM_MOVEABLE, utf8.length() + 1); - ERR_FAIL_COND_MSG(mem == NULL, "Unable to allocate memory for clipboard contents."); + ERR_FAIL_COND_MSG(mem == nullptr, "Unable to allocate memory for clipboard contents."); LPTSTR ptr = (LPTSTR)GlobalLock(mem); memcpy(ptr, utf8.get_data(), utf8.length()); @@ -190,10 +220,10 @@ String DisplayServerWindows::clipboard_get() const { if (IsClipboardFormatAvailable(CF_UNICODETEXT)) { HGLOBAL mem = GetClipboardData(CF_UNICODETEXT); - if (mem != NULL) { + if (mem != nullptr) { LPWSTR ptr = (LPWSTR)GlobalLock(mem); - if (ptr != NULL) { + if (ptr != nullptr) { ret = String((CharType *)ptr); GlobalUnlock(mem); @@ -203,10 +233,10 @@ String DisplayServerWindows::clipboard_get() const { } else if (IsClipboardFormatAvailable(CF_TEXT)) { HGLOBAL mem = GetClipboardData(CF_UNICODETEXT); - if (mem != NULL) { + if (mem != nullptr) { LPTSTR ptr = (LPTSTR)GlobalLock(mem); - if (ptr != NULL) { + if (ptr != nullptr) { ret.parse_utf8((const char *)ptr); GlobalUnlock(mem); @@ -247,7 +277,7 @@ int DisplayServerWindows::get_screen_count() const { _THREAD_SAFE_METHOD_ int data = 0; - EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcCount, (LPARAM)&data); + EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcCount, (LPARAM)&data); return data; } @@ -273,7 +303,7 @@ Point2i DisplayServerWindows::screen_get_position(int p_screen) const { _THREAD_SAFE_METHOD_ EnumPosData data = { 0, p_screen == SCREEN_OF_MAIN_WINDOW ? window_get_current_screen() : p_screen, Point2() }; - EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcPos, (LPARAM)&data); + EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcPos, (LPARAM)&data); return data.pos; } @@ -306,7 +336,7 @@ Size2i DisplayServerWindows::screen_get_size(int p_screen) const { _THREAD_SAFE_METHOD_ EnumSizeData data = { 0, p_screen == SCREEN_OF_MAIN_WINDOW ? window_get_current_screen() : p_screen, Size2() }; - EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcSize, (LPARAM)&data); + EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcSize, (LPARAM)&data); return data.size; } @@ -334,7 +364,7 @@ Rect2i DisplayServerWindows::screen_get_usable_rect(int p_screen) const { _THREAD_SAFE_METHOD_ EnumRectData data = { 0, p_screen == SCREEN_OF_MAIN_WINDOW ? window_get_current_screen() : p_screen, Rect2i() }; - EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcUsableSize, (LPARAM)&data); + EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcUsableSize, (LPARAM)&data); return data.rect; } @@ -355,15 +385,15 @@ static int QueryDpiForMonitor(HMONITOR hmon, _MonitorDpiType dpiType = MDT_Defau int dpiX = 96, dpiY = 96; - static HMODULE Shcore = NULL; + static HMODULE Shcore = nullptr; typedef HRESULT(WINAPI * GetDPIForMonitor_t)(HMONITOR hmonitor, _MonitorDpiType dpiType, UINT * dpiX, UINT * dpiY); - static GetDPIForMonitor_t getDPIForMonitor = NULL; + static GetDPIForMonitor_t getDPIForMonitor = nullptr; - if (Shcore == NULL) { + if (Shcore == nullptr) { Shcore = LoadLibraryW(L"Shcore.dll"); - getDPIForMonitor = Shcore ? (GetDPIForMonitor_t)GetProcAddress(Shcore, "GetDpiForMonitor") : NULL; + getDPIForMonitor = Shcore ? (GetDPIForMonitor_t)GetProcAddress(Shcore, "GetDpiForMonitor") : nullptr; - if ((Shcore == NULL) || (getDPIForMonitor == NULL)) { + if ((Shcore == nullptr) || (getDPIForMonitor == nullptr)) { if (Shcore) FreeLibrary(Shcore); Shcore = (HMODULE)INVALID_HANDLE_VALUE; @@ -382,11 +412,11 @@ static int QueryDpiForMonitor(HMONITOR hmon, _MonitorDpiType dpiType = MDT_Defau } else { static int overallX = 0, overallY = 0; if (overallX <= 0 || overallY <= 0) { - HDC hdc = GetDC(NULL); + HDC hdc = GetDC(nullptr); if (hdc) { overallX = GetDeviceCaps(hdc, LOGPIXELSX); overallY = GetDeviceCaps(hdc, LOGPIXELSY); - ReleaseDC(NULL, hdc); + ReleaseDC(nullptr, hdc); } } if (overallX > 0 && overallY > 0) { @@ -413,7 +443,7 @@ int DisplayServerWindows::screen_get_dpi(int p_screen) const { _THREAD_SAFE_METHOD_ EnumDpiData data = { 0, p_screen == SCREEN_OF_MAIN_WINDOW ? window_get_current_screen() : p_screen, 72 }; - EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcDpi, (LPARAM)&data); + EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcDpi, (LPARAM)&data); return data.dpi; } bool DisplayServerWindows::screen_is_touchscreen(int p_screen) const { @@ -588,7 +618,7 @@ int DisplayServerWindows::window_get_current_screen(WindowID p_window) const { ERR_FAIL_COND_V(!windows.has(p_window), -1); EnumScreenData data = { 0, 0, MonitorFromWindow(windows[p_window].hWnd, MONITOR_DEFAULTTONEAREST) }; - EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcScreen, (LPARAM)&data); + EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcScreen, (LPARAM)&data); return data.screen; } void DisplayServerWindows::window_set_current_screen(int p_screen, WindowID p_window) { @@ -704,7 +734,7 @@ void DisplayServerWindows::window_set_transient(WindowID p_window, WindowID p_pa wd_window.transient_parent = INVALID_WINDOW_ID; wd_parent.transient_children.erase(p_window); - SetWindowLongPtr(wd_window.hWnd, GWLP_HWNDPARENT, NULL); + SetWindowLongPtr(wd_window.hWnd, GWLP_HWNDPARENT, (LONG_PTR) nullptr); } else { ERR_FAIL_COND(!windows.has(p_parent)); ERR_FAIL_COND_MSG(wd_window.transient_parent != INVALID_WINDOW_ID, "Window already has a transient parent"); @@ -989,7 +1019,8 @@ bool DisplayServerWindows::window_is_maximize_allowed(WindowID p_window) const { _THREAD_SAFE_METHOD_ ERR_FAIL_COND_V(!windows.has(p_window), false); - const WindowData &wd = windows[p_window]; + + // FIXME: Implement this, or confirm that it should always be true. return true; //no idea } @@ -1019,14 +1050,17 @@ void DisplayServerWindows::window_set_flag(WindowFlags p_flag, bool p_enabled, W } break; case WINDOW_FLAG_TRANSPARENT: { + // FIXME: Implement. } break; case WINDOW_FLAG_NO_FOCUS: { wd.no_focus = p_enabled; _update_window_style(p_window); } break; + case WINDOW_FLAG_MAX: break; } } + bool DisplayServerWindows::window_get_flag(WindowFlags p_flag, WindowID p_window) const { _THREAD_SAFE_METHOD_ @@ -1048,7 +1082,13 @@ bool DisplayServerWindows::window_get_flag(WindowFlags p_flag, WindowID p_window } break; case WINDOW_FLAG_TRANSPARENT: { + // FIXME: Implement. + } break; + case WINDOW_FLAG_NO_FOCUS: { + + return wd.no_focus; } break; + case WINDOW_FLAG_MAX: break; } return false; @@ -1184,7 +1224,7 @@ void DisplayServerWindows::cursor_set_shape(CursorShape p_shape) { IDC_HELP }; - if (cursors[p_shape] != NULL) { + if (cursors[p_shape] != nullptr) { SetCursor(cursors[p_shape]); } else { SetCursor(LoadCursor(hInstance, win_cursors[p_shape])); @@ -1199,7 +1239,7 @@ DisplayServer::CursorShape DisplayServerWindows::cursor_get_shape() const { void DisplayServerWindows::GetMaskBitmaps(HBITMAP hSourceBitmap, COLORREF clrTransparent, OUT HBITMAP &hAndMaskBitmap, OUT HBITMAP &hXorMaskBitmap) { // Get the system display DC - HDC hDC = GetDC(NULL); + HDC hDC = GetDC(nullptr); // Create helper DC HDC hMainDC = CreateCompatibleDC(hDC); @@ -1215,7 +1255,7 @@ void DisplayServerWindows::GetMaskBitmaps(HBITMAP hSourceBitmap, COLORREF clrTra hXorMaskBitmap = CreateCompatibleBitmap(hDC, bm.bmWidth, bm.bmHeight); // color // Release the system display DC - ReleaseDC(NULL, hDC); + ReleaseDC(nullptr, hDC); // Select the bitmaps to helper DC HBITMAP hOldMainBitmap = (HBITMAP)SelectObject(hMainDC, hSourceBitmap); @@ -1319,12 +1359,12 @@ void DisplayServerWindows::cursor_set_custom_image(const RES &p_cursor, CursorSh COLORREF clrTransparent = -1; // Create the AND and XOR masks for the bitmap - HBITMAP hAndMask = NULL; - HBITMAP hXorMask = NULL; + HBITMAP hAndMask = nullptr; + HBITMAP hXorMask = nullptr; GetMaskBitmaps(bitmap, clrTransparent, hAndMask, hXorMask); - if (NULL == hAndMask || NULL == hXorMask) { + if (nullptr == hAndMask || nullptr == hXorMask) { memfree(buffer); DeleteObject(bitmap); return; @@ -1354,11 +1394,11 @@ void DisplayServerWindows::cursor_set_custom_image(const RES &p_cursor, CursorSh } } - if (hAndMask != NULL) { + if (hAndMask != nullptr) { DeleteObject(hAndMask); } - if (hXorMask != NULL) { + if (hXorMask != nullptr) { DeleteObject(hXorMask); } @@ -1368,7 +1408,7 @@ void DisplayServerWindows::cursor_set_custom_image(const RES &p_cursor, CursorSh // Reset to default system cursor if (cursors[p_shape]) { DestroyIcon(cursors[p_shape]); - cursors[p_shape] = NULL; + cursors[p_shape] = nullptr; } CursorShape c = cursor_shape; @@ -1430,7 +1470,7 @@ DisplayServer::LatinKeyboardVariant DisplayServerWindows::get_latin_keyboard_var name[0] = 0; GetKeyboardLayoutNameA(name); - unsigned long hex = strtoul(name, NULL, 16); + unsigned long hex = strtoul(name, nullptr, 16); int i = 0; while (azerty[i] != 0) { @@ -1463,7 +1503,7 @@ void DisplayServerWindows::process_events() { joypad->process_joypads(); } - while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) { + while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessageW(&msg); @@ -1852,7 +1892,6 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA _send_window_event(windows[window_id], WINDOW_EVENT_CLOSE_REQUEST); - //force_quit=true; return 0; // Jump Back } case WM_MOUSELEAVE: { @@ -1870,9 +1909,9 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA UINT dwSize; - GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER)); + GetRawInputData((HRAWINPUT)lParam, RID_INPUT, nullptr, &dwSize, sizeof(RAWINPUTHEADER)); LPBYTE lpb = new BYTE[dwSize]; - if (lpb == NULL) { + if (lpb == nullptr) { return 0; } @@ -2395,7 +2434,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biSizeImage = dib_size.x * dib_size.y * 4; - hBitmap = CreateDIBSection(hDC_dib, &bmi, DIB_RGB_COLORS, (void **)&dib_data, NULL, 0x0); + hBitmap = CreateDIBSection(hDC_dib, &bmi, DIB_RGB_COLORS, (void **)&dib_data, nullptr, 0x0); SelectObject(hDC_dib, hBitmap); ZeroMemory(dib_data, dib_size.x * dib_size.y * 4); @@ -2406,7 +2445,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA case WM_ENTERSIZEMOVE: { InputFilter::get_singleton()->release_pressed_events(); - move_timer_id = SetTimer(windows[window_id].hWnd, 1, USER_TIMER_MINIMUM, (TIMERPROC)NULL); + move_timer_id = SetTimer(windows[window_id].hWnd, 1, USER_TIMER_MINIMUM, (TIMERPROC) nullptr); } break; case WM_EXITSIZEMOVE: { KillTimer(windows[window_id].hWnd, move_timer_id); @@ -2521,16 +2560,16 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA if (LOWORD(lParam) == HTCLIENT) { if (windows[window_id].window_has_focus && (mouse_mode == MOUSE_MODE_HIDDEN || mouse_mode == MOUSE_MODE_CAPTURED)) { //Hide the cursor - if (hCursor == NULL) - hCursor = SetCursor(NULL); + if (hCursor == nullptr) + hCursor = SetCursor(nullptr); else - SetCursor(NULL); + SetCursor(nullptr); } else { - if (hCursor != NULL) { + if (hCursor != nullptr) { CursorShape c = cursor_shape; cursor_shape = CURSOR_MAX; cursor_set_shape(c); - hCursor = NULL; + hCursor = nullptr; } } } @@ -2542,7 +2581,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA const int buffsize = 4096; wchar_t buf[buffsize]; - int fcount = DragQueryFileW(hDropInfo, 0xFFFFFFFF, NULL, 0); + int fcount = DragQueryFileW(hDropInfo, 0xFFFFFFFF, nullptr, 0); Vector<String> files; @@ -2693,9 +2732,9 @@ DisplayServer::WindowID DisplayServerWindows::_create_window(WindowMode p_mode, WindowRect.top, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top, - NULL, NULL, hInstance, NULL); + nullptr, nullptr, hInstance, nullptr); if (!wd.hWnd) { - MessageBoxW(NULL, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION); + MessageBoxW(nullptr, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION); return INVALID_WINDOW_ID; } #ifdef VULKAN_ENABLED @@ -2703,7 +2742,7 @@ DisplayServer::WindowID DisplayServerWindows::_create_window(WindowMode p_mode, if (rendering_driver == "vulkan") { if (context_vulkan->window_create(id, wd.hWnd, hInstance, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top) == -1) { memdelete(context_vulkan); - context_vulkan = NULL; + context_vulkan = nullptr; ERR_FAIL_V(INVALID_WINDOW_ID); } } @@ -2775,7 +2814,7 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win if (OS::get_singleton()->is_hidpi_allowed()) { HMODULE Shcore = LoadLibraryW(L"Shcore.dll"); - if (Shcore != NULL) { + if (Shcore != nullptr) { typedef HRESULT(WINAPI * SetProcessDpiAwareness_t)(SHC_PROCESS_DPI_AWARENESS); SetProcessDpiAwareness_t SetProcessDpiAwareness = (SetProcessDpiAwareness_t)GetProcAddress(Shcore, "SetProcessDpiAwareness"); @@ -2793,15 +2832,15 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win wc.cbClsExtra = 0; wc.cbWndExtra = 0; //wc.hInstance = hInstance; - wc.hInstance = hInstance ? hInstance : GetModuleHandle(NULL); - wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); - wc.hCursor = NULL; //LoadCursor(NULL, IDC_ARROW); - wc.hbrBackground = NULL; - wc.lpszMenuName = NULL; + wc.hInstance = hInstance ? hInstance : GetModuleHandle(nullptr); + wc.hIcon = LoadIcon(nullptr, IDI_WINLOGO); + wc.hCursor = nullptr; //LoadCursor(nullptr, IDC_ARROW); + wc.hbrBackground = nullptr; + wc.lpszMenuName = nullptr; wc.lpszClassName = L"Engine"; if (!RegisterClassExW(&wc)) { - MessageBox(NULL, "Failed To Register The Window Class.", "ERROR", MB_OK | MB_ICONEXCLAMATION); + MessageBox(nullptr, "Failed To Register The Window Class.", "ERROR", MB_OK | MB_ICONEXCLAMATION); r_error = ERR_UNAVAILABLE; return; } @@ -2828,7 +2867,7 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win context_vulkan = memnew(VulkanContextWindows); if (context_vulkan->initialize() != OK) { memdelete(context_vulkan); - context_vulkan = NULL; + context_vulkan = nullptr; r_error = ERR_UNAVAILABLE; return; } @@ -2841,7 +2880,7 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win if (context_gles2->initialize() != OK) { memdelete(context_gles2); - context_gles2 = NULL; + context_gles2 = nullptr; ERR_FAIL_V(ERR_UNAVAILABLE); } @@ -2853,7 +2892,7 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win RasterizerGLES2::make_current(); } else { memdelete(context_gles2); - context_gles2 = NULL; + context_gles2 = nullptr; ERR_FAIL_V(ERR_UNAVAILABLE); } } diff --git a/platform/windows/display_server_windows.h b/platform/windows/display_server_windows.h index 47bb3f59a6..5cd240ffb0 100644 --- a/platform/windows/display_server_windows.h +++ b/platform/windows/display_server_windows.h @@ -1,3 +1,33 @@ +/*************************************************************************/ +/* display_server_windows.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + #ifndef DISPLAY_SERVER_WINDOWS_H #define DISPLAY_SERVER_WINDOWS_H @@ -13,9 +43,9 @@ #include "joypad_windows.h" #include "key_mapping_windows.h" #include "servers/audio_server.h" -#include "servers/visual/rasterizer.h" -#include "servers/visual/rasterizer_rd/rasterizer_rd.h" -#include "servers/visual_server.h" +#include "servers/rendering/rasterizer.h" +#include "servers/rendering/rasterizer_rd/rasterizer_rd.h" +#include "servers/rendering_server.h" #ifdef XAUDIO2_ENABLED #include "drivers/xaudio2/audio_driver_xaudio2.h" @@ -236,7 +266,6 @@ class DisplayServerWindows : public DisplayServer { bool shift_mem = false; bool control_mem = false; bool meta_mem = false; - bool force_quit = false; uint32_t last_button_state = 0; bool use_raw_input = false; bool drop_events = false; @@ -244,7 +273,7 @@ class DisplayServerWindows : public DisplayServer { WNDCLASSEXW wc; - HCURSOR cursors[CURSOR_MAX] = { NULL }; + HCURSOR cursors[CURSOR_MAX] = { nullptr }; CursorShape cursor_shape; Map<CursorShape, Vector<Variant>> cursors_cache; diff --git a/platform/windows/export/export.cpp b/platform/windows/export/export.cpp index 78a3fc8f79..d63067587c 100644 --- a/platform/windows/export/export.cpp +++ b/platform/windows/export/export.cpp @@ -315,7 +315,7 @@ Error EditorExportPlatformWindows::_code_sign(const Ref<EditorExportPreset> &p_p #endif String str; - Error err = OS::get_singleton()->execute(signtool_path, args, true, NULL, &str, NULL, true); + Error err = OS::get_singleton()->execute(signtool_path, args, true, nullptr, &str, nullptr, true); ERR_FAIL_COND_V(err != OK, err); print_line("codesign (" + p_path + "): " + str); diff --git a/platform/windows/godot_windows.cpp b/platform/windows/godot_windows.cpp index dcc12b7649..2aa928c2a7 100644 --- a/platform/windows/godot_windows.cpp +++ b/platform/windows/godot_windows.cpp @@ -121,23 +121,23 @@ CommandLineToArgvA( i++; } _argv[j] = '\0'; - argv[argc] = NULL; + argv[argc] = nullptr; (*_argc) = argc; return argv; } char *wc_to_utf8(const wchar_t *wc) { - int ulen = WideCharToMultiByte(CP_UTF8, 0, wc, -1, NULL, 0, NULL, NULL); + int ulen = WideCharToMultiByte(CP_UTF8, 0, wc, -1, nullptr, 0, nullptr, nullptr); char *ubuf = new char[ulen + 1]; - WideCharToMultiByte(CP_UTF8, 0, wc, -1, ubuf, ulen, NULL, NULL); + WideCharToMultiByte(CP_UTF8, 0, wc, -1, ubuf, ulen, nullptr, nullptr); ubuf[ulen] = 0; return ubuf; } int widechar_main(int argc, wchar_t **argv) { - OS_Windows os(NULL); + OS_Windows os(nullptr); setlocale(LC_CTYPE, ""); @@ -176,7 +176,7 @@ int _main() { wc_argv = CommandLineToArgvW(GetCommandLineW(), &argc); - if (NULL == wc_argv) { + if (nullptr == wc_argv) { wprintf(L"CommandLineToArgvW failed\n"); return 0; } @@ -202,9 +202,9 @@ int main(int _argc, char **_argv) { #endif } -HINSTANCE godot_hinstance = NULL; +HINSTANCE godot_hinstance = nullptr; int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { godot_hinstance = hInstance; - return main(0, NULL); + return main(0, nullptr); } diff --git a/platform/windows/joypad_windows.cpp b/platform/windows/joypad_windows.cpp index 9de1b7b194..437c3b733d 100644 --- a/platform/windows/joypad_windows.cpp +++ b/platform/windows/joypad_windows.cpp @@ -57,10 +57,10 @@ JoypadWindows::JoypadWindows(HWND *hwnd) { input = InputFilter::get_singleton(); hWnd = hwnd; joypad_count = 0; - dinput = NULL; - xinput_dll = NULL; - xinput_get_state = NULL; - xinput_set_state = NULL; + dinput = nullptr; + xinput_dll = nullptr; + xinput_get_state = nullptr; + xinput_set_state = nullptr; load_xinput(); @@ -68,7 +68,7 @@ JoypadWindows::JoypadWindows(HWND *hwnd) { attached_joypads[i] = false; HRESULT result; - result = DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (void **)&dinput, NULL); + result = DirectInput8Create(GetModuleHandle(nullptr), DIRECTINPUT_VERSION, IID_IDirectInput8, (void **)&dinput, nullptr); if (FAILED(result)) { printf("failed init DINPUT: %ld\n", result); } @@ -105,10 +105,10 @@ bool JoypadWindows::is_xinput_device(const GUID *p_guid) { if (p_guid == &IID_ValveStreamingGamepad || p_guid == &IID_X360WiredGamepad || p_guid == &IID_X360WirelessGamepad) return true; - PRAWINPUTDEVICELIST dev_list = NULL; + PRAWINPUTDEVICELIST dev_list = nullptr; unsigned int dev_list_count = 0; - if (GetRawInputDeviceList(NULL, &dev_list_count, sizeof(RAWINPUTDEVICELIST)) == (UINT)-1) { + if (GetRawInputDeviceList(nullptr, &dev_list_count, sizeof(RAWINPUTDEVICELIST)) == (UINT)-1) { return false; } dev_list = (PRAWINPUTDEVICELIST)malloc(sizeof(RAWINPUTDEVICELIST) * dev_list_count); @@ -130,7 +130,7 @@ bool JoypadWindows::is_xinput_device(const GUID *p_guid) { (GetRawInputDeviceInfoA(dev_list[i].hDevice, RIDI_DEVICEINFO, &rdi, &rdiSize) != (UINT)-1) && (MAKELONG(rdi.hid.dwVendorId, rdi.hid.dwProductId) == (LONG)p_guid->Data1) && (GetRawInputDeviceInfoA(dev_list[i].hDevice, RIDI_DEVICENAME, &dev_name, &nameSize) != (UINT)-1) && - (strstr(dev_name, "IG_") != NULL)) { + (strstr(dev_name, "IG_") != nullptr)) { free(dev_list); return true; @@ -157,7 +157,7 @@ bool JoypadWindows::setup_dinput_joypad(const DIDEVICEINSTANCE *instance) { return false; } - hr = dinput->CreateDevice(instance->guidInstance, &joy->di_joy, NULL); + hr = dinput->CreateDevice(instance->guidInstance, &joy->di_joy, nullptr); if (FAILED(hr)) { return false; diff --git a/platform/windows/joypad_windows.h b/platform/windows/joypad_windows.h index f010fd08ff..0db789c335 100644 --- a/platform/windows/joypad_windows.h +++ b/platform/windows/joypad_windows.h @@ -39,9 +39,9 @@ #ifndef SAFE_RELEASE // when Windows Media Device M? is not present #define SAFE_RELEASE(x) \ - if (x != NULL) { \ + if (x != nullptr) { \ x->Release(); \ - x = NULL; \ + x = nullptr; \ } #endif diff --git a/platform/windows/os_windows.cpp b/platform/windows/os_windows.cpp index f78c87be93..0a67a591b7 100644 --- a/platform/windows/os_windows.cpp +++ b/platform/windows/os_windows.cpp @@ -46,8 +46,8 @@ #include "main/main.h" #include "platform/windows/display_server_windows.h" #include "servers/audio_server.h" -#include "servers/visual/visual_server_raster.h" -#include "servers/visual/visual_server_wrap_mt.h" +#include "servers/rendering/rendering_server_raster.h" +#include "servers/rendering/rendering_server_wrap_mt.h" #include "windows_terminal_logger.h" #include <avrt.h> @@ -81,9 +81,9 @@ __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; #ifdef DEBUG_ENABLED static String format_error_message(DWORD id) { - LPWSTR messageBuffer = NULL; + LPWSTR messageBuffer = nullptr; size_t size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0, NULL); + nullptr, id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0, nullptr); String msg = "Error " + itos(id) + ": " + String(messageBuffer, size); @@ -129,7 +129,7 @@ void RedirectIOToConsole() { *stdout = *fp; - setvbuf(stdout, NULL, _IONBF, 0); + setvbuf(stdout, nullptr, _IONBF, 0); // redirect unbuffered STDIN to the console @@ -141,7 +141,7 @@ void RedirectIOToConsole() { *stdin = *fp; - setvbuf(stdin, NULL, _IONBF, 0); + setvbuf(stdin, nullptr, _IONBF, 0); // redirect unbuffered STDERR to the console @@ -153,7 +153,7 @@ void RedirectIOToConsole() { *stderr = *fp; - setvbuf(stderr, NULL, _IONBF, 0); + setvbuf(stderr, nullptr, _IONBF, 0); // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog @@ -213,14 +213,14 @@ void OS_Windows::initialize() { process_map = memnew((Map<ProcessID, ProcessInfo>)); IP_Unix::make_default(); - main_loop = NULL; + main_loop = nullptr; } void OS_Windows::delete_main_loop() { if (main_loop) memdelete(main_loop); - main_loop = NULL; + main_loop = nullptr; } void OS_Windows::set_main_loop(MainLoop *p_main_loop) { @@ -237,7 +237,7 @@ void OS_Windows::finalize() { if (main_loop) memdelete(main_loop); - main_loop = NULL; + main_loop = nullptr; } void OS_Windows::finalize_core() { @@ -263,14 +263,14 @@ Error OS_Windows::open_dynamic_library(const String p_path, void *&p_library_han PAddDllDirectory add_dll_directory = (PAddDllDirectory)GetProcAddress(GetModuleHandle("kernel32.dll"), "AddDllDirectory"); PRemoveDllDirectory remove_dll_directory = (PRemoveDllDirectory)GetProcAddress(GetModuleHandle("kernel32.dll"), "RemoveDllDirectory"); - bool has_dll_directory_api = ((add_dll_directory != NULL) && (remove_dll_directory != NULL)); - DLL_DIRECTORY_COOKIE cookie = NULL; + bool has_dll_directory_api = ((add_dll_directory != nullptr) && (remove_dll_directory != nullptr)); + DLL_DIRECTORY_COOKIE cookie = nullptr; if (p_also_set_library_path && has_dll_directory_api) { cookie = add_dll_directory(path.get_base_dir().c_str()); } - p_library_handle = (void *)LoadLibraryExW(path.c_str(), NULL, (p_also_set_library_path && has_dll_directory_api) ? LOAD_LIBRARY_SEARCH_DEFAULT_DIRS : 0); + p_library_handle = (void *)LoadLibraryExW(path.c_str(), nullptr, (p_also_set_library_path && has_dll_directory_api) ? LOAD_LIBRARY_SEARCH_DEFAULT_DIRS : 0); ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ", error: " + format_error_message(GetLastError()) + "."); if (cookie) { @@ -490,7 +490,7 @@ Error OS_Windows::execute(const String &p_path, const List<String> &p_arguments, modstr.resize(cmdline.size()); for (int i = 0; i < cmdline.size(); i++) modstr.write[i] = cmdline[i]; - int ret = CreateProcessW(NULL, modstr.ptrw(), NULL, NULL, 0, NORMAL_PRIORITY_CLASS & CREATE_NO_WINDOW, NULL, NULL, si_w, &pi.pi); + int ret = CreateProcessW(nullptr, modstr.ptrw(), nullptr, nullptr, 0, NORMAL_PRIORITY_CLASS & CREATE_NO_WINDOW, nullptr, nullptr, si_w, &pi.pi); ERR_FAIL_COND_V(ret == 0, ERR_CANT_FORK); if (p_blocking) { @@ -542,7 +542,7 @@ Error OS_Windows::set_cwd(const String &p_cwd) { String OS_Windows::get_executable_path() const { wchar_t bufname[4096]; - GetModuleFileNameW(NULL, bufname, 4096); + GetModuleFileNameW(nullptr, bufname, 4096); String s = bufname; return s; } @@ -550,12 +550,12 @@ String OS_Windows::get_executable_path() const { bool OS_Windows::has_environment(const String &p_var) const { #ifdef MINGW_ENABLED - return _wgetenv(p_var.c_str()) != NULL; + return _wgetenv(p_var.c_str()) != nullptr; #else wchar_t *env; size_t len; _wdupenv_s(&env, &len, p_var.c_str()); - const bool has_env = env != NULL; + const bool has_env = env != nullptr; free(env); return has_env; #endif @@ -588,7 +588,7 @@ String OS_Windows::get_stdin_string(bool p_block) { Error OS_Windows::shell_open(String p_uri) { - ShellExecuteW(NULL, NULL, p_uri.c_str(), NULL, NULL, SW_SHOWNORMAL); + ShellExecuteW(nullptr, nullptr, p_uri.c_str(), nullptr, nullptr, SW_SHOWNORMAL); return OK; } @@ -739,7 +739,7 @@ String OS_Windows::get_system_dir(SystemDir p_dir) const { } PWSTR szPath; - HRESULT res = SHGetKnownFolderPath(id, 0, NULL, &szPath); + HRESULT res = SHGetKnownFolderPath(id, 0, nullptr, &szPath); ERR_FAIL_COND_V(res != S_OK, String()); String path = String(szPath); CoTaskMemFree(szPath); @@ -794,11 +794,11 @@ Error OS_Windows::move_to_trash(const String &p_path) { sf.hwnd = main_window; sf.wFunc = FO_DELETE; sf.pFrom = from; - sf.pTo = NULL; + sf.pTo = nullptr; sf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; sf.fAnyOperationsAborted = FALSE; - sf.hNameMappings = NULL; - sf.lpszProgressTitle = NULL; + sf.hNameMappings = nullptr; + sf.lpszProgressTitle = nullptr; int ret = SHFileOperationW(&sf); delete[] from; diff --git a/platform/windows/os_windows.h b/platform/windows/os_windows.h index 040951668d..6bdfc75ebb 100644 --- a/platform/windows/os_windows.h +++ b/platform/windows/os_windows.h @@ -40,8 +40,8 @@ #include "drivers/winmidi/midi_driver_winmidi.h" #include "key_mapping_windows.h" #include "servers/audio_server.h" -#include "servers/visual/rasterizer.h" -#include "servers/visual_server.h" +#include "servers/rendering/rasterizer.h" +#include "servers/rendering_server.h" #ifdef XAUDIO2_ENABLED #include "drivers/xaudio2/audio_driver_xaudio2.h" #endif @@ -130,7 +130,7 @@ public: virtual void delay_usec(uint32_t p_usec) const; virtual uint64_t get_ticks_usec() const; - virtual Error execute(const String &p_path, const List<String> &p_arguments, bool p_blocking = true, ProcessID *r_child_id = NULL, String *r_pipe = NULL, int *r_exitcode = NULL, bool read_stderr = false, Mutex *p_pipe_mutex = NULL); + virtual Error execute(const String &p_path, const List<String> &p_arguments, bool p_blocking = true, ProcessID *r_child_id = nullptr, String *r_pipe = nullptr, int *r_exitcode = nullptr, bool read_stderr = false, Mutex *p_pipe_mutex = nullptr); virtual Error kill(const ProcessID &p_pid); virtual int get_process_id() const; diff --git a/platform/windows/platform_windows_builders.py b/platform/windows/platform_windows_builders.py index a1ad3b8b50..22e33b51b4 100644 --- a/platform/windows/platform_windows_builders.py +++ b/platform/windows/platform_windows_builders.py @@ -9,14 +9,14 @@ from platform_methods import subprocess_main def make_debug_mingw(target, source, env): mingw_prefix = "" - if (env["bits"] == "32"): + if env["bits"] == "32": mingw_prefix = env["mingw_prefix_32"] else: mingw_prefix = env["mingw_prefix_64"] - os.system(mingw_prefix + 'objcopy --only-keep-debug {0} {0}.debugsymbols'.format(target[0])) - os.system(mingw_prefix + 'strip --strip-debug --strip-unneeded {0}'.format(target[0])) - os.system(mingw_prefix + 'objcopy --add-gnu-debuglink={0}.debugsymbols {0}'.format(target[0])) + os.system(mingw_prefix + "objcopy --only-keep-debug {0} {0}.debugsymbols".format(target[0])) + os.system(mingw_prefix + "strip --strip-debug --strip-unneeded {0}".format(target[0])) + os.system(mingw_prefix + "objcopy --add-gnu-debuglink={0}.debugsymbols {0}".format(target[0])) -if __name__ == '__main__': +if __name__ == "__main__": subprocess_main(globals()) diff --git a/platform/windows/vulkan_context_win.cpp b/platform/windows/vulkan_context_win.cpp index 66b5cf8113..98aa21411f 100644 --- a/platform/windows/vulkan_context_win.cpp +++ b/platform/windows/vulkan_context_win.cpp @@ -39,13 +39,13 @@ int VulkanContextWindows::window_create(DisplayServer::WindowID p_window_id, HWN VkWin32SurfaceCreateInfoKHR createInfo; createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; - createInfo.pNext = NULL; + createInfo.pNext = nullptr; createInfo.flags = 0; createInfo.hinstance = p_instance; createInfo.hwnd = p_window; VkSurfaceKHR surface; - VkResult err = vkCreateWin32SurfaceKHR(_get_instance(), &createInfo, NULL, &surface); + VkResult err = vkCreateWin32SurfaceKHR(_get_instance(), &createInfo, nullptr, &surface); ERR_FAIL_COND_V(err, -1); return _window_create(p_window_id, surface, p_width, p_height); } diff --git a/platform/windows/windows_terminal_logger.cpp b/platform/windows/windows_terminal_logger.cpp index 520b654b94..884d95e082 100644 --- a/platform/windows/windows_terminal_logger.cpp +++ b/platform/windows/windows_terminal_logger.cpp @@ -49,7 +49,7 @@ void WindowsTerminalLogger::logv(const char *p_format, va_list p_list, bool p_er len = BUFFER_SIZE; // Output is too big, will be truncated buf[len] = 0; - int wlen = MultiByteToWideChar(CP_UTF8, 0, buf, len, NULL, 0); + int wlen = MultiByteToWideChar(CP_UTF8, 0, buf, len, nullptr, 0); if (wlen < 0) return; |