diff options
Diffstat (limited to 'platform')
96 files changed, 2412 insertions, 1972 deletions
diff --git a/platform/SCsub b/platform/SCsub index 2019a30be7..0f9c2047a0 100644 --- a/platform/SCsub +++ b/platform/SCsub @@ -18,10 +18,13 @@ for platform in env.platform_apis: 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_utf8('register_platform_apis.gen.cpp', 'w') as f: - f.write(reg_apis_inc) - f.write(reg_apis) - f.write(unreg_apis) + f.write(reg_apis_inc) + f.write(reg_apis) + f.write(unreg_apis) + platform_sources.append('register_platform_apis.gen.cpp') lib = env.add_library('platform', platform_sources) diff --git a/platform/android/AndroidManifest.xml.template b/platform/android/AndroidManifest.xml.template index 13d10b5026..81f4c15849 100644 --- a/platform/android/AndroidManifest.xml.template +++ b/platform/android/AndroidManifest.xml.template @@ -32,174 +32,9 @@ $$ADD_APPLICATION_CHUNKS$$ </application> - <uses-feature android:glEsVersion="0x00030000" android:required="true" /> + <uses-feature android:glEsVersion="0x00020000" android:required="true" /> $$ADD_PERMISSION_CHUNKS$$ -<uses-permission android:name="godot.ACCESS_CHECKIN_PROPERTIES"/> -<uses-permission android:name="godot.ACCESS_COARSE_LOCATION"/> -<uses-permission android:name="godot.ACCESS_FINE_LOCATION"/> -<uses-permission android:name="godot.ACCESS_LOCATION_EXTRA_COMMANDS"/> -<uses-permission android:name="godot.ACCESS_MOCK_LOCATION"/> -<uses-permission android:name="godot.ACCESS_NETWORK_STATE"/> -<uses-permission android:name="godot.ACCESS_SURFACE_FLINGER"/> -<uses-permission android:name="godot.ACCESS_WIFI_STATE"/> -<uses-permission android:name="godot.ACCOUNT_MANAGER"/> -<uses-permission android:name="godot.ADD_VOICEMAIL"/> -<uses-permission android:name="godot.AUTHENTICATE_ACCOUNTS"/> -<uses-permission android:name="godot.BATTERY_STATS"/> -<uses-permission android:name="godot.BIND_ACCESSIBILITY_SERVICE"/> -<uses-permission android:name="godot.BIND_APPWIDGET"/> -<uses-permission android:name="godot.BIND_DEVICE_ADMIN"/> -<uses-permission android:name="godot.BIND_INPUT_METHOD"/> -<uses-permission android:name="godot.BIND_NFC_SERVICE"/> -<uses-permission android:name="godot.BIND_NOTIFICATION_LISTENER_SERVICE"/> -<uses-permission android:name="godot.BIND_PRINT_SERVICE"/> -<uses-permission android:name="godot.BIND_REMOTEVIEWS"/> -<uses-permission android:name="godot.BIND_TEXT_SERVICE"/> -<uses-permission android:name="godot.BIND_VPN_SERVICE"/> -<uses-permission android:name="godot.BIND_WALLPAPER"/> -<uses-permission android:name="godot.BLUETOOTH"/> -<uses-permission android:name="godot.BLUETOOTH_ADMIN"/> -<uses-permission android:name="godot.BLUETOOTH_PRIVILEGED"/> -<uses-permission android:name="godot.BRICK"/> -<uses-permission android:name="godot.BROADCAST_PACKAGE_REMOVED"/> -<uses-permission android:name="godot.BROADCAST_SMS"/> -<uses-permission android:name="godot.BROADCAST_STICKY"/> -<uses-permission android:name="godot.BROADCAST_WAP_PUSH"/> -<uses-permission android:name="godot.CALL_PHONE"/> -<uses-permission android:name="godot.CALL_PRIVILEGED"/> -<uses-permission android:name="godot.CAMERA"/> -<uses-permission android:name="godot.CAPTURE_AUDIO_OUTPUT"/> -<uses-permission android:name="godot.CAPTURE_SECURE_VIDEO_OUTPUT"/> -<uses-permission android:name="godot.CAPTURE_VIDEO_OUTPUT"/> -<uses-permission android:name="godot.CHANGE_COMPONENT_ENABLED_STATE"/> -<uses-permission android:name="godot.CHANGE_CONFIGURATION"/> -<uses-permission android:name="godot.CHANGE_NETWORK_STATE"/> -<uses-permission android:name="godot.CHANGE_WIFI_MULTICAST_STATE"/> -<uses-permission android:name="godot.CHANGE_WIFI_STATE"/> -<uses-permission android:name="godot.CLEAR_APP_CACHE"/> -<uses-permission android:name="godot.CLEAR_APP_USER_DATA"/> -<uses-permission android:name="godot.CONTROL_LOCATION_UPDATES"/> -<uses-permission android:name="godot.DELETE_CACHE_FILES"/> -<uses-permission android:name="godot.DELETE_PACKAGES"/> -<uses-permission android:name="godot.DEVICE_POWER"/> -<uses-permission android:name="godot.DIAGNOSTIC"/> -<uses-permission android:name="godot.DISABLE_KEYGUARD"/> -<uses-permission android:name="godot.DUMP"/> -<uses-permission android:name="godot.EXPAND_STATUS_BAR"/> -<uses-permission android:name="godot.FACTORY_TEST"/> -<uses-permission android:name="godot.FLASHLIGHT"/> -<uses-permission android:name="godot.FORCE_BACK"/> -<uses-permission android:name="godot.GET_ACCOUNTS"/> -<uses-permission android:name="godot.GET_PACKAGE_SIZE"/> -<uses-permission android:name="godot.GET_TASKS"/> -<uses-permission android:name="godot.GET_TOP_ACTIVITY_INFO"/> -<uses-permission android:name="godot.GLOBAL_SEARCH"/> -<uses-permission android:name="godot.HARDWARE_TEST"/> -<uses-permission android:name="godot.INJECT_EVENTS"/> -<uses-permission android:name="godot.INSTALL_LOCATION_PROVIDER"/> -<uses-permission android:name="godot.INSTALL_PACKAGES"/> -<uses-permission android:name="godot.INSTALL_SHORTCUT"/> -<uses-permission android:name="godot.INTERNAL_SYSTEM_WINDOW"/> -<uses-permission android:name="godot.INTERNET"/> -<uses-permission android:name="godot.KILL_BACKGROUND_PROCESSES"/> -<uses-permission android:name="godot.LOCATION_HARDWARE"/> -<uses-permission android:name="godot.MANAGE_ACCOUNTS"/> -<uses-permission android:name="godot.MANAGE_APP_TOKENS"/> -<uses-permission android:name="godot.MANAGE_DOCUMENTS"/> -<uses-permission android:name="godot.MASTER_CLEAR"/> -<uses-permission android:name="godot.MEDIA_CONTENT_CONTROL"/> -<uses-permission android:name="godot.MODIFY_AUDIO_SETTINGS"/> -<uses-permission android:name="godot.MODIFY_PHONE_STATE"/> -<uses-permission android:name="godot.MOUNT_FORMAT_FILESYSTEMS"/> -<uses-permission android:name="godot.MOUNT_UNMOUNT_FILESYSTEMS"/> -<uses-permission android:name="godot.NFC"/> -<uses-permission android:name="godot.PERSISTENT_ACTIVITY"/> -<uses-permission android:name="godot.PROCESS_OUTGOING_CALLS"/> -<uses-permission android:name="godot.READ_CALENDAR"/> -<uses-permission android:name="godot.READ_CALL_LOG"/> -<uses-permission android:name="godot.READ_CONTACTS"/> -<uses-permission android:name="godot.READ_EXTERNAL_STORAGE"/> -<uses-permission android:name="godot.READ_FRAME_BUFFER"/> -<uses-permission android:name="godot.READ_HISTORY_BOOKMARKS"/> -<uses-permission android:name="godot.READ_INPUT_STATE"/> -<uses-permission android:name="godot.READ_LOGS"/> -<uses-permission android:name="godot.READ_PHONE_STATE"/> -<uses-permission android:name="godot.READ_PROFILE"/> -<uses-permission android:name="godot.READ_SMS"/> -<uses-permission android:name="godot.READ_SOCIAL_STREAM"/> -<uses-permission android:name="godot.READ_SYNC_SETTINGS"/> -<uses-permission android:name="godot.READ_SYNC_STATS"/> -<uses-permission android:name="godot.READ_USER_DICTIONARY"/> -<uses-permission android:name="godot.REBOOT"/> -<uses-permission android:name="godot.RECEIVE_BOOT_COMPLETED"/> -<uses-permission android:name="godot.RECEIVE_MMS"/> -<uses-permission android:name="godot.RECEIVE_SMS"/> -<uses-permission android:name="godot.RECEIVE_WAP_PUSH"/> -<uses-permission android:name="godot.RECORD_AUDIO"/> -<uses-permission android:name="godot.REORDER_TASKS"/> -<uses-permission android:name="godot.RESTART_PACKAGES"/> -<uses-permission android:name="godot.SEND_RESPOND_VIA_MESSAGE"/> -<uses-permission android:name="godot.SEND_SMS"/> -<uses-permission android:name="godot.SET_ACTIVITY_WATCHER"/> -<uses-permission android:name="godot.SET_ALARM"/> -<uses-permission android:name="godot.SET_ALWAYS_FINISH"/> -<uses-permission android:name="godot.SET_ANIMATION_SCALE"/> -<uses-permission android:name="godot.SET_DEBUG_APP"/> -<uses-permission android:name="godot.SET_ORIENTATION"/> -<uses-permission android:name="godot.SET_POINTER_SPEED"/> -<uses-permission android:name="godot.SET_PREFERRED_APPLICATIONS"/> -<uses-permission android:name="godot.SET_PROCESS_LIMIT"/> -<uses-permission android:name="godot.SET_TIME"/> -<uses-permission android:name="godot.SET_TIME_ZONE"/> -<uses-permission android:name="godot.SET_WALLPAPER"/> -<uses-permission android:name="godot.SET_WALLPAPER_HINTS"/> -<uses-permission android:name="godot.SIGNAL_PERSISTENT_PROCESSES"/> -<uses-permission android:name="godot.STATUS_BAR"/> -<uses-permission android:name="godot.SUBSCRIBED_FEEDS_READ"/> -<uses-permission android:name="godot.SUBSCRIBED_FEEDS_WRITE"/> -<uses-permission android:name="godot.SYSTEM_ALERT_WINDOW"/> -<uses-permission android:name="godot.TRANSMIT_IR"/> -<uses-permission android:name="godot.UNINSTALL_SHORTCUT"/> -<uses-permission android:name="godot.UPDATE_DEVICE_STATS"/> -<uses-permission android:name="godot.USE_CREDENTIALS"/> -<uses-permission android:name="godot.USE_SIP"/> -<uses-permission android:name="godot.VIBRATE"/> -<uses-permission android:name="godot.WAKE_LOCK"/> -<uses-permission android:name="godot.WRITE_APN_SETTINGS"/> -<uses-permission android:name="godot.WRITE_CALENDAR"/> -<uses-permission android:name="godot.WRITE_CALL_LOG"/> -<uses-permission android:name="godot.WRITE_CONTACTS"/> -<uses-permission android:name="godot.WRITE_EXTERNAL_STORAGE"/> -<uses-permission android:name="godot.WRITE_GSERVICES"/> -<uses-permission android:name="godot.WRITE_HISTORY_BOOKMARKS"/> -<uses-permission android:name="godot.WRITE_PROFILE"/> -<uses-permission android:name="godot.WRITE_SECURE_SETTINGS"/> -<uses-permission android:name="godot.WRITE_SETTINGS"/> -<uses-permission android:name="godot.WRITE_SMS"/> -<uses-permission android:name="godot.WRITE_SOCIAL_STREAM"/> -<uses-permission android:name="godot.WRITE_SYNC_SETTINGS"/> -<uses-permission android:name="godot.WRITE_USER_DICTIONARY"/> -<uses-permission android:name="godot.custom.0"/> -<uses-permission android:name="godot.custom.1"/> -<uses-permission android:name="godot.custom.2"/> -<uses-permission android:name="godot.custom.3"/> -<uses-permission android:name="godot.custom.4"/> -<uses-permission android:name="godot.custom.5"/> -<uses-permission android:name="godot.custom.6"/> -<uses-permission android:name="godot.custom.7"/> -<uses-permission android:name="godot.custom.8"/> -<uses-permission android:name="godot.custom.9"/> -<uses-permission android:name="godot.custom.10"/> -<uses-permission android:name="godot.custom.11"/> -<uses-permission android:name="godot.custom.12"/> -<uses-permission android:name="godot.custom.13"/> -<uses-permission android:name="godot.custom.14"/> -<uses-permission android:name="godot.custom.15"/> -<uses-permission android:name="godot.custom.16"/> -<uses-permission android:name="godot.custom.17"/> -<uses-permission android:name="godot.custom.18"/> -<uses-permission android:name="godot.custom.19"/> <uses-sdk android:minSdkVersion="18" android:targetSdkVersion="27"/> diff --git a/platform/android/SCsub b/platform/android/SCsub index 8c08289932..31fee5722c 100644 --- a/platform/android/SCsub +++ b/platform/android/SCsub @@ -2,6 +2,8 @@ import shutil from compat import open_utf8 +from distutils.version import LooseVersion +from detect import get_ndk_version Import('env') @@ -53,7 +55,7 @@ if len(env.android_flat_dirs) > 0: gradle_maven_flat_text = gradle_maven_flat_text[:-1] gradle_maven_flat_text += "\n\t}\n" - + gradle_maven_repos_text = "" gradle_maven_repos_text += gradle_maven_flat_text @@ -99,6 +101,9 @@ for x in env.android_jni_dirs: gradle_asset_dirs_text = "" +for x in env.android_asset_dirs: + gradle_asset_dirs_text += ",'" + x.replace("\\", "/") + "'" + gradle_default_config_text = "" minSdk = 18 @@ -166,3 +171,7 @@ if lib_arch_dir != '': out_dir = '#platform/android/java/libs/' + lib_type_dir + '/' + lib_arch_dir env_android.Command(out_dir + '/libgodot_android.so', '#bin/libgodot' + env['SHLIBSUFFIX'], Move("$TARGET", "$SOURCE")) + ndk_version = get_ndk_version(env["ANDROID_NDK_ROOT"]) + if ndk_version != None and LooseVersion(ndk_version) >= LooseVersion("15.0.4075724"): + 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"))
\ No newline at end of file diff --git a/platform/android/audio_driver_jandroid.cpp b/platform/android/audio_driver_jandroid.cpp index 3d80e76707..46bd691290 100644 --- a/platform/android/audio_driver_jandroid.cpp +++ b/platform/android/audio_driver_jandroid.cpp @@ -78,13 +78,11 @@ Error AudioDriverAndroid::init() { // __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDL audio: opening device"); JNIEnv *env = ThreadAndroid::get_env(); - int mix_rate = GLOBAL_DEF("audio/mix_rate", 44100); + int mix_rate = GLOBAL_DEF_RST("audio/mix_rate", 44100); - int latency = GLOBAL_DEF("audio/output_latency", 25); + int latency = GLOBAL_DEF_RST("audio/output_latency", 25); unsigned int buffer_size = next_power_of_2(latency * mix_rate / 1000); - if (OS::get_singleton()->is_stdout_verbose()) { - print_line("audio buffer size: " + itos(buffer_size)); - } + print_verbose("Audio buffer size: " + itos(buffer_size)); audioBuffer = env->CallObjectMethod(io, _init_audio, mix_rate, buffer_size); diff --git a/platform/android/audio_driver_opensl.cpp b/platform/android/audio_driver_opensl.cpp index e6bd3ff253..28e3ea962f 100644 --- a/platform/android/audio_driver_opensl.cpp +++ b/platform/android/audio_driver_opensl.cpp @@ -42,7 +42,8 @@ void AudioDriverOpenSL::_buffer_callback( /* SLuint32 eventFlags, const void * pBuffer, SLuint32 bufferSize, - SLuint32 dataUsed*/) { + SLuint32 dataUsed*/ +) { bool mix = true; @@ -145,9 +146,6 @@ void AudioDriverOpenSL::start() { res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void *)&EngineItf); ERR_FAIL_COND(res != SL_RESULT_SUCCESS); - /* Initialize arrays required[] and iidArray[] */ - SLboolean required[MAX_NUMBER_INTERFACES]; - SLInterfaceID iidArray[MAX_NUMBER_INTERFACES]; { const SLInterfaceID ids[1] = { SL_IID_ENVIRONMENTALREVERB }; @@ -187,10 +185,7 @@ void AudioDriverOpenSL::start() { //cntxt.pDataBase = (void*)&pcmData; //cntxt.pData = cntxt.pDataBase; //cntxt.size = sizeof(pcmData); - /* Set arrays required[] and iidArray[] for SEEK interface - (PlayItf is implicit) */ - required[0] = SL_BOOLEAN_TRUE; - iidArray[0] = SL_IID_BUFFERQUEUE; + /* Create the music player */ { diff --git a/platform/android/audio_driver_opensl.h b/platform/android/audio_driver_opensl.h index 2022bad02a..88cb122414 100644 --- a/platform/android/audio_driver_opensl.h +++ b/platform/android/audio_driver_opensl.h @@ -74,7 +74,8 @@ class AudioDriverOpenSL : public AudioDriver { /* SLuint32 eventFlags, const void * pBuffer, SLuint32 bufferSize, - SLuint32 dataUsed*/); + SLuint32 dataUsed*/ + ); static void _buffer_callbacks( SLAndroidSimpleBufferQueueItf queueItf, diff --git a/platform/android/detect.py b/platform/android/detect.py index 971368db17..953a2fa6d2 100644 --- a/platform/android/detect.py +++ b/platform/android/detect.py @@ -128,7 +128,7 @@ def configure(env): 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 andorid-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' target_subpath = "aarch64-linux-android-4.9" @@ -139,8 +139,13 @@ def configure(env): ## Build type if (env["target"].startswith("release")): - env.Append(LINKFLAGS=['-O2']) - env.Append(CPPFLAGS=['-O2', '-DNDEBUG', '-ffast-math', '-funsafe-math-optimizations', '-fomit-frame-pointer']) + if (env["optimize"] == "speed"): #optimize for speed (default) + env.Append(LINKFLAGS=['-O2']) + env.Append(CPPFLAGS=['-O2', '-DNDEBUG', '-ffast-math', '-funsafe-math-optimizations', '-fomit-frame-pointer']) + else: #optimize for size + env.Append(CPPFLAGS=['-Os', '-DNDEBUG']) + env.Append(LINKFLAGS=['-Os']) + if (can_vectorize): env.Append(CPPFLAGS=['-ftree-vectorize']) if (env["target"] == "release_debug"): @@ -199,18 +204,26 @@ def configure(env): ## Compile flags + if env['android_stl']: + env.Append(CPPFLAGS=["-isystem", env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/include"]) + env.Append(CPPFLAGS=["-isystem", env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++abi/include"]) + env.Append(CXXFLAGS=['-frtti',"-std=gnu++14"]) + else: + env.Append(CXXFLAGS=['-fno-rtti', '-fno-exceptions', '-DNO_SAFE_CAST']) + ndk_version = get_ndk_version(env["ANDROID_NDK_ROOT"]) if ndk_version != None and LooseVersion(ndk_version) >= LooseVersion("15.0.4075724"): print("Using NDK unified headers") sysroot = env["ANDROID_NDK_ROOT"] + "/sysroot" - env.Append(CPPFLAGS=["-isystem", sysroot + "/usr/include"]) + env.Append(CPPFLAGS=["--sysroot="+sysroot]) 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(CPPFLAGS=["-D__ANDROID_API__=" + str(get_platform(env['ndk_platform']))]) else: print("Using NDK deprecated headers") env.Append(CPPFLAGS=["-isystem", lib_sysroot + "/usr/include"]) - + env.Append(CPPFLAGS='-fpic -ffunction-sections -funwind-tables -fstack-protector-strong -fvisibility=hidden -fno-strict-aliasing'.split()) env.Append(CPPFLAGS='-DNO_STATVFS -DGLES_ENABLED'.split()) @@ -241,23 +254,25 @@ def configure(env): env.Append(CPPFLAGS=target_opts) env.Append(CPPFLAGS=common_opts) - if env['android_stl']: - env.Append(CPPPATH=[env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/gnu-libstdc++/4.9/include"]) - env.Append(CPPPATH=[env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/gnu-libstdc++/4.9/libs/" + arch_subpath + "/include"]) - env.Append(LIBPATH=[env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/gnu-libstdc++/4.9/libs/" + arch_subpath]) - env.Append(LIBS=["gnustl_static"]) - else: - env.Append(CXXFLAGS=['-fno-rtti', '-fno-exceptions', '-DNO_SAFE_CAST']) - ## Link flags - - env['LINKFLAGS'] = ['-shared', '--sysroot=' + lib_sysroot, '-Wl,--warn-shared-textrel'] + if ndk_version != None and LooseVersion(ndk_version) >= LooseVersion("15.0.4075724"): + if LooseVersion(ndk_version) >= LooseVersion("17.1.4828580"): + 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(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"]) + else: + env.Append(LINKFLAGS=['-shared', '--sysroot=' + lib_sysroot, '-Wl,--warn-shared-textrel']) + if mt_link: + env.Append(LINKFLAGS=['-Wl,--threads']) + 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()) - if mt_link: - env.Append(LINKFLAGS=['-Wl,--threads']) + env.Append(LINKFLAGS=target_opts) env.Append(LINKFLAGS=common_opts) diff --git a/platform/android/dir_access_jandroid.cpp b/platform/android/dir_access_jandroid.cpp index 3e40b59de9..ee5ae156b7 100644 --- a/platform/android/dir_access_jandroid.cpp +++ b/platform/android/dir_access_jandroid.cpp @@ -153,7 +153,6 @@ String DirAccessJAndroid::get_current_dir() { bool DirAccessJAndroid::file_exists(String p_file) { - JNIEnv *env = ThreadAndroid::get_env(); String sd; if (current_dir == "") sd = p_file; diff --git a/platform/android/export/export.cpp b/platform/android/export/export.cpp index 9e6377f4fe..5c8d9e078f 100644 --- a/platform/android/export/export.cpp +++ b/platform/android/export/export.cpp @@ -228,7 +228,7 @@ class EditorExportAndroid : public EditorExportPlatform { }; Vector<Device> devices; - bool devices_changed; + volatile bool devices_changed; Mutex *device_lock; Thread *device_thread; volatile bool quit_request; @@ -257,7 +257,6 @@ class EditorExportAndroid : public EditorExportPlatform { if (dpos == -1) continue; d = d.substr(0, dpos).strip_edges(); - //print_line("found device: "+d); ldevices.push_back(d); } @@ -345,8 +344,6 @@ class EditorExportAndroid : public EditorExportPlatform { } d.name = vendor + " " + device; - //print_line("name: "+d.name); - //print_line("description: "+d.description); } ndevices.push_back(d); @@ -528,11 +525,9 @@ class EditorExportAndroid : public EditorExportPlatform { bool exported = false; for (int i = 0; i < p_so.tags.size(); ++i) { // shared objects can be fat (compatible with multiple ABIs) - int start_pos = 0; int abi_index = abis.find(p_so.tags[i]); if (abi_index != -1) { exported = true; - start_pos = abi_index + 1; String abi = abis[abi_index]; String dst_path = "lib/" + abi + "/" + p_so.path.get_file(); Vector<uint8_t> array = FileAccess::get_file_as_array(p_so.path); @@ -570,7 +565,7 @@ class EditorExportAndroid : public EditorExportPlatform { // const int CHUNK_RESOURCEIDS = 0x00080180; const int CHUNK_STRINGS = 0x001C0001; // const int CHUNK_XML_END_NAMESPACE = 0x00100101; - // const int CHUNK_XML_END_TAG = 0x00100103; + const int CHUNK_XML_END_TAG = 0x00100103; // const int CHUNK_XML_START_NAMESPACE = 0x00100100; const int CHUNK_XML_START_TAG = 0x00100102; // const int CHUNK_XML_TEXT = 0x00100104; @@ -601,24 +596,28 @@ class EditorExportAndroid : public EditorExportPlatform { bool screen_support_large = p_preset->get("screen/support_large"); bool screen_support_xlarge = p_preset->get("screen/support_xlarge"); - String user_perms[MAX_USER_PERMISSIONS]; - - for (int i = 0; i < MAX_USER_PERMISSIONS; i++) { - - user_perms[i] = p_preset->get("user_permissions/" + itos(i)); - } - - Set<String> perms; + Vector<String> perms; const char **aperms = android_perms; while (*aperms) { bool enabled = p_preset->get("permissions/" + String(*aperms).to_lower()); if (enabled) - perms.insert(String(*aperms)); + perms.push_back("android.permission." + String(*aperms)); aperms++; } + for (int i = 0; i < MAX_USER_PERMISSIONS; i++) { + String user_perm = p_preset->get("user_permissions/" + itos(i)); + if (user_perm.strip_edges() != "" && user_perm.strip_edges() != "False") + perms.push_back(user_perm.strip_edges()); + } + + if (p_give_internet) { + if (perms.find("android.permission.INTERNET") == -1) + perms.push_back("android.permission.INTERNET"); + } + while (ofs < (uint32_t)p_manifest.size()) { uint32_t chunk = decode_uint32(&p_manifest[ofs]); @@ -663,25 +662,20 @@ class EditorExportAndroid : public EditorExportPlatform { ucstring.resize(len + 1); for (uint32_t j = 0; j < len; j++) { uint16_t c = decode_uint16(&p_manifest[string_at + 2 + 2 * j]); - ucstring[j] = c; + ucstring.write[j] = c; } string_end = MAX(string_at + 2 + 2 * len, string_end); - ucstring[len] = 0; - string_table[i] = ucstring.ptr(); + ucstring.write[len] = 0; + string_table.write[i] = ucstring.ptr(); } - - //print_line("String "+itos(i)+": "+string_table[i]); } for (uint32_t i = string_end; i < (ofs + size); i++) { stable_extra.push_back(p_manifest[i]); } - //printf("stable extra: %i\n",int(stable_extra.size())); string_table_ends = ofs + size; - //print_line("STABLE SIZE: "+itos(size)+" ACTUAL: "+itos(string_table_ends)); - } break; case CHUNK_XML_START_TAG: { @@ -712,79 +706,132 @@ class EditorExportAndroid : public EditorExportPlatform { //replace project information if (tname == "manifest" && attrname == "package") { - - print_line("FOUND package"); - string_table[attr_value] = get_package_name(package_name); + string_table.write[attr_value] = get_package_name(package_name); } - if (tname == "manifest" && /*nspace=="android" &&*/ attrname == "versionCode") { - - print_line("FOUND versionCode"); - encode_uint32(version_code, &p_manifest[iofs + 16]); + if (tname == "manifest" && attrname == "versionCode") { + encode_uint32(version_code, &p_manifest.write[iofs + 16]); } - if (tname == "manifest" && /*nspace=="android" &&*/ attrname == "versionName") { - - print_line("FOUND versionName"); + if (tname == "manifest" && attrname == "versionName") { if (attr_value == 0xFFFFFFFF) { WARN_PRINT("Version name in a resource, should be plaintext") } else - string_table[attr_value] = version_name; + string_table.write[attr_value] = version_name; } - if (tname == "activity" && /*nspace=="android" &&*/ attrname == "screenOrientation") { + if (tname == "activity" && attrname == "screenOrientation") { - encode_uint32(orientation == 0 ? 0 : 1, &p_manifest[iofs + 16]); + encode_uint32(orientation == 0 ? 0 : 1, &p_manifest.write[iofs + 16]); } - if (tname == "uses-feature" && /*nspace=="android" &&*/ attrname == "glEsVersion") { - print_line("version number: " + itos(decode_uint32(&p_manifest[iofs + 16]))); - } + if (tname == "supports-screens") { - if (tname == "uses-permission" && /*nspace=="android" &&*/ attrname == "name") { + if (attrname == "smallScreens") { - if (value.begins_with("godot.custom")) { + encode_uint32(screen_support_small ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]); - int which = value.get_slice(".", 2).to_int(); - if (which >= 0 && which < MAX_USER_PERMISSIONS && user_perms[which].strip_edges() != "") { + } else if (attrname == "normalScreens") { - string_table[attr_value] = user_perms[which].strip_edges(); - } + encode_uint32(screen_support_normal ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]); - } else if (value.begins_with("godot.")) { - String perm = value.get_slice(".", 1); + } else if (attrname == "largeScreens") { - if (perms.has(perm) || (p_give_internet && perm == "INTERNET")) { + encode_uint32(screen_support_large ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]); - print_line("PERM: " + perm); - string_table[attr_value] = "android.permission." + perm; - } + } else if (attrname == "xlargeScreens") { + + encode_uint32(screen_support_xlarge ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]); } } - if (tname == "supports-screens") { + iofs += 20; + } - if (attrname == "smallScreens") { + } break; + case CHUNK_XML_END_TAG: { + int iofs = ofs + 8; + uint32_t name = decode_uint32(&p_manifest[iofs + 12]); + String tname = string_table[name]; - encode_uint32(screen_support_small ? 0xFFFFFFFF : 0, &p_manifest[iofs + 16]); + if (tname == "manifest") { - } else if (attrname == "normalScreens") { + // save manifest ending so we can restore it + Vector<uint8_t> manifest_end; + uint32_t manifest_cur_size = p_manifest.size(); + uint32_t node_size = size; - encode_uint32(screen_support_normal ? 0xFFFFFFFF : 0, &p_manifest[iofs + 16]); + manifest_end.resize(p_manifest.size() - ofs); + memcpy(manifest_end.ptrw(), &p_manifest[ofs], manifest_end.size()); - } else if (attrname == "largeScreens") { + int32_t attr_name_string = string_table.find("name"); + ERR_EXPLAIN("Template does not have 'name' attribute"); + ERR_FAIL_COND(attr_name_string == -1); - encode_uint32(screen_support_large ? 0xFFFFFFFF : 0, &p_manifest[iofs + 16]); + int32_t ns_android_string = string_table.find("android"); + ERR_EXPLAIN("Template does not have 'android' namespace"); + ERR_FAIL_COND(ns_android_string == -1); - } else if (attrname == "xlargeScreens") { + int32_t attr_uses_permission_string = string_table.find("uses-permission"); + if (attr_uses_permission_string == -1) { + string_table.push_back("uses-permission"); + attr_uses_permission_string = string_table.size() - 1; + } - encode_uint32(screen_support_xlarge ? 0xFFFFFFFF : 0, &p_manifest[iofs + 16]); + for (int i = 0; i < perms.size(); ++i) { + print_line("Adding permission " + perms[i]); + + manifest_cur_size += 56 + 24; // node + end node + p_manifest.resize(manifest_cur_size); + + // Add permission to the string pool + int32_t perm_string = string_table.find(perms[i]); + if (perm_string == -1) { + string_table.push_back(perms[i]); + perm_string = string_table.size() - 1; } + + // start tag + encode_uint16(0x102, &p_manifest.write[ofs]); // type + encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize + encode_uint32(56, &p_manifest.write[ofs + 4]); // size + encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno + encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment + encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns + encode_uint32(attr_uses_permission_string, &p_manifest.write[ofs + 20]); // name + encode_uint16(20, &p_manifest.write[ofs + 24]); // attr_start + encode_uint16(20, &p_manifest.write[ofs + 26]); // attr_size + encode_uint16(1, &p_manifest.write[ofs + 28]); // num_attrs + encode_uint16(0, &p_manifest.write[ofs + 30]); // id_index + encode_uint16(0, &p_manifest.write[ofs + 32]); // class_index + encode_uint16(0, &p_manifest.write[ofs + 34]); // style_index + + // attribute + encode_uint32(ns_android_string, &p_manifest.write[ofs + 36]); // ns + encode_uint32(attr_name_string, &p_manifest.write[ofs + 40]); // 'name' + encode_uint32(perm_string, &p_manifest.write[ofs + 44]); // raw_value + encode_uint16(8, &p_manifest.write[ofs + 48]); // typedvalue_size + p_manifest.write[ofs + 50] = 0; // typedvalue_always0 + p_manifest.write[ofs + 51] = 0x03; // typedvalue_type (string) + encode_uint32(perm_string, &p_manifest.write[ofs + 52]); // typedvalue reference + + ofs += 56; + + // end tag + encode_uint16(0x103, &p_manifest.write[ofs]); // type + encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize + encode_uint32(24, &p_manifest.write[ofs + 4]); // size + encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno + encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment + encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns + encode_uint32(attr_uses_permission_string, &p_manifest.write[ofs + 20]); // name + + ofs += 24; } - iofs += 20; + // copy footer back in + memcpy(&p_manifest.write[ofs], manifest_end.ptr(), manifest_end.size()); } - } break; } @@ -798,25 +845,25 @@ class EditorExportAndroid : public EditorExportPlatform { for (uint32_t i = 0; i < string_table_begins; i++) { - ret[i] = p_manifest[i]; + ret.write[i] = p_manifest[i]; } ofs = 0; for (int i = 0; i < string_table.size(); i++) { - encode_uint32(ofs, &ret[string_table_begins + i * 4]); + encode_uint32(ofs, &ret.write[string_table_begins + i * 4]); ofs += string_table[i].length() * 2 + 2 + 2; - //print_line("ofs: "+itos(i)+": "+itos(ofs)); } + ret.resize(ret.size() + ofs); - uint8_t *chars = &ret[ret.size() - ofs]; + string_data_offset = ret.size() - ofs; + uint8_t *chars = &ret.write[string_data_offset]; for (int i = 0; i < string_table.size(); i++) { String s = string_table[i]; - //print_line("savint string :"+s); encode_uint16(s.length(), chars); chars += 2; - for (int j = 0; j < s.length(); j++) { //include zero? + for (int j = 0; j < s.length(); j++) { encode_uint16(s[j], chars); chars += 2; } @@ -828,6 +875,7 @@ class EditorExportAndroid : public EditorExportPlatform { ret.push_back(stable_extra[i]); } + //pad while (ret.size() % 4) ret.push_back(0); @@ -836,15 +884,15 @@ class EditorExportAndroid : public EditorExportPlatform { uint32_t extra = (p_manifest.size() - string_table_ends); ret.resize(new_stable_end + extra); for (uint32_t i = 0; i < extra; i++) - ret[new_stable_end + i] = p_manifest[string_table_ends + i]; + ret.write[new_stable_end + i] = p_manifest[string_table_ends + i]; while (ret.size() % 4) ret.push_back(0); - encode_uint32(ret.size(), &ret[4]); //update new file size + encode_uint32(ret.size(), &ret.write[4]); //update new file size - encode_uint32(new_stable_end - 8, &ret[12]); //update new string table size - - //print_line("file size: "+itos(ret.size())); + encode_uint32(new_stable_end - 8, &ret.write[12]); //update new string table size + encode_uint32(string_table.size(), &ret.write[16]); //update new number of strings + encode_uint32(string_data_offset - 8, &ret.write[28]); //update new string data offset p_manifest = ret; } @@ -866,9 +914,9 @@ class EditorExportAndroid : public EditorExportPlatform { Vector<uint8_t> str8; str8.resize(len + 1); for (uint32_t i = 0; i < len; i++) { - str8[i] = p_bytes[offset + i]; + str8.write[i] = p_bytes[offset + i]; } - str8[len] = 0; + str8.write[len] = 0; String str; str.parse_utf8((const char *)str8.ptr()); return str; @@ -887,7 +935,6 @@ class EditorExportAndroid : public EditorExportPlatform { void _fix_resources(const Ref<EditorExportPreset> &p_preset, Vector<uint8_t> &p_manifest) { const int UTF8_FLAG = 0x00000100; - print_line("*******************GORRRGLE***********************"); uint32_t string_block_len = decode_uint32(&p_manifest[16]); uint32_t string_count = decode_uint32(&p_manifest[20]); @@ -932,18 +979,18 @@ class EditorExportAndroid : public EditorExportPlatform { for (uint32_t i = 0; i < string_table_begins; i++) { - ret[i] = p_manifest[i]; + ret.write[i] = p_manifest[i]; } int ofs = 0; for (int i = 0; i < string_table.size(); i++) { - encode_uint32(ofs, &ret[string_table_begins + i * 4]); + encode_uint32(ofs, &ret.write[string_table_begins + i * 4]); ofs += string_table[i].length() * 2 + 2 + 2; } ret.resize(ret.size() + ofs); - uint8_t *chars = &ret[ret.size() - ofs]; + uint8_t *chars = &ret.write[ret.size() - ofs]; for (int i = 0; i < string_table.size(); i++) { String s = string_table[i]; @@ -962,19 +1009,19 @@ class EditorExportAndroid : public EditorExportPlatform { ret.push_back(0); //change flags to not use utf8 - encode_uint32(string_flags & ~0x100, &ret[28]); + encode_uint32(string_flags & ~0x100, &ret.write[28]); //change length - encode_uint32(ret.size() - 12, &ret[16]); + encode_uint32(ret.size() - 12, &ret.write[16]); //append the rest... int rest_from = 12 + string_block_len; int rest_to = ret.size(); int rest_len = (p_manifest.size() - rest_from); ret.resize(ret.size() + (p_manifest.size() - rest_from)); for (int i = 0; i < rest_len; i++) { - ret[rest_to + i] = p_manifest[rest_from + i]; + ret.write[rest_to + i] = p_manifest[rest_from + i]; } //finally update the size - encode_uint32(ret.size(), &ret[4]); + encode_uint32(ret.size(), &ret.write[4]); p_manifest = ret; //printf("end\n"); @@ -1017,16 +1064,15 @@ public: virtual void get_export_options(List<ExportOption> *r_options) { - /*r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "graphics/api", PROPERTY_HINT_ENUM, "OpenGL ES 2.0,OpenGL ES 3.0"), 1));*/ r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "graphics/32_bits_framebuffer"), true)); r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "one_click_deploy/clear_previous_install"), true)); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_package/debug", PROPERTY_HINT_GLOBAL_FILE, "apk"), "")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_package/release", PROPERTY_HINT_GLOBAL_FILE, "apk"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_package/debug", PROPERTY_HINT_GLOBAL_FILE, "*.apk"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_package/release", PROPERTY_HINT_GLOBAL_FILE, "*.apk"), "")); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "command_line/extra_args"), "")); r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "version/code", PROPERTY_HINT_RANGE, "1,4096,1,or_greater"), 1)); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "version/name"), "1.0")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/unique_name"), "org.godotengine.$genname")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/name"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/unique_name", PROPERTY_HINT_PLACEHOLDER_TEXT, "com.example.$genname"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/name", PROPERTY_HINT_PLACEHOLDER_TEXT, "Game Name"), "")); r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "package/signed"), true)); r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/immersive_mode"), true)); r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "screen/orientation", PROPERTY_HINT_ENUM, "Landscape,Portrait"), 0)); @@ -1036,10 +1082,10 @@ public: r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_xlarge"), true)); for (int i = 0; i < sizeof(launcher_icons) / sizeof(launcher_icons[0]); ++i) { - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, launcher_icons[i].option_id, PROPERTY_HINT_FILE, "png"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, launcher_icons[i].option_id, PROPERTY_HINT_FILE, "*.png"), "")); } - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release", PROPERTY_HINT_GLOBAL_FILE, "keystore"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release", PROPERTY_HINT_GLOBAL_FILE, "*.keystore"), "")); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release_user"), "")); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release_password"), "")); r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "apk_expansion/enable"), false)); @@ -1064,8 +1110,6 @@ public: r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "user_permissions/" + itos(i)), false)); } - - //r_options->push_back( PropertyInfo( Variant::INT, "resources/pack_mode", PROPERTY_HINT_ENUM,"Copy,Single Exec.,Pack (.pck),Bundles (Optical)")); } virtual String get_name() const { @@ -1083,7 +1127,10 @@ public: virtual bool poll_devices() { bool dc = devices_changed; - devices_changed = false; + if (dc) { + // don't clear unless we're reporting true, to avoid race + devices_changed = false; + } return dc; } @@ -1165,8 +1212,8 @@ public: err = OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv); } - print_line("Installing into device (please wait..): " + devices[p_device].name); - ep.step("Installing to Device (please wait..)..", 2); + print_line("Installing to device (please wait...): " + devices[p_device].name); + ep.step("Installing to device (please wait...)", 2); args.clear(); args.push_back("-s"); @@ -1264,12 +1311,28 @@ public: virtual bool can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const { + String err; r_missing_templates = find_export_template("android_debug.apk") == String() || find_export_template("android_release.apk") == String(); + if (p_preset->get("custom_package/debug") != "") { + if (FileAccess::exists(p_preset->get("custom_package/debug"))) { + r_missing_templates = false; + } else { + err += "Custom debug package not found.\n"; + } + } + + if (p_preset->get("custom_package/release") != "") { + if (FileAccess::exists(p_preset->get("custom_package/release"))) { + r_missing_templates = false; + } else { + err += "Custom release package not found.\n"; + } + } + bool valid = !r_missing_templates; String adb = EditorSettings::get_singleton()->get("export/android/adb"); - String err; if (!FileAccess::exists(adb)) { @@ -1528,8 +1591,11 @@ public: String apkfname = "main." + itos(version_code) + "." + get_package_name(package_name) + ".obb"; String fullpath = p_path.get_base_dir().plus_file(apkfname); err = save_pack(p_preset, fullpath); + if (err != OK) { + unzClose(pkg); EditorNode::add_io_error("Could not write expansion package file: " + apkfname); + return OK; } @@ -1572,7 +1638,7 @@ public: //add comandline Vector<uint8_t> clf; clf.resize(4); - encode_uint32(cl.size(), &clf[0]); + encode_uint32(cl.size(), &clf.write[0]); for (int i = 0; i < cl.size(); i++) { print_line(itos(i) + " param: " + cl[i]); @@ -1582,8 +1648,8 @@ public: if (!length) continue; clf.resize(base + 4 + length); - encode_uint32(length, &clf[base]); - copymem(&clf[base + 4], txt.ptr(), length); + encode_uint32(length, &clf.write[base]); + copymem(&clf.write[base + 4], txt.ptr(), length); } zip_fileinfo zipfi = get_zip_fileinfo(); @@ -1775,6 +1841,9 @@ public: r_features->push_back("Android"); } + virtual void resolve_platform_feature_priorities(const Ref<EditorExportPreset> &p_preset, Set<String> &p_features) { + } + EditorExportAndroid() { Ref<Image> img = memnew(Image(_android_logo)); @@ -1786,9 +1855,9 @@ public: run_icon->create_from_image(img); device_lock = Mutex::create(); - device_thread = Thread::create(_device_poll_thread, this); devices_changed = true; quit_request = false; + device_thread = Thread::create(_device_poll_thread, this); } ~EditorExportAndroid() { @@ -1811,7 +1880,7 @@ void register_android_exporter() { EDITOR_DEF("export/android/jarsigner", ""); EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/jarsigner", PROPERTY_HINT_GLOBAL_FILE, exe_ext)); EDITOR_DEF("export/android/debug_keystore", ""); - EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/debug_keystore", PROPERTY_HINT_GLOBAL_FILE, "keystore")); + EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/debug_keystore", PROPERTY_HINT_GLOBAL_FILE, "*.keystore")); EDITOR_DEF("export/android/debug_keystore_user", "androiddebugkey"); EDITOR_DEF("export/android/debug_keystore_pass", "android"); EDITOR_DEF("export/android/force_system_user", false); diff --git a/platform/android/godot_android.cpp b/platform/android/godot_android.cpp index 0e5f4fb93a..061e05f5ee 100644 --- a/platform/android/godot_android.cpp +++ b/platform/android/godot_android.cpp @@ -928,7 +928,7 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_Godot_registerMethod(JNIEnv *e jmethodID mid = env->GetMethodID(cls, mname.ascii().get_data(), cs.ascii().get_data()); if (!mid) { - print_line("FAILED GETTING METHOD ID " + mname); + print_line("RegisterMethod: Failed getting method ID: " + mname); } s->add_method(mname, mid, types, get_jni_type(retval)); diff --git a/platform/android/java/res/drawable-hdpi/notify_panel_notification_icon_bg.png b/platform/android/java/res/drawable-hdpi/notify_panel_notification_icon_bg.png Binary files differindex 94bc406416..372b763ec5 100644 --- a/platform/android/java/res/drawable-hdpi/notify_panel_notification_icon_bg.png +++ b/platform/android/java/res/drawable-hdpi/notify_panel_notification_icon_bg.png diff --git a/platform/android/java/res/drawable-mdpi/notify_panel_notification_icon_bg.png b/platform/android/java/res/drawable-mdpi/notify_panel_notification_icon_bg.png Binary files differindex ef6fe4e836..c61c440636 100644 --- a/platform/android/java/res/drawable-mdpi/notify_panel_notification_icon_bg.png +++ b/platform/android/java/res/drawable-mdpi/notify_panel_notification_icon_bg.png diff --git a/platform/android/java/res/drawable/icon.png b/platform/android/java/res/drawable/icon.png Binary files differindex 29c4a7b8fc..6ad9b43117 100644 --- a/platform/android/java/res/drawable/icon.png +++ b/platform/android/java/res/drawable/icon.png diff --git a/platform/android/java/src/org/godotengine/godot/Godot.java b/platform/android/java/src/org/godotengine/godot/Godot.java index 8a2d789dc5..ef798fc790 100644 --- a/platform/android/java/src/org/godotengine/godot/Godot.java +++ b/platform/android/java/src/org/godotengine/godot/Godot.java @@ -297,7 +297,7 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC runOnUiThread(new Runnable() { @Override public void run() { - view.setKeepScreenOn("True".equals(GodotLib.getGlobal("display/driver/keep_screen_on"))); + view.setKeepScreenOn("True".equals(GodotLib.getGlobal("display/window/energy_saving/keep_screen_on"))); } }); } diff --git a/platform/android/java/src/org/godotengine/godot/payments/ConsumeTask.java b/platform/android/java/src/org/godotengine/godot/payments/ConsumeTask.java index afe5f81b6d..5d94e77cd7 100644 --- a/platform/android/java/src/org/godotengine/godot/payments/ConsumeTask.java +++ b/platform/android/java/src/org/godotengine/godot/payments/ConsumeTask.java @@ -66,7 +66,6 @@ abstract public class ConsumeTask { } final String token = _token; new AsyncTask<String, String, String>() { - @Override protected String doInBackground(String... params) { try { @@ -89,7 +88,6 @@ abstract public class ConsumeTask { error(param); } } - } .execute(); } diff --git a/platform/android/java/src/org/godotengine/godot/payments/HandlePurchaseTask.java b/platform/android/java/src/org/godotengine/godot/payments/HandlePurchaseTask.java index 766989f953..aaf18c74bf 100644 --- a/platform/android/java/src/org/godotengine/godot/payments/HandlePurchaseTask.java +++ b/platform/android/java/src/org/godotengine/godot/payments/HandlePurchaseTask.java @@ -58,17 +58,15 @@ abstract public class HandlePurchaseTask { public void handlePurchaseRequest(int resultCode, Intent data) { //Log.d("XXX", "Handling purchase response"); - //int responseCode = data.getIntExtra("RESPONSE_CODE", 0); - PaymentsCache pc = new PaymentsCache(context); - - String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA"); - //Log.d("XXX", "Purchase data:" + purchaseData); - String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE"); - //Log.d("XXX", "Purchase signature:" + dataSignature); - if (resultCode == Activity.RESULT_OK) { - try { + //int responseCode = data.getIntExtra("RESPONSE_CODE", 0); + PaymentsCache pc = new PaymentsCache(context); + + String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA"); + //Log.d("XXX", "Purchase data:" + purchaseData); + String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE"); + //Log.d("XXX", "Purchase signature:" + dataSignature); //Log.d("SARLANGA", purchaseData); JSONObject jo = new JSONObject(purchaseData); diff --git a/platform/android/java/src/org/godotengine/godot/payments/PaymentsManager.java b/platform/android/java/src/org/godotengine/godot/payments/PaymentsManager.java index b7bf2362cc..d4c7380424 100644 --- a/platform/android/java/src/org/godotengine/godot/payments/PaymentsManager.java +++ b/platform/android/java/src/org/godotengine/godot/payments/PaymentsManager.java @@ -113,7 +113,6 @@ public class PaymentsManager { public void requestPurchase(final String sku, String transactionId) { new PurchaseTask(mService, Godot.getInstance()) { - @Override protected void error(String message) { godotPaymentV3.callbackFail(message); @@ -128,7 +127,6 @@ public class PaymentsManager { protected void alreadyOwned() { godotPaymentV3.callbackAlreadyOwned(sku); } - } .purchase(sku, transactionId); } @@ -139,7 +137,6 @@ public class PaymentsManager { public void consumeUnconsumedPurchases() { new ReleaseAllConsumablesTask(mService, activity) { - @Override protected void success(String sku, String receipt, String signature, String token) { godotPaymentV3.callbackSuccessProductMassConsumed(receipt, signature, sku); @@ -208,14 +205,12 @@ public class PaymentsManager { public void processPurchaseResponse(int resultCode, Intent data) { new HandlePurchaseTask(activity) { - @Override protected void success(final String sku, final String signature, final String ticket) { godotPaymentV3.callbackSuccess(ticket, signature, sku); if (auto_consume) { new ConsumeTask(mService, activity) { - @Override protected void success(String ticket) { } @@ -245,12 +240,10 @@ public class PaymentsManager { public void validatePurchase(String purchaseToken, final String sku) { new ValidateTask(activity, godotPaymentV3) { - @Override protected void success() { new ConsumeTask(mService, activity) { - @Override protected void success(String ticket) { godotPaymentV3.callbackSuccess(ticket, null, sku); @@ -283,7 +276,6 @@ public class PaymentsManager { public void consume(final String sku) { new ConsumeTask(mService, activity) { - @Override protected void success(String ticket) { godotPaymentV3.callbackSuccessProductMassConsumed(ticket, "", sku); diff --git a/platform/android/java/src/org/godotengine/godot/payments/ReleaseAllConsumablesTask.java b/platform/android/java/src/org/godotengine/godot/payments/ReleaseAllConsumablesTask.java index e00e37f9d1..eccc6f671b 100644 --- a/platform/android/java/src/org/godotengine/godot/payments/ReleaseAllConsumablesTask.java +++ b/platform/android/java/src/org/godotengine/godot/payments/ReleaseAllConsumablesTask.java @@ -88,7 +88,6 @@ abstract public class ReleaseAllConsumablesTask { String signature = mySignatures.get(i); //Log.d("godot", "A punto de consumir un item con token:" + token + "\n" + receipt); new GenericConsumeTask(context, mService, sku, receipt, signature, token) { - @Override public void onSuccess(String sku, String receipt, String signature, String token) { ReleaseAllConsumablesTask.this.success(sku, receipt, signature, token); diff --git a/platform/android/java/src/org/godotengine/godot/payments/ValidateTask.java b/platform/android/java/src/org/godotengine/godot/payments/ValidateTask.java index 1eb9d001e0..0626e50bb1 100644 --- a/platform/android/java/src/org/godotengine/godot/payments/ValidateTask.java +++ b/platform/android/java/src/org/godotengine/godot/payments/ValidateTask.java @@ -63,7 +63,6 @@ abstract public class ValidateTask { public void validatePurchase(final String sku) { new AsyncTask<String, String, String>() { - private ProgressDialog dialog; @Override @@ -113,7 +112,6 @@ abstract public class ValidateTask { error(e.getMessage()); } } - } .execute(); } diff --git a/platform/android/java_class_wrapper.cpp b/platform/android/java_class_wrapper.cpp index 446a5911e5..022ccb7d89 100644 --- a/platform/android/java_class_wrapper.cpp +++ b/platform/android/java_class_wrapper.cpp @@ -554,7 +554,6 @@ bool JavaClassWrapper::_get_type_sig(JNIEnv *env, jobject obj, uint32_t &sig, St jstring name2 = (jstring)env->CallObjectMethod(obj, Class_getName); String str_type = env->GetStringUTFChars(name2, NULL); - print_line("name: " + str_type); env->DeleteLocalRef(name2); uint32_t t = 0; @@ -1191,9 +1190,6 @@ Ref<JavaClass> JavaClassWrapper::wrap(const String &p_class) { env->DeleteLocalRef(obj); env->DeleteLocalRef(param_types); env->DeleteLocalRef(return_type); - - //args[i] = _jobject_to_variant(env, obj); - //print_line("\targ"+itos(i)+": "+Variant::get_type_name(args[i].get_type())); }; env->DeleteLocalRef(methods); @@ -1210,7 +1206,6 @@ Ref<JavaClass> JavaClassWrapper::wrap(const String &p_class) { jstring name = (jstring)env->CallObjectMethod(obj, Field_getName); String str_field = env->GetStringUTFChars(name, NULL); env->DeleteLocalRef(name); - print_line("FIELD: " + str_field); int mods = env->CallIntMethod(obj, Field_getModifiers); if ((mods & 0x8) && (mods & 0x10) && (mods & 0x1)) { //static final public! diff --git a/platform/android/java_glue.cpp b/platform/android/java_glue.cpp index e6240ad9e9..8bb1c38345 100644 --- a/platform/android/java_glue.cpp +++ b/platform/android/java_glue.cpp @@ -880,7 +880,6 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_setup(JNIEnv *env, jo const char **cmdline = NULL; int cmdlen = 0; - bool use_apk_expansion = false; if (p_cmdline) { cmdlen = env->GetArrayLength(p_cmdline); if (cmdlen) { @@ -891,9 +890,6 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_setup(JNIEnv *env, jo jstring string = (jstring)env->GetObjectArrayElement(p_cmdline, i); const char *rawString = env->GetStringUTFChars(string, 0); - if (rawString && strcmp(rawString, "--main-pack") == 0) { - use_apk_expansion = true; - } cmdline[i] = rawString; } diff --git a/platform/android/logo.png b/platform/android/logo.png Binary files differindex fcf684c026..ba2a0e366a 100644 --- a/platform/android/logo.png +++ b/platform/android/logo.png diff --git a/platform/android/os_android.cpp b/platform/android/os_android.cpp index 9188f09f21..74c40bde72 100644 --- a/platform/android/os_android.cpp +++ b/platform/android/os_android.cpp @@ -62,12 +62,19 @@ public: int OS_Android::get_video_driver_count() const { - return 1; + return 2; } const char *OS_Android::get_video_driver_name(int p_driver) const { - return "GLES2"; + switch (p_driver) { + case VIDEO_DRIVER_GLES3: + return "GLES3"; + case VIDEO_DRIVER_GLES2: + return "GLES2"; + } + ERR_EXPLAIN("Invalid video driver index " + itos(p_driver)); + ERR_FAIL_V(NULL); } int OS_Android::get_audio_driver_count() const { @@ -124,28 +131,63 @@ void OS_Android::set_opengl_extensions(const char *p_gl_extensions) { gl_extensions = p_gl_extensions; } +int OS_Android::get_current_video_driver() const { + return video_driver_index; +} + Error OS_Android::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { bool use_gl3 = get_gl_version_code_func() >= 0x00030000; use_gl3 = use_gl3 && (GLOBAL_GET("rendering/quality/driver/driver_name") == "GLES3"); - use_gl2 = !use_gl3; - - if (gfx_init_func) - gfx_init_func(gfx_init_ud, use_gl2); + bool gl_initialization_error = false; + + while (true) { + if (use_gl3) { + if (RasterizerGLES3::is_viable() == OK) { + if (gfx_init_func) + gfx_init_func(gfx_init_ud, false); + RasterizerGLES3::register_config(); + RasterizerGLES3::make_current(); + break; + } else { + if (GLOBAL_GET("rendering/quality/driver/driver_fallback") == "Best") { + p_video_driver = VIDEO_DRIVER_GLES2; + use_gl3 = false; + continue; + } else { + gl_initialization_error = true; + break; + } + } + } else { + if (RasterizerGLES2::is_viable() == OK) { + if (gfx_init_func) + gfx_init_func(gfx_init_ud, true); + RasterizerGLES2::register_config(); + RasterizerGLES2::make_current(); + break; + } else { + gl_initialization_error = true; + break; + } + } + } - if (use_gl2) { - RasterizerGLES2::register_config(); - RasterizerGLES2::make_current(); - } else { - RasterizerGLES3::register_config(); - RasterizerGLES3::make_current(); + 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; } + 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(); // visual_server->cursor_set_visible(false, 0); @@ -331,8 +373,6 @@ void OS_Android::process_event(Ref<InputEvent> p_event) { void OS_Android::process_touch(int p_what, int p_pointer, const Vector<TouchPos> &p_points) { - //print_line("ev: "+itos(p_what)+" pnt: "+itos(p_pointer)+" pointc: "+itos(p_points.size())); - switch (p_what) { case 0: { //gesture begin @@ -351,8 +391,8 @@ void OS_Android::process_touch(int p_what, int p_pointer, const Vector<TouchPos> touch.resize(p_points.size()); for (int i = 0; i < p_points.size(); i++) { - touch[i].id = p_points[i].id; - touch[i].pos = p_points[i].pos; + touch.write[i].id = p_points[i].id; + touch.write[i].pos = p_points[i].pos; } //send touch @@ -393,7 +433,7 @@ void OS_Android::process_touch(int p_what, int p_pointer, const Vector<TouchPos> ev->set_position(p_points[idx].pos); ev->set_relative(p_points[idx].pos - touch[i].pos); input->parse_input_event(ev); - touch[i].pos = p_points[idx].pos; + touch.write[i].pos = p_points[idx].pos; } } break; diff --git a/platform/android/os_android.h b/platform/android/os_android.h index ac901d4832..c4220906a3 100644 --- a/platform/android/os_android.h +++ b/platform/android/os_android.h @@ -137,6 +137,7 @@ private: AlertFunc alert_func; //power_android *power_manager; + int video_driver_index; public: // functions used by main to initialize/deintialize the OS @@ -146,6 +147,8 @@ public: 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); diff --git a/platform/android/run_icon.png b/platform/android/run_icon.png Binary files differindex e53f8e9da5..b687c9ac31 100644 --- a/platform/android/run_icon.png +++ b/platform/android/run_icon.png diff --git a/platform/android/thread_jandroid.cpp b/platform/android/thread_jandroid.cpp index e85813605f..b13baf69c2 100644 --- a/platform/android/thread_jandroid.cpp +++ b/platform/android/thread_jandroid.cpp @@ -132,7 +132,7 @@ JNIEnv *ThreadAndroid::get_env() { } JNIEnv *env = NULL; - int status = java_vm->AttachCurrentThread(&env, NULL); + java_vm->AttachCurrentThread(&env, NULL); return env; } diff --git a/platform/haiku/audio_driver_media_kit.cpp b/platform/haiku/audio_driver_media_kit.cpp index 278a994c54..aeaf698015 100644 --- a/platform/haiku/audio_driver_media_kit.cpp +++ b/platform/haiku/audio_driver_media_kit.cpp @@ -43,7 +43,7 @@ Error AudioDriverMediaKit::init() { speaker_mode = SPEAKER_MODE_STEREO; channels = 2; - int latency = GLOBAL_DEF("audio/output_latency", 25); + int latency = GLOBAL_DEF_RST("audio/output_latency", 25); buffer_size = next_power_of_2(latency * mix_rate / 1000); samples_in = memnew_arr(int32_t, buffer_size * channels); @@ -100,7 +100,7 @@ int AudioDriverMediaKit::get_mix_rate() const { return mix_rate; } -AudioDriverSW::SpeakerMode AudioDriverMediaKit::get_speaker_mode() const { +AudioDriverMediaKit::SpeakerMode AudioDriverMediaKit::get_speaker_mode() const { return speaker_mode; } diff --git a/platform/haiku/audio_driver_media_kit.h b/platform/haiku/audio_driver_media_kit.h index a09403e7d6..02fefcf52a 100644 --- a/platform/haiku/audio_driver_media_kit.h +++ b/platform/haiku/audio_driver_media_kit.h @@ -35,9 +35,10 @@ #include "core/os/mutex.h" #include "core/os/thread.h" -#include <SoundPlayer.h> #include <kernel/image.h> // needed for image_id +#include <SoundPlayer.h> + class AudioDriverMediaKit : public AudioDriver { Mutex *mutex; diff --git a/platform/haiku/detect.py b/platform/haiku/detect.py index 2959023204..7ecdd2bb11 100644 --- a/platform/haiku/detect.py +++ b/platform/haiku/detect.py @@ -64,6 +64,87 @@ def configure(env): env["CC"] = "gcc-x86" env["CXX"] = "g++-x86" + ## Dependencies + + 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 not env['builtin_freetype']: + env.ParseConfig('pkg-config freetype2 --cflags --libs') + + if not env['builtin_libpng']: + env.ParseConfig('pkg-config libpng --cflags --libs') + + if not env['builtin_bullet']: + # We need at least version 2.88 + import subprocess + 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")) + sys.exit(255) + env.ParseConfig('pkg-config bullet --cflags --libs') + + if not env['builtin_enet']: + env.ParseConfig('pkg-config libenet --cflags --libs') + + if not env['builtin_squish'] and env['tools']: + env.ParseConfig('pkg-config libsquish --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_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_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 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_libwebsockets']: + env.ParseConfig('pkg-config libwebsockets --cflags --libs') + + 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']) + + if not env['builtin_miniupnpc']: + # No pkgconfig file so far, hardcode default paths. + env.Append(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') + ## Flags env.Append(CPPPATH=['#platform/haiku']) diff --git a/platform/haiku/haiku_application.h b/platform/haiku/haiku_application.h index f92969bbb1..a870037985 100644 --- a/platform/haiku/haiku_application.h +++ b/platform/haiku/haiku_application.h @@ -31,9 +31,10 @@ #ifndef HAIKU_APPLICATION_H #define HAIKU_APPLICATION_H -#include <Application.h> #include <kernel/image.h> // needed for image_id +#include <Application.h> + class HaikuApplication : public BApplication { public: HaikuApplication(); diff --git a/platform/haiku/haiku_direct_window.cpp b/platform/haiku/haiku_direct_window.cpp index b234a2ff91..7eeb226167 100644 --- a/platform/haiku/haiku_direct_window.cpp +++ b/platform/haiku/haiku_direct_window.cpp @@ -41,10 +41,14 @@ HaikuDirectWindow::HaikuDirectWindow(BRect p_frame) : last_buttons_state = 0; last_button_mask = 0; last_key_modifier_state = 0; + + view = NULL; + update_runner = NULL; + input = NULL; + main_loop = NULL; } HaikuDirectWindow::~HaikuDirectWindow() { - delete update_runner; } void HaikuDirectWindow::SetHaikuGLView(HaikuGLView *p_view) { @@ -53,7 +57,7 @@ void HaikuDirectWindow::SetHaikuGLView(HaikuGLView *p_view) { void HaikuDirectWindow::StartMessageRunner() { update_runner = new BMessageRunner(BMessenger(this), - new BMessage(REDRAW_MSG), 1000000 / 30 /* 30 fps */); + new BMessage(REDRAW_MSG), 1000000 / 60 /* 60 fps */); } void HaikuDirectWindow::StopMessageRunner() { @@ -69,6 +73,7 @@ void HaikuDirectWindow::SetMainLoop(MainLoop *p_main_loop) { } bool HaikuDirectWindow::QuitRequested() { + StopMessageRunner(); main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST); return false; } @@ -152,39 +157,36 @@ void HaikuDirectWindow::HandleMouseButton(BMessage *message) { } */ - Ref<InputEvent> mouse_event; - mouse_event.type = Ref<InputEvent>::MOUSE_BUTTON; - mouse_event.device = 0; + Ref<InputEventMouseButton> mouse_event; + mouse_event.instance(); - mouse_event.mouse_button.mod = GetKeyModifierState(modifiers); - mouse_event->get_button_mask() = GetMouseButtonState(buttons); - mouse_event->get_position().x = where.x; - mouse_event->get_position().y = where.y; - mouse_event.mouse_button.global_x = where.x; - mouse_event.mouse_button.global_y = where.y; + mouse_event->set_button_mask(GetMouseButtonState(buttons)); + mouse_event->set_position({ where.x, where.y }); + mouse_event->set_global_position({ where.x, where.y }); + GetKeyModifierState(mouse_event, modifiers); switch (button) { default: case B_PRIMARY_MOUSE_BUTTON: - mouse_event->get_button_index() = 1; + mouse_event->set_button_index(1); break; case B_SECONDARY_MOUSE_BUTTON: - mouse_event->get_button_index() = 2; + mouse_event->set_button_index(2); break; case B_TERTIARY_MOUSE_BUTTON: - mouse_event->get_button_index() = 3; + mouse_event->set_button_index(3); break; } - mouse_event->is_pressed() = (message->what == B_MOUSE_DOWN); + mouse_event->set_pressed(message->what == B_MOUSE_DOWN); if (message->what == B_MOUSE_DOWN && mouse_event->get_button_index() == 1) { int32 clicks = message->FindInt32("clicks"); if (clicks > 1) { - mouse_event.mouse_button.doubleclick = true; + mouse_event->set_doubleclick(true); } } @@ -208,22 +210,18 @@ void HaikuDirectWindow::HandleMouseMoved(BMessage *message) { Point2i rel = pos - last_mouse_position; - Ref<InputEvent> motion_event; - motion_event.type = Ref<InputEvent>::MOUSE_MOTION; - motion_event.device = 0; + Ref<InputEventMouseMotion> motion_event; + motion_event.instance(); + GetKeyModifierState(motion_event, modifiers); - motion_event.mouse_motion.mod = GetKeyModifierState(modifiers); - motion_event->get_button_mask() = GetMouseButtonState(buttons); - motion_event.mouse_motion.x = pos.x; - motion_event.mouse_motion.y = pos.y; + motion_event->set_button_mask(GetMouseButtonState(buttons)); + motion_event->set_position({ pos.x, pos.y }); input->set_mouse_position(pos); - motion_event.mouse_motion.global_x = pos.x; - motion_event.mouse_motion.global_y = pos.y; - motion_event.mouse_motion.speed_x = input->get_last_mouse_speed().x; - motion_event.mouse_motion.speed_y = input->get_last_mouse_speed().y; + motion_event->set_global_position({ pos.x, pos.y }); + motion_event->set_speed({ input->get_last_mouse_speed().x, + input->get_last_mouse_speed().y }); - motion_event->get_relative().x = rel.x; - motion_event->get_relative().y = rel.y; + motion_event->set_relative({ rel.x, rel.y }); last_mouse_position = pos; @@ -236,22 +234,21 @@ void HaikuDirectWindow::HandleMouseWheelChanged(BMessage *message) { return; } - Ref<InputEvent> mouse_event; - mouse_event.type = Ref<InputEvent>::MOUSE_BUTTON; - mouse_event.device = 0; + Ref<InputEventMouseButton> mouse_event; + mouse_event.instance(); + //GetKeyModifierState(mouse_event, modifiers); - mouse_event->get_button_index() = wheel_delta_y < 0 ? 4 : 5; - mouse_event.mouse_button.mod = GetKeyModifierState(last_key_modifier_state); - mouse_event->get_button_mask() = last_button_mask; - mouse_event->get_position().x = last_mouse_position.x; - mouse_event->get_position().y = last_mouse_position.y; - mouse_event.mouse_button.global_x = last_mouse_position.x; - mouse_event.mouse_button.global_y = last_mouse_position.y; + mouse_event->set_button_index(wheel_delta_y < 0 ? 4 : 5); + mouse_event->set_button_mask(last_button_mask); + mouse_event->set_position({ last_mouse_position.x, + last_mouse_position.y }); + mouse_event->set_global_position({ last_mouse_position.x, + last_mouse_position.y }); - mouse_event->is_pressed() = true; + mouse_event->set_pressed(true); input->parse_input_event(mouse_event); - mouse_event->is_pressed() = false; + mouse_event->set_pressed(false); input->parse_input_event(mouse_event); } @@ -272,24 +269,23 @@ void HaikuDirectWindow::HandleKeyboardEvent(BMessage *message) { return; } - Ref<InputEvent> event; - event.type = Ref<InputEvent>::KEY; - event.device = 0; - event.key.mod = GetKeyModifierState(modifiers); - event->is_pressed() = (message->what == B_KEY_DOWN); - event->get_scancode() = KeyMappingHaiku::get_keysym(raw_char, key); - event->is_echo() = message->HasInt32("be:key_repeat"); - event.key.unicode = 0; + Ref<InputEventKey> event; + event.instance(); + GetKeyModifierState(event, modifiers); + event->set_pressed(message->what == B_KEY_DOWN); + event->set_scancode(KeyMappingHaiku::get_keysym(raw_char, key)); + event->set_echo(message->HasInt32("be:key_repeat")); + event->set_unicode(0); const char *bytes = NULL; if (message->FindString("bytes", &bytes) == B_OK) { - event.key.unicode = BUnicodeChar::FromUTF8(&bytes); + event->set_unicode(BUnicodeChar::FromUTF8(&bytes)); } //make it consistent across platforms. if (event->get_scancode() == KEY_BACKTAB) { - event->get_scancode() = KEY_TAB; - event->get_shift() = true; + event->set_scancode(KEY_TAB); + event->set_shift(true); } input->parse_input_event(event); @@ -309,14 +305,14 @@ void HaikuDirectWindow::HandleKeyboardModifierEvent(BMessage *message) { int32 key = old_modifiers ^ modifiers; - Ref<InputEvent> event; - event.type = Ref<InputEvent>::KEY; - event.device = 0; - event.key.mod = GetKeyModifierState(modifiers); - event->is_pressed() = ((modifiers & key) != 0); - event->get_scancode() = KeyMappingHaiku::get_modifier_keysym(key); - event->is_echo() = false; - event.key.unicode = 0; + Ref<InputEventWithModifiers> event; + event.instance(); + GetKeyModifierState(event, modifiers); + + event->set_shift(key & B_SHIFT_KEY); + event->set_alt(key & B_OPTION_KEY); + event->set_control(key & B_CONTROL_KEY); + event->set_command(key & B_COMMAND_KEY); input->parse_input_event(event); } @@ -333,14 +329,13 @@ void HaikuDirectWindow::HandleWindowResized(BMessage *message) { current_video_mode->height = height; } -inline InputModifierState HaikuDirectWindow::GetKeyModifierState(uint32 p_state) { +inline void HaikuDirectWindow::GetKeyModifierState(Ref<InputEventWithModifiers> event, uint32 p_state) { last_key_modifier_state = p_state; - InputModifierState state; - state.shift = (p_state & B_SHIFT_KEY) != 0; - state.control = (p_state & B_CONTROL_KEY) != 0; - state.alt = (p_state & B_OPTION_KEY) != 0; - state.meta = (p_state & B_COMMAND_KEY) != 0; + event->set_shift(p_state & B_SHIFT_KEY); + event->set_control(p_state & B_CONTROL_KEY); + event->set_alt(p_state & B_OPTION_KEY); + event->set_metakey(p_state & B_COMMAND_KEY); return state; } diff --git a/platform/haiku/haiku_direct_window.h b/platform/haiku/haiku_direct_window.h index 55c2f5fccc..eee09191fa 100644 --- a/platform/haiku/haiku_direct_window.h +++ b/platform/haiku/haiku_direct_window.h @@ -31,9 +31,10 @@ #ifndef HAIKU_DIRECT_WINDOW_H #define HAIKU_DIRECT_WINDOW_H -#include <DirectWindow.h> #include <kernel/image.h> // needed for image_id +#include <DirectWindow.h> + #include "core/os/os.h" #include "main/input_default.h" @@ -63,7 +64,7 @@ private: void HandleWindowResized(BMessage *message); void HandleKeyboardEvent(BMessage *message); void HandleKeyboardModifierEvent(BMessage *message); - inline InputModifierState GetKeyModifierState(uint32 p_state); + inline void GetKeyModifierState(Ref<InputEventWithModifiers> event, uint32 p_state); inline int GetMouseButtonState(uint32 p_state); public: diff --git a/platform/haiku/haiku_gl_view.h b/platform/haiku/haiku_gl_view.h index 1a694dc13b..6869cb7de7 100644 --- a/platform/haiku/haiku_gl_view.h +++ b/platform/haiku/haiku_gl_view.h @@ -31,9 +31,10 @@ #ifndef HAIKU_GL_VIEW_H #define HAIKU_GL_VIEW_H -#include <GLView.h> #include <kernel/image.h> // needed for image_id +#include <GLView.h> + class HaikuGLView : public BGLView { public: HaikuGLView(BRect frame, uint32 type); diff --git a/platform/haiku/logo.png b/platform/haiku/logo.png Binary files differindex d5d98e4cc6..a2d8e242a6 100644 --- a/platform/haiku/logo.png +++ b/platform/haiku/logo.png diff --git a/platform/haiku/os_haiku.cpp b/platform/haiku/os_haiku.cpp index 97fab5ca0d..c80365f1f3 100644 --- a/platform/haiku/os_haiku.cpp +++ b/platform/haiku/os_haiku.cpp @@ -28,9 +28,10 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ +#include "drivers/gles3/rasterizer_gles3.h" + #include "os_haiku.h" -#include "drivers/gles3/rasterizer_gles3.h" #include "main/main.h" #include "servers/physics/physics_server_sw.h" #include "servers/visual/visual_server_raster.h" @@ -80,6 +81,10 @@ const char *OS_Haiku::get_video_driver_name(int p_driver) const { return "GLES3"; } +int OS_Haiku::get_current_video_driver() const { + return video_driver_index; +} + Error OS_Haiku::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { main_loop = NULL; current_video_mode = p_desired; @@ -107,13 +112,12 @@ Error OS_Haiku::initialize(const VideoMode &p_desired, int p_video_driver, int p context_gl->initialize(); context_gl->make_current(); context_gl->set_use_vsync(current_video_mode.use_vsync); - - /* Port to GLES 3 rasterizer */ - //rasterizer = memnew(RasterizerGLES2); + RasterizerGLES3::register_config(); + RasterizerGLES3::make_current(); #endif - visual_server = memnew(VisualServerRaster(rasterizer)); + visual_server = memnew(VisualServerRaster()); ERR_FAIL_COND_V(!visual_server, ERR_UNAVAILABLE); @@ -124,6 +128,8 @@ Error OS_Haiku::initialize(const VideoMode &p_desired, int p_video_driver, int p } */ + video_driver_index = p_video_driver; + input = memnew(InputDefault); window->SetInput(input); @@ -132,8 +138,6 @@ Error OS_Haiku::initialize(const VideoMode &p_desired, int p_video_driver, int p AudioDriverManager::initialize(p_audio_driver); - power_manager = memnew(PowerHaiku); - return OK; } @@ -146,7 +150,6 @@ void OS_Haiku::finalize() { visual_server->finish(); memdelete(visual_server); - memdelete(rasterizer); memdelete(input); @@ -330,7 +333,7 @@ String OS_Haiku::get_config_path() const { if (has_environment("XDG_CONFIG_HOME")) { return get_environment("XDG_CONFIG_HOME"); } else if (has_environment("HOME")) { - return get_environment("HOME").plus_file(".config"); + return get_environment("HOME").plus_file("config/settings"); } else { return "."; } @@ -341,7 +344,7 @@ String OS_Haiku::get_data_path() const { if (has_environment("XDG_DATA_HOME")) { return get_environment("XDG_DATA_HOME"); } else if (has_environment("HOME")) { - return get_environment("HOME").plus_file(".local/share"); + return get_environment("HOME").plus_file("config/data"); } else { return get_config_path(); } @@ -352,8 +355,23 @@ String OS_Haiku::get_cache_path() const { if (has_environment("XDG_CACHE_HOME")) { return get_environment("XDG_CACHE_HOME"); } else if (has_environment("HOME")) { - return get_environment("HOME").plus_file(".cache"); + return get_environment("HOME").plus_file("config/cache"); } else { return get_config_path(); } } + +OS::PowerState OS_Haiku::get_power_state() { + WARN_PRINT("Power management is not implemented on this platform, defaulting to POWERSTATE_UNKNOWN"); + return OS::POWERSTATE_UNKNOWN; +} + +int OS_Haiku::get_power_seconds_left() { + WARN_PRINT("Power management is not implemented on this platform, defaulting to -1"); + return -1; +} + +int OS_Haiku::get_power_percent_left() { + WARN_PRINT("Power management is not implemented on this platform, defaulting to -1"); + return -1; +} diff --git a/platform/haiku/os_haiku.h b/platform/haiku/os_haiku.h index 615ae682ef..e862eb44c3 100644 --- a/platform/haiku/os_haiku.h +++ b/platform/haiku/os_haiku.h @@ -37,9 +37,7 @@ #include "haiku_application.h" #include "haiku_direct_window.h" #include "main/input_default.h" -#include "power_haiku.h" #include "servers/audio_server.h" -#include "servers/visual/rasterizer.h" #include "servers/visual_server.h" class OS_Haiku : public OS_Unix { @@ -48,10 +46,9 @@ private: HaikuDirectWindow *window; MainLoop *main_loop; InputDefault *input; - Rasterizer *rasterizer; VisualServer *visual_server; VideoMode current_video_mode; - PowerHaiku *power_manager; + int video_driver_index; #ifdef MEDIA_KIT_ENABLED AudioDriverMediaKit driver_media_kit; @@ -66,6 +63,7 @@ private: protected: virtual int get_video_driver_count() const; virtual const char *get_video_driver_name(int p_driver) const; + virtual int get_current_video_driver() const; virtual Error initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver); virtual void finalize(); diff --git a/platform/haiku/platform_config.h b/platform/haiku/platform_config.h index bbd72dfeb6..72c8ee2535 100644 --- a/platform/haiku/platform_config.h +++ b/platform/haiku/platform_config.h @@ -34,3 +34,4 @@ #define _BSD_SOURCE 1 #define GLES3_INCLUDE_H "glad/glad.h" +#define GLES2_INCLUDE_H "glad/glad.h" diff --git a/platform/haiku/power_haiku.cpp b/platform/haiku/power_haiku.cpp deleted file mode 100644 index 2a26dd0f9c..0000000000 --- a/platform/haiku/power_haiku.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/*************************************************************************/ -/* power_haiku.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2018 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 "core/error_macros.h" - -#include "power_haiku.h" - -bool PowerHaiku::UpdatePowerInfo() { - - return false; -} - -OS::PowerState PowerHaiku::get_power_state() { - if (UpdatePowerInfo()) { - return power_state; - } else { - WARN_PRINT("Power management is not implemented on this platform, defaulting to POWERSTATE_UNKNOWN"); - return OS::POWERSTATE_UNKNOWN; - } -} - -int PowerX11::get_power_seconds_left() { - if (UpdatePowerInfo()) { - return nsecs_left; - } else { - WARN_PRINT("Power management is not implemented on this platform, defaulting to -1"); - return -1; - } -} - -int PowerX11::get_power_percent_left() { - if (UpdatePowerInfo()) { - return percent_left; - } else { - WARN_PRINT("Power management is not implemented on this platform, defaulting to -1"); - return -1; - } -} - -PowerHaiku::PowerHaiku() : - nsecs_left(-1), - percent_left(-1), - power_state(OS::POWERSTATE_UNKNOWN) { -} - -PowerHaiku::~PowerHaiku() { -} diff --git a/platform/haiku/power_haiku.h b/platform/haiku/power_haiku.h deleted file mode 100644 index 2fe85cd23d..0000000000 --- a/platform/haiku/power_haiku.h +++ /dev/null @@ -1,53 +0,0 @@ -/*************************************************************************/ -/* power_haiku.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2018 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 PLATFORM_HAIKU_POWER_HAIKU_H_ -#define PLATFORM_HAIKU_POWER_HAIKU_H_ - -#include <os/os.h> - -class PowerHaiku { -private: - int nsecs_left; - int percent_left; - OS::PowerState power_state; - - bool UpdatePowerInfo(); - -public: - PowerHaiku(); - virtual ~PowerHaiku(); - - OS::PowerState get_power_state(); - int get_power_seconds_left(); - int get_power_percent_left(); -}; - -#endif /* PLATFORM_HAIKU_POWER_HAIKU_H_ */ diff --git a/platform/iphone/app_delegate.mm b/platform/iphone/app_delegate.mm index dd5ce4ab10..cc4985eb0c 100644 --- a/platform/iphone/app_delegate.mm +++ b/platform/iphone/app_delegate.mm @@ -643,7 +643,7 @@ static int frame_count = 0; view_controller.view = glView; window.rootViewController = view_controller; - _set_keep_screen_on(bool(GLOBAL_DEF("display/window/keep_screen_on", true)) ? YES : NO); + _set_keep_screen_on(bool(GLOBAL_DEF("display/window/energy_saving/keep_screen_on", true)) ? YES : NO); glView.useCADisplayLink = bool(GLOBAL_DEF("display.iOS/use_cadisplaylink", true)) ? YES : NO; printf("cadisaplylink: %d", glView.useCADisplayLink); diff --git a/platform/iphone/detect.py b/platform/iphone/detect.py index 25674c2b47..b13a1e9643 100644 --- a/platform/iphone/detect.py +++ b/platform/iphone/detect.py @@ -47,8 +47,12 @@ def configure(env): if (env["target"].startswith("release")): env.Append(CPPFLAGS=['-DNDEBUG', '-DNS_BLOCK_ASSERTIONS=1']) - env.Append(CPPFLAGS=['-O2', '-ftree-vectorize', '-fomit-frame-pointer', '-ffast-math', '-funsafe-math-optimizations']) - env.Append(LINKFLAGS=['-O2']) + if (env["optimize"] == "speed"): #optimize for speed (default) + env.Append(CPPFLAGS=['-O2', '-ftree-vectorize', '-fomit-frame-pointer', '-ffast-math', '-funsafe-math-optimizations']) + env.Append(LINKFLAGS=['-O2']) + else: #optimize for size + env.Append(CPPFLAGS=['-Os', '-ftree-vectorize']) + env.Append(LINKFLAGS=['-Os']) if env["target"] == "release_debug": env.Append(CPPFLAGS=['-DDEBUG_ENABLED']) diff --git a/platform/iphone/export/export.cpp b/platform/iphone/export/export.cpp index 4c1e02baf7..008e213e5e 100644 --- a/platform/iphone/export/export.cpp +++ b/platform/iphone/export/export.cpp @@ -119,6 +119,9 @@ public: r_features->push_back("iOS"); } + virtual void resolve_platform_feature_priorities(const Ref<EditorExportPreset> &p_preset, Set<String> &p_features) { + } + EditorExportPlatformIOS(); ~EditorExportPlatformIOS(); }; @@ -169,39 +172,39 @@ static const LoadingScreenInfo loading_screen_infos[] = { void EditorExportPlatformIOS::get_export_options(List<ExportOption> *r_options) { - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_package/debug", PROPERTY_HINT_GLOBAL_FILE, "zip"), "")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_package/release", PROPERTY_HINT_GLOBAL_FILE, "zip"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_package/debug", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_package/release", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), "")); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/app_store_team_id"), "")); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/provisioning_profile_uuid_debug"), "")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/code_sign_identity_debug"), "iPhone Developer")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/code_sign_identity_debug", PROPERTY_HINT_PLACEHOLDER_TEXT, "iPhone Developer"), "")); r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "application/export_method_debug", PROPERTY_HINT_ENUM, "App Store,Development,Ad-Hoc,Enterprise"), 1)); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/provisioning_profile_uuid_release"), "")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/code_sign_identity_release"), "iPhone Distribution")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/code_sign_identity_release", PROPERTY_HINT_PLACEHOLDER_TEXT, "iPhone Distribution"), "")); r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "application/export_method_release", PROPERTY_HINT_ENUM, "App Store,Development,Ad-Hoc,Enterprise"), 0)); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/name"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/name", PROPERTY_HINT_PLACEHOLDER_TEXT, "Game Name"), "")); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/info"), "Made with Godot Engine")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/identifier"), "org.godotengine.iosgame")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/signature"), "????")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/identifier", PROPERTY_HINT_PLACEHOLDER_TEXT, "come.example.game"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/signature"), "")); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/short_version"), "1.0")); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/version"), "1.0")); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/copyright"), "")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "required_icons/iphone_120x120", PROPERTY_HINT_FILE, "png"), "")); // Home screen on iPhone/iPod Touch with retina display - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "required_icons/ipad_76x76", PROPERTY_HINT_FILE, "png"), "")); // Home screen on iPad - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "required_icons/app_store_1024x1024", PROPERTY_HINT_FILE, "png"), "")); // App Store + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "required_icons/iphone_120x120", PROPERTY_HINT_FILE, "*.png"), "")); // Home screen on iPhone/iPod Touch with retina display + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "required_icons/ipad_76x76", PROPERTY_HINT_FILE, "*.png"), "")); // Home screen on iPad + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "required_icons/app_store_1024x1024", PROPERTY_HINT_FILE, "*.png"), "")); // App Store - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "optional_icons/iphone_180x180", PROPERTY_HINT_FILE, "png"), "")); // Home screen on iPhone with retina HD display - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "optional_icons/ipad_152x152", PROPERTY_HINT_FILE, "png"), "")); // Home screen on iPad with retina display - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "optional_icons/ipad_167x167", PROPERTY_HINT_FILE, "png"), "")); // Home screen on iPad Pro - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "optional_icons/spotlight_40x40", PROPERTY_HINT_FILE, "png"), "")); // Spotlight - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "optional_icons/spotlight_80x80", PROPERTY_HINT_FILE, "png"), "")); // Spotlight on devices with retina display + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "optional_icons/iphone_180x180", PROPERTY_HINT_FILE, "*.png"), "")); // Home screen on iPhone with retina HD display + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "optional_icons/ipad_152x152", PROPERTY_HINT_FILE, "*.png"), "")); // Home screen on iPad with retina display + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "optional_icons/ipad_167x167", PROPERTY_HINT_FILE, "*.png"), "")); // Home screen on iPad Pro + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "optional_icons/spotlight_40x40", PROPERTY_HINT_FILE, "*.png"), "")); // Spotlight + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "optional_icons/spotlight_80x80", PROPERTY_HINT_FILE, "*.png"), "")); // Spotlight on devices with retina display for (int i = 0; i < sizeof(loading_screen_infos) / sizeof(loading_screen_infos[0]); ++i) { - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, loading_screen_infos[i].preset_key, PROPERTY_HINT_FILE, "png"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, loading_screen_infos[i].preset_key, PROPERTY_HINT_FILE, "*.png"), "")); } r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "texture_format/s3tc"), false)); @@ -276,7 +279,7 @@ void EditorExportPlatformIOS::_fix_config_file(const Ref<EditorExportPreset> &p_ CharString cs = strnew.utf8(); pfile.resize(cs.size() - 1); for (int i = 0; i < cs.size() - 1; i++) { - pfile[i] = cs[i]; + pfile.write[i] = cs[i]; } } @@ -489,7 +492,7 @@ private: ret.resize(sizeof(num) * 2); for (int i = 0; i < sizeof(num) * 2; ++i) { uint8_t four_bits = (num >> (sizeof(num) * 8 - (i + 1) * 4)) & 0xF; - ret[i] = _hex_char(four_bits); + ret.write[i] = _hex_char(four_bits); } return String::utf8(ret.ptr(), ret.size()); } @@ -587,7 +590,7 @@ void EditorExportPlatformIOS::_add_assets_to_project(Vector<uint8_t> &p_project_ CharString cs = str.utf8(); p_project_data.resize(cs.size() - 1); for (int i = 0; i < cs.size() - 1; i++) { - p_project_data[i] = cs[i]; + p_project_data.write[i] = cs[i]; } } @@ -736,7 +739,7 @@ Error EditorExportPlatformIOS::export_project(const Ref<EditorExportPreset> &p_p String library_to_use = "libgodot.iphone." + String(p_debug ? "debug" : "release") + ".fat.a"; - print_line("static library: " + library_to_use); + print_line("Static library: " + library_to_use); String pkg_name; if (p_preset->get("application/name") != "") pkg_name = p_preset->get("application/name"); // app_name @@ -781,7 +784,9 @@ Error EditorExportPlatformIOS::export_project(const Ref<EditorExportPreset> &p_p int ret = unzGoToFirstFile(src_pkg_zip); Vector<uint8_t> project_file_data; while (ret == UNZ_OK) { +#if defined(OSX_ENABLED) || defined(X11_ENABLED) bool is_execute = false; +#endif //get filename unz_file_info info; @@ -804,7 +809,6 @@ Error EditorExportPlatformIOS::export_project(const Ref<EditorExportPreset> &p_p file = file.replace_first("iphone/", ""); if (files_to_parse.has(file)) { - print_line(String("parse ") + file); _fix_config_file(p_preset, data, config_data, p_debug); } else if (file.begins_with("libgodot.iphone")) { if (file != library_to_use) { @@ -812,7 +816,9 @@ Error EditorExportPlatformIOS::export_project(const Ref<EditorExportPreset> &p_p continue; //ignore! } found_library = true; +#if defined(OSX_ENABLED) || defined(X11_ENABLED) is_execute = true; +#endif file = "godot_ios.a"; } if (file == project_file) { @@ -855,7 +861,7 @@ Error EditorExportPlatformIOS::export_project(const Ref<EditorExportPreset> &p_p f->close(); memdelete(f); -#ifdef OSX_ENABLED +#if defined(OSX_ENABLED) || defined(X11_ENABLED) if (is_execute) { // we need execute rights on this file chmod(file.utf8().get_data(), 0755); diff --git a/platform/iphone/game_center.mm b/platform/iphone/game_center.mm index 57ff79f7bc..e210bfb862 100644 --- a/platform/iphone/game_center.mm +++ b/platform/iphone/game_center.mm @@ -139,7 +139,6 @@ Error GameCenter::post_score(Variant p_score) { [GKScore reportScores:@[ reporter ] withCompletionHandler:^(NSError *error) { - Dictionary ret; ret["type"] = "post_score"; if (error == nil) { @@ -177,7 +176,6 @@ Error GameCenter::award_achievement(Variant p_params) { [GKAchievement reportAchievements:@[ achievement ] withCompletionHandler:^(NSError *error) { - Dictionary ret; ret["type"] = "award_achievement"; if (error == nil) { @@ -196,7 +194,6 @@ Error GameCenter::award_achievement(Variant p_params) { void GameCenter::request_achievement_descriptions() { [GKAchievementDescription loadAchievementDescriptionsWithCompletionHandler:^(NSArray *descriptions, NSError *error) { - Dictionary ret; ret["type"] = "achievement_descriptions"; if (error == nil) { @@ -252,7 +249,6 @@ void GameCenter::request_achievement_descriptions() { void GameCenter::request_achievements() { [GKAchievement loadAchievementsWithCompletionHandler:^(NSArray *achievements, NSError *error) { - Dictionary ret; ret["type"] = "achievements"; if (error == nil) { @@ -347,7 +343,6 @@ Error GameCenter::request_identity_verification_signature() { GKLocalPlayer *player = [GKLocalPlayer localPlayer]; [player generateIdentityVerificationSignatureWithCompletionHandler:^(NSURL *publicKeyUrl, NSData *signature, NSData *salt, uint64_t timestamp, NSError *error) { - Dictionary ret; ret["type"] = "identity_verification_signature"; if (error == nil) { diff --git a/platform/iphone/logo.png b/platform/iphone/logo.png Binary files differindex 8dd718524c..405b6f93ca 100644 --- a/platform/iphone/logo.png +++ b/platform/iphone/logo.png diff --git a/platform/iphone/os_iphone.cpp b/platform/iphone/os_iphone.cpp index f618c80a77..addef61ec7 100644 --- a/platform/iphone/os_iphone.cpp +++ b/platform/iphone/os_iphone.cpp @@ -64,11 +64,6 @@ OSIPhone *OSIPhone::get_singleton() { return (OSIPhone *)OS::get_singleton(); }; -uint8_t OSIPhone::get_orientations() const { - - return supported_orientations; -}; - extern int gl_view_base_fb; // from gl_view.mm void OSIPhone::set_data_dir(String p_dir) { @@ -98,14 +93,17 @@ void OSIPhone::initialize_core() { set_data_dir(data_dir); }; +int OSIPhone::get_current_video_driver() const { + return video_driver_index; +} + Error OSIPhone::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { - supported_orientations = 0; - supported_orientations |= ((GLOBAL_DEF("video_mode/allow_horizontal", true) ? 1 : 0) << LandscapeLeft); - supported_orientations |= ((GLOBAL_DEF("video_mode/allow_horizontal_flipped", false) ? 1 : 0) << LandscapeRight); - supported_orientations |= ((GLOBAL_DEF("video_mode/allow_vertical", false) ? 1 : 0) << PortraitDown); - supported_orientations |= ((GLOBAL_DEF("video_mode/allow_vertical_flipped", false) ? 1 : 0) << PortraitUp); + video_driver_index = VIDEO_DRIVER_GLES3; + if (RasterizerGLES3::is_viable() != OK) { + return ERR_UNAVAILABLE; + } RasterizerGLES3::register_config(); RasterizerGLES3::make_current(); diff --git a/platform/iphone/os_iphone.h b/platform/iphone/os_iphone.h index 7d73a6fe5c..db2912ad93 100644 --- a/platform/iphone/os_iphone.h +++ b/platform/iphone/os_iphone.h @@ -47,14 +47,6 @@ class OSIPhone : public OS_Unix { -public: - enum Orientations { - PortraitDown, - PortraitUp, - LandscapeLeft, - LandscapeRight, - }; - private: enum { MAX_MOUSE_COUNT = 8, @@ -64,8 +56,6 @@ private: static HashMap<String, void *> dynamic_symbol_lookup_table; friend void register_dynamic_symbol(char *name, void *address); - uint8_t supported_orientations; - VisualServer *visual_server; AudioDriverCoreAudio audio_driver; @@ -87,6 +77,8 @@ private: virtual int get_video_driver_count() const; virtual const char *get_video_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); @@ -122,6 +114,8 @@ private: int virtual_keyboard_height; + int video_driver_index; + public: bool iterate(); diff --git a/platform/iphone/view_controller.mm b/platform/iphone/view_controller.mm index cdaae0cb81..f75f0fd812 100644 --- a/platform/iphone/view_controller.mm +++ b/platform/iphone/view_controller.mm @@ -83,51 +83,36 @@ int add_cmdline(int p_argc, char **p_args) { printf("*********** did receive memory warning!\n"); }; -- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)p_orientation { - - if (/*OSIPhone::get_singleton() == NULL*/ TRUE) { - - printf("checking on info.plist\n"); - NSArray *arr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations"]; - switch (p_orientation) { - - case UIInterfaceOrientationLandscapeLeft: - return [arr indexOfObject:@"UIInterfaceOrientationLandscapeLeft"] != NSNotFound ? YES : NO; - - case UIInterfaceOrientationLandscapeRight: - return [arr indexOfObject:@"UIInterfaceOrientationLandscapeRight"] != NSNotFound ? YES : NO; - - case UIInterfaceOrientationPortrait: - return [arr indexOfObject:@"UIInterfaceOrientationPortrait"] != NSNotFound ? YES : NO; - - case UIInterfaceOrientationPortraitUpsideDown: - return [arr indexOfObject:@"UIInterfaceOrientationPortraitUpsideDown"] != NSNotFound ? YES : NO; - - default: - return NO; - } - }; - - uint8_t supported = OSIPhone::get_singleton()->get_orientations(); - switch (p_orientation) { - - case UIInterfaceOrientationLandscapeLeft: - return supported & (1 << OSIPhone::LandscapeLeft) ? YES : NO; - - case UIInterfaceOrientationLandscapeRight: - return supported & (1 << OSIPhone::LandscapeRight) ? YES : NO; - - case UIInterfaceOrientationPortrait: - return supported & (1 << OSIPhone::PortraitDown) ? YES : NO; - - case UIInterfaceOrientationPortraitUpsideDown: - return supported & (1 << OSIPhone::PortraitUp) ? YES : NO; - +- (BOOL)shouldAutorotate { + switch (OS::get_singleton()->get_screen_orientation()) { + case OS::SCREEN_SENSOR: + case OS::SCREEN_SENSOR_LANDSCAPE: + case OS::SCREEN_SENSOR_PORTRAIT: + return YES; default: return NO; } }; +- (UIInterfaceOrientationMask)supportedInterfaceOrientations { + switch (OS::get_singleton()->get_screen_orientation()) { + case OS::SCREEN_PORTRAIT: + return UIInterfaceOrientationMaskPortrait; + case OS::SCREEN_REVERSE_LANDSCAPE: + return UIInterfaceOrientationMaskLandscapeRight; + case OS::SCREEN_REVERSE_PORTRAIT: + return UIInterfaceOrientationMaskPortraitUpsideDown; + case OS::SCREEN_SENSOR_LANDSCAPE: + return UIInterfaceOrientationMaskLandscape; + case OS::SCREEN_SENSOR_PORTRAIT: + return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown; + case OS::SCREEN_SENSOR: + return UIInterfaceOrientationMaskAll; + case OS::SCREEN_LANDSCAPE: + return UIInterfaceOrientationMaskLandscapeLeft; + } +}; + - (BOOL)prefersStatusBarHidden { return YES; } diff --git a/platform/javascript/SCsub b/platform/javascript/SCsub index 98988d97fd..a93c98a89f 100644 --- a/platform/javascript/SCsub +++ b/platform/javascript/SCsub @@ -32,6 +32,6 @@ zip_files = env.InstallAs([ ], [ js_wrapped, wasm, - '#misc/dist/html/default.html' + '#misc/dist/html/full-size.html' ]) env.Zip('#bin/godot', zip_files, ZIPROOT=zip_dir, ZIPSUFFIX='${PROGSUFFIX}${ZIPSUFFIX}', ZIPCOMSTR='Archving $SOURCES as $TARGET') diff --git a/platform/javascript/detect.py b/platform/javascript/detect.py index fc909f6619..17b31f8d73 100644 --- a/platform/javascript/detect.py +++ b/platform/javascript/detect.py @@ -25,7 +25,6 @@ def get_opts(): def get_flags(): return [ ('tools', False), - ('module_theora_enabled', 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 diff --git a/platform/javascript/dom_keys.h b/platform/javascript/dom_keys.inc index 4edca63c6d..dc8d67d52b 100644 --- a/platform/javascript/dom_keys.h +++ b/platform/javascript/dom_keys.inc @@ -1,5 +1,5 @@ /*************************************************************************/ -/* dom_keys.h */ +/* dom_keys.inc */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,9 +28,6 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef DOM_KEYS_H -#define DOM_KEYS_H - #include "os/keyboard.h" // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode#Constants_for_keyCode_value @@ -295,8 +292,8 @@ int dom2godot_scancode(int dom_keycode) { //case DOM_VK_SELECT: return KEY_UNKNOWN; - case DOM_VK_PRINTSCREEN: // this is the usual printScreen key - case DOM_VK_PRINT: // maybe for alt+printScreen or physical printers? + case DOM_VK_PRINTSCREEN: + case DOM_VK_PRINT: return KEY_PRINT; //case DOM_VK_EXECUTE: return KEY_UNKNOWN; @@ -311,11 +308,11 @@ int dom2godot_scancode(int dom_keycode) { case DOM_VK_SLEEP: return KEY_STANDBY; - // these are numpad keys according to MDN + // Numpad keys case DOM_VK_MULTIPLY: return KEY_KP_MULTIPLY; case DOM_VK_ADD: return KEY_KP_ADD; case DOM_VK_SEPARATOR: - return KEY_KP_PERIOD; // good enough? + return KEY_KP_PERIOD; // Good enough? case DOM_VK_SUBTRACT: return KEY_KP_SUBTRACT; case DOM_VK_DECIMAL: return KEY_KP_PERIOD; case DOM_VK_DIVIDE: @@ -376,10 +373,8 @@ int dom2godot_scancode(int dom_keycode) { case DOM_VK_QUOTE: return KEY_APOSTROPHE; - // rest is OEM/unusual + // The rest is OEM/unusual. default: return KEY_UNKNOWN; }; } - -#endif diff --git a/platform/javascript/export/export.cpp b/platform/javascript/export/export.cpp index 9591850662..a7f0084562 100644 --- a/platform/javascript/export/export.cpp +++ b/platform/javascript/export/export.cpp @@ -74,6 +74,9 @@ public: r_features->push_back(get_os_name()); } + virtual void resolve_platform_feature_priorities(const Ref<EditorExportPreset> &p_preset, Set<String> &p_features) { + } + EditorExportPlatformJavaScript(); }; @@ -95,7 +98,7 @@ void EditorExportPlatformJavaScript::_fix_html(Vector<uint8_t> &p_html, const Re CharString cs = str_export.utf8(); p_html.resize(cs.length()); for (int i = 0; i < cs.length(); i++) { - p_html[i] = cs[i]; + p_html.write[i] = cs[i]; } } @@ -117,10 +120,10 @@ void EditorExportPlatformJavaScript::get_export_options(List<ExportOption> *r_op r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "texture_format/s3tc"), true)); r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "texture_format/etc"), false)); r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "texture_format/etc2"), true)); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/custom_html_shell", PROPERTY_HINT_FILE, "html"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/custom_html_shell", PROPERTY_HINT_FILE, "*.html"), "")); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/head_include", PROPERTY_HINT_MULTILINE_TEXT), "")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "zip"), "")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "zip"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), "")); } String EditorExportPlatformJavaScript::get_name() const { @@ -140,14 +143,35 @@ Ref<Texture> EditorExportPlatformJavaScript::get_logo() const { bool EditorExportPlatformJavaScript::can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const { - r_missing_templates = false; + bool valid = false; + String err; + + if (find_export_template(EXPORT_TEMPLATE_WEBASSEMBLY_RELEASE) != "") + valid = true; + else if (find_export_template(EXPORT_TEMPLATE_WEBASSEMBLY_DEBUG) != "") + valid = true; + + if (p_preset->get("custom_template/debug") != "") { + if (FileAccess::exists(p_preset->get("custom_template/debug"))) { + valid = true; + } else { + err += "Custom debug template not found.\n"; + } + } + + if (p_preset->get("custom_template/release") != "") { + if (FileAccess::exists(p_preset->get("custom_template/release"))) { + valid = true; + } else { + err += "Custom release template not found.\n"; + } + } - if (find_export_template(EXPORT_TEMPLATE_WEBASSEMBLY_RELEASE) == String()) - r_missing_templates = true; - else if (find_export_template(EXPORT_TEMPLATE_WEBASSEMBLY_DEBUG) == String()) - r_missing_templates = true; + if (!err.empty()) + r_error = err; - return !r_missing_templates; + r_missing_templates = !valid; + return valid; } String EditorExportPlatformJavaScript::get_binary_extension(const Ref<EditorExportPreset> &p_preset) const { diff --git a/platform/javascript/http_request.js b/platform/javascript/http_request.js index c420052e54..ee1c06c623 100644 --- a/platform/javascript/http_request.js +++ b/platform/javascript/http_request.js @@ -82,7 +82,7 @@ var GodotHTTPRequest = { godot_xhr_send_string: function(xhrId, strPtr) { if (!strPtr) { - Module.printErr("Failed to send string per XHR: null pointer"); + console.warn("Failed to send string per XHR: null pointer"); return; } GodotHTTPRequest.requests[xhrId].send(UTF8ToString(strPtr)); @@ -90,11 +90,11 @@ var GodotHTTPRequest = { godot_xhr_send_data: function(xhrId, ptr, len) { if (!ptr) { - Module.printErr("Failed to send data per XHR: null pointer"); + console.warn("Failed to send data per XHR: null pointer"); return; } if (len < 0) { - Module.printErr("Failed to send data per XHR: buffer length less than 0"); + console.warn("Failed to send data per XHR: buffer length less than 0"); return; } GodotHTTPRequest.requests[xhrId].send(HEAPU8.subarray(ptr, ptr + len)); diff --git a/platform/javascript/javascript_eval.cpp b/platform/javascript/javascript_eval.cpp index 2ef88345f6..07b4c192e6 100644 --- a/platform/javascript/javascript_eval.cpp +++ b/platform/javascript/javascript_eval.cpp @@ -69,7 +69,7 @@ Variant JavaScript::eval(const String &p_code, bool p_use_global_exec_context) { eval_ret = eval(UTF8ToString(CODE)); } } catch (e) { - Module.printErr(e); + console.warn(e); eval_ret = null; } @@ -97,7 +97,7 @@ Variant JavaScript::eval(const String &p_code, bool p_use_global_exec_context) { if (array_ptr!==0) { _free(array_ptr) } - Module.printErr(e); + console.warn(e); // fall through } break; diff --git a/platform/javascript/javascript_main.cpp b/platform/javascript/javascript_main.cpp index 68a2d72464..3829e8d406 100644 --- a/platform/javascript/javascript_main.cpp +++ b/platform/javascript/javascript_main.cpp @@ -28,17 +28,11 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "emscripten.h" #include "io/resource_loader.h" #include "main/main.h" #include "os_javascript.h" -OS_JavaScript *os = NULL; - -static void main_loop() { - - os->main_loop_iterate(); -} +#include <emscripten/emscripten.h> extern "C" EMSCRIPTEN_KEEPALIVE void main_after_fs_sync(char *p_idbfs_err) { @@ -46,18 +40,18 @@ extern "C" EMSCRIPTEN_KEEPALIVE void main_after_fs_sync(char *p_idbfs_err) { if (!idbfs_err.empty()) { print_line("IndexedDB not available: " + idbfs_err); } - os->set_idbfs_available(idbfs_err.empty()); - // Ease up compatibility + OS_JavaScript *os = OS_JavaScript::get_singleton(); + os->set_idb_available(idbfs_err.empty()); + // Ease up compatibility. ResourceLoader::set_abort_on_missing_resources(false); Main::start(); - os->main_loop_begin(); - emscripten_set_main_loop(main_loop, 0, false); + os->run_async(); } int main(int argc, char *argv[]) { - // sync from persistent state into memory and then - // run the 'main_after_fs_sync' function + // Sync from persistent state into memory and then + // run the 'main_after_fs_sync' function. /* clang-format off */ EM_ASM( FS.mkdir('/userfs'); @@ -68,9 +62,10 @@ int main(int argc, char *argv[]) { ); /* clang-format on */ - os = new OS_JavaScript(argv[0], NULL); - Error err = Main::setup(argv[0], argc - 1, &argv[1]); + new OS_JavaScript(argc, argv); + // TODO: Check error return value. + Main::setup(argv[0], argc - 1, &argv[1]); return 0; - // continued async in main_after_fs_sync() from syncfs() callback + // Continued async in main_after_fs_sync() from the syncfs() callback. } diff --git a/platform/javascript/logo.png b/platform/javascript/logo.png Binary files differindex ce911180ac..36832d93ba 100644 --- a/platform/javascript/logo.png +++ b/platform/javascript/logo.png diff --git a/platform/javascript/os_javascript.cpp b/platform/javascript/os_javascript.cpp index 6c6e4d2d1c..a7a26411b7 100644 --- a/platform/javascript/os_javascript.cpp +++ b/platform/javascript/os_javascript.cpp @@ -30,290 +30,188 @@ #include "os_javascript.h" -#include "core/engine.h" -#include "core/io/file_access_buffered_fa.h" -#include "dom_keys.h" -#include "drivers/gles2/rasterizer_gles2.h" -#include "drivers/gles3/rasterizer_gles3.h" -#include "drivers/unix/dir_access_unix.h" -#include "drivers/unix/file_access_unix.h" +#include "gles2/rasterizer_gles2.h" +#include "gles3/rasterizer_gles3.h" +#include "io/file_access_buffered_fa.h" #include "main/main.h" #include "servers/visual/visual_server_raster.h" +#include "unix/dir_access_unix.h" +#include "unix/file_access_unix.h" #include <emscripten.h> #include <stdlib.h> +#include "dom_keys.inc" + #define DOM_BUTTON_LEFT 0 #define DOM_BUTTON_MIDDLE 1 #define DOM_BUTTON_RIGHT 2 +#define DOM_BUTTON_XBUTTON1 3 +#define DOM_BUTTON_XBUTTON2 4 -template <typename T> -static void dom2godot_mod(T emscripten_event_ptr, Ref<InputEventWithModifiers> godot_event) { +// Window (canvas) - godot_event->set_shift(emscripten_event_ptr->shiftKey); - godot_event->set_alt(emscripten_event_ptr->altKey); - godot_event->set_control(emscripten_event_ptr->ctrlKey); - godot_event->set_metakey(emscripten_event_ptr->metaKey); -} - -int OS_JavaScript::get_video_driver_count() const { +static void focus_canvas() { - return VIDEO_DRIVER_MAX; + /* clang-format off */ + EM_ASM( + Module.canvas.focus(); + ); + /* clang-format on */ } -const char *OS_JavaScript::get_video_driver_name(int p_driver) const { +static bool is_canvas_focused() { - switch (p_driver) { - case VIDEO_DRIVER_GLES3: - return "GLES3"; - case VIDEO_DRIVER_GLES2: - return "GLES2"; - } - ERR_EXPLAIN("Invalid video driver index " + itos(p_driver)); - ERR_FAIL_V(NULL); + /* clang-format off */ + return EM_ASM_INT_V( + return document.activeElement == Module.canvas; + ); + /* clang-format on */ } -int OS_JavaScript::get_audio_driver_count() const { +static bool cursor_inside_canvas = true; - return 1; -} - -const char *OS_JavaScript::get_audio_driver_name(int p_driver) const { +EM_BOOL OS_JavaScript::fullscreen_change_callback(int p_event_type, const EmscriptenFullscreenChangeEvent *p_event, void *p_user_data) { - return "JavaScript"; + OS_JavaScript *os = get_singleton(); + // Empty ID is canvas. + String target_id = String::utf8(p_event->id); + if (target_id.empty() || target_id == "canvas") { + // This event property is the only reliable data on + // browser fullscreen state. + os->video_mode.fullscreen = p_event->isFullscreen; + if (os->video_mode.fullscreen) { + os->entering_fullscreen = false; + } else { + // Restoring maximized window now will cause issues, + // so delay until main_loop_iterate. + os->just_exited_fullscreen = true; + } + } + return false; } -void OS_JavaScript::initialize_core() { +void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) { - OS_Unix::initialize_core(); - FileAccess::make_default<FileAccessBufferedFA<FileAccessUnix> >(FileAccess::ACCESS_RESOURCES); + video_mode = p_video_mode; } -static EM_BOOL _browser_resize_callback(int event_type, const EmscriptenUiEvent *ui_event, void *user_data) { - - ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_RESIZE, false); +OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const { - OS_JavaScript *os = static_cast<OS_JavaScript *>(user_data); - // The order of the fullscreen change event and the window size change - // event varies, even within just one browser, so defer handling - os->request_canvas_size_adjustment(); - return false; + return video_mode; } -static EM_BOOL _fullscreen_change_callback(int event_type, const EmscriptenFullscreenChangeEvent *event, void *user_data) { +Size2 OS_JavaScript::get_screen_size(int p_screen) const { - ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_FULLSCREENCHANGE, false); + EmscriptenFullscreenChangeEvent ev; + EMSCRIPTEN_RESULT result = emscripten_get_fullscreen_status(&ev); + ERR_FAIL_COND_V(result != EMSCRIPTEN_RESULT_SUCCESS, Size2()); + return Size2(ev.screenWidth, ev.screenHeight); +} - OS_JavaScript *os = static_cast<OS_JavaScript *>(user_data); - String id = String::utf8(event->id); - // empty id is canvas - if (id.empty() || id == "canvas") { +void OS_JavaScript::set_window_size(const Size2 p_size) { - OS::VideoMode vm = os->get_video_mode(); - // this event property is the only reliable information on - // browser fullscreen state - vm.fullscreen = event->isFullscreen; - os->set_video_mode(vm); - os->request_canvas_size_adjustment(); + windowed_size = p_size; + if (video_mode.fullscreen) { + window_maximized = false; + set_window_fullscreen(false); + } else { + if (window_maximized) { + emscripten_exit_soft_fullscreen(); + window_maximized = false; + } + emscripten_set_canvas_size(p_size.x, p_size.y); } - return false; } -static InputDefault *_input; - -static bool is_canvas_focused() { +Size2 OS_JavaScript::get_window_size() const { - /* clang-format off */ - return EM_ASM_INT_V( - return document.activeElement == Module.canvas; - ); - /* clang-format on */ + int canvas[3]; + emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2); + return Size2(canvas[0], canvas[1]); } -static void focus_canvas() { +void OS_JavaScript::set_window_maximized(bool p_enabled) { - /* clang-format off */ - EM_ASM( - Module.canvas.focus(); - ); - /* clang-format on */ + if (video_mode.fullscreen) { + window_maximized = p_enabled; + set_window_fullscreen(false); + } else if (!p_enabled) { + emscripten_exit_soft_fullscreen(); + window_maximized = false; + } else if (!window_maximized) { + // Prevent calling emscripten_enter_soft_fullscreen mutltiple times, + // this would hide page elements permanently. + EmscriptenFullscreenStrategy strategy; + strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH; + strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF; + strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT; + strategy.canvasResizedCallback = NULL; + emscripten_enter_soft_fullscreen(NULL, &strategy); + window_maximized = p_enabled; + } } -static bool _cursor_inside_canvas = true; +bool OS_JavaScript::is_window_maximized() const { -static bool is_cursor_inside_canvas() { - - return _cursor_inside_canvas; + return window_maximized; } -static EM_BOOL _mousebutton_callback(int event_type, const EmscriptenMouseEvent *mouse_event, void *user_data) { - - ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_MOUSEDOWN && event_type != EMSCRIPTEN_EVENT_MOUSEUP, false); +void OS_JavaScript::set_window_fullscreen(bool p_enabled) { - Ref<InputEventMouseButton> ev; - ev.instance(); - ev->set_pressed(event_type == EMSCRIPTEN_EVENT_MOUSEDOWN); - ev->set_position(Point2(mouse_event->canvasX, mouse_event->canvasY)); - ev->set_global_position(ev->get_position()); - dom2godot_mod(mouse_event, ev); - - switch (mouse_event->button) { - case DOM_BUTTON_LEFT: ev->set_button_index(BUTTON_LEFT); break; - case DOM_BUTTON_MIDDLE: ev->set_button_index(BUTTON_MIDDLE); break; - case DOM_BUTTON_RIGHT: ev->set_button_index(BUTTON_RIGHT); break; - default: return false; + if (p_enabled == video_mode.fullscreen) { + return; } - int mask = _input->get_mouse_button_mask(); - int button_flag = 1 << (ev->get_button_index() - 1); - if (ev->is_pressed()) { - // Since the event is consumed, focus manually. The containing iframe, - // if used, may not have focus yet, so focus even if already focused. - focus_canvas(); - mask |= button_flag; - } else if (mask & button_flag) { - mask &= ~button_flag; + // Just request changes here, if successful, logic continues in + // fullscreen_change_callback. + if (p_enabled) { + if (window_maximized) { + // Soft fullsreen during real fullscreen can cause issues, so exit. + // This must be called before requesting full screen. + emscripten_exit_soft_fullscreen(); + } + EmscriptenFullscreenStrategy strategy; + strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH; + strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF; + strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT; + strategy.canvasResizedCallback = NULL; + EMSCRIPTEN_RESULT result = emscripten_request_fullscreen_strategy(NULL, false, &strategy); + ERR_EXPLAIN("Enabling fullscreen is only possible from an input callback for the HTML5 platform"); + ERR_FAIL_COND(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED); + ERR_FAIL_COND(result != EMSCRIPTEN_RESULT_SUCCESS); + // Not fullscreen yet, so prevent "windowed" canvas dimensions from + // being overwritten. + entering_fullscreen = true; } else { - // release event, but press was outside the canvas, so ignore - return false; + // No logic allowed here, since exiting w/ ESC key won't use this function. + ERR_FAIL_COND(emscripten_exit_fullscreen() != EMSCRIPTEN_RESULT_SUCCESS); } - ev->set_button_mask(mask); - - _input->parse_input_event(ev); - // Prevent multi-click text selection and wheel-click scrolling anchor. - // Context menu is prevented through contextmenu event. - return true; } -static EM_BOOL _mousemove_callback(int event_type, const EmscriptenMouseEvent *mouse_event, void *user_data) { - - ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_MOUSEMOVE, false); - OS_JavaScript *os = static_cast<OS_JavaScript *>(user_data); - int input_mask = _input->get_mouse_button_mask(); - Point2 pos = Point2(mouse_event->canvasX, mouse_event->canvasY); - // outside the canvas, only read mouse movement if dragging started inside - // the canvas; imitating desktop app behaviour - if (!is_cursor_inside_canvas() && !input_mask) - return false; - - Ref<InputEventMouseMotion> ev; - ev.instance(); - dom2godot_mod(mouse_event, ev); - ev->set_button_mask(input_mask); - - ev->set_position(pos); - ev->set_global_position(ev->get_position()); - - ev->set_relative(Vector2(mouse_event->movementX, mouse_event->movementY)); - _input->set_mouse_position(ev->get_position()); - ev->set_speed(_input->get_last_mouse_speed()); - - _input->parse_input_event(ev); - // don't suppress mouseover/leave events - return false; -} - -static EM_BOOL _wheel_callback(int event_type, const EmscriptenWheelEvent *wheel_event, void *user_data) { - - ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_WHEEL, false); - if (!is_canvas_focused()) { - if (is_cursor_inside_canvas()) { - focus_canvas(); - } else { - return false; - } - } - - Ref<InputEventMouseButton> ev; - ev.instance(); - ev->set_button_mask(_input->get_mouse_button_mask()); - ev->set_position(_input->get_mouse_position()); - ev->set_global_position(ev->get_position()); - - ev->set_shift(_input->is_key_pressed(KEY_SHIFT)); - ev->set_alt(_input->is_key_pressed(KEY_ALT)); - ev->set_control(_input->is_key_pressed(KEY_CONTROL)); - ev->set_metakey(_input->is_key_pressed(KEY_META)); - - if (wheel_event->deltaY < 0) - ev->set_button_index(BUTTON_WHEEL_UP); - else if (wheel_event->deltaY > 0) - ev->set_button_index(BUTTON_WHEEL_DOWN); - else if (wheel_event->deltaX > 0) - ev->set_button_index(BUTTON_WHEEL_LEFT); - else if (wheel_event->deltaX < 0) - ev->set_button_index(BUTTON_WHEEL_RIGHT); - else - return false; - - // Different browsers give wildly different delta values, and we can't - // interpret deltaMode, so use default value for wheel events' factor - - ev->set_pressed(true); - _input->parse_input_event(ev); - - ev->set_pressed(false); - _input->parse_input_event(ev); +bool OS_JavaScript::is_window_fullscreen() const { - return true; + return video_mode.fullscreen; } -static Point2 _prev_touches[32]; - -static EM_BOOL _touchpress_callback(int event_type, const EmscriptenTouchEvent *touch_event, void *user_data) { - - ERR_FAIL_COND_V( - event_type != EMSCRIPTEN_EVENT_TOUCHSTART && - event_type != EMSCRIPTEN_EVENT_TOUCHEND && - event_type != EMSCRIPTEN_EVENT_TOUCHCANCEL, - false); - - Ref<InputEventScreenTouch> ev; - ev.instance(); - int lowest_id_index = -1; - for (int i = 0; i < touch_event->numTouches; ++i) { - - const EmscriptenTouchPoint &touch = touch_event->touches[i]; - if (lowest_id_index == -1 || touch.identifier < touch_event->touches[lowest_id_index].identifier) - lowest_id_index = i; - if (!touch.isChanged) - continue; - ev->set_index(touch.identifier); - ev->set_position(Point2(touch.canvasX, touch.canvasY)); - _prev_touches[i] = ev->get_position(); - ev->set_pressed(event_type == EMSCRIPTEN_EVENT_TOUCHSTART); +void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const { - _input->parse_input_event(ev); - } - return true; + Size2 screen = get_screen_size(); + p_list->push_back(OS::VideoMode(screen.width, screen.height, true)); } -static EM_BOOL _touchmove_callback(int event_type, const EmscriptenTouchEvent *touch_event, void *user_data) { - - ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_TOUCHMOVE, false); +// Keys - Ref<InputEventScreenDrag> ev; - ev.instance(); - int lowest_id_index = -1; - for (int i = 0; i < touch_event->numTouches; ++i) { - - const EmscriptenTouchPoint &touch = touch_event->touches[i]; - if (lowest_id_index == -1 || touch.identifier < touch_event->touches[lowest_id_index].identifier) - lowest_id_index = i; - if (!touch.isChanged) - continue; - ev->set_index(touch.identifier); - ev->set_position(Point2(touch.canvasX, touch.canvasY)); - Point2 &prev = _prev_touches[i]; - ev->set_relative(ev->get_position() - prev); - prev = ev->get_position(); +template <typename T> +static void dom2godot_mod(T *emscripten_event_ptr, Ref<InputEventWithModifiers> godot_event) { - _input->parse_input_event(ev); - } - return true; + godot_event->set_shift(emscripten_event_ptr->shiftKey); + godot_event->set_alt(emscripten_event_ptr->altKey); + godot_event->set_control(emscripten_event_ptr->ctrlKey); + godot_event->set_metakey(emscripten_event_ptr->metaKey); } -static Ref<InputEventKey> _setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) { +static Ref<InputEventKey> setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) { Ref<InputEventKey> ev; ev.instance(); @@ -322,9 +220,9 @@ static Ref<InputEventKey> _setup_key_event(const EmscriptenKeyboardEvent *emscri ev->set_scancode(dom2godot_scancode(emscripten_event->keyCode)); String unicode = String::utf8(emscripten_event->key); - // check if empty or multi-character (e.g. `CapsLock`) + // Check if empty or multi-character (e.g. `CapsLock`). if (unicode.length() != 1) { - // might be empty as well, but better than nonsense + // Might be empty as well, but better than nonsense. unicode = String::utf8(emscripten_event->charValue); } if (unicode.length() == 1) { @@ -334,175 +232,115 @@ static Ref<InputEventKey> _setup_key_event(const EmscriptenKeyboardEvent *emscri return ev; } -static Ref<InputEventKey> deferred_key_event; - -static EM_BOOL _keydown_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) { +EM_BOOL OS_JavaScript::keydown_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) { - ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYDOWN, false); - - Ref<InputEventKey> ev = _setup_key_event(key_event); + OS_JavaScript *os = get_singleton(); + Ref<InputEventKey> ev = setup_key_event(p_event); ev->set_pressed(true); if (ev->get_unicode() == 0 && keycode_has_unicode(ev->get_scancode())) { - // defer to keypress event for legacy unicode retrieval - deferred_key_event = ev; - return false; // do not suppress keypress event + // Defer to keypress event for legacy unicode retrieval. + os->deferred_key_event = ev; + // Do not suppress keypress event. + return false; } - _input->parse_input_event(ev); + os->input->parse_input_event(ev); return true; } -static EM_BOOL _keypress_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) { +EM_BOOL OS_JavaScript::keypress_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) { - ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYPRESS, false); - - deferred_key_event->set_unicode(key_event->charCode); - _input->parse_input_event(deferred_key_event); + OS_JavaScript *os = get_singleton(); + os->deferred_key_event->set_unicode(p_event->charCode); + os->input->parse_input_event(os->deferred_key_event); return true; } -static EM_BOOL _keyup_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) { - - ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYUP, false); +EM_BOOL OS_JavaScript::keyup_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) { - Ref<InputEventKey> ev = _setup_key_event(key_event); + Ref<InputEventKey> ev = setup_key_event(p_event); ev->set_pressed(false); - _input->parse_input_event(ev); + get_singleton()->input->parse_input_event(ev); return ev->get_scancode() != KEY_UNKNOWN && ev->get_scancode() != 0; } -static EM_BOOL joy_callback_func(int p_type, const EmscriptenGamepadEvent *p_event, void *p_user) { - OS_JavaScript *os = (OS_JavaScript *)OS::get_singleton(); - if (os) { - return os->joy_connection_changed(p_type, p_event); - } - return false; +// Mouse + +Point2 OS_JavaScript::get_mouse_position() const { + + return input->get_mouse_position(); } -extern "C" EMSCRIPTEN_KEEPALIVE void send_notification(int notif) { +int OS_JavaScript::get_mouse_button_state() const { - if (notif == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || notif == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) { - _cursor_inside_canvas = notif == MainLoop::NOTIFICATION_WM_MOUSE_ENTER; - } - OS_JavaScript::get_singleton()->get_main_loop()->notification(notif); + return input->get_mouse_button_mask(); } -Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { +EM_BOOL OS_JavaScript::mouse_button_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) { - print_line("Init OS"); + OS_JavaScript *os = get_singleton(); - EmscriptenWebGLContextAttributes attributes; - emscripten_webgl_init_context_attributes(&attributes); - attributes.alpha = false; - attributes.antialias = false; - ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER); - switch (p_video_driver) { - case VIDEO_DRIVER_GLES3: - attributes.majorVersion = 2; - RasterizerGLES3::register_config(); - RasterizerGLES3::make_current(); - break; - case VIDEO_DRIVER_GLES2: - attributes.majorVersion = 1; - RasterizerGLES2::register_config(); - RasterizerGLES2::make_current(); - break; + Ref<InputEventMouseButton> ev; + ev.instance(); + ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_MOUSEDOWN); + ev->set_position(Point2(p_event->canvasX, p_event->canvasY)); + ev->set_global_position(ev->get_position()); + dom2godot_mod(p_event, ev); + switch (p_event->button) { + case DOM_BUTTON_LEFT: ev->set_button_index(BUTTON_LEFT); break; + case DOM_BUTTON_MIDDLE: ev->set_button_index(BUTTON_MIDDLE); break; + case DOM_BUTTON_RIGHT: ev->set_button_index(BUTTON_RIGHT); break; + case DOM_BUTTON_XBUTTON1: ev->set_button_index(BUTTON_XBUTTON1); break; + case DOM_BUTTON_XBUTTON2: ev->set_button_index(BUTTON_XBUTTON2); break; + default: return false; } - EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(NULL, &attributes); - ERR_EXPLAIN("WebGL " + itos(attributes.majorVersion) + ".0 not available"); - ERR_FAIL_COND_V(emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS, ERR_UNAVAILABLE); - video_mode = p_desired; - // can't fulfil fullscreen request due to browser security - video_mode.fullscreen = false; - /* clang-format off */ - if (EM_ASM_INT_V({ return Module.resizeCanvasOnStart })) { - /* clang-format on */ - set_window_size(Size2(video_mode.width, video_mode.height)); + int mask = os->input->get_mouse_button_mask(); + int button_flag = 1 << (ev->get_button_index() - 1); + if (ev->is_pressed()) { + // Since the event is consumed, focus manually. The containing iframe, + // if exists, may not have focus yet, so focus even if already focused. + focus_canvas(); + mask |= button_flag; + } else if (mask & button_flag) { + mask &= ~button_flag; } else { - set_window_size(get_window_size()); + // Received release event, but press was outside the canvas, so ignore. + return false; } + ev->set_button_mask(mask); - char locale_ptr[16]; - /* clang-format off */ - EM_ASM_ARGS({ - stringToUTF8(Module.locale, $0, 16); - }, locale_ptr); - /* clang-format on */ - setenv("LANG", locale_ptr, true); - - print_line("Init Audio"); - - AudioDriverManager::initialize(p_audio_driver); - - print_line("Init VS"); - - visual_server = memnew(VisualServerRaster()); - // visual_server->cursor_set_visible(false, 0); - - print_line("Init Physicsserver"); - - input = memnew(InputDefault); - _input = input; - -#define EM_CHECK(ev) \ - if (result != EMSCRIPTEN_RESULT_SUCCESS) \ - ERR_PRINTS("Error while setting " #ev " callback: Code " + itos(result)) -#define SET_EM_CALLBACK(target, ev, cb) \ - result = emscripten_set_##ev##_callback(target, this, true, &cb); \ - EM_CHECK(ev) -#define SET_EM_CALLBACK_NODATA(ev, cb) \ - result = emscripten_set_##ev##_callback(NULL, true, &cb); \ - EM_CHECK(ev) - - EMSCRIPTEN_RESULT result; - SET_EM_CALLBACK("#window", mousemove, _mousemove_callback) - SET_EM_CALLBACK("#canvas", mousedown, _mousebutton_callback) - SET_EM_CALLBACK("#window", mouseup, _mousebutton_callback) - SET_EM_CALLBACK("#window", wheel, _wheel_callback) - SET_EM_CALLBACK("#window", touchstart, _touchpress_callback) - SET_EM_CALLBACK("#window", touchmove, _touchmove_callback) - SET_EM_CALLBACK("#window", touchend, _touchpress_callback) - SET_EM_CALLBACK("#window", touchcancel, _touchpress_callback) - SET_EM_CALLBACK("#canvas", keydown, _keydown_callback) - SET_EM_CALLBACK("#canvas", keypress, _keypress_callback) - SET_EM_CALLBACK("#canvas", keyup, _keyup_callback) - SET_EM_CALLBACK(NULL, resize, _browser_resize_callback) - SET_EM_CALLBACK(NULL, fullscreenchange, _fullscreen_change_callback) - SET_EM_CALLBACK_NODATA(gamepadconnected, joy_callback_func) - SET_EM_CALLBACK_NODATA(gamepaddisconnected, joy_callback_func) - -#undef SET_EM_CALLBACK_NODATA -#undef SET_EM_CALLBACK -#undef EM_CHECK - - visual_server->init(); - - return OK; + os->input->parse_input_event(ev); + // Prevent multi-click text selection and wheel-click scrolling anchor. + // Context menu is prevented through contextmenu event. + return true; } -void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) { - - main_loop = p_main_loop; - input->set_main_loop(p_main_loop); -} +EM_BOOL OS_JavaScript::mousemove_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) { -void OS_JavaScript::delete_main_loop() { + OS_JavaScript *os = get_singleton(); - memdelete(main_loop); -} + int input_mask = os->input->get_mouse_button_mask(); + Point2 pos = Point2(p_event->canvasX, p_event->canvasY); + // For motion outside the canvas, only read mouse movement if dragging + // started inside the canvas; imitating desktop app behaviour. + if (!cursor_inside_canvas && !input_mask) + return false; -void OS_JavaScript::finalize() { + Ref<InputEventMouseMotion> ev; + ev.instance(); + dom2godot_mod(p_event, ev); + ev->set_button_mask(input_mask); - memdelete(input); -} + ev->set_position(pos); + ev->set_global_position(ev->get_position()); -void OS_JavaScript::alert(const String &p_alert, const String &p_title) { + ev->set_relative(Vector2(p_event->movementX, p_event->movementY)); + os->input->set_mouse_position(ev->get_position()); + ev->set_speed(os->input->get_last_mouse_speed()); - /* clang-format off */ - EM_ASM_({ - window.alert(UTF8ToString($0)); - }, p_alert.utf8().get_data()); - /* clang-format on */ + os->input->parse_input_event(ev); + // Don't suppress mouseover/-leave events. + return false; } static const char *godot2dom_cursor(OS::CursorShape p_shape) { @@ -530,7 +368,7 @@ static const char *godot2dom_cursor(OS::CursorShape p_shape) { } } -void OS_JavaScript::set_css_cursor(const char *p_cursor) { +static void set_css_cursor(const char *p_cursor) { /* clang-format off */ EM_ASM_({ @@ -539,7 +377,7 @@ void OS_JavaScript::set_css_cursor(const char *p_cursor) { /* clang-format on */ } -const char *OS_JavaScript::get_css_cursor() const { +static const char *get_css_cursor() { char cursor[16]; /* clang-format off */ @@ -550,9 +388,20 @@ const char *OS_JavaScript::get_css_cursor() const { return cursor; } +void OS_JavaScript::set_cursor_shape(CursorShape p_shape) { + + ERR_FAIL_INDEX(p_shape, CURSOR_MAX); + + cursor_shape = p_shape; + if (get_mouse_mode() != MOUSE_MODE_HIDDEN) + set_css_cursor(godot2dom_cursor(cursor_shape)); +} + +void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) { +} + void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) { - ERR_FAIL_INDEX(p_mode, MOUSE_MODE_CONFINED + 1); ERR_EXPLAIN("MOUSE_MODE_CONFINED is not supported for the HTML5 platform"); ERR_FAIL_COND(p_mode == MOUSE_MODE_CONFINED); if (p_mode == get_mouse_mode()) @@ -580,190 +429,344 @@ void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) { OS::MouseMode OS_JavaScript::get_mouse_mode() const { - if (!strcmp(get_css_cursor(), "none")) + if (String::utf8(get_css_cursor()) == "none") return MOUSE_MODE_HIDDEN; EmscriptenPointerlockChangeEvent ev; emscripten_get_pointerlock_status(&ev); - return ev.isActive && (strcmp(ev.id, "canvas") == 0) ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE; + return (ev.isActive && String::utf8(ev.id) == "canvas") ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE; } -Point2 OS_JavaScript::get_mouse_position() const { +// Wheel - return input->get_mouse_position(); -} +EM_BOOL OS_JavaScript::wheel_callback(int p_event_type, const EmscriptenWheelEvent *p_event, void *p_user_data) { -int OS_JavaScript::get_mouse_button_state() const { + ERR_FAIL_COND_V(p_event_type != EMSCRIPTEN_EVENT_WHEEL, false); + if (!is_canvas_focused()) { + if (cursor_inside_canvas) { + focus_canvas(); + } else { + return false; + } + } - return input->get_mouse_button_mask(); -} + InputDefault *input = get_singleton()->input; + Ref<InputEventMouseButton> ev; + ev.instance(); + ev->set_button_mask(input->get_mouse_button_mask()); + ev->set_position(input->get_mouse_position()); + ev->set_global_position(ev->get_position()); -void OS_JavaScript::set_window_title(const String &p_title) { + ev->set_shift(input->is_key_pressed(KEY_SHIFT)); + ev->set_alt(input->is_key_pressed(KEY_ALT)); + ev->set_control(input->is_key_pressed(KEY_CONTROL)); + ev->set_metakey(input->is_key_pressed(KEY_META)); - /* clang-format off */ - EM_ASM_({ - document.title = UTF8ToString($0); - }, p_title.utf8().get_data()); - /* clang-format on */ -} + if (p_event->deltaY < 0) + ev->set_button_index(BUTTON_WHEEL_UP); + else if (p_event->deltaY > 0) + ev->set_button_index(BUTTON_WHEEL_DOWN); + else if (p_event->deltaX > 0) + ev->set_button_index(BUTTON_WHEEL_LEFT); + else if (p_event->deltaX < 0) + ev->set_button_index(BUTTON_WHEEL_RIGHT); + else + return false; -//interesting byt not yet -//void set_clipboard(const String& p_text); -//String get_clipboard() const; + // Different browsers give wildly different delta values, and we can't + // interpret deltaMode, so use default value for wheel events' factor. -void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) { + ev->set_pressed(true); + input->parse_input_event(ev); - video_mode = p_video_mode; + ev->set_pressed(false); + input->parse_input_event(ev); + + return true; } -OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const { +// Touch - return video_mode; +bool OS_JavaScript::has_touchscreen_ui_hint() const { + + /* clang-format off */ + return EM_ASM_INT_V( + return 'ontouchstart' in window; + ); + /* clang-format on */ } -Size2 OS_JavaScript::get_screen_size(int p_screen) const { +EM_BOOL OS_JavaScript::touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) { - EmscriptenFullscreenChangeEvent ev; - EMSCRIPTEN_RESULT result = emscripten_get_fullscreen_status(&ev); - ERR_FAIL_COND_V(result != EMSCRIPTEN_RESULT_SUCCESS, Size2()); - return Size2(ev.screenWidth, ev.screenHeight); -} + OS_JavaScript *os = get_singleton(); + Ref<InputEventScreenTouch> ev; + ev.instance(); + int lowest_id_index = -1; + for (int i = 0; i < p_event->numTouches; ++i) { -void OS_JavaScript::set_window_size(const Size2 p_size) { + const EmscriptenTouchPoint &touch = p_event->touches[i]; + if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier) + lowest_id_index = i; + if (!touch.isChanged) + continue; + ev->set_index(touch.identifier); + ev->set_position(Point2(touch.canvasX, touch.canvasY)); + os->touches[i] = ev->get_position(); + ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_TOUCHSTART); - windowed_size = p_size; - if (is_window_fullscreen()) { - window_maximized = false; - set_window_fullscreen(false); - } else if (is_window_maximized()) { - set_window_maximized(false); - } else { - video_mode.width = p_size.x; - video_mode.height = p_size.y; - emscripten_set_canvas_size(p_size.x, p_size.y); + os->input->parse_input_event(ev); } + return true; } -Size2 OS_JavaScript::get_window_size() const { +EM_BOOL OS_JavaScript::touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) { - int canvas[3]; - emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2); - return Size2(canvas[0], canvas[1]); -} + OS_JavaScript *os = get_singleton(); + Ref<InputEventScreenDrag> ev; + ev.instance(); + int lowest_id_index = -1; + for (int i = 0; i < p_event->numTouches; ++i) { -void OS_JavaScript::set_window_maximized(bool p_enabled) { + const EmscriptenTouchPoint &touch = p_event->touches[i]; + if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier) + lowest_id_index = i; + if (!touch.isChanged) + continue; + ev->set_index(touch.identifier); + ev->set_position(Point2(touch.canvasX, touch.canvasY)); + Point2 &prev = os->touches[i]; + ev->set_relative(ev->get_position() - prev); + prev = ev->get_position(); - window_maximized = p_enabled; - if (is_window_fullscreen()) { - set_window_fullscreen(false); - return; + os->input->parse_input_event(ev); } - // Calling emscripten_enter_soft_fullscreen mutltiple times hides all - // page elements except the canvas permanently, so track state - if (p_enabled && !soft_fs_enabled) { + return true; +} - EmscriptenFullscreenStrategy strategy; - strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH; - strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF; - strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT; - strategy.canvasResizedCallback = NULL; - emscripten_enter_soft_fullscreen(NULL, &strategy); - soft_fs_enabled = true; - video_mode.width = get_window_size().width; - video_mode.height = get_window_size().height; - } else if (!p_enabled) { +// Gamepad - emscripten_exit_soft_fullscreen(); - soft_fs_enabled = false; - video_mode.width = windowed_size.width; - video_mode.height = windowed_size.height; - emscripten_set_canvas_size(video_mode.width, video_mode.height); +EM_BOOL OS_JavaScript::gamepad_change_callback(int p_event_type, const EmscriptenGamepadEvent *p_event, void *p_user_data) { + + InputDefault *input = get_singleton()->input; + if (p_event_type == EMSCRIPTEN_EVENT_GAMEPADCONNECTED) { + + String guid = ""; + if (String::utf8(p_event->mapping) == "standard") + guid = "Default HTML5 Gamepad"; + input->joy_connection_changed(p_event->index, true, String::utf8(p_event->id), guid); + } else { + input->joy_connection_changed(p_event->index, false, ""); } + return true; } -void OS_JavaScript::set_window_fullscreen(bool p_enable) { +void OS_JavaScript::process_joypads() { - if (p_enable == is_window_fullscreen()) { - return; - } + int joypad_count = emscripten_get_num_gamepads(); + for (int joypad = 0; joypad < joypad_count; joypad++) { + EmscriptenGamepadEvent state; + EMSCRIPTEN_RESULT query_result = emscripten_get_gamepad_status(joypad, &state); + // Chromium reserves gamepads slots, so NO_DATA is an expected result. + ERR_CONTINUE(query_result != EMSCRIPTEN_RESULT_SUCCESS && + query_result != EMSCRIPTEN_RESULT_NO_DATA); + if (query_result == EMSCRIPTEN_RESULT_SUCCESS && state.connected) { + + int button_count = MIN(state.numButtons, 18); + int axis_count = MIN(state.numAxes, 8); + for (int button = 0; button < button_count; button++) { + + float value = state.analogButton[button]; + if (String::utf8(state.mapping) == "standard" && (button == JOY_ANALOG_L2 || button == JOY_ANALOG_R2)) { + InputDefault::JoyAxis joy_axis; + joy_axis.min = 0; + joy_axis.value = value; + input->joy_axis(joypad, button, joy_axis); + } else { + input->joy_button(joypad, button, value); + } + } + for (int axis = 0; axis < axis_count; axis++) { - // only requesting changes here, if successful, canvas is resized in - // _browser_resize_callback or _fullscreen_change_callback - EMSCRIPTEN_RESULT result; - if (p_enable) { - if (window_maximized) { - // soft fs during real fs can cause issues - set_window_maximized(false); - window_maximized = true; - } - EmscriptenFullscreenStrategy strategy; - strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH; - strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF; - strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT; - strategy.canvasResizedCallback = NULL; - emscripten_request_fullscreen_strategy(NULL, false, &strategy); - } else { - result = emscripten_exit_fullscreen(); - if (result != EMSCRIPTEN_RESULT_SUCCESS) { - ERR_PRINTS("Failed to exit fullscreen: Code " + itos(result)); + InputDefault::JoyAxis joy_axis; + joy_axis.min = -1; + joy_axis.value = state.axis[axis]; + input->joy_axis(joypad, axis, joy_axis); + } } } } -bool OS_JavaScript::is_window_fullscreen() const { +bool OS_JavaScript::is_joy_known(int p_device) { - return video_mode.fullscreen; + return input->is_joy_mapped(p_device); } -void OS_JavaScript::request_canvas_size_adjustment() { +String OS_JavaScript::get_joy_guid(int p_device) const { - canvas_size_adjustment_requested = true; + return input->get_joy_guid_remapped(p_device); } -void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const { +// Video - Size2 screen = get_screen_size(); - p_list->push_back(OS::VideoMode(screen.width, screen.height, true)); +int OS_JavaScript::get_video_driver_count() const { + + return VIDEO_DRIVER_MAX; } -String OS_JavaScript::get_name() { +const char *OS_JavaScript::get_video_driver_name(int p_driver) const { - return "HTML5"; + switch (p_driver) { + case VIDEO_DRIVER_GLES3: + return "GLES3"; + case VIDEO_DRIVER_GLES2: + return "GLES2"; + } + ERR_EXPLAIN("Invalid video driver index " + itos(p_driver)); + ERR_FAIL_V(NULL); } -MainLoop *OS_JavaScript::get_main_loop() const { +// Audio - return main_loop; +int OS_JavaScript::get_audio_driver_count() const { + + return 1; } -bool OS_JavaScript::can_draw() const { +const char *OS_JavaScript::get_audio_driver_name(int p_driver) const { - return true; //always? + return "JavaScript"; } -void OS_JavaScript::set_cursor_shape(CursorShape p_shape) { +// Lifecycle +int OS_JavaScript::get_current_video_driver() const { + return video_driver_index; +} - ERR_FAIL_INDEX(p_shape, CURSOR_MAX); +void OS_JavaScript::initialize_core() { - cursor_shape = p_shape; - if (get_mouse_mode() != MOUSE_MODE_HIDDEN) - set_css_cursor(godot2dom_cursor(cursor_shape)); + OS_Unix::initialize_core(); + FileAccess::make_default<FileAccessBufferedFA<FileAccessUnix> >(FileAccess::ACCESS_RESOURCES); } -void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) { -} +Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { + + EmscriptenWebGLContextAttributes attributes; + emscripten_webgl_init_context_attributes(&attributes); + attributes.alpha = false; + attributes.antialias = false; + ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER); + + bool gles3 = true; + if (p_video_driver == VIDEO_DRIVER_GLES2) { + gles3 = false; + } + + bool gl_initialization_error = false; + + while (true) { + if (gles3) { + if (RasterizerGLES3::is_viable() == OK) { + attributes.majorVersion = 2; + RasterizerGLES3::register_config(); + RasterizerGLES3::make_current(); + break; + } else { + if (GLOBAL_GET("rendering/quality/driver/driver_fallback") == "Best") { + p_video_driver = VIDEO_DRIVER_GLES2; + gles3 = false; + continue; + } else { + gl_initialization_error = true; + break; + } + } + } else { + if (RasterizerGLES2::is_viable() == OK) { + attributes.majorVersion = 1; + RasterizerGLES2::register_config(); + RasterizerGLES2::make_current(); + break; + } else { + gl_initialization_error = true; + break; + } + } + } + + EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(NULL, &attributes); + if (emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS) { + gl_initialization_error = true; + } + + if (gl_initialization_error) { + OS::get_singleton()->alert("Your browser does not support any of the supported WebGL versions.\n" + "Please update your browser version.", + "Unable to initialize Video driver"); + return ERR_UNAVAILABLE; + } + + video_driver_index = p_video_driver; + + video_mode = p_desired; + // Can't fulfil fullscreen request during start-up due to browser security. + video_mode.fullscreen = false; + /* clang-format off */ + if (EM_ASM_INT_V({ return Module.resizeCanvasOnStart })) { + /* clang-format on */ + set_window_size(Size2(video_mode.width, video_mode.height)); + } else { + set_window_size(get_window_size()); + } -void OS_JavaScript::main_loop_begin() { + char locale_ptr[16]; + /* clang-format off */ + EM_ASM_ARGS({ + stringToUTF8(Module.locale, $0, 16); + }, locale_ptr); + /* clang-format on */ + setenv("LANG", locale_ptr, true); - if (main_loop) - main_loop->init(); + AudioDriverManager::initialize(p_audio_driver); + VisualServer *visual_server = memnew(VisualServerRaster()); + input = memnew(InputDefault); + + EMSCRIPTEN_RESULT result; +#define EM_CHECK(ev) \ + if (result != EMSCRIPTEN_RESULT_SUCCESS) \ + ERR_PRINTS("Error while setting " #ev " callback: Code " + itos(result)) +#define SET_EM_CALLBACK(target, ev, cb) \ + result = emscripten_set_##ev##_callback(target, NULL, true, &cb); \ + EM_CHECK(ev) +#define SET_EM_CALLBACK_NOTARGET(ev, cb) \ + result = emscripten_set_##ev##_callback(NULL, 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 + // is used below. + SET_EM_CALLBACK("#window", mousemove, mousemove_callback) + SET_EM_CALLBACK("#canvas", mousedown, mouse_button_callback) + SET_EM_CALLBACK("#window", mouseup, mouse_button_callback) + SET_EM_CALLBACK("#window", wheel, wheel_callback) + SET_EM_CALLBACK("#window", touchstart, touch_press_callback) + SET_EM_CALLBACK("#window", touchmove, touchmove_callback) + SET_EM_CALLBACK("#window", touchend, touch_press_callback) + SET_EM_CALLBACK("#window", touchcancel, touch_press_callback) + SET_EM_CALLBACK("#canvas", keydown, keydown_callback) + SET_EM_CALLBACK("#canvas", keypress, keypress_callback) + SET_EM_CALLBACK("#canvas", keyup, keyup_callback) + SET_EM_CALLBACK(NULL, fullscreenchange, fullscreen_change_callback) + SET_EM_CALLBACK_NOTARGET(gamepadconnected, gamepad_change_callback) + SET_EM_CALLBACK_NOTARGET(gamepaddisconnected, gamepad_change_callback) +#undef SET_EM_CALLBACK_NODATA +#undef SET_EM_CALLBACK +#undef EM_CHECK /* clang-format off */ EM_ASM_ARGS({ const send_notification = cwrap('send_notification', null, ['number']); - const notifs = arguments; - (['mouseover', 'mouseleave', 'focus', 'blur']).forEach(function(event, i) { - Module.canvas.addEventListener(event, send_notification.bind(null, notifs[i])); + const notifications = arguments; + (['mouseover', 'mouseleave', 'focus', 'blur']).forEach(function(event, index) { + Module.canvas.addEventListener(event, send_notification.bind(null, notifications[index])); }); }, MainLoop::NOTIFICATION_WM_MOUSE_ENTER, @@ -772,161 +775,177 @@ void OS_JavaScript::main_loop_begin() { MainLoop::NOTIFICATION_WM_FOCUS_OUT ); /* clang-format on */ + + visual_server->init(); + + return OK; } -bool OS_JavaScript::main_loop_iterate() { +void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) { - if (!main_loop) - return false; + main_loop = p_main_loop; + input->set_main_loop(p_main_loop); +} - if (idbfs_available && time_to_save_sync >= 0) { - int64_t newtime = get_ticks_msec(); - int64_t elapsed = newtime - last_sync_time; - last_sync_time = newtime; +MainLoop *OS_JavaScript::get_main_loop() const { - time_to_save_sync -= elapsed; + return main_loop; +} - if (time_to_save_sync < 0) { - //time to sync, for real +void OS_JavaScript::run_async() { + + main_loop->init(); + emscripten_set_main_loop(main_loop_callback, -1, false); +} + +void OS_JavaScript::main_loop_callback() { + + get_singleton()->main_loop_iterate(); +} + +bool OS_JavaScript::main_loop_iterate() { + + if (is_userfs_persistent() && sync_wait_time >= 0) { + int64_t current_time = get_ticks_msec(); + int64_t elapsed_time = current_time - last_sync_check_time; + last_sync_check_time = current_time; + + sync_wait_time -= elapsed_time; + + if (sync_wait_time < 0) { /* clang-format off */ EM_ASM( FS.syncfs(function(err) { - if (err) { Module.printErr('Failed to save IDB file system: ' + err.message); } + if (err) { console.warn('Failed to save IDB file system: ' + err.message); } }); ); /* clang-format on */ } } + process_joypads(); - if (canvas_size_adjustment_requested) { - if (video_mode.fullscreen || window_maximized) { - video_mode.width = get_window_size().width; - video_mode.height = get_window_size().height; - } - if (!video_mode.fullscreen) { - set_window_maximized(window_maximized); + if (just_exited_fullscreen) { + if (window_maximized) { + EmscriptenFullscreenStrategy strategy; + strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH; + strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF; + strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT; + strategy.canvasResizedCallback = NULL; + emscripten_enter_soft_fullscreen(NULL, &strategy); + } else { + emscripten_set_canvas_size(windowed_size.width, windowed_size.height); } - canvas_size_adjustment_requested = false; + just_exited_fullscreen = false; + } + + int canvas[3]; + emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2); + video_mode.width = canvas[0]; + video_mode.height = canvas[1]; + if (!window_maximized && !video_mode.fullscreen && !just_exited_fullscreen && !entering_fullscreen) { + windowed_size.width = canvas[0]; + windowed_size.height = canvas[1]; } + return Main::iteration(); } -void OS_JavaScript::main_loop_end() { +void OS_JavaScript::delete_main_loop() { - if (main_loop) - main_loop->finish(); + memdelete(main_loop); } -void OS_JavaScript::process_accelerometer(const Vector3 &p_accelerometer) { +void OS_JavaScript::finalize() { - input->set_accelerometer(p_accelerometer); + memdelete(input); } -bool OS_JavaScript::has_touchscreen_ui_hint() const { +// Miscellaneous - /* clang-format off */ - return EM_ASM_INT_V( - return 'ontouchstart' in window; - ); - /* clang-format on */ +extern "C" EMSCRIPTEN_KEEPALIVE void send_notification(int p_notification) { + + if (p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || p_notification == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) { + cursor_inside_canvas = p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER; + } + OS_JavaScript::get_singleton()->get_main_loop()->notification(p_notification); } -void OS_JavaScript::main_loop_request_quit() { +bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) { - if (main_loop) - main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST); + if (p_feature == "HTML5" || p_feature == "web") + return true; + +#ifdef JAVASCRIPT_EVAL_ENABLED + if (p_feature == "JavaScript") + return true; +#endif + + EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context(); + // All extensions are already automatically enabled, this function allows + // checking WebGL extension support without inline JavaScript + if (p_feature == "s3tc") + return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_s3tc_srgb"); + if (p_feature == "etc") + return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc1"); + if (p_feature == "etc2") + return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc"); + + return false; } -Error OS_JavaScript::shell_open(String p_uri) { +void OS_JavaScript::alert(const String &p_alert, const String &p_title) { + /* clang-format off */ EM_ASM_({ - window.open(UTF8ToString($0), '_blank'); - }, p_uri.utf8().get_data()); + window.alert(UTF8ToString($0)); + }, p_alert.utf8().get_data()); /* clang-format on */ - return OK; } -String OS_JavaScript::get_resource_dir() const { +void OS_JavaScript::set_window_title(const String &p_title) { - return "/"; //javascript has it's own filesystem for resources inside the APK + /* clang-format off */ + EM_ASM_({ + document.title = UTF8ToString($0); + }, p_title.utf8().get_data()); + /* clang-format on */ } -String OS_JavaScript::get_user_data_dir() const { - - /* - if (get_user_data_dir_func) - return get_user_data_dir_func(); - */ - return "/userfs"; -}; - String OS_JavaScript::get_executable_path() const { return OS::get_executable_path(); } -void OS_JavaScript::_close_notification_funcs(const String &p_file, int p_flags) { +Error OS_JavaScript::shell_open(String p_uri) { - OS_JavaScript *os = static_cast<OS_JavaScript *>(get_singleton()); - if (os->idbfs_available && p_file.begins_with("/userfs") && p_flags & FileAccess::WRITE) { - os->last_sync_time = OS::get_singleton()->get_ticks_msec(); - os->time_to_save_sync = 5000; //five seconds since last save - } + // Open URI in a new tab, browser will deal with it by protocol. + /* clang-format off */ + EM_ASM_({ + window.open(UTF8ToString($0), '_blank'); + }, p_uri.utf8().get_data()); + /* clang-format on */ + return OK; } -void OS_JavaScript::process_joypads() { - - int joy_count = emscripten_get_num_gamepads(); - for (int i = 0; i < joy_count; i++) { - EmscriptenGamepadEvent state; - emscripten_get_gamepad_status(i, &state); - if (state.connected) { - - int num_buttons = MIN(state.numButtons, 18); - int num_axes = MIN(state.numAxes, 8); - for (int j = 0; j < num_buttons; j++) { - - float value = state.analogButton[j]; - if (String(state.mapping) == "standard" && (j == 6 || j == 7)) { - InputDefault::JoyAxis jx; - jx.min = 0; - jx.value = value; - input->joy_axis(i, j, jx); - } else { - input->joy_button(i, j, value); - } - } - for (int j = 0; j < num_axes; j++) { +String OS_JavaScript::get_name() { - InputDefault::JoyAxis jx; - jx.min = -1; - jx.value = state.axis[j]; - input->joy_axis(i, j, jx); - } - } - } + return "HTML5"; } -bool OS_JavaScript::joy_connection_changed(int p_type, const EmscriptenGamepadEvent *p_event) { - if (p_type == EMSCRIPTEN_EVENT_GAMEPADCONNECTED) { +bool OS_JavaScript::can_draw() const { - String guid = ""; - if (String(p_event->mapping) == "standard") - guid = "Default HTML5 Gamepad"; - input->joy_connection_changed(p_event->index, true, String(p_event->id), guid); - } else { - input->joy_connection_changed(p_event->index, false, ""); - } - return true; + return true; // Always? } -bool OS_JavaScript::is_joy_known(int p_device) { - return input->is_joy_mapped(p_device); -} +String OS_JavaScript::get_user_data_dir() const { -String OS_JavaScript::get_joy_guid(int p_device) const { - return input->get_joy_guid_remapped(p_device); + return "/userfs"; +}; + +String OS_JavaScript::get_resource_dir() const { + + return "/"; } OS::PowerState OS_JavaScript::get_power_state() { @@ -947,59 +966,53 @@ int OS_JavaScript::get_power_percent_left() { return -1; } -bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) { - - if (p_feature == "HTML5" || p_feature == "web") - return true; +void OS_JavaScript::file_access_close_callback(const String &p_file, int p_flags) { -#ifdef JAVASCRIPT_EVAL_ENABLED - if (p_feature == "JavaScript") - return true; -#endif + OS_JavaScript *os = get_singleton(); + if (os->is_userfs_persistent() && p_file.begins_with("/userfs") && p_flags & FileAccess::WRITE) { + os->last_sync_check_time = OS::get_singleton()->get_ticks_msec(); + // Wait five seconds in case more files are about to be closed. + os->sync_wait_time = 5000; + } +} - EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context(); - // all extensions are already automatically enabled, this function allows - // checking WebGL extension support without inline JavaScript - if (p_feature == "s3tc" && emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_s3tc_srgb")) - return true; - if (p_feature == "etc" && emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc1")) - return true; - if (p_feature == "etc2" && emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc")) - return true; +void OS_JavaScript::set_idb_available(bool p_idb_available) { - return false; + idb_available = p_idb_available; } -void OS_JavaScript::set_idbfs_available(bool p_idbfs_available) { +bool OS_JavaScript::is_userfs_persistent() const { - idbfs_available = p_idbfs_available; + return idb_available; } -bool OS_JavaScript::is_userfs_persistent() const { +OS_JavaScript *OS_JavaScript::get_singleton() { - return idbfs_available; + return static_cast<OS_JavaScript *>(OS::get_singleton()); } -OS_JavaScript::OS_JavaScript(const char *p_execpath, GetUserDataDirFunc p_get_user_data_dir_func) { +OS_JavaScript::OS_JavaScript(int p_argc, char *p_argv[]) { + + List<String> arguments; + for (int i = 1; i < p_argc; i++) { + arguments.push_back(String::utf8(p_argv[i])); + } + set_cmdline(p_argv[0], arguments); - set_cmdline(p_execpath, get_cmdline_args()); - main_loop = NULL; window_maximized = false; - soft_fs_enabled = false; - canvas_size_adjustment_requested = false; + entering_fullscreen = false; + just_exited_fullscreen = false; + + main_loop = NULL; - get_user_data_dir_func = p_get_user_data_dir_func; - FileAccessUnix::close_notification_func = _close_notification_funcs; + idb_available = false; + sync_wait_time = -1; - idbfs_available = false; - time_to_save_sync = -1; + AudioDriverManager::add_driver(&audio_driver_javascript); Vector<Logger *> loggers; loggers.push_back(memnew(StdLogger)); _set_logger(memnew(CompositeLogger(loggers))); - AudioDriverManager::add_driver(&audio_driver_javascript); -} - -OS_JavaScript::~OS_JavaScript() { + FileAccessUnix::close_notification_func = file_access_close_callback; } diff --git a/platform/javascript/os_javascript.h b/platform/javascript/os_javascript.h index 46eb1b3f13..f40fb8fc7e 100644 --- a/platform/javascript/os_javascript.h +++ b/platform/javascript/os_javascript.h @@ -32,51 +32,58 @@ #define OS_JAVASCRIPT_H #include "audio_driver_javascript.h" -#include "drivers/unix/os_unix.h" #include "main/input_default.h" -#include "os/input.h" -#include "os/main_loop.h" #include "servers/audio_server.h" #include "servers/visual/rasterizer.h" +#include "unix/os_unix.h" #include <emscripten/html5.h> -typedef String (*GetUserDataDirFunc)(); - class OS_JavaScript : public OS_Unix { - bool idbfs_available; - int64_t time_to_save_sync; - int64_t last_sync_time; - - VisualServer *visual_server; - AudioDriverJavaScript audio_driver_javascript; - - InputDefault *input; + VideoMode video_mode; Vector2 windowed_size; bool window_maximized; - bool soft_fs_enabled; - bool canvas_size_adjustment_requested; - VideoMode video_mode; + bool entering_fullscreen; + bool just_exited_fullscreen; + + InputDefault *input; + Ref<InputEventKey> deferred_key_event; CursorShape cursor_shape; + Point2 touches[32]; + MainLoop *main_loop; + AudioDriverJavaScript audio_driver_javascript; + + bool idb_available; + int64_t sync_wait_time; + int64_t last_sync_check_time; + + static EM_BOOL fullscreen_change_callback(int p_event_type, const EmscriptenFullscreenChangeEvent *p_event, void *p_user_data); + + static EM_BOOL keydown_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data); + static EM_BOOL keypress_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data); + static EM_BOOL keyup_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data); + + static EM_BOOL mousemove_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data); + static EM_BOOL mouse_button_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data); - GetUserDataDirFunc get_user_data_dir_func; + static EM_BOOL wheel_callback(int p_event_type, const EmscriptenWheelEvent *p_event, void *p_user_data); - static void _close_notification_funcs(const String &p_file, int p_flags); + static EM_BOOL touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data); + static EM_BOOL touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data); + static EM_BOOL gamepad_change_callback(int p_event_type, const EmscriptenGamepadEvent *p_event, void *p_user_data); void process_joypads(); - void set_css_cursor(const char *); - const char *get_css_cursor() const; + static void main_loop_callback(); -public: - // functions used by main to initialize/deintialize the OS - virtual int get_video_driver_count() const; - virtual const char *get_video_driver_name(int p_driver) const; + static void file_access_close_callback(const String &p_file, int p_flags); - virtual int get_audio_driver_count() const; - virtual const char *get_audio_driver_name(int p_driver) const; + int video_driver_index; + +protected: + 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); @@ -86,77 +93,64 @@ public: virtual void finalize(); - typedef int64_t ProcessID; - - //static OS* get_singleton(); - - virtual void alert(const String &p_alert, const String &p_title = "ALERT!"); - - virtual void set_mouse_mode(MouseMode p_mode); - virtual MouseMode get_mouse_mode() const; - virtual Point2 get_mouse_position() const; - virtual int get_mouse_button_state() const; - virtual void set_window_title(const String &p_title); + virtual bool _check_internal_feature_support(const String &p_feature); - //virtual void set_clipboard(const String& p_text); - //virtual String get_clipboard() const; +public: + // Override return type to make writing static callbacks less tedious. + static OS_JavaScript *get_singleton(); 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 Size2 get_screen_size(int p_screen = -1) const; - virtual void set_window_size(const Size2); virtual Size2 get_window_size() const; virtual void set_window_maximized(bool p_enabled); - virtual bool is_window_maximized() const { return window_maximized; } - virtual void set_window_fullscreen(bool p_enable); + virtual bool is_window_maximized() const; + virtual void set_window_fullscreen(bool p_enabled); virtual bool is_window_fullscreen() const; + virtual Size2 get_screen_size(int p_screen = -1) const; - void request_canvas_size_adjustment(); + virtual Point2 get_mouse_position() const; + virtual int get_mouse_button_state() const; + virtual void set_cursor_shape(CursorShape p_shape); + virtual void set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot); + virtual void set_mouse_mode(MouseMode p_mode); + virtual MouseMode get_mouse_mode() const; - virtual String get_name(); - virtual MainLoop *get_main_loop() const; + virtual bool has_touchscreen_ui_hint() const; - virtual bool can_draw() const; + virtual bool is_joy_known(int p_device); + virtual String get_joy_guid(int p_device) const; - virtual bool is_userfs_persistent() const; + virtual int get_video_driver_count() const; + virtual const char *get_video_driver_name(int p_driver) const; - virtual void set_cursor_shape(CursorShape p_shape); - virtual void set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot); + virtual int get_audio_driver_count() const; + virtual const char *get_audio_driver_name(int p_driver) const; - void main_loop_begin(); + virtual MainLoop *get_main_loop() const; + void run_async(); bool main_loop_iterate(); - void main_loop_request_quit(); - void main_loop_end(); - void main_loop_focusout(); - void main_loop_focusin(); - virtual bool has_touchscreen_ui_hint() const; - - virtual Error shell_open(String p_uri); - virtual String get_user_data_dir() const; + virtual void alert(const String &p_alert, const String &p_title = "ALERT!"); + virtual void set_window_title(const String &p_title); String get_executable_path() const; - virtual String get_resource_dir() const; - - void process_accelerometer(const Vector3 &p_accelerometer); - void push_input(const Ref<InputEvent> &p_ev); + virtual Error shell_open(String p_uri); + virtual String get_name(); + virtual bool can_draw() const; - virtual bool is_joy_known(int p_device); - virtual String get_joy_guid(int p_device) const; - bool joy_connection_changed(int p_type, const EmscriptenGamepadEvent *p_event); + virtual String get_resource_dir() const; + virtual String get_user_data_dir() const; virtual OS::PowerState get_power_state(); virtual int get_power_seconds_left(); virtual int get_power_percent_left(); - virtual bool _check_internal_feature_support(const String &p_feature); - - void set_idbfs_available(bool p_idbfs_available); + void set_idb_available(bool p_idb_available); + virtual bool is_userfs_persistent() const; - OS_JavaScript(const char *p_execpath, GetUserDataDirFunc p_get_user_data_dir_func); - ~OS_JavaScript(); + OS_JavaScript(int p_argc, char *p_argv[]); }; #endif diff --git a/platform/javascript/run_icon.png b/platform/javascript/run_icon.png Binary files differindex dedee6f479..574abb0150 100644 --- a/platform/javascript/run_icon.png +++ b/platform/javascript/run_icon.png diff --git a/platform/osx/SCsub b/platform/osx/SCsub index 4dfa46528a..5c973c30c2 100644 --- a/platform/osx/SCsub +++ b/platform/osx/SCsub @@ -3,14 +3,8 @@ import os Import('env') -def make_debug(target, source, env): - 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])) - else: - os.system('dsymutil {0} -o {0}.dSYM'.format(target[0])) - os.system('strip -u -r {0}'.format(target[0])) +from platform_methods import run_in_subprocess +import platform_osx_builders files = [ 'crash_handler_osx.mm', @@ -25,5 +19,5 @@ 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, make_debug) + env.AddPostAction(prog, run_in_subprocess(platform_osx_builders.make_debug_osx)) diff --git a/platform/osx/crash_handler_osx.mm b/platform/osx/crash_handler_osx.mm index 99ce25adfb..1664c5ce8e 100644 --- a/platform/osx/crash_handler_osx.mm +++ b/platform/osx/crash_handler_osx.mm @@ -78,6 +78,10 @@ static void handle_crash(int sig) { // Dump the backtrace to stderr with a message to the user fprintf(stderr, "%s: Program crashed with signal %d\n", __FUNCTION__, sig); + + if (OS::get_singleton()->get_main_loop()) + OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_CRASH); + fprintf(stderr, "Dumping the backtrace. %ls\n", msg.c_str()); char **strings = backtrace_symbols(bt_buffer, size); if (strings) { diff --git a/platform/osx/detect.py b/platform/osx/detect.py index 72b8aa99f8..8a0883eca3 100644 --- a/platform/osx/detect.py +++ b/platform/osx/detect.py @@ -39,14 +39,21 @@ def configure(env): ## Build type if (env["target"] == "release"): - env.Prepend(CCFLAGS=['-O3', '-ffast-math', '-fomit-frame-pointer', '-ftree-vectorize', '-msse2']) + if (env["optimize"] == "speed"): #optimize for speed (default) + env.Prepend(CCFLAGS=['-O3', '-ffast-math', '-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"): - env.Prepend(CCFLAGS=['-O2', '-DDEBUG_ENABLED']) + if (env["optimize"] == "speed"): #optimize for speed (default) + env.Prepend(CCFLAGS=['-O2', '-DDEBUG_ENABLED']) + else: #optimize for size + env.Prepend(CCFLAGS=['-Os', '-DDEBUG_ENABLED']) if (env["debug_symbols"] == "yes"): env.Prepend(CCFLAGS=['-g1']) if (env["debug_symbols"] == "full"): @@ -108,8 +115,8 @@ def configure(env): ## Flags env.Append(CPPPATH=['#platform/osx']) - env.Append(CPPFLAGS=['-DOSX_ENABLED', '-DUNIX_ENABLED', '-DGLES_ENABLED', '-DAPPLE_STYLE_KEYS', '-DCOREAUDIO_ENABLED']) - env.Append(LINKFLAGS=['-framework', 'Cocoa', '-framework', 'Carbon', '-framework', 'OpenGL', '-framework', 'AGL', '-framework', 'AudioUnit', '-framework', 'CoreAudio', '-lz', '-framework', 'IOKit', '-framework', 'ForceFeedback']) + env.Append(CPPFLAGS=['-DOSX_ENABLED', '-DUNIX_ENABLED', '-DGLES_ENABLED', '-DAPPLE_STYLE_KEYS', '-DCOREAUDIO_ENABLED', '-DCOREMIDI_ENABLED']) + env.Append(LINKFLAGS=['-framework', 'Cocoa', '-framework', 'Carbon', '-framework', 'OpenGL', '-framework', 'AGL', '-framework', 'AudioUnit', '-framework', 'CoreAudio', '-framework', 'CoreMIDI', '-lz', '-framework', 'IOKit', '-framework', 'ForceFeedback']) env.Append(LIBS=['pthread']) env.Append(CPPFLAGS=['-mmacosx-version-min=10.9']) diff --git a/platform/osx/export/export.cpp b/platform/osx/export/export.cpp index db265812fa..880705b507 100644 --- a/platform/osx/export/export.cpp +++ b/platform/osx/export/export.cpp @@ -86,6 +86,9 @@ public: r_features->push_back("OSX"); } + virtual void resolve_platform_feature_priorities(const Ref<EditorExportPreset> &p_preset, Set<String> &p_features) { + } + EditorExportPlatformOSX(); ~EditorExportPlatformOSX(); }; @@ -106,14 +109,14 @@ void EditorExportPlatformOSX::get_preset_features(const Ref<EditorExportPreset> void EditorExportPlatformOSX::get_export_options(List<ExportOption> *r_options) { - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_package/debug", PROPERTY_HINT_GLOBAL_FILE, "zip"), "")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_package/release", PROPERTY_HINT_GLOBAL_FILE, "zip"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_package/debug", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_package/release", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), "")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/name"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/name", PROPERTY_HINT_PLACEHOLDER_TEXT, "Game Name"), "")); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/info"), "Made with Godot Engine")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/icon", PROPERTY_HINT_FILE, "png"), "")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/identifier"), "org.godotengine.macgame")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/signature"), "godotmacgame")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/icon", PROPERTY_HINT_FILE, "*.png"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/identifier", PROPERTY_HINT_PLACEHOLDER_TEXT, "com.example.game"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/signature"), "")); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/short_version"), "1.0")); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/version"), "1.0")); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/copyright"), "")); @@ -137,10 +140,10 @@ void EditorExportPlatformOSX::_make_icon(const Ref<Image> &p_icon, Vector<uint8_ Vector<uint8_t> data; data.resize(8); - data[0] = 'i'; - data[1] = 'c'; - data[2] = 'n'; - data[3] = 's'; + data.write[0] = 'i'; + data.write[1] = 'c'; + data.write[2] = 'n'; + data.write[3] = 's'; const char *name[] = { "ic09", "ic08", "ic07", "icp6", "icp5", "icp4" }; int index = 0; @@ -160,19 +163,19 @@ void EditorExportPlatformOSX::_make_icon(const Ref<Image> &p_icon, Vector<uint8_ int ofs = data.size(); uint32_t len = f->get_len(); data.resize(data.size() + len + 8); - f->get_buffer(&data[ofs + 8], len); + f->get_buffer(&data.write[ofs + 8], len); memdelete(f); len += 8; len = BSWAP32(len); - copymem(&data[ofs], name[index], 4); - encode_uint32(len, &data[ofs + 4]); + copymem(&data.write[ofs], name[index], 4); + encode_uint32(len, &data.write[ofs + 4]); index++; size /= 2; } uint32_t total_len = data.size(); total_len = BSWAP32(total_len); - encode_uint32(total_len, &data[4]); + encode_uint32(total_len, &data.write[4]); p_data = data; } @@ -210,7 +213,7 @@ void EditorExportPlatformOSX::_fix_plist(const Ref<EditorExportPreset> &p_preset CharString cs = strnew.utf8(); plist.resize(cs.size() - 1); for (int i = 0; i < cs.size() - 1; i++) { - plist[i] = cs[i]; + plist.write[i] = cs[i]; } } @@ -377,7 +380,6 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p String file = fname; - print_line("READ: " + file); Vector<uint8_t> data; data.resize(info.uncompressed_size); @@ -391,7 +393,6 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p file = file.replace_first("osx_template.app/", ""); if (file == "Contents/Info.plist") { - print_line("parse plist"); _fix_plist(p_preset, data, pkg_name); } @@ -412,13 +413,12 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p iconpath = p_preset->get("application/icon"); else iconpath = ProjectSettings::get_singleton()->get("application/config/icon"); - print_line("icon? " + iconpath); + if (iconpath != "") { Ref<Image> icon; icon.instance(); icon->load(iconpath); if (!icon->empty()) { - print_line("loaded?"); _make_icon(icon, data); } } @@ -472,9 +472,7 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p Z_DEFLATED, Z_DEFAULT_COMPRESSION); - print_line("OPEN ERR: " + itos(zerr)); zerr = zipWriteInFileInZip(dst_pkg_zip, data.ptr(), data.size()); - print_line("WRITE ERR: " + itos(zerr)); zipCloseFileInZip(dst_pkg_zip); } } diff --git a/platform/osx/joypad_osx.cpp b/platform/osx/joypad_osx.cpp index 20ceadca9d..365b39c573 100644 --- a/platform/osx/joypad_osx.cpp +++ b/platform/osx/joypad_osx.cpp @@ -271,7 +271,7 @@ void JoypadOSX::_device_removed(int p_id) { ERR_FAIL_COND(device == -1); input->joy_connection_changed(p_id, false, ""); - device_list[device].free(); + device_list.write[device].free(); device_list.remove(device); } @@ -460,19 +460,19 @@ void JoypadOSX::process_joypads() { poll_joypads(); for (int i = 0; i < device_list.size(); i++) { - joypad &joy = device_list[i]; + joypad &joy = device_list.write[i]; for (int j = 0; j < joy.axis_elements.size(); j++) { - rec_element &elem = joy.axis_elements[j]; + rec_element &elem = joy.axis_elements.write[j]; int value = joy.get_hid_element_state(&elem); input->joy_axis(joy.id, j, axis_correct(value, elem.min, elem.max)); } for (int j = 0; j < joy.button_elements.size(); j++) { - int value = joy.get_hid_element_state(&joy.button_elements[j]); + int value = joy.get_hid_element_state(&joy.button_elements.write[j]); input->joy_button(joy.id, j, (value >= 1)); } for (int j = 0; j < joy.hat_elements.size(); j++) { - rec_element &elem = joy.hat_elements[j]; + rec_element &elem = joy.hat_elements.write[j]; int value = joy.get_hid_element_state(&elem); int hat_value = process_hat_value(elem.min, elem.max, value); input->joy_hat(joy.id, hat_value); @@ -495,7 +495,7 @@ void JoypadOSX::process_joypads() { } void JoypadOSX::joypad_vibration_start(int p_id, float p_magnitude, float p_duration, uint64_t p_timestamp) { - joypad *joy = &device_list[get_joy_index(p_id)]; + joypad *joy = &device_list.write[get_joy_index(p_id)]; joy->ff_timestamp = p_timestamp; joy->ff_effect.dwDuration = p_duration * FF_SECONDS; joy->ff_effect.dwGain = p_magnitude * FF_FFNOMINALMAX; @@ -504,7 +504,7 @@ void JoypadOSX::joypad_vibration_start(int p_id, float p_magnitude, float p_dura } void JoypadOSX::joypad_vibration_stop(int p_id, uint64_t p_timestamp) { - joypad *joy = &device_list[get_joy_index(p_id)]; + joypad *joy = &device_list.write[get_joy_index(p_id)]; joy->ff_timestamp = p_timestamp; FFEffectStop(joy->ff_object); } @@ -596,7 +596,7 @@ JoypadOSX::JoypadOSX() { JoypadOSX::~JoypadOSX() { for (int i = 0; i < device_list.size(); i++) { - device_list[i].free(); + device_list.write[i].free(); } IOHIDManagerUnscheduleFromRunLoop(hid_manager, CFRunLoopGetCurrent(), GODOT_JOY_LOOP_RUN_MODE); diff --git a/platform/osx/logo.png b/platform/osx/logo.png Binary files differindex 93c6890e85..62086fc415 100644 --- a/platform/osx/logo.png +++ b/platform/osx/logo.png diff --git a/platform/osx/os_osx.h b/platform/osx/os_osx.h index 7bd5b16f36..686e3f8c90 100644 --- a/platform/osx/os_osx.h +++ b/platform/osx/os_osx.h @@ -33,6 +33,7 @@ #include "crash_handler_osx.h" #include "drivers/coreaudio/audio_driver_coreaudio.h" +#include "drivers/coremidi/core_midi.h" #include "drivers/unix/os_unix.h" #include "joypad_osx.h" #include "main/input_default.h" @@ -74,6 +75,7 @@ public: IP_Unix *ip_unix; AudioDriverCoreAudio audio_driver; + MIDIDriverCoreMidi midi_driver; InputDefault *input; JoypadOSX *joypad_osx; @@ -137,6 +139,9 @@ public: void _update_window(); + int video_driver_index; + virtual int get_current_video_driver() const; + protected: virtual void initialize_core(); virtual Error initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver); diff --git a/platform/osx/os_osx.mm b/platform/osx/os_osx.mm index 4ece1e0325..44b4223a65 100644 --- a/platform/osx/os_osx.mm +++ b/platform/osx/os_osx.mm @@ -95,7 +95,7 @@ static void push_to_key_event_buffer(const OS_OSX::KeyEvent &p_event) { if (OS_OSX::singleton->key_event_pos >= buffer.size()) { buffer.resize(1 + OS_OSX::singleton->key_event_pos); } - buffer[OS_OSX::singleton->key_event_pos++] = p_event; + buffer.write[OS_OSX::singleton->key_event_pos++] = p_event; } static int mouse_x = 0; @@ -602,8 +602,8 @@ static void _mouseDownEvent(NSEvent *event, int index, int mask, bool pressed) { mm->set_position(pos); mm->set_global_position(pos); Vector2 relativeMotion = Vector2(); - relativeMotion.x = [event deltaX] * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]); - relativeMotion.y = [event deltaY] * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]); + relativeMotion.x = [event deltaX] * OS_OSX::singleton -> _mouse_scale([[event window] backingScaleFactor]); + relativeMotion.y = [event deltaY] * OS_OSX::singleton -> _mouse_scale([[event window] backingScaleFactor]); mm->set_relative(relativeMotion); get_key_modifier_state([event modifierFlags], mm); @@ -625,10 +625,18 @@ static void _mouseDownEvent(NSEvent *event, int index, int mask, bool pressed) { - (void)otherMouseDown:(NSEvent *)event { - if ((int)[event buttonNumber] != 2) - return; + if ((int)[event buttonNumber] == 2) { + _mouseDownEvent(event, BUTTON_MIDDLE, BUTTON_MASK_MIDDLE, true); + + } else if ((int)[event buttonNumber] == 3) { + _mouseDownEvent(event, BUTTON_XBUTTON1, BUTTON_MASK_XBUTTON1, true); + + } else if ((int)[event buttonNumber] == 4) { + _mouseDownEvent(event, BUTTON_XBUTTON2, BUTTON_MASK_XBUTTON2, true); - _mouseDownEvent(event, BUTTON_MIDDLE, BUTTON_MASK_MIDDLE, true); + } else { + return; + } } - (void)otherMouseDragged:(NSEvent *)event { @@ -637,10 +645,18 @@ static void _mouseDownEvent(NSEvent *event, int index, int mask, bool pressed) { - (void)otherMouseUp:(NSEvent *)event { - if ((int)[event buttonNumber] != 2) - return; + if ((int)[event buttonNumber] == 2) { + _mouseDownEvent(event, BUTTON_MIDDLE, BUTTON_MASK_MIDDLE, false); + + } else if ((int)[event buttonNumber] == 3) { + _mouseDownEvent(event, BUTTON_XBUTTON1, BUTTON_MASK_XBUTTON1, false); + + } else if ((int)[event buttonNumber] == 4) { + _mouseDownEvent(event, BUTTON_XBUTTON2, BUTTON_MASK_XBUTTON2, false); - _mouseDownEvent(event, BUTTON_MIDDLE, BUTTON_MASK_MIDDLE, false); + } else { + return; + } } - (void)mouseExited:(NSEvent *)event { @@ -1160,6 +1176,10 @@ static void displays_arrangement_changed(CGDirectDisplayID display_id, CGDisplay displays_arrangement_dirty = true; } +int OS_OSX::get_current_video_driver() const { + return video_driver_index; +} + Error OS_OSX::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { /*** OSX INITIALIZATION ***/ @@ -1311,22 +1331,58 @@ Error OS_OSX::initialize(const VideoMode &p_desired, int p_video_driver, int p_a /*** END OSX INITIALIZATION ***/ - // only opengl support here... + bool gles3 = true; if (p_video_driver == VIDEO_DRIVER_GLES2) { - RasterizerGLES2::register_config(); - RasterizerGLES2::make_current(); - } else { - RasterizerGLES3::register_config(); - RasterizerGLES3::make_current(); + gles3 = false; } + bool editor = Engine::get_singleton()->is_editor_hint(); + bool gl_initialization_error = false; + + while (true) { + if (gles3) { + if (RasterizerGLES3::is_viable() == OK) { + RasterizerGLES3::register_config(); + RasterizerGLES3::make_current(); + break; + } else { + if (GLOBAL_GET("rendering/quality/driver/driver_fallback") == "Best" || editor) { + p_video_driver = VIDEO_DRIVER_GLES2; + gles3 = false; + continue; + } else { + gl_initialization_error = true; + break; + } + } + } else { + if (RasterizerGLES2::is_viable() == OK) { + RasterizerGLES2::register_config(); + RasterizerGLES2::make_current(); + break; + } else { + gl_initialization_error = true; + break; + } + } + } + + if (gl_initialization_error) { + OS::get_singleton()->alert("Your video card driver does not support any of the supported OpenGL versions.\n" + "Please update your drivers or if you have a very old or integrated GPU upgrade it.", + "Unable to initialize Video driver"); + return ERR_UNAVAILABLE; + } + + video_driver_index = p_video_driver; + visual_server = memnew(VisualServerRaster); if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD)); } - visual_server->init(); + visual_server->init(); AudioDriverManager::initialize(p_audio_driver); input = memnew(InputDefault); @@ -1346,6 +1402,8 @@ Error OS_OSX::initialize(const VideoMode &p_desired, int p_video_driver, int p_a void OS_OSX::finalize() { + midi_driver.close(); + CFNotificationCenterRemoveObserver(CFNotificationCenterGetDistributedCenter(), NULL, kTISNotifySelectedKeyboardInputSourceChanged, NULL); CGDisplayRemoveReconfigurationCallback(displays_arrangement_changed, NULL); @@ -1546,7 +1604,9 @@ void OS_OSX::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, c } ERR_FAIL_COND(!texture.is_valid()); + ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0); ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256); + ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height); image = texture->get_data(); @@ -2381,7 +2441,7 @@ void OS_OSX::process_key_events() { Ref<InputEventKey> k; for (int i = 0; i < key_event_pos; i++) { - KeyEvent &ke = key_event_buffer[i]; + const KeyEvent &ke = key_event_buffer[i]; if ((i == 0 && ke.scancode == 0) || (i > 0 && key_event_buffer[i - 1].scancode == 0)) { k.instance(); diff --git a/platform/osx/platform_osx_builders.py b/platform/osx/platform_osx_builders.py new file mode 100644 index 0000000000..81997f674b --- /dev/null +++ b/platform/osx/platform_osx_builders.py @@ -0,0 +1,21 @@ +"""Functions used to generate source files during build time + +All such functions are invoked in a subprocess on Windows to prevent build flakiness. + +""" +import os +from platform_methods import subprocess_main + + +def make_debug_osx(target, source, env): + 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])) + else: + os.system('dsymutil {0} -o {0}.dSYM'.format(target[0])) + os.system('strip -u -r {0}'.format(target[0])) + + +if __name__ == '__main__': + subprocess_main(globals()) diff --git a/platform/server/logo.png b/platform/server/logo.png Binary files differindex 5e98ac26ec..8666ada9ca 100644 --- a/platform/server/logo.png +++ b/platform/server/logo.png diff --git a/platform/server/os_server.cpp b/platform/server/os_server.cpp index 3b1be780d4..1c17780ad7 100644 --- a/platform/server/os_server.cpp +++ b/platform/server/os_server.cpp @@ -28,16 +28,17 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "os_server.h" + #include "drivers/dummy/audio_driver_dummy.h" #include "drivers/dummy/rasterizer_dummy.h" #include "drivers/dummy/texture_loader_dummy.h" #include "print_string.h" #include "servers/visual/visual_server_raster.h" -#include <stdio.h> -#include <stdlib.h> #include "main/main.h" +#include <stdio.h> +#include <stdlib.h> #include <unistd.h> int OS_Server::get_video_driver_count() const { @@ -58,6 +59,10 @@ const char *OS_Server::get_audio_driver_name(int p_driver) const { return "Dummy"; } +int OS_Server::get_current_video_driver() const { + return video_driver_index; +} + void OS_Server::initialize_core() { crash_handler.initialize(); @@ -73,6 +78,8 @@ Error OS_Server::initialize(const VideoMode &p_desired, int p_video_driver, int 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(); diff --git a/platform/server/os_server.h b/platform/server/os_server.h index f1a880ecc2..07d70e5236 100644 --- a/platform/server/os_server.h +++ b/platform/server/os_server.h @@ -30,12 +30,12 @@ #ifndef OS_SERVER_H #define OS_SERVER_H -#include "../x11/crash_handler_x11.h" -#include "../x11/power_x11.h" #include "drivers/dummy/texture_loader_dummy.h" #include "drivers/rtaudio/audio_driver_rtaudio.h" #include "drivers/unix/os_unix.h" #include "main/input_default.h" +#include "platform/x11/crash_handler_x11.h" +#include "platform/x11/power_x11.h" #include "servers/audio_server.h" #include "servers/visual/rasterizer.h" #include "servers/visual_server.h" @@ -47,7 +47,6 @@ class OS_Server : public OS_Unix { - //Rasterizer *rasterizer; VisualServer *visual_server; VideoMode current_videomode; List<String> args; @@ -66,12 +65,14 @@ class OS_Server : public OS_Unix { CrashHandler crash_handler; + int video_driver_index; + ResourceFormatDummyTexture *resource_loader_dummy; protected: virtual int get_video_driver_count() const; virtual const char *get_video_driver_name(int p_driver) const; - + virtual int get_current_video_driver() const; virtual int get_audio_driver_count() const; virtual const char *get_audio_driver_name(int p_driver) const; diff --git a/platform/uwp/app.cpp b/platform/uwp/app.cpp index c18aa36402..b769925849 100644 --- a/platform/uwp/app.cpp +++ b/platform/uwp/app.cpp @@ -143,14 +143,13 @@ void App::SetWindow(CoreWindow ^ p_window) { window->KeyUp += ref new TypedEventHandler<CoreWindow ^, KeyEventArgs ^>(this, &App::OnKeyUp); + os->set_window(window); + unsigned int argc; char **argv = get_command_line(&argc); Main::setup("uwp", argc, argv, false); - // The CoreWindow has been created, so EGL can be initialized. - ContextEGL *context = memnew(ContextEGL(window)); - os->set_gl_context(context); UpdateWindowSize(Size(window->Bounds.Width, window->Bounds.Height)); Main::setup2(); @@ -513,7 +512,7 @@ char **App::get_command_line(unsigned int *out_argc) { if (f == NULL) { - wprintf(L"Couldn't open command line file."); + wprintf(L"Couldn't open command line file.\n"); return fail_cl; } @@ -527,7 +526,7 @@ char **App::get_command_line(unsigned int *out_argc) { if (r < 4) { fclose(f); - wprintf(L"Wrong cmdline length."); + wprintf(L"Wrong cmdline length.\n"); return (fail_cl); } @@ -539,7 +538,7 @@ char **App::get_command_line(unsigned int *out_argc) { if (r < 4) { fclose(f); - wprintf(L"Wrong cmdline param length."); + wprintf(L"Wrong cmdline param length.\n"); return (fail_cl); } @@ -547,7 +546,7 @@ char **App::get_command_line(unsigned int *out_argc) { if (strlen > CMD_MAX_LEN) { fclose(f); - wprintf(L"Wrong command length."); + wprintf(L"Wrong command length.\n"); return (fail_cl); } @@ -568,7 +567,7 @@ char **App::get_command_line(unsigned int *out_argc) { delete[] arg; fclose(f); - wprintf(L"Error reading command."); + wprintf(L"Error reading command.\n"); return (fail_cl); } } diff --git a/platform/uwp/export/export.cpp b/platform/uwp/export/export.cpp index 35c0b30ce4..1ad5293b44 100644 --- a/platform/uwp/export/export.cpp +++ b/platform/uwp/export/export.cpp @@ -301,37 +301,37 @@ Vector<uint8_t> AppxPackager::make_file_header(FileMeta p_file_meta) { int offs = 0; // Write magic - offs += buf_put_int32(FILE_HEADER_MAGIC, &buf[offs]); + offs += buf_put_int32(FILE_HEADER_MAGIC, &buf.write[offs]); // Version - offs += buf_put_int16(ZIP_VERSION, &buf[offs]); + offs += buf_put_int16(ZIP_VERSION, &buf.write[offs]); // Special flag - offs += buf_put_int16(GENERAL_PURPOSE, &buf[offs]); + offs += buf_put_int16(GENERAL_PURPOSE, &buf.write[offs]); // Compression - offs += buf_put_int16(p_file_meta.compressed ? Z_DEFLATED : 0, &buf[offs]); + offs += buf_put_int16(p_file_meta.compressed ? Z_DEFLATED : 0, &buf.write[offs]); // File date and time - offs += buf_put_int32(0, &buf[offs]); + offs += buf_put_int32(0, &buf.write[offs]); // CRC-32 - offs += buf_put_int32(p_file_meta.file_crc32, &buf[offs]); + offs += buf_put_int32(p_file_meta.file_crc32, &buf.write[offs]); // Compressed size - offs += buf_put_int32(p_file_meta.compressed_size, &buf[offs]); + offs += buf_put_int32(p_file_meta.compressed_size, &buf.write[offs]); // Uncompressed size - offs += buf_put_int32(p_file_meta.uncompressed_size, &buf[offs]); + offs += buf_put_int32(p_file_meta.uncompressed_size, &buf.write[offs]); // File name length - offs += buf_put_int16(p_file_meta.name.length(), &buf[offs]); + offs += buf_put_int16(p_file_meta.name.length(), &buf.write[offs]); // Extra data length - offs += buf_put_int16(0, &buf[offs]); + offs += buf_put_int16(0, &buf.write[offs]); // File name - offs += buf_put_string(p_file_meta.name, &buf[offs]); + offs += buf_put_string(p_file_meta.name, &buf.write[offs]); // Done! return buf; @@ -344,47 +344,47 @@ void AppxPackager::store_central_dir_header(const FileMeta &p_file, bool p_do_ha buf.resize(buf.size() + BASE_CENTRAL_DIR_SIZE + p_file.name.length()); // Write magic - offs += buf_put_int32(CENTRAL_DIR_MAGIC, &buf[offs]); + offs += buf_put_int32(CENTRAL_DIR_MAGIC, &buf.write[offs]); // ZIP versions - offs += buf_put_int16(ZIP_ARCHIVE_VERSION, &buf[offs]); - offs += buf_put_int16(ZIP_VERSION, &buf[offs]); + offs += buf_put_int16(ZIP_ARCHIVE_VERSION, &buf.write[offs]); + offs += buf_put_int16(ZIP_VERSION, &buf.write[offs]); // General purpose flag - offs += buf_put_int16(GENERAL_PURPOSE, &buf[offs]); + offs += buf_put_int16(GENERAL_PURPOSE, &buf.write[offs]); // Compression - offs += buf_put_int16(p_file.compressed ? Z_DEFLATED : 0, &buf[offs]); + offs += buf_put_int16(p_file.compressed ? Z_DEFLATED : 0, &buf.write[offs]); // Modification date/time - offs += buf_put_int32(0, &buf[offs]); + offs += buf_put_int32(0, &buf.write[offs]); // Crc-32 - offs += buf_put_int32(p_file.file_crc32, &buf[offs]); + offs += buf_put_int32(p_file.file_crc32, &buf.write[offs]); // File sizes - offs += buf_put_int32(p_file.compressed_size, &buf[offs]); - offs += buf_put_int32(p_file.uncompressed_size, &buf[offs]); + offs += buf_put_int32(p_file.compressed_size, &buf.write[offs]); + offs += buf_put_int32(p_file.uncompressed_size, &buf.write[offs]); // File name length - offs += buf_put_int16(p_file.name.length(), &buf[offs]); + offs += buf_put_int16(p_file.name.length(), &buf.write[offs]); // Extra field length - offs += buf_put_int16(0, &buf[offs]); + offs += buf_put_int16(0, &buf.write[offs]); // Comment length - offs += buf_put_int16(0, &buf[offs]); + offs += buf_put_int16(0, &buf.write[offs]); // Disk number start, internal/external file attributes for (int i = 0; i < 8; i++) { - buf[offs++] = 0; + buf.write[offs++] = 0; } // Relative offset - offs += buf_put_int32(p_file.zip_offset, &buf[offs]); + offs += buf_put_int32(p_file.zip_offset, &buf.write[offs]); // File name - offs += buf_put_string(p_file.name, &buf[offs]); + offs += buf_put_string(p_file.name, &buf.write[offs]); // Done! } @@ -397,62 +397,62 @@ Vector<uint8_t> AppxPackager::make_end_of_central_record() { int offs = 0; // Write magic - offs += buf_put_int32(ZIP64_END_OF_CENTRAL_DIR_MAGIC, &buf[offs]); + offs += buf_put_int32(ZIP64_END_OF_CENTRAL_DIR_MAGIC, &buf.write[offs]); // Size of this record - offs += buf_put_int64(ZIP64_END_OF_CENTRAL_DIR_SIZE, &buf[offs]); + offs += buf_put_int64(ZIP64_END_OF_CENTRAL_DIR_SIZE, &buf.write[offs]); // Version (yes, twice) - offs += buf_put_int16(ZIP_ARCHIVE_VERSION, &buf[offs]); - offs += buf_put_int16(ZIP_ARCHIVE_VERSION, &buf[offs]); + offs += buf_put_int16(ZIP_ARCHIVE_VERSION, &buf.write[offs]); + offs += buf_put_int16(ZIP_ARCHIVE_VERSION, &buf.write[offs]); // Disk number for (int i = 0; i < 8; i++) { - buf[offs++] = 0; + buf.write[offs++] = 0; } // Number of entries (total and per disk) - offs += buf_put_int64(file_metadata.size(), &buf[offs]); - offs += buf_put_int64(file_metadata.size(), &buf[offs]); + offs += buf_put_int64(file_metadata.size(), &buf.write[offs]); + offs += buf_put_int64(file_metadata.size(), &buf.write[offs]); // Size of central dir - offs += buf_put_int64(central_dir_data.size(), &buf[offs]); + offs += buf_put_int64(central_dir_data.size(), &buf.write[offs]); // Central dir offset - offs += buf_put_int64(central_dir_offset, &buf[offs]); + offs += buf_put_int64(central_dir_offset, &buf.write[offs]); ////// ZIP64 locator // Write magic for zip64 central dir locator - offs += buf_put_int32(ZIP64_END_DIR_LOCATOR_MAGIC, &buf[offs]); + offs += buf_put_int32(ZIP64_END_DIR_LOCATOR_MAGIC, &buf.write[offs]); // Disk number for (int i = 0; i < 4; i++) { - buf[offs++] = 0; + buf.write[offs++] = 0; } // Relative offset - offs += buf_put_int64(end_of_central_dir_offset, &buf[offs]); + offs += buf_put_int64(end_of_central_dir_offset, &buf.write[offs]); // Number of disks - offs += buf_put_int32(1, &buf[offs]); + offs += buf_put_int32(1, &buf.write[offs]); /////// End of zip directory // Write magic for end central dir - offs += buf_put_int32(END_OF_CENTRAL_DIR_MAGIC, &buf[offs]); + offs += buf_put_int32(END_OF_CENTRAL_DIR_MAGIC, &buf.write[offs]); // Dummy stuff for Zip64 for (int i = 0; i < 4; i++) { - buf[offs++] = 0x0; + buf.write[offs++] = 0x0; } for (int i = 0; i < 12; i++) { - buf[offs++] = 0xFF; + buf.write[offs++] = 0xFF; } // Size of comments for (int i = 0; i < 2; i++) { - buf[offs++] = 0; + buf.write[offs++] = 0; } // Done! @@ -508,7 +508,7 @@ void AppxPackager::add_file(String p_file_name, const uint8_t *p_buffer, size_t size_t block_size = (p_len - step) > BLOCK_SIZE ? BLOCK_SIZE : (p_len - step); for (uint32_t i = 0; i < block_size; i++) { - strm_in[i] = p_buffer[step + i]; + strm_in.write[i] = p_buffer[step + i]; } BlockHash bh; @@ -530,14 +530,14 @@ void AppxPackager::add_file(String p_file_name, const uint8_t *p_buffer, size_t int start = file_buffer.size(); file_buffer.resize(file_buffer.size() + bh.compressed_size); for (uint32_t i = 0; i < bh.compressed_size; i++) - file_buffer[start + i] = strm_out[i]; + file_buffer.write[start + i] = strm_out[i]; } else { bh.compressed_size = block_size; //package->store_buffer(strm_in.ptr(), block_size); int start = file_buffer.size(); file_buffer.resize(file_buffer.size() + block_size); for (uint32_t i = 0; i < bh.compressed_size; i++) - file_buffer[start + i] = strm_in[i]; + file_buffer.write[start + i] = strm_in[i]; } meta.hashes.push_back(bh); @@ -560,7 +560,7 @@ void AppxPackager::add_file(String p_file_name, const uint8_t *p_buffer, size_t int start = file_buffer.size(); file_buffer.resize(file_buffer.size() + (strm.total_out - total_out_before)); for (uint32_t i = 0; i < (strm.total_out - total_out_before); i++) - file_buffer[start + i] = strm_out[i]; + file_buffer.write[start + i] = strm_out[i]; deflateEnd(&strm); meta.compressed_size = strm.total_out; @@ -864,7 +864,7 @@ class EditorExportUWP : public EditorExportPlatform { r_ret.resize(result.length()); for (int i = 0; i < result.length(); i++) - r_ret[i] = result.utf8().get(i); + r_ret.write[i] = result.utf8().get(i); return r_ret; } @@ -1050,15 +1050,15 @@ public: r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "command_line/extra_args"), "")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/display_name"), "")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/short_name"), "Godot")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/unique_name"), "Godot.Engine")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/description"), "Godot Engine")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/publisher"), "CN=GodotEngine")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/publisher_display_name"), "Godot Engine")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/display_name", PROPERTY_HINT_PLACEHOLDER_TEXT, "Game Name"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/short_name", PROPERTY_HINT_PLACEHOLDER_TEXT, "Game Name"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/unique_name", PROPERTY_HINT_PLACEHOLDER_TEXT, "Game.Name"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/description"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/publisher", PROPERTY_HINT_PLACEHOLDER_TEXT, "CN=CompanyName"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/publisher_display_name", PROPERTY_HINT_PLACEHOLDER_TEXT, "Company Name"), "")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "identity/product_guid"), "00000000-0000-0000-0000-000000000000")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "identity/publisher_guid"), "00000000-0000-0000-0000-000000000000")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "identity/product_guid", PROPERTY_HINT_PLACEHOLDER_TEXT, "00000000-0000-0000-0000-000000000000"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "identity/publisher_guid", PROPERTY_HINT_PLACEHOLDER_TEXT, "00000000-0000-0000-0000-000000000000"), "")); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "signing/certificate", PROPERTY_HINT_GLOBAL_FILE, "*.pfx"), "")); r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "signing/password"), "")); @@ -1087,8 +1087,8 @@ public: r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "tiles/show_name_on_wide310x150"), false)); r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "tiles/show_name_on_square310x310"), false)); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "zip"), "")); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "zip"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), "")); // Capabilities const char **basic = uwp_capabilities; @@ -1371,8 +1371,8 @@ public: CharString txt = cl[i].utf8(); int base = clf.size(); clf.resize(base + 4 + txt.length()); - encode_uint32(txt.length(), &clf[base]); - copymem(&clf[base + 4], txt.ptr(), txt.length()); + encode_uint32(txt.length(), &clf.write[base]); + copymem(&clf.write[base + 4], txt.ptr(), txt.length()); print_line(itos(i) + " param: " + cl[i]); } @@ -1454,6 +1454,9 @@ public: r_features->push_back("UWP"); } + virtual void resolve_platform_feature_priorities(const Ref<EditorExportPreset> &p_preset, Set<String> &p_features) { + } + EditorExportUWP() { Ref<Image> img = memnew(Image(_uwp_logo)); logo.instance(); diff --git a/platform/uwp/gl_context_egl.cpp b/platform/uwp/gl_context_egl.cpp index 88c9c8d687..6c60b27f5a 100644 --- a/platform/uwp/gl_context_egl.cpp +++ b/platform/uwp/gl_context_egl.cpp @@ -93,12 +93,26 @@ Error ContextEGL::initialize() { EGLint numConfigs = 0; EGLint majorVersion = 1; - EGLint minorVersion = 0; + EGLint minorVersion; + if (driver == GLES_2_0) { + minorVersion = 0; + } else { + minorVersion = 5; + } EGLDisplay display = EGL_NO_DISPLAY; EGLContext context = EGL_NO_CONTEXT; EGLSurface surface = EGL_NO_SURFACE; EGLConfig config = nullptr; - EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE, EGL_NONE }; + EGLint contextAttribs[3]; + if (driver == GLES_2_0) { + contextAttribs[0] = EGL_CONTEXT_CLIENT_VERSION; + contextAttribs[1] = 2; + contextAttribs[2] = EGL_NONE; + } else { + contextAttribs[0] = EGL_CONTEXT_CLIENT_VERSION; + contextAttribs[1] = 3; + contextAttribs[2] = EGL_NONE; + } try { @@ -114,7 +128,8 @@ Error ContextEGL::initialize() { // EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER is an optimization that can have large performance benefits on mobile devices. // Its syntax is subject to change, though. Please update your Visual Studio templates if you experience compilation issues with it. - //EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER, EGL_TRUE, + EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER, + EGL_TRUE, // EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE is an option that enables ANGLE to automatically call // the IDXGIDevice3::Trim method on behalf of the application when it gets suspended. @@ -193,13 +208,12 @@ void ContextEGL::cleanup() { } }; -ContextEGL::ContextEGL(CoreWindow ^ p_window) : +ContextEGL::ContextEGL(CoreWindow ^ p_window, Driver p_driver) : mEglDisplay(EGL_NO_DISPLAY), mEglContext(EGL_NO_CONTEXT), - mEglSurface(EGL_NO_SURFACE) { - - window = p_window; -}; + mEglSurface(EGL_NO_SURFACE), + driver(p_driver), + window(p_window) {} ContextEGL::~ContextEGL() { diff --git a/platform/uwp/gl_context_egl.h b/platform/uwp/gl_context_egl.h index 527baf1054..df0108c124 100644 --- a/platform/uwp/gl_context_egl.h +++ b/platform/uwp/gl_context_egl.h @@ -42,6 +42,13 @@ using namespace Windows::UI::Core; class ContextEGL : public ContextGL { +public: + enum Driver { + GLES_2_0, + GLES_3_0, + }; + +private: CoreWindow ^ window; EGLDisplay mEglDisplay; @@ -53,6 +60,8 @@ class ContextEGL : public ContextGL { bool vsync; + Driver driver; + public: virtual void release_current(); @@ -70,7 +79,7 @@ public: void cleanup(); - ContextEGL(CoreWindow ^ p_window); + ContextEGL(CoreWindow ^ p_window, Driver p_driver); ~ContextEGL(); }; diff --git a/platform/uwp/os_uwp.cpp b/platform/uwp/os_uwp.cpp index d00da3dbcd..b2eb3450e2 100644 --- a/platform/uwp/os_uwp.cpp +++ b/platform/uwp/os_uwp.cpp @@ -30,6 +30,7 @@ #include "os_uwp.h" +#include "drivers/gles2/rasterizer_gles2.h" #include "drivers/gles3/rasterizer_gles3.h" #include "drivers/unix/ip_unix.h" #include "drivers/windows/dir_access_windows.h" @@ -66,12 +67,7 @@ using namespace Windows::ApplicationModel::DataTransfer; using namespace concurrency; int OSUWP::get_video_driver_count() const { - - return 1; -} -const char *OSUWP::get_video_driver_name(int p_driver) const { - - return "GLES3"; + return 2; } Size2 OSUWP::get_window_size() const { @@ -81,6 +77,10 @@ Size2 OSUWP::get_window_size() const { return size; } +int OSUWP::get_current_video_driver() const { + return video_driver_index; +} + void OSUWP::set_window_size(const Size2 p_size) { Windows::Foundation::Size new_size; @@ -133,18 +133,6 @@ void OSUWP::set_keep_screen_on(bool p_enabled) { OS::set_keep_screen_on(p_enabled); } -int OSUWP::get_audio_driver_count() const { - - return AudioDriverManager::get_driver_count(); -} - -const char *OSUWP::get_audio_driver_name(int p_driver) const { - - AudioDriver *driver = AudioDriverManager::get_driver(p_driver); - ERR_FAIL_COND_V(!driver, ""); - return AudioDriverManager::get_driver(p_driver)->get_name(); -} - void OSUWP::initialize_core() { last_button_state = 0; @@ -185,10 +173,9 @@ bool OSUWP::can_draw() const { return !minimized; }; -void OSUWP::set_gl_context(ContextEGL *p_context) { - - gl_context = p_context; -}; +void OSUWP::set_window(Windows::UI::Core::CoreWindow ^ p_window) { + window = p_window; +} void OSUWP::screen_size_changed() { @@ -200,7 +187,78 @@ Error OSUWP::initialize(const VideoMode &p_desired, int p_video_driver, int p_au main_loop = NULL; outside = true; - gl_context->initialize(); + ContextEGL::Driver opengl_api_type = ContextEGL::GLES_2_0; + + if (p_video_driver == VIDEO_DRIVER_GLES2) { + opengl_api_type = ContextEGL::GLES_2_0; + } + + bool gl_initialization_error = false; + + gl_context = NULL; + while (!gl_context) { + gl_context = memnew(ContextEGL(window, opengl_api_type)); + + if (gl_context->initialize() != OK) { + memdelete(gl_context); + gl_context = NULL; + + if (GLOBAL_GET("rendering/quality/driver/driver_fallback") == "Best") { + if (p_video_driver == VIDEO_DRIVER_GLES2) { + gl_initialization_error = true; + break; + } + + p_video_driver = VIDEO_DRIVER_GLES2; + opengl_api_type = ContextEGL::GLES_2_0; + } else { + gl_initialization_error = true; + break; + } + } + } + + while (true) { + if (opengl_api_type == ContextEGL::GLES_3_0) { + if (RasterizerGLES3::is_viable() == OK) { + RasterizerGLES3::register_config(); + RasterizerGLES3::make_current(); + break; + } else { + if (GLOBAL_GET("rendering/quality/driver/driver_fallback") == "Best") { + p_video_driver = VIDEO_DRIVER_GLES2; + opengl_api_type = ContextEGL::GLES_2_0; + continue; + } else { + gl_initialization_error = true; + break; + } + } + } + + if (opengl_api_type == ContextEGL::GLES_2_0) { + if (RasterizerGLES2::is_viable() == OK) { + RasterizerGLES2::register_config(); + RasterizerGLES2::make_current(); + break; + } else { + gl_initialization_error = true; + break; + } + } + } + + if (gl_initialization_error) { + OS::get_singleton()->alert("Your video card driver does not support any of the supported OpenGL versions.\n" + "Please update your drivers or if you have a very old or integrated GPU upgrade it.", + "Unable to initialize Video driver"); + return ERR_UNAVAILABLE; + } + + video_driver_index = p_video_driver; + gl_context->make_current(); + gl_context->set_use_vsync(video_mode.use_vsync); + VideoMode vm; vm.width = gl_context->get_window_width(); vm.height = gl_context->get_window_height(); @@ -238,12 +296,6 @@ Error OSUWP::initialize(const VideoMode &p_desired, int p_video_driver, int p_au set_video_mode(vm); - gl_context->make_current(); - - RasterizerGLES3::register_config(); - RasterizerGLES3::make_current(); - gl_context->set_use_vsync(vm.use_vsync); - visual_server = memnew(VisualServerRaster); // FIXME: Reimplement threaded rendering? Or remove? /* @@ -254,7 +306,6 @@ Error OSUWP::initialize(const VideoMode &p_desired, int p_video_driver, int p_au */ visual_server->init(); - input = memnew(InputDefault); joypad = ref new JoypadUWP(input); @@ -297,7 +348,7 @@ Error OSUWP::initialize(const VideoMode &p_desired, int p_video_driver, int p_au if (is_keep_screen_on()) display_request->RequestActive(); - set_keep_screen_on(GLOBAL_DEF("display/window/keep_screen_on", true)); + set_keep_screen_on(GLOBAL_DEF("display/window/energy_saving/keep_screen_on", true)); return OK; } @@ -392,7 +443,6 @@ void OSUWP::ManagedType::update_clipboard() { if (data->Contains(StandardDataFormats::Text)) { create_task(data->GetTextAsync()).then([this](Platform::String ^ clipboard_content) { - this->clipboard = clipboard_content; }); } diff --git a/platform/uwp/os_uwp.h b/platform/uwp/os_uwp.h index 95afdab469..89f71f0013 100644 --- a/platform/uwp/os_uwp.h +++ b/platform/uwp/os_uwp.h @@ -31,7 +31,7 @@ #ifndef OSUWP_H #define OSUWP_H -#include "core/math/math_2d.h" +#include "core/math/transform_2d.h" #include "core/ustring.h" #include "drivers/xaudio2/audio_driver_xaudio2.h" #include "gl_context_egl.h" @@ -96,8 +96,10 @@ private: int pressrc; ContextEGL *gl_context; + Windows::UI::Core::CoreWindow ^ window; VideoMode video_mode; + int video_driver_index; MainLoop *main_loop; @@ -153,10 +155,7 @@ private: // functions used by main to initialize/deintialize the OS protected: 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); @@ -231,7 +230,7 @@ public: virtual bool _check_internal_feature_support(const String &p_feature); - void set_gl_context(ContextEGL *p_context); + void set_window(Windows::UI::Core::CoreWindow ^ p_window); void screen_size_changed(); virtual void release_rendering_thread(); diff --git a/platform/windows/SCsub b/platform/windows/SCsub index ed3827353d..586533e817 100644 --- a/platform/windows/SCsub +++ b/platform/windows/SCsub @@ -3,17 +3,11 @@ import os Import('env') -def make_debug_mingw(target, source, env): - mingw_prefix = "" - 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])) +from platform_methods import run_in_subprocess +import platform_windows_builders common_win = [ + "godot_win.cpp", "context_gl_win.cpp", "crash_handler_win.cpp", "os_windows.cpp", @@ -24,20 +18,20 @@ common_win = [ "windows_terminal_logger.cpp" ] -restarget = "godot_res" + env["OBJSUFFIX"] +res_file = 'godot_res.rc' -obj = env.RES(restarget, 'godot_res.rc') +res_target = "godot_res" + env["OBJSUFFIX"] -common_win.append(obj) +res_obj = env.RES(res_target, res_file) -prog = env.add_program('#bin/godot', ['godot_win.cpp'] + common_win, PROGSUFFIX=env["PROGSUFFIX"]) +prog = env.add_program('#bin/godot', common_win + res_obj, PROGSUFFIX=env["PROGSUFFIX"]) # Microsoft Visual Studio Project Generation if env['vsproj']: - env.vs_srcs = env.vs_srcs + ["platform/windows/godot_win.cpp"] + env.vs_srcs = env.vs_srcs + ["platform/windows/" + res_file] for x in common_win: env.vs_srcs = env.vs_srcs + ["platform/windows/" + str(x)] if not os.getenv("VCINSTALLDIR"): if (env["debug_symbols"] == "full" or env["debug_symbols"] == "yes") and env["separate_debug_symbols"]: - env.AddPostAction(prog, make_debug_mingw) + env.AddPostAction(prog, run_in_subprocess(platform_windows_builders.make_debug_mingw)) diff --git a/platform/windows/context_gl_win.cpp b/platform/windows/context_gl_win.cpp index d312fbcb12..794f6df31f 100644 --- a/platform/windows/context_gl_win.cpp +++ b/platform/windows/context_gl_win.cpp @@ -68,20 +68,6 @@ void ContextGL_Win::swap_buffers() { SwapBuffers(hDC); } -/* -static GLWrapperFuncPtr wrapper_get_proc_address(const char* p_function) { - - print_line(String()+"getting proc of: "+p_function); - GLWrapperFuncPtr func=(GLWrapperFuncPtr)get_gl_proc_address(p_function); - if (!func) { - print_line("Couldn't find function: "+String(p_function)); - print_line("error: "+itos(GetLastError())); - } - return func; - -} -*/ - void ContextGL_Win::set_use_vsync(bool p_use) { if (wglSwapIntervalEXT) { @@ -106,9 +92,9 @@ Error ContextGL_Win::initialize() { PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, - 24, + OS::get_singleton()->is_layered_allowed() ? 32 : 24, 0, 0, 0, 0, 0, 0, // Color Bits Ignored - 0, // No Alpha Buffer + OS::get_singleton()->is_layered_allowed() ? 8 : 0, // Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored @@ -122,28 +108,24 @@ Error ContextGL_Win::initialize() { hDC = GetDC(hWnd); if (!hDC) { - MessageBox(NULL, "Can't Create A GL Device Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return ERR_CANT_CREATE; // Return FALSE } pixel_format = ChoosePixelFormat(hDC, &pfd); if (!pixel_format) // Did Windows Find A Matching Pixel Format? { - MessageBox(NULL, "Can't Find A Suitable pixel_format.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return ERR_CANT_CREATE; // Return FALSE } BOOL ret = SetPixelFormat(hDC, pixel_format, &pfd); if (!ret) // Are We Able To Set The Pixel Format? { - MessageBox(NULL, "Can't Set The pixel_format.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return ERR_CANT_CREATE; // Return FALSE } hRC = wglCreateContext(hDC); if (!hRC) // Are We Able To Get A Rendering Context? { - MessageBox(NULL, "Can't Create A Temporary GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return ERR_CANT_CREATE; // Return FALSE } @@ -165,7 +147,6 @@ Error ContextGL_Win::initialize() { if (wglCreateContextAttribsARB == NULL) //OpenGL 3.0 is not supported { - MessageBox(NULL, "Cannot get Proc Address for CreateContextAttribs", "ERROR", MB_OK | MB_ICONEXCLAMATION); wglDeleteContext(hRC); return ERR_CANT_CREATE; } @@ -173,7 +154,6 @@ Error ContextGL_Win::initialize() { HGLRC new_hRC = wglCreateContextAttribsARB(hDC, 0, attribs); if (!new_hRC) { wglDeleteContext(hRC); - MessageBox(NULL, "Can't Create An OpenGL 3.3 Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return ERR_CANT_CREATE; // Return false } wglMakeCurrent(hDC, NULL); @@ -182,7 +162,6 @@ Error ContextGL_Win::initialize() { if (!wglMakeCurrent(hDC, hRC)) // Try To Activate The Rendering Context { - MessageBox(NULL, "Can't Activate The GL 3.3 Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return ERR_CANT_CREATE; // Return FALSE } } diff --git a/platform/windows/crash_handler_win.cpp b/platform/windows/crash_handler_win.cpp index 804c2d44eb..76a227c608 100644 --- a/platform/windows/crash_handler_win.cpp +++ b/platform/windows/crash_handler_win.cpp @@ -124,6 +124,9 @@ DWORD CrashHandlerException(EXCEPTION_POINTERS *ep) { fprintf(stderr, "%s: Program crashed\n", __FUNCTION__); + if (OS::get_singleton()->get_main_loop()) + OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_CRASH); + // Load the symbols: if (!SymInitialize(process, NULL, false)) return EXCEPTION_CONTINUE_SEARCH; diff --git a/platform/windows/detect.py b/platform/windows/detect.py index 05806d2fe8..150d418502 100644 --- a/platform/windows/detect.py +++ b/platform/windows/detect.py @@ -166,20 +166,22 @@ def configure_msvc(env, manual_msvc_config): # Build type if (env["target"] == "release"): - env.Append(CCFLAGS=['/O2']) + 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"): - env.Append(CCFLAGS=['/O2']) + 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']) - - elif (env["target"] == "debug_release"): - env.Append(CCFLAGS=['/Z7', '/Od']) - env.Append(LINKFLAGS=['/DEBUG']) - env.Append(LINKFLAGS=['/SUBSYSTEM:WINDOWS']) - env.Append(LINKFLAGS=['/ENTRY:mainCRTStartup']) + env.Append(LINKFLAGS=['/OPT:REF']) elif (env["target"] == "debug"): env.AppendUnique(CCFLAGS=['/Z7', '/Od', '/EHsc']) @@ -188,6 +190,10 @@ def configure_msvc(env, manual_msvc_config): 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']) @@ -200,9 +206,11 @@ def configure_msvc(env, manual_msvc_config): env.AppendUnique(CPPDEFINES = ['WINDOWS_ENABLED', 'OPENGL_ENABLED', 'RTAUDIO_ENABLED', 'WASAPI_ENABLED', - 'TYPED_METHOD_BIND', 'WIN32', 'MSVC', + 'WINMIDI_ENABLED', 'TYPED_METHOD_BIND', + 'WIN32', 'MSVC', {'WINVER' : '$target_win_version', '_WIN32_WINNT': '$target_win_version'}]) + env.AppendUnique(CPPDEFINES=['NOMINMAX']) # disable bogus min/max WinDef.h macros if env["bits"] == "64": env.AppendUnique(CPPDEFINES=['_WIN64']) @@ -247,10 +255,14 @@ def configure_mingw(env): if (env["target"] == "release"): env.Append(CCFLAGS=['-msse2']) - if (env["bits"] == "64"): - env.Append(CCFLAGS=['-O3']) - else: - env.Append(CCFLAGS=['-O2']) + 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']) @@ -265,7 +277,11 @@ def configure_mingw(env): 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', '-DDEBUG_ENABLED', '-DDEBUG_MEMORY_ENABLED']) diff --git a/platform/windows/export/export.cpp b/platform/windows/export/export.cpp index 97544c18f5..38fd6366c7 100644 --- a/platform/windows/export/export.cpp +++ b/platform/windows/export/export.cpp @@ -137,14 +137,14 @@ Error EditorExportPlatformWindows::export_project(const Ref<EditorExportPreset> void EditorExportPlatformWindows::get_export_options(List<ExportOption> *r_options) { EditorExportPlatformPC::get_export_options(r_options); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/icon", PROPERTY_HINT_GLOBAL_FILE, "*.ico"), String())); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/file_version"), String())); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/product_version"), String())); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/company_name"), String())); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/product_name"), String())); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/file_description"), String())); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/copyright"), String())); - r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/trademarks"), String())); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/icon", PROPERTY_HINT_GLOBAL_FILE, "*.ico"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/file_version"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/product_version"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/company_name", PROPERTY_HINT_PLACEHOLDER_TEXT, "Company Name"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/product_name", PROPERTY_HINT_PLACEHOLDER_TEXT, "Game Name"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/file_description"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/copyright"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/trademarks"), "")); } void register_windows_exporter() { diff --git a/platform/windows/godot_win.cpp b/platform/windows/godot_win.cpp index 80f53dd1a1..504a9a0380 100644 --- a/platform/windows/godot_win.cpp +++ b/platform/windows/godot_win.cpp @@ -176,8 +176,8 @@ int _main() { } int main(int _argc, char **_argv) { -// _argc and _argv are ignored -// we are going to use the WideChar version of them instead + // _argc and _argv are ignored + // we are going to use the WideChar version of them instead #ifdef CRASH_HANDLER_EXCEPTION __try { diff --git a/platform/windows/joypad.cpp b/platform/windows/joypad.cpp index 796531fe24..b56fb6509e 100644 --- a/platform/windows/joypad.cpp +++ b/platform/windows/joypad.cpp @@ -540,9 +540,7 @@ void JoypadWindows::load_xinput() { } if (!xinput_dll) { - if (OS::get_singleton()->is_stdout_verbose()) { - print_line("Could not find XInput, using DirectInput only"); - } + print_verbose("Could not find XInput, using DirectInput only"); return; } diff --git a/platform/windows/lang_table.h b/platform/windows/lang_table.h index 1a966b502a..78bfadfeae 100644 --- a/platform/windows/lang_table.h +++ b/platform/windows/lang_table.h @@ -186,6 +186,7 @@ static const _WinLocale _win_locales[] = { { "zh_CN", LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED }, { "zh_HK", LANG_CHINESE, SUBLANG_CHINESE_HONGKONG }, { "zh_SG", LANG_CHINESE, SUBLANG_CHINESE_SINGAPORE }, + { "zh_TW", LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL }, { 0, 0, 0 }, }; diff --git a/platform/windows/logo.png b/platform/windows/logo.png Binary files differindex 4376abd563..f06b463850 100644 --- a/platform/windows/logo.png +++ b/platform/windows/logo.png diff --git a/platform/windows/os_windows.cpp b/platform/windows/os_windows.cpp index ca6c793d5d..88793386ab 100644 --- a/platform/windows/os_windows.cpp +++ b/platform/windows/os_windows.cpp @@ -70,6 +70,30 @@ __attribute__((visibility("default"))) DWORD NvOptimusEnablement = 0x00000001; #define WM_TOUCH 576 #endif +typedef struct { + int count; + int screen; + Size2 size; +} EnumSizeData; + +typedef struct { + int count; + int screen; + Point2 pos; +} EnumPosData; + +static BOOL CALLBACK _MonitorEnumProcSize(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) { + + EnumSizeData *data = (EnumSizeData *)dwData; + if (data->count == data->screen) { + data->size.x = lprcMonitor->right - lprcMonitor->left; + data->size.y = lprcMonitor->bottom - lprcMonitor->top; + } + + data->count++; + return TRUE; +} + static String format_error_message(DWORD id) { LPWSTR messageBuffer = NULL; @@ -225,7 +249,11 @@ bool OS_Windows::can_draw() const { #define MI_WP_SIGNATURE 0xFF515700 #define SIGNATURE_MASK 0xFFFFFF00 +// Keeping the name suggested by Microsoft, but this macro really answers: +// Is this mouse event emulated from touch or pen input? #define IsPenEvent(dw) (((dw)&SIGNATURE_MASK) == MI_WP_SIGNATURE) +// This one tells whether the event comes from touchscreen (and not from pen) +#define IsTouchEvent(dw) (IsPenEvent(dw) && ((dw)&0x80)) void OS_Windows::_touch_event(bool p_pressed, float p_x, float p_y, int idx) { @@ -363,12 +391,89 @@ LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) input->set_mouse_in_window(false); } break; + case WM_INPUT: { + if (mouse_mode != MOUSE_MODE_CAPTURED || !use_raw_input) { + break; + } + + UINT dwSize; + + GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER)); + LPBYTE lpb = new BYTE[dwSize]; + if (lpb == NULL) { + return 0; + } + + if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER)) != dwSize) + OutputDebugString(TEXT("GetRawInputData does not return correct size !\n")); + + RAWINPUT *raw = (RAWINPUT *)lpb; + + if (raw->header.dwType == RIM_TYPEMOUSE) { + Ref<InputEventMouseMotion> mm; + mm.instance(); + + mm->set_control(control_mem); + mm->set_shift(shift_mem); + mm->set_alt(alt_mem); + + mm->set_button_mask(last_button_state); + + Point2i c(video_mode.width / 2, video_mode.height / 2); + + // centering just so it works as before + POINT pos = { (int)c.x, (int)c.y }; + ClientToScreen(hWnd, &pos); + SetCursorPos(pos.x, pos.y); + + mm->set_position(c); + mm->set_global_position(c); + input->set_mouse_position(c); + mm->set_speed(Vector2(0, 0)); + + if (raw->data.mouse.usFlags == MOUSE_MOVE_RELATIVE) { + mm->set_relative(Vector2(raw->data.mouse.lLastX, raw->data.mouse.lLastY)); + + } else if (raw->data.mouse.usFlags == MOUSE_MOVE_ABSOLUTE) { + + int nScreenWidth = GetSystemMetrics(SM_CXVIRTUALSCREEN); + int nScreenHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN); + int nScreenLeft = GetSystemMetrics(SM_XVIRTUALSCREEN); + int nScreenTop = GetSystemMetrics(SM_YVIRTUALSCREEN); + + Vector2 abs_pos( + (double(raw->data.mouse.lLastX) - 65536.0 / (nScreenWidth)) * nScreenWidth / 65536.0 + nScreenLeft, + (double(raw->data.mouse.lLastY) - 65536.0 / (nScreenHeight)) * nScreenHeight / 65536.0 + nScreenTop); + + POINT coords; //client coords + coords.x = abs_pos.x; + coords.y = abs_pos.y; + + ScreenToClient(hWnd, &coords); + + mm->set_relative(Vector2(coords.x - old_x, coords.y - old_y)); + old_x = coords.x; + old_y = coords.y; + + /*Input.mi.dx = (int)((((double)(pos.x)-nScreenLeft) * 65536) / nScreenWidth + 65536 / (nScreenWidth)); + Input.mi.dy = (int)((((double)(pos.y)-nScreenTop) * 65536) / nScreenHeight + 65536 / (nScreenHeight)); + */ + } + + if (window_has_focus && main_loop) + input->parse_input_event(mm); + } + delete[] lpb; + } break; case WM_MOUSEMOVE: { + if (mouse_mode == MOUSE_MODE_CAPTURED && use_raw_input) { + break; + } if (input->is_emulating_mouse_from_touch()) { // Universal translation enabled; ignore OS translation LPARAM extra = GetMessageExtraInfo(); - if (IsPenEvent(extra)) { + if (IsTouchEvent(extra)) { break; } } @@ -410,11 +515,12 @@ LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) bmask |= (wParam & MK_LBUTTON) ? (1 << 0) : 0; bmask |= (wParam & MK_RBUTTON) ? (1 << 1) : 0; bmask |= (wParam & MK_MBUTTON) ? (1 << 2) : 0; + bmask |= (wParam & MK_XBUTTON1) ? (1 << 7) : 0; + bmask |= (wParam & MK_XBUTTON2) ? (1 << 8) : 0; mm->set_button_mask(bmask); last_button_state = mm->get_button_mask(); - /*mm->get_button_mask()|=(wParam&MK_XBUTTON1)?(1<<5):0; - mm->get_button_mask()|=(wParam&MK_XBUTTON2)?(1<<6):0;*/ + mm->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); mm->set_global_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); @@ -455,6 +561,13 @@ LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) } break; case WM_LBUTTONDOWN: case WM_LBUTTONUP: + if (input->is_emulating_mouse_from_touch()) { + // Universal translation enabled; ignore OS translations for left button + LPARAM extra = GetMessageExtraInfo(); + if (IsTouchEvent(extra)) { + break; + } + } case WM_MBUTTONDOWN: case WM_MBUTTONUP: case WM_RBUTTONDOWN: @@ -464,161 +577,168 @@ LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_LBUTTONDBLCLK: case WM_MBUTTONDBLCLK: case WM_RBUTTONDBLCLK: - /*case WM_XBUTTONDOWN: - case WM_XBUTTONUP: */ { - - if (input->is_emulating_mouse_from_touch()) { - // Universal translation enabled; ignore OS translation - LPARAM extra = GetMessageExtraInfo(); - if (IsPenEvent(extra)) { - break; - } - } + case WM_XBUTTONDBLCLK: + case WM_XBUTTONDOWN: + case WM_XBUTTONUP: { - Ref<InputEventMouseButton> mb; - mb.instance(); - - switch (uMsg) { - case WM_LBUTTONDOWN: { - mb->set_pressed(true); - mb->set_button_index(1); - } break; - case WM_LBUTTONUP: { - mb->set_pressed(false); - mb->set_button_index(1); - } break; - case WM_MBUTTONDOWN: { - mb->set_pressed(true); - mb->set_button_index(3); - - } break; - case WM_MBUTTONUP: { - mb->set_pressed(false); - mb->set_button_index(3); - } break; - case WM_RBUTTONDOWN: { - mb->set_pressed(true); - mb->set_button_index(2); - } break; - case WM_RBUTTONUP: { - mb->set_pressed(false); - mb->set_button_index(2); - } break; - case WM_LBUTTONDBLCLK: { - - mb->set_pressed(true); - mb->set_button_index(1); - mb->set_doubleclick(true); - } break; - case WM_RBUTTONDBLCLK: { - - mb->set_pressed(true); - mb->set_button_index(2); - mb->set_doubleclick(true); - } break; - case WM_MBUTTONDBLCLK: { - - mb->set_pressed(true); - mb->set_button_index(3); - mb->set_doubleclick(true); - } break; - case WM_MOUSEWHEEL: { - - mb->set_pressed(true); - int motion = (short)HIWORD(wParam); - if (!motion) - return 0; - - if (motion > 0) - mb->set_button_index(BUTTON_WHEEL_UP); - else - mb->set_button_index(BUTTON_WHEEL_DOWN); - - } break; - case WM_MOUSEHWHEEL: { - - mb->set_pressed(true); - int motion = (short)HIWORD(wParam); - if (!motion) - return 0; - - if (motion < 0) { - mb->set_button_index(BUTTON_WHEEL_LEFT); - mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA)); - } else { - mb->set_button_index(BUTTON_WHEEL_RIGHT); - mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA)); - } - } break; - /* - case WM_XBUTTONDOWN: { - mb->is_pressed()=true; - mb->get_button_index()=(HIWORD(wParam)==XBUTTON1)?6:7; + Ref<InputEventMouseButton> mb; + mb.instance(); + + switch (uMsg) { + case WM_LBUTTONDOWN: { + mb->set_pressed(true); + mb->set_button_index(1); } break; - case WM_XBUTTONUP: - mb->is_pressed()=true; - mb->get_button_index()=(HIWORD(wParam)==XBUTTON1)?6:7; - } break;*/ - default: { return 0; } - } + case WM_LBUTTONUP: { + mb->set_pressed(false); + mb->set_button_index(1); + } break; + case WM_MBUTTONDOWN: { + mb->set_pressed(true); + mb->set_button_index(3); - mb->set_control((wParam & MK_CONTROL) != 0); - mb->set_shift((wParam & MK_SHIFT) != 0); - mb->set_alt(alt_mem); - //mb->get_alt()=(wParam&MK_MENU)!=0; - int bmask = 0; - bmask |= (wParam & MK_LBUTTON) ? (1 << 0) : 0; - bmask |= (wParam & MK_RBUTTON) ? (1 << 1) : 0; - bmask |= (wParam & MK_MBUTTON) ? (1 << 2) : 0; - mb->set_button_mask(bmask); - - last_button_state = mb->get_button_mask(); - /* - mb->get_button_mask()|=(wParam&MK_XBUTTON1)?(1<<5):0; - mb->get_button_mask()|=(wParam&MK_XBUTTON2)?(1<<6):0;*/ - mb->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); - - if (mouse_mode == MOUSE_MODE_CAPTURED) { - - mb->set_position(Vector2(old_x, old_y)); - } + } break; + case WM_MBUTTONUP: { + mb->set_pressed(false); + mb->set_button_index(3); + } break; + case WM_RBUTTONDOWN: { + mb->set_pressed(true); + mb->set_button_index(2); + } break; + case WM_RBUTTONUP: { + mb->set_pressed(false); + mb->set_button_index(2); + } break; + case WM_LBUTTONDBLCLK: { + + mb->set_pressed(true); + mb->set_button_index(1); + mb->set_doubleclick(true); + } break; + case WM_RBUTTONDBLCLK: { - if (uMsg != WM_MOUSEWHEEL && uMsg != WM_MOUSEHWHEEL) { - if (mb->is_pressed()) { + mb->set_pressed(true); + mb->set_button_index(2); + mb->set_doubleclick(true); + } break; + case WM_MBUTTONDBLCLK: { - if (++pressrc > 0) - SetCapture(hWnd); - } else { + mb->set_pressed(true); + mb->set_button_index(3); + mb->set_doubleclick(true); + } break; + case WM_MOUSEWHEEL: { - if (--pressrc <= 0) { - ReleaseCapture(); - pressrc = 0; - } + mb->set_pressed(true); + int motion = (short)HIWORD(wParam); + if (!motion) + return 0; + + if (motion > 0) + mb->set_button_index(BUTTON_WHEEL_UP); + else + mb->set_button_index(BUTTON_WHEEL_DOWN); + + } break; + case WM_MOUSEHWHEEL: { + + mb->set_pressed(true); + int motion = (short)HIWORD(wParam); + if (!motion) + return 0; + + if (motion < 0) { + mb->set_button_index(BUTTON_WHEEL_LEFT); + mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA)); + } else { + mb->set_button_index(BUTTON_WHEEL_RIGHT); + mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA)); } - } else if (mouse_mode != MOUSE_MODE_CAPTURED) { - // for reasons unknown to mankind, wheel comes in screen cordinates - POINT coords; - coords.x = mb->get_position().x; - coords.y = mb->get_position().y; + } break; + case WM_XBUTTONDOWN: { - ScreenToClient(hWnd, &coords); + mb->set_pressed(true); + if (HIWORD(wParam) == XBUTTON1) + mb->set_button_index(BUTTON_XBUTTON1); + else + mb->set_button_index(BUTTON_XBUTTON2); + } break; + case WM_XBUTTONUP: { - mb->set_position(Vector2(coords.x, coords.y)); - } + mb->set_pressed(false); + if (HIWORD(wParam) == XBUTTON1) + mb->set_button_index(BUTTON_XBUTTON1); + else + mb->set_button_index(BUTTON_XBUTTON2); + } break; + case WM_XBUTTONDBLCLK: { - mb->set_global_position(mb->get_position()); + mb->set_pressed(true); + if (HIWORD(wParam) == XBUTTON1) + mb->set_button_index(BUTTON_XBUTTON1); + else + mb->set_button_index(BUTTON_XBUTTON2); + mb->set_doubleclick(true); + } break; + default: { return 0; } + } - if (main_loop) { - input->parse_input_event(mb); - if (mb->is_pressed() && mb->get_button_index() > 3) { - //send release for mouse wheel - Ref<InputEventMouseButton> mbd = mb->duplicate(); - mbd->set_pressed(false); - input->parse_input_event(mbd); + mb->set_control((wParam & MK_CONTROL) != 0); + mb->set_shift((wParam & MK_SHIFT) != 0); + mb->set_alt(alt_mem); + //mb->get_alt()=(wParam&MK_MENU)!=0; + int bmask = 0; + bmask |= (wParam & MK_LBUTTON) ? (1 << 0) : 0; + bmask |= (wParam & MK_RBUTTON) ? (1 << 1) : 0; + bmask |= (wParam & MK_MBUTTON) ? (1 << 2) : 0; + bmask |= (wParam & MK_XBUTTON1) ? (1 << 7) : 0; + bmask |= (wParam & MK_XBUTTON2) ? (1 << 8) : 0; + mb->set_button_mask(bmask); + + last_button_state = mb->get_button_mask(); + mb->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); + + if (mouse_mode == MOUSE_MODE_CAPTURED) { + + mb->set_position(Vector2(old_x, old_y)); + } + + if (uMsg != WM_MOUSEWHEEL && uMsg != WM_MOUSEHWHEEL) { + if (mb->is_pressed()) { + + if (++pressrc > 0) + SetCapture(hWnd); + } else { + + if (--pressrc <= 0) { + ReleaseCapture(); + pressrc = 0; } } + } else if (mouse_mode != MOUSE_MODE_CAPTURED) { + // for reasons unknown to mankind, wheel comes in screen cordinates + POINT coords; + coords.x = mb->get_position().x; + coords.y = mb->get_position().y; + + ScreenToClient(hWnd, &coords); + + mb->set_position(Vector2(coords.x, coords.y)); } - break; + + mb->set_global_position(mb->get_position()); + + if (main_loop) { + input->parse_input_event(mb); + if (mb->is_pressed() && mb->get_button_index() > 3 && mb->get_button_index() < 8) { + //send release for mouse wheel + Ref<InputEventMouseButton> mbd = mb->duplicate(); + mbd->set_pressed(false); + input->parse_input_event(mbd); + } + } + } break; case WM_SIZE: { int window_w = LOWORD(lParam); @@ -715,14 +835,6 @@ LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) if (ke.uMsg == WM_SYSKEYUP) ke.uMsg = WM_KEYUP; - /*if (ke.uMsg==WM_KEYDOWN && alt_mem && uMsg!=WM_SYSKEYDOWN) { - //altgr hack for intl keyboards, not sure how good it is - //windows is weeeeird - ke.mod_state.alt=false; - ke.mod_state.control=false; - print_line("") - }*/ - ke.wParam = wParam; ke.lParam = lParam; key_event_buffer[key_event_pos++] = ke; @@ -730,7 +842,7 @@ LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) } break; case WM_INPUTLANGCHANGEREQUEST: { - print_line("input lang change"); + // FIXME: Do something? } break; case WM_TOUCH: { @@ -742,13 +854,18 @@ LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) if (GetTouchInputInfo((HTOUCHINPUT)lParam, cInputs, pInputs, sizeof(TOUCHINPUT))) { for (UINT i = 0; i < cInputs; i++) { TOUCHINPUT ti = pInputs[i]; + POINT touch_pos = { + TOUCH_COORD_TO_PIXEL(ti.x), + TOUCH_COORD_TO_PIXEL(ti.y), + }; + ScreenToClient(hWnd, &touch_pos); //do something with each touch input entry if (ti.dwFlags & TOUCHEVENTF_MOVE) { - _drag_event(ti.x / 100.0f, ti.y / 100.0f, ti.dwID); + _drag_event(touch_pos.x, touch_pos.y, ti.dwID); } else if (ti.dwFlags & (TOUCHEVENTF_UP | TOUCHEVENTF_DOWN)) { - _touch_event(ti.dwFlags & TOUCHEVENTF_DOWN, ti.x / 100.0f, ti.y / 100.0f, ti.dwID); + _touch_event(ti.dwFlags & TOUCHEVENTF_DOWN, touch_pos.x, touch_pos.y, ti.dwID); }; } bHandled = TRUE; @@ -968,6 +1085,10 @@ typedef enum _SHC_PROCESS_DPI_AWARENESS { SHC_PROCESS_PER_MONITOR_DPI_AWARE = 2 } SHC_PROCESS_DPI_AWARENESS; +int OS_Windows::get_current_video_driver() const { + return video_driver_index; +} + Error OS_Windows::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { main_loop = NULL; @@ -1017,9 +1138,24 @@ Error OS_Windows::initialize(const VideoMode &p_desired, int p_video_driver, int return ERR_UNAVAILABLE; } + use_raw_input = true; + + RAWINPUTDEVICE Rid[1]; + + Rid[0].usUsagePage = 0x01; + Rid[0].usUsage = 0x02; + Rid[0].dwFlags = 0; + Rid[0].hwndTarget = 0; + + if (RegisterRawInputDevices(Rid, 1, sizeof(Rid[0])) == FALSE) { + //registration failed. + use_raw_input = false; + } + pre_fs_valid = true; if (video_mode.fullscreen) { + /* this returns DPI unaware size, commenting DEVMODE current; memset(¤t, 0, sizeof(current)); EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, ¤t); @@ -1027,6 +1163,14 @@ Error OS_Windows::initialize(const VideoMode &p_desired, int p_video_driver, int WindowRect.right = current.dmPelsWidth; WindowRect.bottom = current.dmPelsHeight; + */ + + EnumSizeData data = { 0, 0, Size2() }; + EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcSize, (LPARAM)&data); + + WindowRect.right = data.size.width; + WindowRect.bottom = data.size.height; + /* DEVMODE dmScreenSettings; memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); dmScreenSettings.dmSize=sizeof(dmScreenSettings); @@ -1111,20 +1255,75 @@ Error OS_Windows::initialize(const VideoMode &p_desired, int p_video_driver, int } #if defined(OPENGL_ENABLED) + + bool gles3_context = true; if (p_video_driver == VIDEO_DRIVER_GLES2) { - gl_context = memnew(ContextGL_Win(hWnd, false)); - gl_context->initialize(); + gles3_context = false; + } - RasterizerGLES2::register_config(); - RasterizerGLES2::make_current(); - } else { - gl_context = memnew(ContextGL_Win(hWnd, true)); - gl_context->initialize(); + bool editor = Engine::get_singleton()->is_editor_hint(); + bool gl_initialization_error = false; - RasterizerGLES3::register_config(); - RasterizerGLES3::make_current(); + gl_context = NULL; + while (!gl_context) { + gl_context = memnew(ContextGL_Win(hWnd, gles3_context)); + + if (gl_context->initialize() != OK) { + memdelete(gl_context); + gl_context = NULL; + + if (GLOBAL_GET("rendering/quality/driver/driver_fallback") == "Best" || editor) { + if (p_video_driver == VIDEO_DRIVER_GLES2) { + gl_initialization_error = true; + break; + } + + p_video_driver = VIDEO_DRIVER_GLES2; + gles3_context = false; + } else { + gl_initialization_error = true; + break; + } + } } + while (true) { + if (gles3_context) { + if (RasterizerGLES3::is_viable() == OK) { + RasterizerGLES3::register_config(); + RasterizerGLES3::make_current(); + break; + } else { + if (GLOBAL_GET("rendering/quality/driver/driver_fallback") == "Best" || editor) { + p_video_driver = VIDEO_DRIVER_GLES2; + gles3_context = false; + continue; + } else { + gl_initialization_error = true; + break; + } + } + } else { + if (RasterizerGLES2::is_viable() == OK) { + RasterizerGLES2::register_config(); + RasterizerGLES2::make_current(); + break; + } else { + gl_initialization_error = true; + break; + } + } + } + + if (gl_initialization_error) { + OS::get_singleton()->alert("Your video card driver does not support any of the supported OpenGL versions.\n" + "Please update your drivers or if you have a very old or integrated GPU upgrade it.", + "Unable to initialize Video driver"); + return ERR_UNAVAILABLE; + } + + video_driver_index = p_video_driver; + gl_context->set_use_vsync(video_mode.use_vsync); #endif @@ -1285,6 +1484,10 @@ void OS_Windows::set_main_loop(MainLoop *p_main_loop) { void OS_Windows::finalize() { +#ifdef WINMIDI_ENABLED + driver_midi.close(); +#endif + if (main_loop) memdelete(main_loop); @@ -1304,12 +1507,6 @@ void OS_Windows::finalize() { if (user_proc) { SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)user_proc); }; - - /* - if (debugger_connection_console) { - memdelete(debugger_connection_console); - } - */ } void OS_Windows::finalize_core() { @@ -1451,12 +1648,6 @@ void OS_Windows::set_current_screen(int p_screen) { set_window_position(ofs + get_screen_position(p_screen)); } -typedef struct { - int count; - int screen; - Point2 pos; -} EnumPosData; - static BOOL CALLBACK _MonitorEnumProcPos(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) { EnumPosData *data = (EnumPosData *)dwData; @@ -1476,24 +1667,6 @@ Point2 OS_Windows::get_screen_position(int p_screen) const { return data.pos; } -typedef struct { - int count; - int screen; - Size2 size; -} EnumSizeData; - -static BOOL CALLBACK _MonitorEnumProcSize(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) { - - EnumSizeData *data = (EnumSizeData *)dwData; - if (data->count == data->screen) { - data->size.x = lprcMonitor->right - lprcMonitor->left; - data->size.y = lprcMonitor->bottom - lprcMonitor->top; - } - - data->count++; - return TRUE; -} - Size2 OS_Windows::get_screen_size(int p_screen) const { EnumSizeData data = { 0, p_screen == -1 ? get_current_screen() : p_screen, Size2() }; @@ -1553,16 +1726,16 @@ Size2 OS_Windows::get_real_window_size() const { } void OS_Windows::set_window_size(const Size2 p_size) { - video_mode.width = p_size.width; - video_mode.height = p_size.height; + int w = p_size.width; + int h = p_size.height; + + video_mode.width = w; + video_mode.height = h; if (video_mode.fullscreen) { return; } - int w = p_size.width; - int h = p_size.height; - RECT rect; GetWindowRect(hWnd, &rect); @@ -1597,9 +1770,6 @@ void OS_Windows::set_window_fullscreen(bool p_enabled) { if (pre_fs_valid) { GetWindowRect(hWnd, &pre_fs_rect); - //print_line("A: "+itos(pre_fs_rect.left)+","+itos(pre_fs_rect.top)+","+itos(pre_fs_rect.right-pre_fs_rect.left)+","+itos(pre_fs_rect.bottom-pre_fs_rect.top)); - //MapWindowPoints(hWnd, GetParent(hWnd), (LPPOINT) &pre_fs_rect, 2); - //print_line("B: "+itos(pre_fs_rect.left)+","+itos(pre_fs_rect.top)+","+itos(pre_fs_rect.right-pre_fs_rect.left)+","+itos(pre_fs_rect.bottom-pre_fs_rect.top)); } int cs = get_current_screen(); @@ -2082,7 +2252,9 @@ void OS_Windows::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shap } ERR_FAIL_COND(!texture.is_valid()); + ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0); ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256); + ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height); image = texture->get_data(); @@ -2253,7 +2425,7 @@ Error OS_Windows::execute(const String &p_path, const List<String> &p_arguments, Vector<CharType> modstr; //windows wants to change this no idea why modstr.resize(cmdline.size()); for (int i = 0; i < cmdline.size(); i++) - modstr[i] = cmdline[i]; + modstr.write[i] = cmdline[i]; int ret = CreateProcessW(NULL, modstr.ptrw(), NULL, NULL, 0, NORMAL_PRIORITY_CLASS, NULL, NULL, si_w, &pi.pi); ERR_FAIL_COND_V(ret == 0, ERR_CANT_FORK); @@ -2263,6 +2435,8 @@ Error OS_Windows::execute(const String &p_path, const List<String> &p_arguments, if (r_exitcode) *r_exitcode = ret; + CloseHandle(pi.pi.hProcess); + CloseHandle(pi.pi.hThread); } else { ProcessID pid = pi.pi.dwProcessId; @@ -2276,17 +2450,15 @@ Error OS_Windows::execute(const String &p_path, const List<String> &p_arguments, Error OS_Windows::kill(const ProcessID &p_pid) { - HANDLE h; + ERR_FAIL_COND_V(!process_map->has(p_pid), FAILED); - if (process_map->has(p_pid)) { - h = (*process_map)[p_pid].pi.hProcess; - process_map->erase(p_pid); - } else { + const PROCESS_INFORMATION pi = (*process_map)[p_pid].pi; + process_map->erase(p_pid); - ERR_FAIL_COND_V(!process_map->has(p_pid), FAILED); - }; + const int ret = TerminateProcess(pi.hProcess, 0); - int ret = TerminateProcess(h, 0); + CloseHandle(pi.hProcess); + CloseHandle(pi.hThread); return ret != 0 ? OK : FAILED; }; @@ -2324,7 +2496,7 @@ void OS_Windows::set_icon(const Ref<Image> &p_icon) { int icon_len = 40 + h * w * 4; Vector<BYTE> v; v.resize(icon_len); - BYTE *icon_bmp = &v[0]; + BYTE *icon_bmp = v.ptrw(); encode_uint32(40, &icon_bmp[0]); encode_uint32(w, &icon_bmp[4]); @@ -2731,7 +2903,7 @@ int OS_Windows::get_power_percent_left() { bool OS_Windows::_check_internal_feature_support(const String &p_feature) { - return p_feature == "pc" || p_feature == "s3tc"; + return p_feature == "pc" || p_feature == "s3tc" || p_feature == "bptc"; } void OS_Windows::disable_crash_handler() { @@ -2743,10 +2915,9 @@ bool OS_Windows::is_disable_crash_handler() const { } Error OS_Windows::move_to_trash(const String &p_path) { - SHFILEOPSTRUCTA sf; - TCHAR *from = new TCHAR[p_path.length() + 2]; - strcpy(from, p_path.utf8().get_data()); - from[p_path.length()] = 0; + SHFILEOPSTRUCTW sf; + WCHAR *from = new WCHAR[p_path.length() + 2]; + wcscpy(from, p_path.c_str()); from[p_path.length() + 1] = 0; sf.hwnd = hWnd; @@ -2758,7 +2929,7 @@ Error OS_Windows::move_to_trash(const String &p_path) { sf.hNameMappings = NULL; sf.lpszProgressTitle = NULL; - int ret = SHFileOperation(&sf); + int ret = SHFileOperationW(&sf); delete[] from; if (ret) { diff --git a/platform/windows/os_windows.h b/platform/windows/os_windows.h index 19af63bae0..c9fa46052a 100644 --- a/platform/windows/os_windows.h +++ b/platform/windows/os_windows.h @@ -35,6 +35,7 @@ #include "crash_handler_win.h" #include "drivers/rtaudio/audio_driver_rtaudio.h" #include "drivers/wasapi/audio_driver_wasapi.h" +#include "drivers/winmidi/win_midi.h" #include "os/input.h" #include "os/os.h" #include "power_windows.h" @@ -124,6 +125,7 @@ class OS_Windows : public OS { bool force_quit; bool window_has_focus; uint32_t last_button_state; + bool use_raw_input; HCURSOR cursors[CURSOR_MAX] = { NULL }; CursorShape cursor_shape; @@ -134,6 +136,7 @@ class OS_Windows : public OS { PowerWindows *power_manager; + int video_driver_index; #ifdef WASAPI_ENABLED AudioDriverWASAPI driver_wasapi; #endif @@ -143,6 +146,9 @@ class OS_Windows : public OS { #ifdef XAUDIO2_ENABLED AudioDriverXAudio2 driver_xaudio2; #endif +#ifdef WINMIDI_ENABLED + MIDIDriverWinMidi driver_midi; +#endif CrashHandler crash_handler; @@ -153,6 +159,8 @@ class OS_Windows : public OS { // functions used by main to initialize/deintialize the OS protected: + 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); diff --git a/platform/windows/platform_windows_builders.py b/platform/windows/platform_windows_builders.py new file mode 100644 index 0000000000..a1ad3b8b50 --- /dev/null +++ b/platform/windows/platform_windows_builders.py @@ -0,0 +1,22 @@ +"""Functions used to generate source files during build time + +All such functions are invoked in a subprocess on Windows to prevent build flakiness. + +""" +import os +from platform_methods import subprocess_main + + +def make_debug_mingw(target, source, env): + mingw_prefix = "" + 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])) + + +if __name__ == '__main__': + subprocess_main(globals()) diff --git a/platform/x11/SCsub b/platform/x11/SCsub index d0f77892ef..d3901eb798 100644 --- a/platform/x11/SCsub +++ b/platform/x11/SCsub @@ -3,10 +3,8 @@ import os Import('env') -def make_debug(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])) +from platform_methods import run_in_subprocess +import platform_x11_builders common_x11 = [ "context_gl_x11.cpp", @@ -20,4 +18,4 @@ common_x11 = [ prog = env.add_program('#bin/godot', ['godot_x11.cpp'] + common_x11) if (env["debug_symbols"] == "full" or env["debug_symbols"] == "yes") and env["separate_debug_symbols"]: - env.AddPostAction(prog, make_debug) + env.AddPostAction(prog, run_in_subprocess(platform_x11_builders.make_debug_x11)) diff --git a/platform/x11/context_gl_x11.cpp b/platform/x11/context_gl_x11.cpp index cd76667c64..8c1869a1f1 100644 --- a/platform/x11/context_gl_x11.cpp +++ b/platform/x11/context_gl_x11.cpp @@ -65,19 +65,6 @@ void ContextGL_X11::swap_buffers() { glXSwapBuffers(x11_display, x11_window); } -/* -static GLWrapperFuncPtr wrapper_get_proc_address(const char* p_function) { - - //print_line(String()+"getting proc of: "+p_function); - GLWrapperFuncPtr func=(GLWrapperFuncPtr)glXGetProcAddress( (const GLubyte*) p_function); - if (!func) { - print_line("Couldn't find function: "+String(p_function)); - } - - return func; - -}*/ - static bool ctxErrorOccurred = false; static int ctxErrorHandler(Display *dpy, XErrorEvent *ev) { ctxErrorOccurred = true; @@ -129,9 +116,14 @@ Error ContextGL_X11::initialize() { }; int fbcount; - GLXFBConfig fbconfig; + GLXFBConfig fbconfig = 0; XVisualInfo *vi = NULL; + XSetWindowAttributes swa; + swa.event_mask = StructureNotifyMask; + swa.border_pixel = 0; + unsigned long valuemask = CWBorderPixel | CWColormap | CWEventMask; + if (OS::get_singleton()->is_layered_allowed()) { GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs_layered, &fbcount); ERR_FAIL_COND_V(!fbc, ERR_UNCONFIGURED); @@ -155,16 +147,10 @@ Error ContextGL_X11::initialize() { } ERR_FAIL_COND_V(!fbconfig, ERR_UNCONFIGURED); - XSetWindowAttributes swa; - - swa.colormap = XCreateColormap(x11_display, RootWindow(x11_display, vi->screen), vi->visual, AllocNone); - swa.border_pixel = 0; swa.background_pixmap = None; swa.background_pixel = 0; swa.border_pixmap = None; - swa.event_mask = StructureNotifyMask; - - x11_window = XCreateWindow(x11_display, RootWindow(x11_display, vi->screen), 0, 0, OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask | CWBackPixel, &swa); + valuemask |= CWBackPixel; } else { GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs, &fbcount); @@ -173,42 +159,21 @@ Error ContextGL_X11::initialize() { vi = glXGetVisualFromFBConfig(x11_display, fbc[0]); fbconfig = fbc[0]; - - XSetWindowAttributes swa; - - swa.colormap = XCreateColormap(x11_display, RootWindow(x11_display, vi->screen), vi->visual, AllocNone); - swa.border_pixel = 0; - swa.event_mask = StructureNotifyMask; - - x11_window = XCreateWindow(x11_display, RootWindow(x11_display, vi->screen), 0, 0, OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask, &swa); } - ERR_FAIL_COND_V(!x11_window, ERR_UNCONFIGURED); - set_class_hint(x11_display, x11_window); - XMapWindow(x11_display, x11_window); - - int (*oldHandler)(Display *, XErrorEvent *) = - XSetErrorHandler(&ctxErrorHandler); + int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&ctxErrorHandler); switch (context_type) { - case GLES_2_0_COMPATIBLE: case OLDSTYLE: { + p->glx_context = glXCreateContext(x11_display, vi, 0, GL_TRUE); + ERR_FAIL_COND_V(!p->glx_context, ERR_UNCONFIGURED); } break; - /* - case ContextType::GLES_2_0_COMPATIBLE: { - - static int context_attribs[] = { - GLX_CONTEXT_MAJOR_VERSION_ARB, 3, - GLX_CONTEXT_MINOR_VERSION_ARB, 0, - None - }; + case GLES_2_0_COMPATIBLE: { - p->glx_context = glXCreateContextAttribsARB(x11_display, fbconfig, NULL, true, context_attribs); - ERR_EXPLAIN("Could not obtain an OpenGL 3.0 context!"); + p->glx_context = glXCreateNewContext(x11_display, fbconfig, GLX_RGBA_TYPE, 0, true); ERR_FAIL_COND_V(!p->glx_context, ERR_UNCONFIGURED); } break; - */ case GLES_3_0_COMPATIBLE: { static int context_attribs[] = { @@ -220,24 +185,22 @@ Error ContextGL_X11::initialize() { }; p->glx_context = glXCreateContextAttribsARB(x11_display, fbconfig, NULL, true, context_attribs); - ERR_EXPLAIN("Could not obtain an OpenGL 3.3 context!"); ERR_FAIL_COND_V(ctxErrorOccurred || !p->glx_context, ERR_UNCONFIGURED); } break; } + 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, OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height, 0, vi->depth, InputOutput, vi->visual, valuemask, &swa); + + ERR_FAIL_COND_V(!x11_window, ERR_UNCONFIGURED); + set_class_hint(x11_display, x11_window); + XMapWindow(x11_display, x11_window); + XSync(x11_display, False); XSetErrorHandler(oldHandler); glXMakeCurrent(x11_display, x11_window, p->glx_context); - /* - glWrapperInit(wrapper_get_proc_address); - glFlush(); - - glXSwapBuffers(x11_display,x11_window); -*/ - //glXMakeCurrent(x11_display, None, NULL); - XFree(vi); return OK; @@ -310,7 +273,6 @@ ContextGL_X11::ContextGL_X11(::Display *p_x11_display, ::Window &p_x11_window, c ContextGL_X11::~ContextGL_X11() { release_current(); glXDestroyContext(x11_display, p->glx_context); - memdelete(p); } diff --git a/platform/x11/crash_handler_x11.cpp b/platform/x11/crash_handler_x11.cpp index d39fc33f81..960105271b 100644 --- a/platform/x11/crash_handler_x11.cpp +++ b/platform/x11/crash_handler_x11.cpp @@ -55,6 +55,10 @@ static void handle_crash(int sig) { // Dump the backtrace to stderr with a message to the user fprintf(stderr, "%s: Program crashed with signal %d\n", __FUNCTION__, sig); + + if (OS::get_singleton()->get_main_loop()) + OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_CRASH); + fprintf(stderr, "Dumping the backtrace. %ls\n", msg.c_str()); char **strings = backtrace_symbols(bt_buffer, size); if (strings) { diff --git a/platform/x11/detect.py b/platform/x11/detect.py index 09e16ad078..6a7a426804 100644 --- a/platform/x11/detect.py +++ b/platform/x11/detect.py @@ -62,6 +62,7 @@ def get_opts(): 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), ] @@ -81,14 +82,22 @@ def configure(env): if (env["target"] == "release"): # -O3 -ffast-math is identical to -Ofast. We need to split it out so we can selectively disable # -ffast-math in code for which it generates wrong results. - env.Prepend(CCFLAGS=['-O3', '-ffast-math']) + if (env["optimize"] == "speed"): #optimize for speed (default) + env.Prepend(CCFLAGS=['-O3', '-ffast-math']) + 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"): - env.Prepend(CCFLAGS=['-O2', '-ffast-math', '-DDEBUG_ENABLED']) + if (env["optimize"] == "speed"): #optimize for speed (default) + env.Prepend(CCFLAGS=['-O2', '-ffast-math', '-DDEBUG_ENABLED']) + else: #optimize for size + env.Prepend(CCFLAGS=['-Os', '-DDEBUG_ENABLED']) + if (env["debug_symbols"] == "yes"): env.Prepend(CCFLAGS=['-g1']) if (env["debug_symbols"] == "full"): @@ -240,7 +249,7 @@ def configure(env): if (os.system("pkg-config --exists alsa") == 0): # 0 means found print("Enabling ALSA") - env.Append(CPPFLAGS=["-DALSA_ENABLED"]) + env.Append(CPPFLAGS=["-DALSA_ENABLED", "-DALSAMIDI_ENABLED"]) env.ParseConfig('pkg-config alsa --cflags --libs') else: print("ALSA libraries not found, disabling driver") @@ -276,6 +285,9 @@ def configure(env): env.Append(LIBS=['dl']) if (platform.system().find("BSD") >= 0): + env["execinfo"] = True + + if env["execinfo"]: env.Append(LIBS=['execinfo']) ## Cross-compilation diff --git a/platform/x11/logo.png b/platform/x11/logo.png Binary files differindex 1cc93b46ac..078654b757 100644 --- a/platform/x11/logo.png +++ b/platform/x11/logo.png diff --git a/platform/x11/os_x11.cpp b/platform/x11/os_x11.cpp index 2bc85f76c9..a57a8c6bb9 100644 --- a/platform/x11/os_x11.cpp +++ b/platform/x11/os_x11.cpp @@ -84,6 +84,10 @@ void OS_X11::initialize_core() { OS_Unix::initialize_core(); } +int OS_X11::get_current_video_driver() const { + return video_driver_index; +} + Error OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { long im_event_mask = 0; @@ -166,13 +170,13 @@ Error OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_a #ifdef TOUCH_ENABLED if (!XQueryExtension(x11_display, "XInputExtension", &touch.opcode, &event_base, &error_base)) { - fprintf(stderr, "XInput extension not available"); + print_verbose("XInput extension not available, touch support disabled."); } else { // 2.2 is the first release with multitouch int xi_major = 2; int xi_minor = 2; if (XIQueryVersion(x11_display, &xi_major, &xi_minor) != Success) { - fprintf(stderr, "XInput 2.2 not available (server supports %d.%d)\n", xi_major, xi_minor); + print_verbose(vformat("XInput 2.2 not available (server supports %d.%d), touch support disabled.", xi_major, xi_minor)); touch.opcode = 0; } else { int dev_count; @@ -194,14 +198,14 @@ Error OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_a } if (direct_touch) { touch.devices.push_back(dev->deviceid); - fprintf(stderr, "Using touch device: %s\n", dev->name); + print_verbose("XInput: Using touch device: " + String(dev->name)); } } XIFreeDeviceInfo(info); - if (is_stdout_verbose() && !touch.devices.size()) { - fprintf(stderr, "No touch devices found\n"); + if (!touch.devices.size()) { + print_verbose("XInput: No touch devices found."); } } } @@ -262,7 +266,6 @@ Error OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_a */ // maybe contextgl wants to be in charge of creating the window -//print_line("def videomode "+itos(current_videomode.width)+","+itos(current_videomode.height)); #if defined(OPENGL_ENABLED) ContextGL_X11::ContextType opengl_api_type = ContextGL_X11::GLES_3_0_COMPATIBLE; @@ -271,20 +274,71 @@ Error OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_a opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE; } - context_gl = memnew(ContextGL_X11(x11_display, x11_window, current_videomode, opengl_api_type)); - context_gl->initialize(); + bool editor = Engine::get_singleton()->is_editor_hint(); + bool gl_initialization_error = false; - switch (opengl_api_type) { - case ContextGL_X11::GLES_2_0_COMPATIBLE: { - RasterizerGLES2::register_config(); - RasterizerGLES2::make_current(); - } break; - case ContextGL_X11::GLES_3_0_COMPATIBLE: { - RasterizerGLES3::register_config(); - RasterizerGLES3::make_current(); - } break; + context_gl = NULL; + while (!context_gl) { + context_gl = memnew(ContextGL_X11(x11_display, x11_window, current_videomode, opengl_api_type)); + + if (context_gl->initialize() != OK) { + memdelete(context_gl); + context_gl = NULL; + + if (GLOBAL_GET("rendering/quality/driver/driver_fallback") == "Best" || editor) { + if (p_video_driver == VIDEO_DRIVER_GLES2) { + gl_initialization_error = true; + break; + } + + p_video_driver = VIDEO_DRIVER_GLES2; + opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE; + } else { + gl_initialization_error = true; + break; + } + } } + while (true) { + if (opengl_api_type == ContextGL_X11::GLES_3_0_COMPATIBLE) { + if (RasterizerGLES3::is_viable() == OK) { + RasterizerGLES3::register_config(); + RasterizerGLES3::make_current(); + break; + } else { + if (GLOBAL_GET("rendering/quality/driver/driver_fallback") == "Best" || editor) { + p_video_driver = VIDEO_DRIVER_GLES2; + opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE; + continue; + } else { + gl_initialization_error = true; + break; + } + } + } + + if (opengl_api_type == ContextGL_X11::GLES_2_0_COMPATIBLE) { + if (RasterizerGLES2::is_viable() == OK) { + RasterizerGLES2::register_config(); + RasterizerGLES2::make_current(); + break; + } else { + gl_initialization_error = true; + break; + } + } + } + + if (gl_initialization_error) { + OS::get_singleton()->alert("Your video card driver does not support any of the supported OpenGL versions.\n" + "Please update your drivers or if you have a very old or integrated GPU upgrade it.", + "Unable to initialize Video driver"); + return ERR_UNAVAILABLE; + } + + video_driver_index = p_video_driver; + context_gl->set_use_vsync(current_videomode.use_vsync); #endif @@ -334,8 +388,6 @@ Error OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_a set_window_always_on_top(true); } - AudioDriverManager::initialize(p_audio_driver); - ERR_FAIL_COND_V(!visual_server, ERR_UNAVAILABLE); ERR_FAIL_COND_V(x11_window == 0, ERR_UNAVAILABLE); @@ -417,9 +469,7 @@ Error OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_a cursor_theme = XcursorGetTheme(x11_display); if (!cursor_theme) { - if (is_stdout_verbose()) { - print_line("XcursorGetTheme could not get cursor theme"); - } + print_verbose("XcursorGetTheme could not get cursor theme"); cursor_theme = "default"; } @@ -432,7 +482,6 @@ Error OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_a current_cursor = CURSOR_ARROW; if (cursor_theme) { - //print_line("cursor theme: "+String(cursor_theme)); for (int i = 0; i < CURSOR_MAX; i++) { static const char *cursor_file[] = { @@ -458,10 +507,8 @@ Error OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_a img[i] = XcursorLibraryLoadImage(cursor_file[i], cursor_theme, cursor_size); if (img[i]) { cursors[i] = XcursorImageLoadCursor(x11_display, img[i]); - //print_line("found cursor: "+String(cursor_file[i])+" id "+itos(cursors[i])); } else { - if (OS::is_stdout_verbose()) - print_line("failed cursor: " + String(cursor_file[i])); + print_verbose("Failed loading custom cursor: " + String(cursor_file[i])); } } } @@ -510,6 +557,8 @@ Error OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_a visual_server->init(); + AudioDriverManager::initialize(p_audio_driver); + input = memnew(InputDefault); window_has_focus = true; // Set focus to true at init @@ -600,6 +649,9 @@ void OS_X11::finalize() { memdelete(debugger_connection_console); } */ +#ifdef ALSAMIDI_ENABLED + driver_alsamidi.close(); +#endif #ifdef JOYDEV_ENABLED memdelete(joypad); @@ -1326,7 +1378,7 @@ void OS_X11::request_attention() { // // Sets the _NET_WM_STATE_DEMANDS_ATTENTION atom for WM_STATE // Will be unset by the window manager after user react on the request for attention - // + XEvent xev; Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False); Atom wm_attention = XInternAtom(x11_display, "_NET_WM_STATE_DEMANDS_ATTENTION", False); @@ -1340,6 +1392,7 @@ void OS_X11::request_attention() { xev.xclient.data.l[1] = wm_attention; XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); + XFlush(x11_display); } void OS_X11::get_key_modifier_state(unsigned int p_x11_state, Ref<InputEventWithModifiers> state) { @@ -1502,7 +1555,6 @@ void OS_X11::handle_key_event(XKeyEvent *p_event, bool p_echo) { // KeyMappingX11 also translates keysym to unicode. // It does a binary search on a table to translate // most properly. - //print_line("keysym_unicode: "+rtos(keysym_unicode)); unsigned int unicode = keysym_unicode > 0 ? KeyMappingX11::get_unicode_from_keysym(keysym_unicode) : 0; /* Phase 4, determine if event must be filtered */ @@ -1525,7 +1577,7 @@ void OS_X11::handle_key_event(XKeyEvent *p_event, bool p_echo) { // know Mod1 was ALT and Mod4 was META (applekey/winkey) // just tried Mods until i found them. - //print_line("mod1: "+itos(xkeyevent->state&Mod1Mask)+" mod 5: "+itos(xkeyevent->state&Mod5Mask)); + //print_verbose("mod1: "+itos(xkeyevent->state&Mod1Mask)+" mod 5: "+itos(xkeyevent->state&Mod5Mask)); Ref<InputEventKey> k; k.instance(); @@ -1825,8 +1877,8 @@ void OS_X11::process_xevents() { GrabModeAsync, GrabModeAsync, x11_window, None, CurrentTime); } #ifdef TOUCH_ENABLED - // Grab touch devices to avoid OS gesture interference - /*for (int i = 0; i < touch.devices.size(); ++i) { + // Grab touch devices to avoid OS gesture interference + /*for (int i = 0; i < touch.devices.size(); ++i) { XIGrabDevice(x11_display, touch.devices[i], x11_window, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, False, &touch.event_mask); }*/ #endif @@ -2092,7 +2144,7 @@ void OS_X11::process_xevents() { Vector<String> files = String((char *)p.data).split("\n", false); for (int i = 0; i < files.size(); i++) { - files[i] = files[i].replace("file://", "").replace("%20", " ").strip_escapes(); + files.write[i] = files[i].replace("file://", "").replace("%20", " ").strip_escapes(); } main_loop->drop_files(files); @@ -2330,7 +2382,7 @@ Error OS_X11::shell_open(String p_uri) { bool OS_X11::_check_internal_feature_support(const String &p_feature) { - return p_feature == "pc" || p_feature == "s3tc"; + return p_feature == "pc" || p_feature == "s3tc" || p_feature == "bptc"; } String OS_X11::get_config_path() const { @@ -2423,7 +2475,19 @@ String OS_X11::get_system_dir(SystemDir p_dir) const { void OS_X11::move_window_to_foreground() { - XRaiseWindow(x11_display, x11_window); + XEvent xev; + Atom net_active_window = XInternAtom(x11_display, "_NET_ACTIVE_WINDOW", False); + + memset(&xev, 0, sizeof(xev)); + xev.type = ClientMessage; + xev.xclient.window = x11_window; + xev.xclient.message_type = net_active_window; + xev.xclient.format = 32; + xev.xclient.data.l[0] = 1; + xev.xclient.data.l[1] = CurrentTime; + + XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); + XFlush(x11_display); } void OS_X11::set_cursor_shape(CursorShape p_shape) { @@ -2470,7 +2534,9 @@ void OS_X11::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, c } ERR_FAIL_COND(!texture.is_valid()); + ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0); ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256); + ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height); image = texture->get_data(); @@ -2549,51 +2615,146 @@ void OS_X11::swap_buffers() { } void OS_X11::alert(const String &p_alert, const String &p_title) { + const char *message_programs[] = { "zenity", "kdialog", "Xdialog", "xmessage" }; + + String path = get_environment("PATH"); + Vector<String> path_elems = path.split(":", false); + String program; + + for (int i = 0; i < path_elems.size(); i++) { + for (unsigned int k = 0; k < sizeof(message_programs) / sizeof(char *); k++) { + String tested_path = path_elems[i] + "/" + message_programs[k]; + + if (FileAccess::exists(tested_path)) { + program = tested_path; + break; + } + } + + if (program.length()) + break; + } List<String> args; - args.push_back("-center"); - args.push_back("-title"); - args.push_back(p_title); - args.push_back(p_alert); - execute("xmessage", args, true); + if (program.ends_with("zenity")) { + args.push_back("--error"); + args.push_back("--width"); + args.push_back("500"); + args.push_back("--title"); + args.push_back(p_title); + args.push_back("--text"); + args.push_back(p_alert); + } + + if (program.ends_with("kdialog")) { + args.push_back("--error"); + args.push_back(p_alert); + args.push_back("--title"); + args.push_back(p_title); + } + + if (program.ends_with("Xdialog")) { + args.push_back("--title"); + args.push_back(p_title); + args.push_back("--msgbox"); + args.push_back(p_alert); + args.push_back("0"); + args.push_back("0"); + } + + if (program.ends_with("xmessage")) { + args.push_back("-center"); + args.push_back("-title"); + args.push_back(p_title); + args.push_back(p_alert); + } + + if (program.length()) { + execute(program, args, true); + } else { + print_line(p_alert); + } + + return; +} + +bool g_set_icon_error = false; +int set_icon_errorhandler(Display *dpy, XErrorEvent *ev) { + g_set_icon_error = true; + return 0; } void OS_X11::set_icon(const Ref<Image> &p_icon) { + int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&set_icon_errorhandler); + Atom net_wm_icon = XInternAtom(x11_display, "_NET_WM_ICON", False); if (p_icon.is_valid()) { Ref<Image> img = p_icon->duplicate(); img->convert(Image::FORMAT_RGBA8); - int w = img->get_width(); - int h = img->get_height(); + while (true) { + int w = img->get_width(); + int h = img->get_height(); - // We're using long to have wordsize (32Bit build -> 32 Bits, 64 Bit build -> 64 Bits - Vector<long> pd; + if (g_set_icon_error) { + g_set_icon_error = false; - pd.resize(2 + w * h); + WARN_PRINT("Icon too large, attempting to resize icon."); - pd[0] = w; - pd[1] = h; + int new_width, new_height; + if (w > h) { + new_width = w / 2; + new_height = h * new_width / w; + } else { + new_height = h / 2; + new_width = w * new_height / h; + } - PoolVector<uint8_t>::Read r = img->get_data().read(); + w = new_width; + h = new_height; - long *wr = &pd[2]; - uint8_t const *pr = r.ptr(); + if (!w || !h) { + WARN_PRINT("Unable to set icon."); + break; + } - for (int i = 0; i < w * h; i++) { - long v = 0; - // A R G B - v |= pr[3] << 24 | pr[0] << 16 | pr[1] << 8 | pr[2]; - *wr++ = v; - pr += 4; + img->resize(w, h, Image::INTERPOLATE_CUBIC); + } + + // We're using long to have wordsize (32Bit build -> 32 Bits, 64 Bit build -> 64 Bits + Vector<long> pd; + + pd.resize(2 + w * h); + + pd.write[0] = w; + pd.write[1] = h; + + PoolVector<uint8_t>::Read r = img->get_data().read(); + + long *wr = &pd.write[2]; + uint8_t const *pr = r.ptr(); + + for (int i = 0; i < w * h; i++) { + long v = 0; + // A R G B + v |= pr[3] << 24 | pr[0] << 16 | pr[1] << 8 | pr[2]; + *wr++ = v; + pr += 4; + } + + XChangeProperty(x11_display, x11_window, net_wm_icon, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)pd.ptr(), pd.size()); + + if (!g_set_icon_error) + break; } - XChangeProperty(x11_display, x11_window, net_wm_icon, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)pd.ptr(), pd.size()); } else { XDeleteProperty(x11_display, x11_window, net_wm_icon); } + XFlush(x11_display); + XSetErrorHandler(oldHandler); } void OS_X11::force_process_input() { diff --git a/platform/x11/os_x11.h b/platform/x11/os_x11.h index 8cab23fe63..44455a2d8d 100644 --- a/platform/x11/os_x11.h +++ b/platform/x11/os_x11.h @@ -38,6 +38,7 @@ #include "servers/visual_server.h" //#include "servers/visual/visual_server_wrap_mt.h" #include "drivers/alsa/audio_driver_alsa.h" +#include "drivers/alsamidi/alsa_midi.h" #include "drivers/pulseaudio/audio_driver_pulseaudio.h" #include "joypad_linux.h" #include "main/input_default.h" @@ -168,6 +169,10 @@ class OS_X11 : public OS_Unix { AudioDriverALSA driver_alsa; #endif +#ifdef ALSAMIDI_ENABLED + MIDIDriverALSAMidi driver_alsamidi; +#endif + #ifdef PULSEAUDIO_ENABLED AudioDriverPulseAudio driver_pulseaudio; #endif @@ -180,6 +185,7 @@ class OS_X11 : public OS_Unix { CrashHandler crash_handler; + int video_driver_index; int audio_driver_index; unsigned int capture_idle; bool maximized; @@ -195,6 +201,8 @@ class OS_X11 : public OS_Unix { Bool xrandr_ext_ok; protected: + 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 finalize(); diff --git a/platform/x11/platform_x11_builders.py b/platform/x11/platform_x11_builders.py new file mode 100644 index 0000000000..5ff0c6fb14 --- /dev/null +++ b/platform/x11/platform_x11_builders.py @@ -0,0 +1,17 @@ +"""Functions used to generate source files during build time + +All such functions are invoked in a subprocess on Windows to prevent build flakiness. + +""" +import os +from platform_methods import subprocess_main + + +def make_debug_x11(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])) + + +if __name__ == '__main__': + subprocess_main(globals()) |