diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 1e85d7b681..741a48aede 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -1,5 +1,3 @@ - - include(${CMAKE_CURRENT_LIST_DIR}/cmake/predefine.cmake) ################################# engine source code ################################## @@ -28,6 +26,7 @@ cc_set_if_undefined(USE_JOB_SYSTEM_TBB OFF) cc_set_if_undefined(USE_PHYSICS_PHYSX OFF) cc_set_if_undefined(USE_MODULES OFF) +add_definitions() if(ANDROID OR WINDOWS) cc_set_if_undefined(CC_USE_GLES3 ON) @@ -154,6 +153,24 @@ if(USE_AUDIO) cocos/audio/oalsoft/AudioPlayer.cpp cocos/audio/oalsoft/AudioPlayer.h ) + elseif(LINUX OR QNX) + cocos_source_files( + cocos/audio/oalsoft/AudioCache.cpp + cocos/audio/oalsoft/AudioCache.h + cocos/audio/oalsoft/AudioDecoder.cpp + cocos/audio/oalsoft/AudioDecoder.h + cocos/audio/oalsoft/AudioDecoderManager.cpp + cocos/audio/oalsoft/AudioDecoderManager.h + cocos/audio/oalsoft/AudioDecoderMp3.cpp + cocos/audio/oalsoft/AudioDecoderMp3.h + cocos/audio/oalsoft/AudioDecoderOgg.cpp + cocos/audio/oalsoft/AudioDecoderOgg.h + cocos/audio/oalsoft/AudioEngine-soft.cpp + cocos/audio/oalsoft/AudioEngine-soft.h + cocos/audio/oalsoft/AudioMacros.h + cocos/audio/oalsoft/AudioPlayer.cpp + cocos/audio/oalsoft/AudioPlayer.h + ) elseif(ANDROID) cocos_source_files( cocos/audio/android/AssetFd.cpp @@ -304,6 +321,282 @@ cocos_source_files( cocos/base/Vector.h ) +############ application +cocos_source_files( + cocos/application/BaseApplication.h + cocos/application/CocosApplication.h + cocos/application/CocosApplication.cpp + cocos/application/ApplicationManager.h + cocos/application/ApplicationManager.cpp +) + +############ engine +cocos_source_files( + cocos/engine/BaseEngine.cpp + cocos/engine/BaseEngine.h + cocos/engine/Engine.cpp + cocos/engine/Engine.h +) + +############ main +if(WINDOWS) + cocos_source_files( + cocos/main/main-win32.cpp + ) +elseif(LINUX) + cocos_source_files( + cocos/main/main-linux.cpp + ) +elseif(QNX) + cocos_source_files( + cocos/main/main-qnx.cpp + ) +elseif(MACOSX) + cocos_source_files( + cocos/main/main-mac.mm + ) +elseif(IOS) + cocos_source_files( + cocos/main/main-ios.mm + ) +endif() + +############ platformex +cocos_source_files( + cocos/platform/IEventDispatch.h + cocos/platform/BasePlatform.cpp + cocos/platform/BasePlatform.h + cocos/platform/UniversalPlatform.cpp + cocos/platform/UniversalPlatform.h +) +if(WINDOWS) + cocos_source_files( + cocos/platform/win32/WindowsPlatform.cpp + cocos/platform/win32/WindowsPlatform.h + ) +elseif(LINUX) + cocos_source_files( + cocos/platform/linux/LinuxPlatform.cpp + cocos/platform/linux/LinuxPlatform.h + ) +elseif(QNX) + cocos_source_files( + cocos/platform/qnx/QnxPlatform.cpp + cocos/platform/qnx/QnxPlatform.h + ) +elseif(ANDROID) + cocos_source_files( + cocos/platform/android/AndroidPlatform.cpp + cocos/platform/android/AndroidPlatform.h + ) +elseif(OHOS) + cocos_source_files( + cocos/platform/ohos/OhosPlatform.cpp + cocos/platform/ohos/OhosPlatform.h + ) +elseif(MACOSX) + cocos_source_files( + cocos/platform/mac/MacPlatform.mm + cocos/platform/mac/MacPlatform.h + cocos/platform/mac/ViewController.h + cocos/platform/mac/ViewController.mm + cocos/platform/mac/AppDelegate.h + cocos/platform/mac/AppDelegate.mm + ) +elseif(IOS) + cocos_source_files( + cocos/platform/ios/IOSPlatform.mm + cocos/platform/ios/IOSPlatform.h + cocos/platform/ios/AppDelegate.mm + cocos/platform/ios/AppDelegate.h + cocos/platform/ios/service/SDKWrapper.m + cocos/platform/ios/service/SDKWrapper.h + cocos/platform/ios/ViewController.mm + cocos/platform/ios/ViewController.h + ) +endif() + +############ platform : Abstract interface +cocos_source_files( + cocos/platform/interfaces/OSInterface.cpp + cocos/platform/interfaces/OSInterface.h + cocos/platform/interfaces/OSInterfaceManager.cpp + cocos/platform/interfaces/OSInterfaceManager.h +) + +############ platform : Interface definition +cocos_source_files( + cocos/platform/interfaces/modules/Device.cpp + cocos/platform/interfaces/modules/Device.h + cocos/platform/interfaces/modules/IAccelerometer.cpp + cocos/platform/interfaces/modules/IAccelerometer.h + cocos/platform/interfaces/modules/IBattery.cpp + cocos/platform/interfaces/modules/IBattery.h + cocos/platform/interfaces/modules/IScreen.cpp + cocos/platform/interfaces/modules/IScreen.h + cocos/platform/interfaces/modules/INetwork.cpp + cocos/platform/interfaces/modules/INetwork.h + cocos/platform/interfaces/modules/ISystem.cpp + cocos/platform/interfaces/modules/ISystem.h + cocos/platform/interfaces/modules/ISystemWindow.cpp + cocos/platform/interfaces/modules/ISystemWindow.h + cocos/platform/interfaces/modules/IVibrator.cpp + cocos/platform/interfaces/modules/IVibrator.h +) + +cocos_source_files( + cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp + cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.h + cocos/platform/interfaces/modules/canvas/ICanvasRenderingContext2D.cpp + cocos/platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h +) +if(WINDOWS) + cocos_source_files( + cocos/platform/win32/modules/CanvasRenderingContext2DDelegate.cpp + cocos/platform/win32/modules/CanvasRenderingContext2DDelegate.h + ) +elseif(ANDROID OR OHOS) + cocos_source_files( + cocos/platform/java/modules/CanvasRenderingContext2DDelegate.cpp + cocos/platform/java/modules/CanvasRenderingContext2DDelegate.h + ) +elseif(MACOSX OR IOS) + cocos_source_files( + cocos/platform/apple/modules/CanvasRenderingContext2DDelegate.mm + cocos/platform/apple/modules/CanvasRenderingContext2DDelegate.h + ) +elseif(QNX) + cocos_source_files( + cocos/platform/qnx/modules/CanvasRenderingContext2DDelegate.cpp + cocos/platform/qnx/modules/CanvasRenderingContext2DDelegate.h + ) +elseif(LINUX) + cocos_source_files( + cocos/platform/linux/modules/CanvasRenderingContext2DDelegate.cpp + cocos/platform/linux/modules/CanvasRenderingContext2DDelegate.h + ) +endif() + +############ platform : Interface implementation of windows +if(WINDOWS) + cocos_source_files( + cocos/platform/win32/modules/Accelerometer.cpp + cocos/platform/win32/modules/Accelerometer.h + cocos/platform/win32/modules/Battery.cpp + cocos/platform/win32/modules/Battery.h + cocos/platform/win32/modules/Screen.cpp + cocos/platform/win32/modules/Screen.h + cocos/platform/win32/modules/Network.cpp + cocos/platform/win32/modules/Network.h + cocos/platform/win32/modules/Vibrator.cpp + cocos/platform/win32/modules/Vibrator.h + cocos/platform/win32/modules/System.cpp + cocos/platform/win32/modules/System.h + cocos/platform/win32/modules/SystemWindow.cpp + cocos/platform/win32/modules/SystemWindow.h + ) +elseif(ANDROID OR OHOS) + cocos_source_files( + cocos/platform/java/modules/Accelerometer.cpp + cocos/platform/java/modules/Accelerometer.h + cocos/platform/java/modules/Battery.cpp + cocos/platform/java/modules/Battery.h + cocos/platform/java/modules/CommonScreen.cpp + cocos/platform/java/modules/CommonScreen.h + cocos/platform/java/modules/Network.cpp + cocos/platform/java/modules/Network.h + cocos/platform/java/modules/Vibrator.cpp + cocos/platform/java/modules/Vibrator.h + cocos/platform/java/modules/CommonSystem.cpp + cocos/platform/java/modules/CommonSystem.h + cocos/platform/java/modules/SystemWindow.cpp + cocos/platform/java/modules/SystemWindow.h + ) +endif() +if(ANDROID) + cocos_source_files( + cocos/platform/android/modules/Screen.cpp + cocos/platform/android/modules/Screen.h + cocos/platform/android/modules/System.cpp + cocos/platform/android/modules/System.h + ) +elseif(OHOS) + cocos_source_files( + cocos/platform/ohos/modules/Screen.cpp + cocos/platform/ohos/modules/Screen.h + cocos/platform/ohos/modules/System.cpp + cocos/platform/ohos/modules/System.h + ) +elseif(MACOSX) + cocos_source_files( + cocos/platform/mac/modules/Accelerometer.mm + cocos/platform/mac/modules/Accelerometer.h + cocos/platform/mac/modules/Battery.mm + cocos/platform/mac/modules/Battery.h + cocos/platform/mac/modules/Screen.mm + cocos/platform/mac/modules/Screen.h + cocos/platform/mac/modules/Network.mm + cocos/platform/mac/modules/Network.h + cocos/platform/mac/modules/Vibrator.mm + cocos/platform/mac/modules/Vibrator.h + cocos/platform/mac/modules/System.mm + cocos/platform/mac/modules/System.h + cocos/platform/mac/modules/SystemWindow.mm + cocos/platform/mac/modules/SystemWindow.h + ) +elseif(IOS) + cocos_source_files( + cocos/platform/ios/modules/Accelerometer.mm + cocos/platform/ios/modules/Accelerometer.h + cocos/platform/ios/modules/Battery.mm + cocos/platform/ios/modules/Battery.h + cocos/platform/ios/modules/Screen.mm + cocos/platform/ios/modules/Screen.h + cocos/platform/ios/modules/Network.mm + cocos/platform/ios/modules/Network.h + cocos/platform/ios/modules/Vibrator.mm + cocos/platform/ios/modules/Vibrator.h + cocos/platform/ios/modules/System.mm + cocos/platform/ios/modules/System.h + cocos/platform/ios/modules/SystemWindow.mm + cocos/platform/ios/modules/SystemWindow.h + ) +elseif(LINUX) + cocos_source_files( + cocos/platform/linux/modules/Accelerometer.cpp + cocos/platform/linux/modules/Accelerometer.h + cocos/platform/linux/modules/Battery.cpp + cocos/platform/linux/modules/Battery.h + cocos/platform/linux/modules/Screen.cpp + cocos/platform/linux/modules/Screen.h + cocos/platform/linux/modules/Network.cpp + cocos/platform/linux/modules/Network.h + cocos/platform/linux/modules/Vibrate.cpp + cocos/platform/linux/modules/Vibrate.h + cocos/platform/linux/modules/System.cpp + cocos/platform/linux/modules/System.h + cocos/platform/linux/modules/SystemWindow.cpp + cocos/platform/linux/modules/SystemWindow.h + ) +elseif(QNX) + cocos_source_files( + cocos/platform/qnx/modules/Accelerometer.cpp + cocos/platform/qnx/modules/Accelerometer.h + cocos/platform/qnx/modules/Battery.cpp + cocos/platform/qnx/modules/Battery.h + cocos/platform/qnx/modules/Screen.cpp + cocos/platform/qnx/modules/Screen.h + cocos/platform/qnx/modules/Network.cpp + cocos/platform/qnx/modules/Network.h + cocos/platform/qnx/modules/Vibrate.cpp + cocos/platform/qnx/modules/Vibrate.h + cocos/platform/qnx/modules/System.cpp + cocos/platform/qnx/modules/System.h + cocos/platform/qnx/modules/SystemWindow.cpp + cocos/platform/qnx/modules/SystemWindow.h + ) +endif() + ############ module log cocos_source_files(MODULE cclog cocos/base/Log.cpp @@ -487,14 +780,14 @@ if(NOT APPLE AND USE_SOCKET) ) endif() -if(WINDOWS) +if(WINDOWS OR LINUX OR QNX) cocos_source_files( NO_WERROR cocos/network/Downloader-curl.cpp cocos/network/Downloader-curl.h ) endif() -if(WINDOWS OR MACOSX) +if(WINDOWS OR MACOSX OR LINUX OR QNX) cocos_source_files( NO_WERROR cocos/network/HttpClient.cpp ) @@ -503,10 +796,6 @@ endif() ##### platform cocos_source_files( - cocos/platform/Application.h - cocos/platform/Application.cpp - cocos/platform/CanvasRenderingContext2D.h - cocos/platform/Device.h cocos/platform/Image.cpp cocos/platform/Image.h cocos/platform/StdC.h @@ -543,11 +832,6 @@ endif() if(WINDOWS) cocos_source_files( - NO_WERROR cocos/platform/win32/Application-win32.cpp - NO_WERROR cocos/platform/win32/CanvasRenderingContext2D-win32.cpp - cocos/platform/win32/Device-win32.cpp - cocos/platform/win32/View-win32.cpp - cocos/platform/win32/View-win32.h cocos/platform/win32/compat cocos/platform/win32/compat/stdint.h cocos/platform/win32/inet_pton_mingw.cpp @@ -558,13 +842,6 @@ if(WINDOWS) cocos/platform/win32/FileUtils-win32.h ) elseif(ANDROID) - cocos_source_files( - cocos/platform/android/Application-android.cpp - cocos/platform/java/CanvasRenderingContext2D-java.cpp - cocos/platform/android/Device-android.cpp - cocos/platform/android/View.cpp - cocos/platform/android/View.h - ) set(CC_JNI_SRC_FILES ${CWD}/cocos/platform/android/jni/JniCocosActivity.cpp ${CWD}/cocos/platform/android/jni/JniCocosActivity.h @@ -576,6 +853,10 @@ elseif(ANDROID) ${CWD}/cocos/platform/java/jni/JniHelper.h ${CWD}/cocos/platform/java/jni/JniImp.cpp ${CWD}/cocos/platform/java/jni/JniImp.h + ${CWD}/cocos/platform/java/jni/glue/JniNativeGlue.cpp + ${CWD}/cocos/platform/java/jni/glue/JniNativeGlue.h + ${CWD}/cocos/platform/java/jni/glue/MessagePipe.cpp + ${CWD}/cocos/platform/java/jni/glue/MessagePipe.h ) cocos_source_files(MODULE ccfilesystem @@ -583,13 +864,6 @@ elseif(ANDROID) cocos/platform/android/FileUtils-android.h ) elseif(OHOS) - cocos_source_files( - cocos/platform/ohos/Application-ohos.cpp - cocos/platform/java/CanvasRenderingContext2D-java.cpp - cocos/platform/ohos/Device-ohos.cpp - cocos/platform/ohos/View.cpp - cocos/platform/ohos/View.h - ) set(CC_JNI_SRC_FILES ${CWD}/cocos/platform/ohos/jni/JniCocosAbility.cpp ${CWD}/cocos/platform/ohos/jni/JniCocosAbility.h @@ -601,6 +875,10 @@ elseif(OHOS) ${CWD}/cocos/platform/java/jni/JniCocosKeyCodeHandler.cpp ${CWD}/cocos/platform/java/jni/JniCocosOrientationHelper.cpp ${CWD}/cocos/platform/ohos/jni/AbilityConsts.h + ${CWD}/cocos/platform/java/jni/glue/JniNativeGlue.cpp + ${CWD}/cocos/platform/java/jni/glue/JniNativeGlue.h + ${CWD}/cocos/platform/java/jni/glue/MessagePipe.cpp + ${CWD}/cocos/platform/java/jni/glue/MessagePipe.h ) cocos_source_files(MODULE ccfilesystem cocos/platform/ohos/FileUtils-ohos.cpp @@ -608,14 +886,8 @@ elseif(OHOS) ) elseif(APPLE) cocos_source_files( - cocos/platform/apple/Device-apple.mm - cocos/platform/apple/CanvasRenderingContext2D-apple.mm - cocos/platform/apple/Device-apple.h - ) - # bad structure - cocos_source_files( - cocos/platform/ios/Reachability.h - cocos/platform/ios/Reachability.cpp + cocos/platform/apple/Reachability.h + cocos/platform/apple/Reachability.cpp ) cocos_source_files(MODULE ccfilesystem @@ -627,18 +899,24 @@ elseif(APPLE) cocos/platform/mac/View.h cocos/platform/mac/KeyCodeHelper.h cocos/platform/mac/View.mm - cocos/platform/mac/Device-mac.mm - cocos/platform/mac/Application-mac.mm cocos/platform/mac/KeyCodeHelper.cpp ) elseif(IOS) cocos_source_files( cocos/platform/ios/View.h NO_WERROR cocos/platform/ios/View.mm # CAMetalLayer bug for apple - NO_WERROR cocos/platform/ios/Application-ios.mm - NO_WERROR cocos/platform/ios/Device-ios.mm ) endif() +elseif(LINUX) + cocos_source_files(MODULE ccfilesystem + cocos/platform/linux/FileUtils-linux.cpp + cocos/platform/linux/FileUtils-linux.h + ) +elseif(QNX) + cocos_source_files(MODULE ccfilesystem + cocos/platform/qnx/FileUtils-qnx.cpp + cocos/platform/qnx/FileUtils-qnx.h + ) endif() ##### renderer @@ -1612,6 +1890,14 @@ elseif(WIN32) cocos_source_files( NO_WERROR cocos/bindings/manual/jsb_platfrom_win32.cpp ) +elseif(LINUX) + cocos_source_files( + NO_WERROR cocos/bindings/manual/jsb_platfrom_linux.cpp + ) +elseif(QNX) + cocos_source_files( + NO_WERROR cocos/bindings/manual/jsb_platfrom_qnx.cpp + ) endif() ############# module bindings @@ -1806,6 +2092,18 @@ elseif(WIN32) NO_WERROR cocos/ui/edit-box/EditBox-win32.cpp ) endif() +elseif(LINUX) + if(USE_EDIT_BOX) + cocos_source_files( + NO_WERROR cocos/ui/edit-box/EditBox-linux.cpp + ) + endif() +elseif(QNX) + if(USE_EDIT_BOX) + cocos_source_files( + NO_WERROR cocos/ui/edit-box/EditBox-linux.cpp + ) + endif() endif() ##### extensions @@ -2148,6 +2446,20 @@ if(APPLE) endif() +if(QNX) + target_link_libraries(cocos2d PUBLIC + socket + ssl + screen + ${CC_EXTERNAL_LIBS} + ) +elseif(LINUX) + target_link_libraries(cocos2d PUBLIC + X11 + ${CC_EXTERNAL_LIBS} + ) +endif() + source_group(TREE ${CWD} PREFIX "Source Files" FILES ${COCOS2D_SOURCE_LIST}) diff --git a/native/cmake/predefine.cmake b/native/cmake/predefine.cmake index fb7f8e3ba4..fe20c5ba74 100644 --- a/native/cmake/predefine.cmake +++ b/native/cmake/predefine.cmake @@ -4,6 +4,8 @@ set(CC_PLATFORM_WINDOWS 2) set(CC_PLATFORM_ANDROID 3) set(CC_PLATFORM_MAC_OSX 4) set(CC_PLATFORM_OHOS 5) +set(CC_PLATFORM_LINUX 6) +set(CC_PLATFORM_QNX 7) set(CC_PLATFORM 1) if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") @@ -19,11 +21,21 @@ elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") set(MACOSX TRUE) set(PLATFORM_FOLDER mac) set(CC_PLATFORM ${CC_PLATFORM_MAC_OSX}) +elseif(${CMAKE_SYSTEM_NAME} MATCHES "Linux") + set(LINUX TRUE) + set(PLATFORM_FOLDER linux) + set(CC_PLATFORM ${CC_PLATFORM_LINUX}) + add_definitions(-D__LINUX__=1) elseif(${CMAKE_SYSTEM_NAME} MATCHES "iOS") set(APPLE TRUE) set(IOS TRUE) set(PLATFORM_FOLDER ios) set(CC_PLATFORM ${CC_PLATFORM_MAC_IOS}) +elseif(${CMAKE_SYSTEM_NAME} MATCHES "QNX") + set(QNX TRUE) + set(PLATFORM_FOLDER qnx) + set(CC_PLATFORM ${CC_PLATFORM_QNX}) + add_definitions(-D__QNX__=1) elseif(OHOS) set(OHOS TRUE) set(CC_PLATFORM ${CC_PLATFORM_OHOS}) @@ -34,12 +46,16 @@ else() return() endif() +MESSAGE(STATUS "platform: ${CMAKE_SYSTEM_NAME}") + # platform macros add_definitions(-DCC_PLATFORM_WINDOWS=${CC_PLATFORM_WINDOWS}) add_definitions(-DCC_PLATFORM_MAC_OSX=${CC_PLATFORM_MAC_OSX}) add_definitions(-DCC_PLATFORM_MAC_IOS=${CC_PLATFORM_MAC_IOS}) add_definitions(-DCC_PLATFORM_ANDROID=${CC_PLATFORM_ANDROID}) add_definitions(-DCC_PLATFORM_OHOS=${CC_PLATFORM_OHOS}) +add_definitions(-DCC_PLATFORM_LINUX=${CC_PLATFORM_LINUX}) +add_definitions(-DCC_PLATFORM_QNX=${CC_PLATFORM_QNX}) add_definitions(-DCC_PLATFORM=${CC_PLATFORM}) include_directories(${CMAKE_CURRENT_LIST_DIR}/../external/sources) diff --git a/native/cocos/application/ApplicationManager.cpp b/native/cocos/application/ApplicationManager.cpp new file mode 100644 index 0000000000..c5a3425453 --- /dev/null +++ b/native/cocos/application/ApplicationManager.cpp @@ -0,0 +1,58 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "application/ApplicationManager.h" +#include "base/Macros.h" + +namespace cc { +// static +ApplicationManager* ApplicationManager::getInstance() { + static ApplicationManager mgr; + return &mgr; +} + +void ApplicationManager::releseAllApplications() { + _apps.clear(); +} + +ApplicationManager::ApplicationPtr ApplicationManager::getCurrentApp() const { + if (_currentApp.expired()) { + return nullptr; + } + return _currentApp.lock(); +} + +ApplicationManager::ApplicationPtr ApplicationManager::getCurrentAppSafe() const { + CC_ASSERT(!_currentApp.expired()); + return _currentApp.lock(); +} +} // namespace cc + +// +void cocos_destory() { // NOLINT(readability-identifier-naming) + // Called in the platform layer, because the platform layer is isolated from the application layer + // It is the platform layer to drive applications and reclaim resources. + cc::ApplicationManager::getInstance()->releseAllApplications(); +} \ No newline at end of file diff --git a/native/cocos/application/ApplicationManager.h b/native/cocos/application/ApplicationManager.h new file mode 100644 index 0000000000..6946e31f74 --- /dev/null +++ b/native/cocos/application/ApplicationManager.h @@ -0,0 +1,93 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include +#include + +#include "application/BaseApplication.h" + +namespace cc { +class ApplicationManager { +public: + static ApplicationManager* getInstance(); + + using ApplicationPtr = std::shared_ptr; + + /** + * @brief Generate application entry. + */ + template + std::enable_if_t::value, ApplicationPtr> + createApplication() { + ApplicationPtr app = std::make_shared(); + _apps.push_back(app); + _currentApp = app; + return app; + } + + /** + * @brief Release all generated applications. + */ + void releseAllApplications(); + /** + * @brief Get the current application, may get empty. + */ + ApplicationPtr getCurrentApp() const; + /** + * @brief Get the current application, make sure it is not empty. + * Used to get the engine. + */ + ApplicationPtr getCurrentAppSafe() const; + +private: + std::weak_ptr _currentApp; + std::vector _apps; +}; +} // namespace cc + +#define CC_APPLICATION_MANAGER() cc::ApplicationManager::getInstance() +#define CC_CURRENT_APPLICATION() CC_APPLICATION_MANAGER()->getCurrentApp() +#define CC_CURRENT_APPLICATION_SAFE() CC_APPLICATION_MANAGER()->getCurrentAppSafe() +#define CC_CURRENT_ENGINE() CC_CURRENT_APPLICATION_SAFE()->getEngine() +#define CC_GET_PLATFORM_INTERFACE(intf) CC_CURRENT_ENGINE()->getInterface() + +/** + * @brief Called at the user-defined main entry + */ +#define CC_START_APPLICATION(className) \ + do { \ + auto app = CC_APPLICATION_MANAGER()->createApplication(); \ + if (app->init()) { \ + return -1; \ + } \ + return app->run(argc, argv); \ + } while (0) + +#define CC_APPLICATION_MAIN(className) \ + int cocos_main(int argc, const char** argv) { \ + CC_START_APPLICATION(className); \ + } diff --git a/native/cocos/application/BaseApplication.h b/native/cocos/application/BaseApplication.h new file mode 100644 index 0000000000..8cbb2f1da8 --- /dev/null +++ b/native/cocos/application/BaseApplication.h @@ -0,0 +1,67 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include +#include "engine/BaseEngine.h" + +namespace cc { + +class BaseApplication { +public: + virtual ~BaseApplication() = default; + /** + * @brief Application initialization + */ + virtual int32_t init() = 0; + /** + * @brief Application main business logic. + */ + virtual int32_t run(int argc, + const char** argv) = 0; + /** + * @brief Pause the application. + */ + virtual void pause() = 0; + /** + * @brief Resume the application. + */ + virtual void resume() = 0; + /** + * @brief Restart the application. + */ + virtual void restart() = 0; + /** + * @brief Close the application. + */ + virtual void close() = 0; + /** + * @brief Get engine. + */ + virtual BaseEngine::Ptr getEngine() const = 0; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/application/CocosApplication.cpp b/native/cocos/application/CocosApplication.cpp new file mode 100644 index 0000000000..75c41ef9fe --- /dev/null +++ b/native/cocos/application/CocosApplication.cpp @@ -0,0 +1,160 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "application/CocosApplication.h" + +#include "base/Macros.h" + +#include "cocos/bindings/event/CustomEventTypes.h" +#include "cocos/bindings/event/EventDispatcher.h" +#include "cocos/bindings/jswrapper/SeApi.h" +#include "cocos/bindings/manual/jsb_classtype.h" +#include "cocos/bindings/manual/jsb_global.h" +#include "cocos/bindings/manual/jsb_module_register.h" +#include "cocos/engine/BaseEngine.h" +#include "cocos/platform/interfaces/modules/IScreen.h" + +namespace cc { + +//const char *kDefaultWindowTitle = "cocos application demo"; + +CocosApplication::CocosApplication() { + _engine = BaseEngine::createEngine(); + _systemWidow = _engine->getInterface(); + CCASSERT(_systemWidow != nullptr, "Invalid interface pointer"); +} + +CocosApplication::~CocosApplication() = default; + +int CocosApplication::init() { + if (_engine->init()) { + return -1; + } + auto callback = std::bind(&CocosApplication::handleAppEvent, this, std::placeholders::_1); // NOLINT(modernize-avoid-bind) + _engine->addEventCallback(OSEventType::APP_OSEVENT, callback); + + se::ScriptEngine *se = se::ScriptEngine::getInstance(); + + jsb_init_file_operation_delegate(); + + se->setExceptionCallback( + std::bind(&CocosApplication::handleException, this, // NOLINT(modernize-avoid-bind) + std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); + + jsb_register_all_modules(); + + se->start(); + +#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) + auto logicSize = _systemWidow->getViewSize(); + IScreen *screen = _engine->getInterface(); + float pixelRatio = screen->getDevicePixelRatio(); + cc::EventDispatcher::dispatchResizeEvent(logicSize.x * pixelRatio, logicSize.y * pixelRatio); +#endif + return 0; +} + +int32_t CocosApplication::run(int argc, const char **argv) { + CC_UNUSED_PARAM(argc); + CC_UNUSED_PARAM(argv); + return _engine->run(); +} + +void CocosApplication::pause() { + _engine->pause(); +} + +void CocosApplication::resume() { + _engine->resume(); +} + +void CocosApplication::restart() { + _engine->restart(); +} + +void CocosApplication::close() { + _engine->close(); +} + +BaseEngine::Ptr CocosApplication::getEngine() const { + return _engine; +} + +void CocosApplication::onPause() { + // TODO(cc): Handling pause events +} + +void CocosApplication::onResume() { + // TODO(cc): Handling resume events +} + +void CocosApplication::onClose() { + // TODO(cc): Handling close events +} + +void CocosApplication::setJsDebugIpAndPort(const std::string &serverAddr, uint32_t port, bool isWaitForConnect) { +#if defined(CC_DEBUG) && (CC_DEBUG > 0) + // Enable debugger here + jsb_enable_debugger(serverAddr, port, isWaitForConnect); +#endif +} + +void CocosApplication::runJsScript(const std::string &filePath) { + jsb_run_script(filePath); +} + +void CocosApplication::handleException(const char *location, const char *message, const char *stack) { + // Send exception information to server like Tencent Bugly. + CC_LOG_ERROR("\nUncaught Exception:\n - location : %s\n - msg : %s\n - detail : \n %s\n", location, message, stack); +} + +void CocosApplication::setXXTeaKey(const std::string &key) { + jsb_set_xxtea_key(key); +} + +void CocosApplication::createWindow(const char *title, + int32_t x, int32_t y, int32_t w, + int32_t h, int32_t flags) { + _systemWidow->createWindow(title, x, y, w, h, flags); +} + +void CocosApplication::handleAppEvent(const OSEvent &ev) { + const AppEvent &appEv = OSEvent::castEvent(ev); + switch (appEv.type) { + case AppEvent::Type::RESUME: + onResume(); + break; + case AppEvent::Type::PAUSE: + onPause(); + break; + case AppEvent::Type::CLOSE: + onClose(); + break; + default: + break; + } +} + +} // namespace cc diff --git a/native/cocos/application/CocosApplication.h b/native/cocos/application/CocosApplication.h new file mode 100644 index 0000000000..a70f46a2a2 --- /dev/null +++ b/native/cocos/application/CocosApplication.h @@ -0,0 +1,120 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include +#include "application/BaseApplication.h" +#include "cocos/platform/interfaces/modules/ISystemWindow.h" + +namespace cc { +class BaseEngine; + +class CocosApplication : public BaseApplication { +public: + CocosApplication(); + ~CocosApplication() override; + + /** + * @brief Application initialization. + */ + int32_t init() override; + /** + * @brief Application main business logic. + */ + int32_t run(int argc, const char** argv) override; + /** + * @brief Pause the application. + */ + void pause() override; + /** + * @brief Resume the application. + */ + void resume() override; + /** + * @brief Restart the application. + */ + void restart() override; + /** + * @brief Close the application. + */ + void close() override; + /** + * @brief Get engine. + */ + BaseEngine::Ptr getEngine() const override; + + /** + * @brief Processing pause events.. + */ + virtual void onPause(); + /** + * @brief Processing recovery events. + */ + virtual void onResume(); + /** + * @brief Processing close events. + */ + virtual void onClose(); + /** + * @brief Create window. + * @param title: Window title + * @param x: x-axis coordinate + * @param y: y-axis coordinate + * @param w: Window width + * @param h: Window height + * @param flags: Window flag + */ + virtual void createWindow(const char* title, + int32_t x, int32_t y, int32_t w, + int32_t h, int32_t flags); + /** + * @brief Set the js debugging server Addr and port + * @param serverAddr:Server address. + * @param port:Server port. + * @param isWaitForConnect:Is Wait for connect. + */ + virtual void setJsDebugIpAndPort(const std::string& serverAddr, uint32_t port, bool isWaitForConnect); + /** + * @brief Run the js code file + * @param filePath:Js file path. + */ + virtual void runJsScript(const std::string& filePath); + /** + * @brief Js exception handling + * @param location,Exception location + * @param message,Exception message + * @param stack,Exception stack + */ + virtual void handleException(const char* location, const char* message, const char* stack); + virtual void setXXTeaKey(const std::string& key); + +private: + void handleAppEvent(const OSEvent& ev); + + ISystemWindow* _systemWidow{nullptr}; + BaseEngine::Ptr _engine{nullptr}; +}; +} // namespace cc diff --git a/native/cocos/audio/AudioEngine.cpp b/native/cocos/audio/AudioEngine.cpp index 45440e2a31..e67c6a9efc 100644 --- a/native/cocos/audio/AudioEngine.cpp +++ b/native/cocos/audio/AudioEngine.cpp @@ -42,8 +42,8 @@ #include "audio/oalsoft/AudioEngine-soft.h" #elif CC_PLATFORM == CC_PLATFORM_WINRT #include "audio/winrt/AudioEngine-winrt.h" -#elif CC_PLATFORM == CC_PLATFORM_LINUX - #include "audio/linux/AudioEngine-linux.h" +#elif CC_PLATFORM == CC_PLATFORM_LINUX || CC_PLATFORM == CC_PLATFORM_QNX + #include "audio/oalsoft/AudioEngine-soft.h" #elif CC_PLATFORM == CC_PLATFORM_TIZEN #include "audio/tizen/AudioEngine-tizen.h" #endif @@ -84,13 +84,13 @@ AudioEngine::AudioInfo::AudioInfo() state(AudioState::INITIALIZING) { } -AudioEngine::AudioInfo::~AudioInfo() = default; - class AudioEngine::AudioEngineThreadPool { public: explicit AudioEngineThreadPool(int threads = 4) { for (int index = 0; index < threads; ++index) { - _workers.emplace_back(std::thread(std::bind(&AudioEngineThreadPool::threadFunc, this))); + _workers.emplace_back(std::thread([this](){ + threadFunc(); + })); } } @@ -204,7 +204,7 @@ int AudioEngine::play2d(const std::string &filePath, bool loop, float volume, co break; } - auto profileHelper = sDefaultProfileHelper; + auto* profileHelper = sDefaultProfileHelper; if (profile && profile != &profileHelper->profile) { CC_ASSERT(!profile->name.empty()); profileHelper = &sAudioPathProfileHelperMap[profile->name]; diff --git a/native/cocos/audio/android/AudioEngine-inl.cpp b/native/cocos/audio/android/AudioEngine-inl.cpp index be5fef56bc..40165c9ead 100644 --- a/native/cocos/audio/android/AudioEngine-inl.cpp +++ b/native/cocos/audio/android/AudioEngine-inl.cpp @@ -40,7 +40,7 @@ #include "base/Log.h" #include "base/Scheduler.h" #include "base/UTF8.h" -#include "platform/Application.h" +#include "application/ApplicationManager.h" #include "platform/android/FileUtils-android.h" #include "platform/java/jni/JniHelper.h" #include "platform/java/jni/JniImp.h" @@ -75,7 +75,7 @@ void getAudioInfo() { class CallerThreadUtils : public ICallerThreadUtils { public: void performFunctionInCallerThread(const std::function &func) override { - Application::getInstance()->getScheduler()->performFunctionInCocosThread(func); + CC_CURRENT_ENGINE()->getScheduler()->performFunctionInCocosThread(func); }; std::thread::id getCallerThreadId() override { @@ -102,7 +102,7 @@ static int fdGetter(const std::string &url, off_t *start, off_t *length) { *length = static_cast(lenV); } if (fd <= 0) { - auto asset = AAssetManager_open(cc::FileUtilsAndroid::getAssetManager(), url.c_str(), AASSET_MODE_UNKNOWN); + auto* asset = AAssetManager_open(cc::FileUtilsAndroid::getAssetManager(), url.c_str(), AASSET_MODE_UNKNOWN); // open asset as file descriptor fd = AAsset_openFileDescriptor(asset, start, length); AAsset_close(asset); @@ -211,7 +211,7 @@ int AudioEngineImpl::play2d(const std::string &filePath, bool loop, float volume audioId = _audioIDIndex++; - auto player = _audioPlayerProvider->getAudioPlayer(fullPath); + auto* player = _audioPlayerProvider->getAudioPlayer(fullPath); if (player != nullptr) { player->setId(audioId); _audioPlayers.insert(std::make_pair(audioId, player)); @@ -261,7 +261,7 @@ int AudioEngineImpl::play2d(const std::string &filePath, bool loop, float volume void AudioEngineImpl::setVolume(int audioID, float volume) { auto iter = _audioPlayers.find(audioID); if (iter != _audioPlayers.end()) { - auto player = iter->second; + auto* player = iter->second; player->setVolume(volume); } } @@ -269,7 +269,7 @@ void AudioEngineImpl::setVolume(int audioID, float volume) { void AudioEngineImpl::setLoop(int audioID, bool loop) { auto iter = _audioPlayers.find(audioID); if (iter != _audioPlayers.end()) { - auto player = iter->second; + auto* player = iter->second; player->setLoop(loop); } } @@ -277,7 +277,7 @@ void AudioEngineImpl::setLoop(int audioID, bool loop) { void AudioEngineImpl::pause(int audioID) { auto iter = _audioPlayers.find(audioID); if (iter != _audioPlayers.end()) { - auto player = iter->second; + auto* player = iter->second; player->pause(); } } @@ -285,7 +285,7 @@ void AudioEngineImpl::pause(int audioID) { void AudioEngineImpl::resume(int audioID) { auto iter = _audioPlayers.find(audioID); if (iter != _audioPlayers.end()) { - auto player = iter->second; + auto* player = iter->second; player->resume(); } } @@ -293,7 +293,7 @@ void AudioEngineImpl::resume(int audioID) { void AudioEngineImpl::stop(int audioID) { auto iter = _audioPlayers.find(audioID); if (iter != _audioPlayers.end()) { - auto player = iter->second; + auto* player = iter->second; player->stop(); } } @@ -313,7 +313,7 @@ void AudioEngineImpl::stopAll() { players.push_back(e.second); } - for (auto p : players) { + for (auto* p : players) { p->stop(); } } @@ -321,7 +321,7 @@ void AudioEngineImpl::stopAll() { float AudioEngineImpl::getDuration(int audioID) { auto iter = _audioPlayers.find(audioID); if (iter != _audioPlayers.end()) { - auto player = iter->second; + auto* player = iter->second; return player->getDuration(); } return 0.0F; @@ -338,7 +338,7 @@ float AudioEngineImpl::getDurationFromFile(const std::string &filePath) { float AudioEngineImpl::getCurrentTime(int audioID) { auto iter = _audioPlayers.find(audioID); if (iter != _audioPlayers.end()) { - auto player = iter->second; + auto* player = iter->second; return player->getPosition(); } return 0.0F; @@ -347,7 +347,7 @@ float AudioEngineImpl::getCurrentTime(int audioID) { bool AudioEngineImpl::setCurrentTime(int audioID, float time) { auto iter = _audioPlayers.find(audioID); if (iter != _audioPlayers.end()) { - auto player = iter->second; + auto* player = iter->second; return player->setPosition(time); } return false; diff --git a/native/cocos/audio/android/utils/Utils.cpp b/native/cocos/audio/android/utils/Utils.cpp index 12eede4d79..860f8e323d 100644 --- a/native/cocos/audio/android/utils/Utils.cpp +++ b/native/cocos/audio/android/utils/Utils.cpp @@ -23,13 +23,13 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "audio/android/utils/Utils.h" -#include "platform/android/jni/JniCocosActivity.h" +#include "platform/BasePlatform.h" #include namespace cc { int getSDKVersion() { - return cocosApp.sdkVersion; + return BasePlatform::getPlatform()->getSdkVersion(); } } // end of namespace cc diff --git a/native/cocos/audio/apple/AudioCache.mm b/native/cocos/audio/apple/AudioCache.mm index 86d8b1b8a5..a6aebd3579 100644 --- a/native/cocos/audio/apple/AudioCache.mm +++ b/native/cocos/audio/apple/AudioCache.mm @@ -31,7 +31,7 @@ #import #import #include -#include "platform/Application.h" +#include "application/ApplicationManager.h" #include "base/Scheduler.h" #include "audio/apple/AudioDecoder.h" @@ -337,7 +337,7 @@ void AudioCache::invokingLoadCallbacks() { } auto isDestroyed = _isDestroyed; - auto scheduler = Application::getInstance()->getScheduler(); + auto scheduler = CC_CURRENT_ENGINE()->getScheduler(); scheduler->performFunctionInCocosThread([&, isDestroyed]() { if (*isDestroyed) { ALOGV("invokingLoadCallbacks perform in cocos thread, AudioCache (%p) was destroyed!", this); diff --git a/native/cocos/audio/apple/AudioEngine-inl.mm b/native/cocos/audio/apple/AudioEngine-inl.mm index 658e9e3fef..57d5c57f15 100644 --- a/native/cocos/audio/apple/AudioEngine-inl.mm +++ b/native/cocos/audio/apple/AudioEngine-inl.mm @@ -35,7 +35,7 @@ #include "audio/include/AudioEngine.h" #include "platform/FileUtils.h" -#include "platform/Application.h" +#include "application/ApplicationManager.h" #include "base/Scheduler.h" #include "base/Utils.h" @@ -307,7 +307,7 @@ bool AudioEngineImpl::init() { // ================ Workaround end ================ // - _scheduler = Application::getInstance()->getScheduler(); + _scheduler = CC_CURRENT_ENGINE()->getScheduler(); ret = true; ALOGI("OpenAL was initialized successfully!"); } diff --git a/native/cocos/audio/include/AudioEngine.h b/native/cocos/audio/include/AudioEngine.h index 572ea91155..049eeb9a59 100644 --- a/native/cocos/audio/include/AudioEngine.h +++ b/native/cocos/audio/include/AudioEngine.h @@ -337,7 +337,7 @@ protected: AudioState state; AudioInfo(); - ~AudioInfo(); + ~AudioInfo() = default; private: AudioInfo(const AudioInfo &info); diff --git a/native/cocos/audio/oalsoft/AudioCache.cpp b/native/cocos/audio/oalsoft/AudioCache.cpp index 22e50cafd5..d94852b24f 100644 --- a/native/cocos/audio/oalsoft/AudioCache.cpp +++ b/native/cocos/audio/oalsoft/AudioCache.cpp @@ -27,13 +27,14 @@ #define LOG_TAG "AudioCache" #include "audio/oalsoft/AudioCache.h" +#include #include -#include "base/Scheduler.h" -#include "platform/Application.h" - +#include "application/ApplicationManager.h" #include "audio/oalsoft/AudioDecoder.h" #include "audio/oalsoft/AudioDecoderManager.h" +#include + #define VERY_VERY_VERBOSE_LOGGING #ifdef VERY_VERY_VERBOSE_LOGGING #define ALOGVV ALOGV @@ -317,7 +318,13 @@ void AudioCache::invokingLoadCallbacks() { } auto isDestroyed = _isDestroyed; - auto scheduler = Application::getInstance()->getScheduler(); + + BaseEngine::SchedulerPtr scheduler = + CC_CURRENT_APPLICATION() ? CC_CURRENT_APPLICATION()->getEngine()->getScheduler() : nullptr; + if (!scheduler) { + return; + } + scheduler->performFunctionInCocosThread([&, isDestroyed]() { if (*isDestroyed) { ALOGV("invokingLoadCallbacks perform in cocos thread, AudioCache (%p) was destroyed!", this); diff --git a/native/cocos/audio/oalsoft/AudioCache.h b/native/cocos/audio/oalsoft/AudioCache.h index 16eb0c52f6..e71be0bd5f 100644 --- a/native/cocos/audio/oalsoft/AudioCache.h +++ b/native/cocos/audio/oalsoft/AudioCache.h @@ -37,6 +37,8 @@ #include #elif CC_PLATFORM == CC_PLATFORM_OHOS #include +#elif CC_PLATFORM == CC_PLATFORM_LINUX || CC_PLATFORM == CC_PLATFORM_QNX + #include #endif #include "audio/oalsoft/AudioMacros.h" #include "base/Macros.h" diff --git a/native/cocos/audio/oalsoft/AudioDecoder.cpp b/native/cocos/audio/oalsoft/AudioDecoder.cpp index f2879f2822..6a9ff8754a 100644 --- a/native/cocos/audio/oalsoft/AudioDecoder.cpp +++ b/native/cocos/audio/oalsoft/AudioDecoder.cpp @@ -26,6 +26,7 @@ #include "audio/oalsoft/AudioDecoder.h" #include "audio/oalsoft/AudioMacros.h" #include "platform/FileUtils.h" +#include #ifdef LOG_TAG #undef LOG_TAG diff --git a/native/cocos/audio/oalsoft/AudioDecoder.h b/native/cocos/audio/oalsoft/AudioDecoder.h index 2db62b15e1..9a7d1fcf68 100644 --- a/native/cocos/audio/oalsoft/AudioDecoder.h +++ b/native/cocos/audio/oalsoft/AudioDecoder.h @@ -30,6 +30,8 @@ #if CC_PLATFORM == CC_PLATFORM_WINDOWS #include "vorbis/vorbisfile.h" +#elif CC_PLATFORM == CC_PLATFORM_LINUX || CC_PLATFORM == CC_PLATFORM_QNX + #include "vorbis/vorbisfile.h" #elif CC_PLATFORM == CC_PLATFORM_OHOS #include "ivorbisfile.h" #endif diff --git a/native/cocos/audio/oalsoft/AudioDecoderMp3.cpp b/native/cocos/audio/oalsoft/AudioDecoderMp3.cpp index 891a52e321..c3356485ee 100644 --- a/native/cocos/audio/oalsoft/AudioDecoderMp3.cpp +++ b/native/cocos/audio/oalsoft/AudioDecoderMp3.cpp @@ -27,7 +27,7 @@ #include "audio/oalsoft/AudioMacros.h" #include "platform/FileUtils.h" -#if CC_PLATFORM == CC_PLATFORM_WINDOWS +#if CC_PLATFORM == CC_PLATFORM_WINDOWS || CC_PLATFORM == CC_PLATFORM_LINUX || CC_PLATFORM == CC_PLATFORM_QNX #include "mpg123/mpg123.h" #elif CC_PLATFORM == CC_PLATFORM_OHOS #include "cocos/platform/ohos/FileUtils-ohos.h" diff --git a/native/cocos/audio/oalsoft/AudioDecoderOgg.cpp b/native/cocos/audio/oalsoft/AudioDecoderOgg.cpp index 546e9801b0..cdccdcd864 100644 --- a/native/cocos/audio/oalsoft/AudioDecoderOgg.cpp +++ b/native/cocos/audio/oalsoft/AudioDecoderOgg.cpp @@ -59,6 +59,8 @@ bool AudioDecoderOgg::open(const char *path) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(path); #if CC_PLATFORM == CC_PLATFORM_WINDOWS if (0 == ov_fopen(FileUtils::getInstance()->getSuitableFOpen(fullPath).c_str(), &_vf)) { +#elif CC_PLATFORM == CC_PLATFORM_LINUX || CC_PLATFORM == CC_PLATFORM_QNX + if (0 == ov_fopen(FileUtils::getInstance()->getSuitableFOpen(fullPath).c_str(), &_vf)) { #elif CC_PLATFORM == CC_PLATFORM_OHOS auto *fp = cc::ohosOpen(FileUtils::getInstance()->getSuitableFOpen(fullPath).c_str(), this); if (0 == ov_open_callbacks(fp, &_vf, nullptr, 0, ogg_callbacks)) { @@ -90,6 +92,8 @@ uint32_t AudioDecoderOgg::read(uint32_t framesToRead, char *pcmBuf) { #elif CC_PLATFORM == CC_PLATFORM_OHOS int bitstream = 0; auto bytesRead = ov_read(&_vf, pcmBuf, bytesToRead, &bitstream); +#elif CC_PLATFORM == CC_PLATFORM_LINUX || CC_PLATFORM == CC_PLATFORM_QNX + auto bytesRead = ov_read(&_vf, pcmBuf, bytesToRead, 0, 2, 1, ¤tSection); #endif return static_cast(bytesRead / _bytesPerFrame); } diff --git a/native/cocos/audio/oalsoft/AudioEngine-soft.cpp b/native/cocos/audio/oalsoft/AudioEngine-soft.cpp index 5cbb5dabf1..65b015cc97 100644 --- a/native/cocos/audio/oalsoft/AudioEngine-soft.cpp +++ b/native/cocos/audio/oalsoft/AudioEngine-soft.cpp @@ -36,11 +36,14 @@ #elif CC_PLATFORM == CC_PLATFORM_OHOS #include "AL/alc.h" #include "AL/alext.h" +#elif CC_PLATFORM == CC_PLATFORM_LINUX || CC_PLATFORM == CC_PLATFORM_QNX + #include "AL/alc.h" + #include "AL/alext.h" #endif #include "audio/include/AudioEngine.h" #include "audio/oalsoft/AudioDecoderManager.h" #include "base/Scheduler.h" -#include "platform/Application.h" +#include "application/ApplicationManager.h" #include "platform/FileUtils.h" #if CC_PLATFORM == CC_PLATFORM_WINDOWS @@ -161,7 +164,7 @@ bool AudioEngineImpl::init() { _alSourceUsed[src] = false; } - _scheduler = Application::getInstance()->getScheduler(); + _scheduler = CC_CURRENT_ENGINE()->getScheduler(); ret = AudioDecoderManager::init(); CC_LOG_DEBUG("OpenAL was initialized successfully!"); } diff --git a/native/cocos/audio/oalsoft/AudioPlayer.cpp b/native/cocos/audio/oalsoft/AudioPlayer.cpp index fbc8484307..ea735fedf2 100644 --- a/native/cocos/audio/oalsoft/AudioPlayer.cpp +++ b/native/cocos/audio/oalsoft/AudioPlayer.cpp @@ -33,6 +33,9 @@ #include "base/Log.h" +#include +#include + using namespace cc; //NOLINT namespace { diff --git a/native/cocos/audio/oalsoft/AudioPlayer.h b/native/cocos/audio/oalsoft/AudioPlayer.h index d9fbddf720..c01d5b06f0 100644 --- a/native/cocos/audio/oalsoft/AudioPlayer.h +++ b/native/cocos/audio/oalsoft/AudioPlayer.h @@ -37,6 +37,8 @@ #include #elif CC_PLATFORM == CC_PLATFORM_OHOS #include +#elif CC_PLATFORM == CC_PLATFORM_LINUX || CC_PLATFORM == CC_PLATFORM_QNX + #include #endif #include "base/Macros.h" diff --git a/native/cocos/base/CachedArray.h b/native/cocos/base/CachedArray.h index 9a470f2ac5..94b0e43abd 100755 --- a/native/cocos/base/CachedArray.h +++ b/native/cocos/base/CachedArray.h @@ -27,6 +27,8 @@ #include "base/Object.h" #include "base/TypeDef.h" +#include +#include namespace cc { diff --git a/native/cocos/base/Data.cpp b/native/cocos/base/Data.cpp index 27567aa6bd..9c2a78ed8b 100644 --- a/native/cocos/base/Data.cpp +++ b/native/cocos/base/Data.cpp @@ -27,6 +27,7 @@ #include "base/Data.h" #include "base/Log.h" +#include namespace cc { diff --git a/native/cocos/base/IndexHandle.h b/native/cocos/base/IndexHandle.h index ea03bbb7db..682b20bad8 100644 --- a/native/cocos/base/IndexHandle.h +++ b/native/cocos/base/IndexHandle.h @@ -35,7 +35,7 @@ template #include +#include +#include #if (CC_PLATFORM == CC_PLATFORM_WINDOWS) #ifndef WIN32_LEAN_AND_MEAN @@ -123,7 +125,7 @@ void Log::logMessage(LogType type, LogLevel level, const char *formats, ...) { va_start(args, formats); // p += StringUtil::vprintf(p, last, formats, args); - ptrdiff_t count = (last - p); + std::ptrdiff_t count = (last - p); int ret = vsnprintf(p, count, formats, args); if (ret >= count - 1) { p += (count - 1); diff --git a/native/cocos/base/Macros.h b/native/cocos/base/Macros.h index 559e8cbf50..360c62fbdc 100644 --- a/native/cocos/base/Macros.h +++ b/native/cocos/base/Macros.h @@ -300,7 +300,11 @@ It should work same as apples CFSwapInt32LittleToHost(..) #elif (CC_PLATFORM == CC_PLATFORM_MAC_IOS) #include #else + #if !defined(__QNX__) #include + #else + #define CC_ENDIAN CC_ENDIAN_LITTLE + #endif #endif // (CC_PLATFORM == CC_PLATFORM_MAC_OSX) # #if __BYTE_ORDER == __LITTLE_ENDIAN @@ -402,22 +406,26 @@ It should work same as apples CFSwapInt32LittleToHost(..) _Pragma("clang diagnostic pop") #endif -#define ENABLE_COPY_SEMANTICS(cls) \ +#define CC_ENABLE_COPY_SEMANTICS(cls) \ cls(const cls &) = default; \ cls &operator=(const cls &) = default; -#define DISABLE_COPY_SEMANTICS(cls) \ +#define CC_DISABLE_COPY_SEMANTICS(cls) \ cls(const cls &) = delete; \ cls &operator=(const cls &) = delete; -#define ENABLE_MOVE_SEMANTICS(cls) \ +#define CC_ENABLE_MOVE_SEMANTICS(cls) \ cls(cls &&) noexcept = default; \ cls &operator=(cls &&) noexcept = default; -#define DISABLE_MOVE_SEMANTICS(cls) \ +#define CC_DISABLE_MOVE_SEMANTICS(cls) \ cls(cls &&) noexcept = delete; \ cls &operator=(cls &&) noexcept = delete; +#define CC_DISABLE_COPY_AND_MOVE_SEMANTICS(cls) \ + CC_DISABLE_COPY_SEMANTICS(cls) \ + CC_DISABLE_MOVE_SEMANTICS(cls) + #if (CC_COMPILER == CC_COMPILER_MSVC) #define CC_ALIGN(N) __declspec(align(N)) #define CC_CACHE_ALIGN __declspec(align(CC_CACHELINE_SIZE)) diff --git a/native/cocos/base/Random.h b/native/cocos/base/Random.h index 22d07ab3b5..5019bdcaa5 100644 --- a/native/cocos/base/Random.h +++ b/native/cocos/base/Random.h @@ -89,7 +89,7 @@ inline double random(double min, double max) { * Returns a random int between 0 and RAND_MAX. */ inline int random() { - return cc::random(0, RAND_MAX); + return cc::random(0, static_cast(RAND_MAX)); }; /** diff --git a/native/cocos/base/Scheduler.cpp b/native/cocos/base/Scheduler.cpp index 3cea32030f..1d945ca0be 100644 --- a/native/cocos/base/Scheduler.cpp +++ b/native/cocos/base/Scheduler.cpp @@ -34,6 +34,7 @@ #include "base/Macros.h" #include "base/Log.h" +#include namespace { constexpr unsigned CC_REPEAT_FOREVER{UINT_MAX - 1}; diff --git a/native/cocos/base/StringUtil.cpp b/native/cocos/base/StringUtil.cpp index 14442a554e..c7bd037224 100755 --- a/native/cocos/base/StringUtil.cpp +++ b/native/cocos/base/StringUtil.cpp @@ -26,6 +26,7 @@ #include "StringUtil.h" #include "memory/Memory.h" #include +#include #if (CC_PLATFORM == CC_PLATFORM_WINDOWS) #ifndef WIN32_LEAN_AND_MEAN @@ -58,7 +59,7 @@ int StringUtil::vprintf(char *buf, const char *last, const char *fmt, va_list ar return 0; } - int count = (int)(last - buf); + int count = static_cast(last - buf); int ret = vsnprintf(buf, count, fmt, args); if (ret >= count - 1) { return count - 1; diff --git a/native/cocos/base/StringUtil.h b/native/cocos/base/StringUtil.h index 3fd93531c4..b4d356452e 100755 --- a/native/cocos/base/StringUtil.h +++ b/native/cocos/base/StringUtil.h @@ -28,6 +28,7 @@ #include "Macros.h" #include "TypeDef.h" #include "memory/Memory.h" +#include namespace cc { diff --git a/native/cocos/base/TypeDef.h b/native/cocos/base/TypeDef.h index 5962e838db..59a6c8b9c9 100755 --- a/native/cocos/base/TypeDef.h +++ b/native/cocos/base/TypeDef.h @@ -27,10 +27,14 @@ #include -using uint = uint32_t; -using ushort = uint16_t; -using ulong = uint32_t; -using FlagBits = uint32_t; + +using uint = std::uint32_t; +using ushort = std::uint16_t; + +#if (CC_PLATFORM != CC_PLATFORM_LINUX && CC_PLATFORM != CC_PLATFORM_QNX) // linux has typedef ulong +using ulong = std::uint32_t; +#endif +using FlagBits = std::uint32_t; #define CC_ENUM_CONVERSION_OPERATOR(T) \ inline std::underlying_type::type toNumber(const T v) { return static_cast::type>(v); } diff --git a/native/cocos/base/Utils.cpp b/native/cocos/base/Utils.cpp index a52f8e75c7..5adc5e1c67 100644 --- a/native/cocos/base/Utils.cpp +++ b/native/cocos/base/Utils.cpp @@ -36,6 +36,7 @@ #include #include +#include #define BOOST_STACKTRACE_GNU_SOURCE_NOT_REQUIRED #include "boost/stacktrace.hpp" diff --git a/native/cocos/base/Utils.h b/native/cocos/base/Utils.h index cfc0abc9ae..7f3d948309 100644 --- a/native/cocos/base/Utils.h +++ b/native/cocos/base/Utils.h @@ -30,6 +30,8 @@ #include #include #include +#include +#include #include "base/Macros.h" #include "base/TypeDef.h" /** @file ccUtils.h diff --git a/native/cocos/base/Value.cpp b/native/cocos/base/Value.cpp index 11f2a18984..e0182f410b 100644 --- a/native/cocos/base/Value.cpp +++ b/native/cocos/base/Value.cpp @@ -32,14 +32,15 @@ #include #include #include +#include #include "base/Utils.h" namespace cc { const ValueVector VALUE_VECTOR_NULL; -const ValueMap VALUE_MAP_NULL; -const ValueMapIntKey VALUE_MAP_INT_KEY_NULL; +const ValueMap VALUE_MAP_NULL = {}; +const ValueMapIntKey VALUE_MAP_INT_KEY_NULL = {}; const Value Value::VALUE_NULL; @@ -128,7 +129,7 @@ Value::Value(ValueMapIntKey &&v) *_field.intKeyMapVal = std::move(v); } -Value::Value(const Value &other) +Value::Value(const Value &other) //NOLINT(misc-no-recursion) : _type(Type::NONE) { *this = other; } @@ -142,7 +143,7 @@ Value::~Value() { clear(); } -Value &Value::operator=(const Value &other) { +Value &Value::operator=(const Value &other) { //NOLINT(misc-no-recursion) if (this != &other) { reset(other._type); @@ -329,7 +330,7 @@ Value &Value::operator=(ValueMapIntKey &&v) { bool Value::operator!=(const Value &v) { return !(*this == v); } -bool Value::operator!=(const Value &v) const { +bool Value::operator!=(const Value &v) const { //NOLINT(misc-no-recursion) return !(*this == v); } @@ -337,7 +338,7 @@ bool Value::operator==(const Value &v) { const auto &t = *this; return t == v; } -bool Value::operator==(const Value &v) const { +bool Value::operator==(const Value &v) const { //NOLINT(misc-no-recursion) if (this == &v) { return true; } @@ -375,7 +376,7 @@ bool Value::operator==(const Value &v) const { case Type::MAP: { const auto &map1 = *(this->_field.mapVal); const auto &map2 = *(v._field.mapVal); - for (const auto &kvp : map1) { + for (const auto &kvp : map1) { //NOLINT auto it = map2.find(kvp.first); if (it == map2.end() || it->second != kvp.second) { return false; @@ -386,7 +387,7 @@ bool Value::operator==(const Value &v) const { case Type::INT_KEY_MAP: { const auto &map1 = *(this->_field.intKeyMapVal); const auto &map2 = *(v._field.intKeyMapVal); - for (const auto &kvp : map1) { + for (const auto &kvp : map1) { //NOLINT auto it = map2.find(kvp.first); if (it == map2.end() || it->second != kvp.second) { return false; @@ -444,7 +445,7 @@ int Value::asInt() const { if (_type == Type::UNSIGNED) { CCASSERT(_field.unsignedVal < INT_MAX, "Can only convert values < INT_MAX"); - return (int)_field.unsignedVal; + return static_cast(_field.unsignedVal); } if (_type == Type::BYTE) { @@ -499,10 +500,10 @@ unsigned int Value::asUnsignedInt() const { } if (_type == Type::BOOLEAN) { - return _field.boolVal ? 1u : 0u; + return _field.boolVal ? 1U : 0U; } - return 0u; + return 0U; } float Value::asFloat() const { @@ -532,10 +533,10 @@ float Value::asFloat() const { } if (_type == Type::BOOLEAN) { - return _field.boolVal ? 1.0f : 0.0f; + return _field.boolVal ? 1.0F : 0.0F; } - return 0.0f; + return 0.0F; } double Value::asDouble() const { @@ -594,7 +595,7 @@ bool Value::asBool() const { } if (_type == Type::FLOAT) { - return _field.floatVal != 0.0f; + return _field.floatVal != 0.0F; } if (_type == Type::DOUBLE) { @@ -680,7 +681,7 @@ static std::string getTabs(int depth) { static std::string visit(const Value &v, int depth); -static std::string visitVector(const ValueVector &v, int depth) { +static std::string visitVector(const ValueVector &v, int depth) { //NOLINT[misc-no-recursion] std::stringstream ret; if (depth > 0) { @@ -701,7 +702,7 @@ static std::string visitVector(const ValueVector &v, int depth) { } template -static std::string visitMap(const T &v, int depth) { +static std::string visitMap(const T &v, int depth) { //NOLINT[misc-no-recursion] std::stringstream ret; if (depth > 0) { @@ -720,7 +721,7 @@ static std::string visitMap(const T &v, int depth) { return ret.str(); } -static std::string visit(const Value &v, int depth) { +static std::string visit(const Value &v, int depth) { //NOLINT[misc-no-recursion] std::stringstream ret; switch (v.getType()) { @@ -767,10 +768,10 @@ void Value::clear() { _field.intVal = 0; break; case Type::UNSIGNED: - _field.unsignedVal = 0u; + _field.unsignedVal = 0U; break; case Type::FLOAT: - _field.floatVal = 0.0f; + _field.floatVal = 0.0F; break; case Type::DOUBLE: _field.doubleVal = 0.0; diff --git a/native/cocos/base/memory/AllocatedObj.h b/native/cocos/base/memory/AllocatedObj.h index d0d4c39f4d..3695ee5ef4 100755 --- a/native/cocos/base/memory/AllocatedObj.h +++ b/native/cocos/base/memory/AllocatedObj.h @@ -27,6 +27,7 @@ THE SOFTWARE. #pragma once #include "../Macros.h" +#include // Anything that has done a #define new will screw operator new definitions up // so undefine diff --git a/native/cocos/base/threading/ConditionVariable.h b/native/cocos/base/threading/ConditionVariable.h index e2515a940c..133a16d1b0 100644 --- a/native/cocos/base/threading/ConditionVariable.h +++ b/native/cocos/base/threading/ConditionVariable.h @@ -28,6 +28,7 @@ #include #include #include +#include namespace cc { diff --git a/native/cocos/bindings/auto/jsb_cocos_auto.cpp b/native/cocos/bindings/auto/jsb_cocos_auto.cpp index 3354c5b4fc..22cf87b8fb 100644 --- a/native/cocos/bindings/auto/jsb_cocos_auto.cpp +++ b/native/cocos/bindings/auto/jsb_cocos_auto.cpp @@ -1,9 +1,11 @@ #include "cocos/bindings/auto/jsb_cocos_auto.h" #include "cocos/bindings/manual/jsb_conversions.h" #include "cocos/bindings/manual/jsb_global.h" + +#include "cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.h" + #include "platform/FileUtils.h" -#include "platform/CanvasRenderingContext2D.h" -#include "platform/Device.h" +#include "platform/interfaces/modules/Device.h" #include "platform/SAXParser.h" #ifndef JSB_ALLOC @@ -882,7 +884,7 @@ se::Class* __jsb_cc_CanvasGradient_class = nullptr; static bool js_engine_CanvasGradient_addColorStop(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasGradient_addColorStop : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -905,7 +907,7 @@ SE_DECLARE_FINALIZE_FUNC(js_cc_CanvasGradient_finalize) static bool js_engine_CanvasGradient_constructor(se::State& s) // NOLINT(readability-identifier-naming) constructor.c { - cc::CanvasGradient* cobj = JSB_ALLOC(cc::CanvasGradient); + cc::ICanvasGradient* cobj = JSB_ALLOC(cc::CanvasGradient); s.thisObject()->setPrivateData(cobj); se::NonRefNativePtrCreatedByCtorMap::emplace(cobj); return true; @@ -916,11 +918,11 @@ SE_BIND_CTOR(js_engine_CanvasGradient_constructor, __jsb_cc_CanvasGradient_class static bool js_cc_CanvasGradient_finalize(se::State& s) // NOLINT(readability-identifier-naming) { - auto iter = se::NonRefNativePtrCreatedByCtorMap::find(SE_THIS_OBJECT(s)); + auto iter = se::NonRefNativePtrCreatedByCtorMap::find(SE_THIS_OBJECT(s)); if (iter != se::NonRefNativePtrCreatedByCtorMap::end()) { se::NonRefNativePtrCreatedByCtorMap::erase(iter); - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); JSB_FREE(cobj); } return true; @@ -934,7 +936,7 @@ bool js_register_engine_CanvasGradient(se::Object* obj) // NOLINT(readability-id cls->defineFunction("addColorStop", _SE(js_engine_CanvasGradient_addColorStop)); cls->defineFinalizeFunction(_SE(js_cc_CanvasGradient_finalize)); cls->install(); - JSBClassType::registerClass(cls); + JSBClassType::registerClass(cls); __jsb_cc_CanvasGradient_proto = cls->getProto(); __jsb_cc_CanvasGradient_class = cls; @@ -947,7 +949,7 @@ se::Class* __jsb_cc_CanvasRenderingContext2D_class = nullptr; static bool js_engine_CanvasRenderingContext2D_beginPath(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_beginPath : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -962,7 +964,7 @@ SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_beginPath) static bool js_engine_CanvasRenderingContext2D_clearRect(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_clearRect : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -987,7 +989,7 @@ SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_clearRect) static bool js_engine_CanvasRenderingContext2D_closePath(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_closePath : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1002,7 +1004,7 @@ SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_closePath) static bool js_engine_CanvasRenderingContext2D_createLinearGradient(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_createLinearGradient : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1017,7 +1019,7 @@ static bool js_engine_CanvasRenderingContext2D_createLinearGradient(se::State& s ok &= sevalue_to_native(args[2], &arg2, s.thisObject()); ok &= sevalue_to_native(args[3], &arg3, s.thisObject()); SE_PRECONDITION2(ok, false, "js_engine_CanvasRenderingContext2D_createLinearGradient : Error processing arguments"); - cc::CanvasGradient* result = cobj->createLinearGradient(arg0.value(), arg1.value(), arg2.value(), arg3.value()); + cc::ICanvasGradient* result = cobj->createLinearGradient(arg0.value(), arg1.value(), arg2.value(), arg3.value()); ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); SE_PRECONDITION2(ok, false, "js_engine_CanvasRenderingContext2D_createLinearGradient : Error processing arguments"); SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); @@ -1030,7 +1032,7 @@ SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_createLinearGradient) static bool js_engine_CanvasRenderingContext2D_fill(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_fill : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1045,7 +1047,7 @@ SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_fill) static bool js_engine_CanvasRenderingContext2D_fillImageData(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_fillImageData : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1072,7 +1074,7 @@ SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_fillImageData) static bool js_engine_CanvasRenderingContext2D_lineTo(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_lineTo : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1093,7 +1095,7 @@ SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_lineTo) static bool js_engine_CanvasRenderingContext2D_moveTo(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_moveTo : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1114,7 +1116,7 @@ SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_moveTo) static bool js_engine_CanvasRenderingContext2D_rect(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_rect : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1139,7 +1141,7 @@ SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_rect) static bool js_engine_CanvasRenderingContext2D_restore(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_restore : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1154,7 +1156,7 @@ SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_restore) static bool js_engine_CanvasRenderingContext2D_rotate(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_rotate : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1173,7 +1175,7 @@ SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_rotate) static bool js_engine_CanvasRenderingContext2D_save(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_save : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1188,7 +1190,7 @@ SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_save) static bool js_engine_CanvasRenderingContext2D_scale(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_scale : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1209,7 +1211,7 @@ SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_scale) static bool js_engine_CanvasRenderingContext2D_setFillStyle(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_setFillStyle : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1228,7 +1230,7 @@ SE_BIND_PROP_SET(js_engine_CanvasRenderingContext2D_setFillStyle) static bool js_engine_CanvasRenderingContext2D_setFont(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_setFont : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1247,7 +1249,7 @@ SE_BIND_PROP_SET(js_engine_CanvasRenderingContext2D_setFont) static bool js_engine_CanvasRenderingContext2D_setGlobalCompositeOperation(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_setGlobalCompositeOperation : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1266,7 +1268,7 @@ SE_BIND_PROP_SET(js_engine_CanvasRenderingContext2D_setGlobalCompositeOperation) static bool js_engine_CanvasRenderingContext2D_setHeight(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_setHeight : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1285,7 +1287,7 @@ SE_BIND_PROP_SET(js_engine_CanvasRenderingContext2D_setHeight) static bool js_engine_CanvasRenderingContext2D_setLineCap(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_setLineCap : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1304,7 +1306,7 @@ SE_BIND_PROP_SET(js_engine_CanvasRenderingContext2D_setLineCap) static bool js_engine_CanvasRenderingContext2D_setLineJoin(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_setLineJoin : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1323,7 +1325,7 @@ SE_BIND_PROP_SET(js_engine_CanvasRenderingContext2D_setLineJoin) static bool js_engine_CanvasRenderingContext2D_setLineWidth(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_setLineWidth : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1342,7 +1344,7 @@ SE_BIND_PROP_SET(js_engine_CanvasRenderingContext2D_setLineWidth) static bool js_engine_CanvasRenderingContext2D_setStrokeStyle(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_setStrokeStyle : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1361,7 +1363,7 @@ SE_BIND_PROP_SET(js_engine_CanvasRenderingContext2D_setStrokeStyle) static bool js_engine_CanvasRenderingContext2D_setTextAlign(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_setTextAlign : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1380,7 +1382,7 @@ SE_BIND_PROP_SET(js_engine_CanvasRenderingContext2D_setTextAlign) static bool js_engine_CanvasRenderingContext2D_setTextBaseline(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_setTextBaseline : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1399,7 +1401,7 @@ SE_BIND_PROP_SET(js_engine_CanvasRenderingContext2D_setTextBaseline) static bool js_engine_CanvasRenderingContext2D_setTransform(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_setTransform : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1428,7 +1430,7 @@ SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_setTransform) static bool js_engine_CanvasRenderingContext2D_setWidth(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_setWidth : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1447,7 +1449,7 @@ SE_BIND_PROP_SET(js_engine_CanvasRenderingContext2D_setWidth) static bool js_engine_CanvasRenderingContext2D_stroke(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_stroke : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1462,7 +1464,7 @@ SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_stroke) static bool js_engine_CanvasRenderingContext2D_transform(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_transform : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1491,7 +1493,7 @@ SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_transform) static bool js_engine_CanvasRenderingContext2D_translate(se::State& s) // NOLINT(readability-identifier-naming) { - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_translate : Invalid Native Object"); const auto& args = s.args(); size_t argc = args.size(); @@ -1521,7 +1523,7 @@ static bool js_engine_CanvasRenderingContext2D_constructor(se::State& s) // NOLI ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); ok &= sevalue_to_native(args[1], &arg1, s.thisObject()); SE_PRECONDITION2(ok, false, "js_engine_CanvasRenderingContext2D_constructor : Error processing arguments"); - cc::CanvasRenderingContext2D* cobj = JSB_ALLOC(cc::CanvasRenderingContext2D, arg0, arg1); + cc::ICanvasRenderingContext2D* cobj = JSB_ALLOC(cc::CanvasRenderingContext2D, arg0, arg1); s.thisObject()->setPrivateData(cobj); se::NonRefNativePtrCreatedByCtorMap::emplace(cobj); return true; @@ -1532,11 +1534,11 @@ SE_BIND_CTOR(js_engine_CanvasRenderingContext2D_constructor, __jsb_cc_CanvasRend static bool js_cc_CanvasRenderingContext2D_finalize(se::State& s) // NOLINT(readability-identifier-naming) { - auto iter = se::NonRefNativePtrCreatedByCtorMap::find(SE_THIS_OBJECT(s)); + auto iter = se::NonRefNativePtrCreatedByCtorMap::find(SE_THIS_OBJECT(s)); if (iter != se::NonRefNativePtrCreatedByCtorMap::end()) { se::NonRefNativePtrCreatedByCtorMap::erase(iter); - auto* cobj = SE_THIS_OBJECT(s); + auto* cobj = SE_THIS_OBJECT(s); JSB_FREE(cobj); } return true; @@ -1577,7 +1579,7 @@ bool js_register_engine_CanvasRenderingContext2D(se::Object* obj) // NOLINT(read cls->defineFunction("translate", _SE(js_engine_CanvasRenderingContext2D_translate)); cls->defineFinalizeFunction(_SE(js_cc_CanvasRenderingContext2D_finalize)); cls->install(); - JSBClassType::registerClass(cls); + JSBClassType::registerClass(cls); __jsb_cc_CanvasRenderingContext2D_proto = cls->getProto(); __jsb_cc_CanvasRenderingContext2D_class = cls; diff --git a/native/cocos/bindings/auto/jsb_cocos_auto.h b/native/cocos/bindings/auto/jsb_cocos_auto.h index 66a55ee430..7cce4f0eaa 100644 --- a/native/cocos/bindings/auto/jsb_cocos_auto.h +++ b/native/cocos/bindings/auto/jsb_cocos_auto.h @@ -4,8 +4,8 @@ #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_conversions.h" #include "cocos/platform/FileUtils.h" -#include "cocos/platform/CanvasRenderingContext2D.h" -#include "cocos/platform/Device.h" +#include "cocos/platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h" +#include "cocos/platform/interfaces/modules/Device.h" #include "cocos/platform/SAXParser.h" extern se::Object* __jsb_cc_FileUtils_proto; @@ -58,7 +58,7 @@ extern se::Class* __jsb_cc_CanvasGradient_class; bool js_register_cc_CanvasGradient(se::Object* obj); bool register_all_engine(se::Object* obj); -JSB_REGISTER_OBJECT_TYPE(cc::CanvasGradient); +JSB_REGISTER_OBJECT_TYPE(cc::ICanvasGradient); SE_DECLARE_FUNC(js_engine_CanvasGradient_addColorStop); SE_DECLARE_FUNC(js_engine_CanvasGradient_CanvasGradient); @@ -68,7 +68,7 @@ extern se::Class* __jsb_cc_CanvasRenderingContext2D_class; bool js_register_cc_CanvasRenderingContext2D(se::Object* obj); bool register_all_engine(se::Object* obj); -JSB_REGISTER_OBJECT_TYPE(cc::CanvasRenderingContext2D); +JSB_REGISTER_OBJECT_TYPE(cc::ICanvasRenderingContext2D); SE_DECLARE_FUNC(js_engine_CanvasRenderingContext2D_beginPath); SE_DECLARE_FUNC(js_engine_CanvasRenderingContext2D_clearRect); SE_DECLARE_FUNC(js_engine_CanvasRenderingContext2D_closePath); diff --git a/native/cocos/bindings/event/EventDispatcher.cpp b/native/cocos/bindings/event/EventDispatcher.cpp index 352ecda6f4..768d802a6b 100644 --- a/native/cocos/bindings/event/EventDispatcher.cpp +++ b/native/cocos/bindings/event/EventDispatcher.cpp @@ -94,7 +94,7 @@ void EventDispatcher::destroy() { tickVal.setUndefined(); } -void EventDispatcher::dispatchTouchEvent(const struct TouchEvent &touchEvent) { +void EventDispatcher::dispatchTouchEvent(const TouchEvent &touchEvent) { se::AutoHandleScope scope; if (!jsTouchObjArray) { jsTouchObjArray = se::Object::createArrayObject(0); @@ -147,7 +147,7 @@ void EventDispatcher::dispatchTouchEvent(const struct TouchEvent &touchEvent) { EventDispatcher::doDispatchEvent(nullptr, eventName, args); } -void EventDispatcher::dispatchMouseEvent(const struct MouseEvent &mouseEvent) { +void EventDispatcher::dispatchMouseEvent(const MouseEvent &mouseEvent) { se::AutoHandleScope scope; if (!jsMouseEventObj) { jsMouseEventObj = se::Object::createPlainObject(); @@ -198,7 +198,7 @@ void EventDispatcher::dispatchMouseEvent(const struct MouseEvent &mouseEvent) { EventDispatcher::doDispatchEvent(eventName, jsFunctionName, args); } -void EventDispatcher::dispatchKeyboardEvent(const struct KeyboardEvent &keyboardEvent) { +void EventDispatcher::dispatchKeyboardEvent(const KeyboardEvent &keyboardEvent) { se::AutoHandleScope scope; if (!jsKeyboardEventObj) { jsKeyboardEventObj = se::Object::createPlainObject(); diff --git a/native/cocos/bindings/event/EventDispatcher.h b/native/cocos/bindings/event/EventDispatcher.h index 9b7ef2f0d3..ff9f0c5394 100644 --- a/native/cocos/bindings/event/EventDispatcher.h +++ b/native/cocos/bindings/event/EventDispatcher.h @@ -36,9 +36,73 @@ class Value; namespace cc { +enum class OSEventType { + KEYBOARD_OSEVENT = 0, + TOUCH_OSEVENT = 1, + MOUSE_OSEVENT = 2, + CUSTOM_OSEVENT = 3, + DEVICE_OSEVENT = 4, + WINDOW_OSEVENT = 5, + APP_OSEVENT = 6, + UNKNOWN_OSEVENT = 7 +}; + +class OSEvent { +public: + explicit OSEvent(OSEventType type) : _type(type) {} + + template + std::enable_if_t::value, const T &> + static castEvent(const cc::OSEvent &ev) { + const T &evDetail = dynamic_cast(ev); + return std::move(evDetail); + } + + virtual OSEventType eventType() const { + return _type; + } + +private: + OSEventType _type = OSEventType::UNKNOWN_OSEVENT; +}; + +#define CONSTRUCT_EVENT(name, type) name() : OSEvent(type) {} + +class AppEvent : public OSEvent { +public: + CONSTRUCT_EVENT(AppEvent, OSEventType::APP_OSEVENT) + enum class Type { + RUN = 0, + PAUSE, + RESUME, + CLOSE, + UNKNOWN, + }; + Type type = Type::UNKNOWN; +}; + +class WindowEvent : public OSEvent { +public: + CONSTRUCT_EVENT(WindowEvent, OSEventType::WINDOW_OSEVENT) + enum class Type { + QUIT = 0, + SHOW, + RESTORED, + SIZE_CHANGED, + RESIZED, + HIDDEN, + MINIMIZED, + CLOSE, + UNKNOWN, + }; + Type type = Type::UNKNOWN; + int width = 0; + int height = 0; +}; // Touch event related -struct TouchInfo { +class TouchInfo { +public: float x = 0; float y = 0; int index = 0; @@ -49,7 +113,9 @@ struct TouchInfo { index(index) {} }; -struct TouchEvent { +class TouchEvent : public OSEvent { +public: + CONSTRUCT_EVENT(TouchEvent, OSEventType::TOUCH_OSEVENT) enum class Type { BEGAN, MOVED, @@ -62,7 +128,9 @@ struct TouchEvent { Type type = Type::UNKNOWN; }; -struct MouseEvent { +class MouseEvent : public OSEvent { +public: + CONSTRUCT_EVENT(MouseEvent, OSEventType::MOUSE_OSEVENT) enum class Type { DOWN, UP, @@ -138,7 +206,9 @@ enum class KeyCode { NUMPAD_9 = 10057 }; -struct KeyboardEvent { +class KeyboardEvent : public OSEvent { +public: + CONSTRUCT_EVENT(KeyboardEvent, OSEventType::KEYBOARD_OSEVENT) enum class Action { PRESS, RELEASE, @@ -155,8 +225,9 @@ struct KeyboardEvent { // TODO(mingo): support caps lock? }; -class CustomEvent { +class CustomEvent : public OSEvent { public: + CONSTRUCT_EVENT(CustomEvent, OSEventType::CUSTOM_OSEVENT) std::string name; union { void * ptrVal; @@ -167,19 +238,37 @@ public: bool boolVal; } args[10]; - CustomEvent() = default; virtual ~CustomEvent() = default; }; +class DeviceEvent : public OSEvent { +public: + CONSTRUCT_EVENT(DeviceEvent, OSEventType::DEVICE_OSEVENT) + enum class Type { + DEVICE_MEMORY, + DEVICE_ORIENTATION, + UNKNOWN + }; + union { + void * ptrVal; + int32_t longVal; + int intVal; + int16_t shortVal; + char charVal; + bool boolVal; + } args[3]; + Type type = Type::DEVICE_MEMORY; +}; + class EventDispatcher { public: static void init(); static void destroy(); static bool initialized(); - static void dispatchTouchEvent(const struct TouchEvent &touchEvent); - static void dispatchMouseEvent(const struct MouseEvent &mouseEvent); - static void dispatchKeyboardEvent(const struct KeyboardEvent &keyboardEvent); + static void dispatchTouchEvent(const TouchEvent &touchEvent); + static void dispatchMouseEvent(const MouseEvent &mouseEvent); + static void dispatchKeyboardEvent(const KeyboardEvent &keyboardEvent); static void dispatchTickEvent(float dt); static void dispatchResizeEvent(int width, int height); static void dispatchOrientationChangeEvent(int orientation); diff --git a/native/cocos/bindings/jswrapper/v8/HelperMacros.h b/native/cocos/bindings/jswrapper/v8/HelperMacros.h index 6376c463c6..df047ae248 100644 --- a/native/cocos/bindings/jswrapper/v8/HelperMacros.h +++ b/native/cocos/bindings/jswrapper/v8/HelperMacros.h @@ -32,6 +32,8 @@ #include #include #include +#include +#include #include "../config.h" #include "base/Log.h" diff --git a/native/cocos/bindings/manual/JavaScriptJavaBridge.cpp b/native/cocos/bindings/manual/JavaScriptJavaBridge.cpp index 40bde75041..cd7c7fd79b 100644 --- a/native/cocos/bindings/manual/JavaScriptJavaBridge.cpp +++ b/native/cocos/bindings/manual/JavaScriptJavaBridge.cpp @@ -26,8 +26,7 @@ #include "cocos/bindings/manual/JavaScriptJavaBridge.h" #include "cocos/base/UTF8.h" #include "cocos/bindings/manual/jsb_conversions.h" -#include - +#include "cocos/application/ApplicationManager.h" #if CC_PLATFORM == CC_PLATFORM_ANDROID #include @@ -211,7 +210,7 @@ Java_com_cocos_lib_JsbBridge_nativeSendToScript(JNIEnv *env, jclass clazz, jstri std::string cArg0{cc::JniHelper::jstring2string(arg0)}; std::string cArg1{cc::JniHelper::jstring2string(arg1)}; - cc::Application::getInstance()->getScheduler()->performFunctionInCocosThread([=]() { + CC_CURRENT_ENGINE()->getScheduler()->performFunctionInCocosThread([=]() { ScriptNativeBridge::bridgeCxxInstance->callByNative(cArg0, cArg1); }); } diff --git a/native/cocos/bindings/manual/jsb_cocos_manual.cpp b/native/cocos/bindings/manual/jsb_cocos_manual.cpp index 4e90d1af8d..8bb2c14b45 100644 --- a/native/cocos/bindings/manual/jsb_cocos_manual.cpp +++ b/native/cocos/bindings/manual/jsb_cocos_manual.cpp @@ -329,8 +329,19 @@ static bool register_sys_localStorage(se::Object *obj) { // NOLINT(readability-i localStorageObj->defineProperty("length", _SE(JSB_localStorage_getLength), nullptr); std::string strFilePath = cc::FileUtils::getInstance()->getWritablePath(); +#if defined(__QNX__) + // In the QNX environment, the execution of this statement will not take effect. + // Not sure why + // strFilePath += "/jsb.sqlite"; + + // Use another way + char path[256] = {0}; + sprintf(path, "%s/jsb.sqlite", strFilePath.c_str()); + localStorageInit(path); +#else strFilePath += "/jsb.sqlite"; localStorageInit(strFilePath); +#endif se::ScriptEngine::getInstance()->addBeforeCleanupHook([]() { localStorageFree(); @@ -343,7 +354,7 @@ static bool register_sys_localStorage(se::Object *obj) { // NOLINT(readability-i //IDEA: move to auto bindings. static bool js_CanvasRenderingContext2D_setCanvasBufferUpdatedCallback(se::State &s) { // NOLINT(readability-identifier-naming) - auto *cobj = static_cast(s.nativeThisObject()); + auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_CanvasRenderingContext2D_setCanvasBufferUpdatedCallback : Invalid Native Object"); const auto & args = s.args(); size_t argc = args.size(); @@ -390,7 +401,7 @@ static bool js_CanvasRenderingContext2D_setCanvasBufferUpdatedCallback(se::State } SE_BIND_FUNC(js_CanvasRenderingContext2D_setCanvasBufferUpdatedCallback) // NOLINT(readability-identifier-naming) -static void setCanvasRenderingContext2DProps(cc::CanvasRenderingContext2D *context, const se::Value &val) { +static void setCanvasRenderingContext2DProps(cc::ICanvasRenderingContext2D *context, const se::Value &val) { se::Object *props = val.toObject(); se::Value propVal; @@ -423,7 +434,7 @@ static void setCanvasRenderingContext2DProps(cc::CanvasRenderingContext2D *conte } static bool js_engine_CanvasRenderingContext2D_measureText(se::State &s) { // NOLINT(readability-identifier-naming) - auto *cobj = static_cast(s.nativeThisObject()); + auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_measureText : Invalid Native Object"); const auto & args = s.args(); size_t argc = args.size(); @@ -445,7 +456,7 @@ static bool js_engine_CanvasRenderingContext2D_measureText(se::State &s) { // NO SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_measureText) // NOLINT(readability-identifier-naming) static bool js_engine_CanvasRenderingContext2D_fillRect(const se::State &s) { // NOLINT(readability-identifier-naming) - auto *cobj = static_cast(s.nativeThisObject()); + auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_fillRect : Invalid Native Object"); const auto & args = s.args(); size_t argc = args.size(); @@ -471,7 +482,7 @@ static bool js_engine_CanvasRenderingContext2D_fillRect(const se::State &s) { // SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_fillRect) // NOLINT(readability-identifier-naming) static bool js_engine_CanvasRenderingContext2D_fillText(const se::State &s) { // NOLINT(readability-identifier-naming) - auto *cobj = static_cast(s.nativeThisObject()); + auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_fillText : Invalid Native Object"); const auto & args = s.args(); size_t argc = args.size(); @@ -488,7 +499,7 @@ static bool js_engine_CanvasRenderingContext2D_fillText(const se::State &s) { // setCanvasRenderingContext2DProps(cobj, args[4]); if (args[3].isUndefined()) { SE_PRECONDITION2(ok, false, "js_engine_CanvasRenderingContext2D_fillText : Error processing arguments"); - cobj->fillText(arg0, arg1, arg2); + cobj->fillText(arg0, arg1, arg2, -1.0F); } else { ok &= seval_to_float(args[3], &arg3); SE_PRECONDITION2(ok, false, "js_engine_CanvasRenderingContext2D_fillText : Error processing arguments"); @@ -502,7 +513,7 @@ static bool js_engine_CanvasRenderingContext2D_fillText(const se::State &s) { // SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_fillText) // NOLINT(readability-identifier-naming) static bool js_engine_CanvasRenderingContext2D_strokeText(const se::State &s) { // NOLINT(readability-identifier-naming) - auto *cobj = static_cast(s.nativeThisObject()); + auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_strokeText : Invalid Native Object"); const auto &args = s.args(); size_t argc = args.size(); @@ -523,7 +534,7 @@ static bool js_engine_CanvasRenderingContext2D_strokeText(const se::State &s) { cobj->strokeText(arg0, arg1, arg2, arg3); } else { SE_PRECONDITION2(ok, false, "js_engine_CanvasRenderingContext2D_strokeText : Error processing arguments"); - cobj->strokeText(arg0, arg1, arg2); + cobj->strokeText(arg0, arg1, arg2, -1.0F); } return true; diff --git a/native/cocos/bindings/manual/jsb_conversions.h b/native/cocos/bindings/manual/jsb_conversions.h index d271f79c0e..c261e5b2cb 100644 --- a/native/cocos/bindings/manual/jsb_conversions.h +++ b/native/cocos/bindings/manual/jsb_conversions.h @@ -134,7 +134,7 @@ struct InputAssemblerInfo; #endif #if __clang__ - #if defined(__has_feature) && __has_feature(cxx_static_assert) && __has_feature(cxx_relaxed_constexpr) + #if defined(__has_feature) && __has_feature(cxx_static_assert) && __has_feature(cxx_relaxed_constexpr) && (__cplusplus > 201402L) #define HAS_CONSTEXPR 1 #else #define HAS_CONSTEXPR 0 @@ -150,10 +150,11 @@ struct InputAssemblerInfo; #define CC_CONSTEXPR constexpr #else #define CC_CONSTEXPR - #define CC_STATIC_ASSERT(cond, msg) assert(cond) + #define CC_STATIC_ASSERT(cond, ...) assert(cond) #endif -#if __clang__ +#if __clang__ && (__cplusplus > 201402L) + #define HAS_PUSH_DIAGNOSTI #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++17-extensions" #endif @@ -1578,7 +1579,7 @@ inline bool nativevalue_to_se(const cc::network::DownloadTask &from, se::Value & return DownloadTask_to_seval(from, &to); } -#if __clang__ +#if __clang__ && defined(HAS_PUSH_DIAGNOSTI) #pragma clang diagnostic pop #endif diff --git a/native/cocos/bindings/manual/jsb_global.cpp b/native/cocos/bindings/manual/jsb_global.cpp index 99caa36576..737a436f8e 100644 --- a/native/cocos/bindings/manual/jsb_global.cpp +++ b/native/cocos/bindings/manual/jsb_global.cpp @@ -24,6 +24,8 @@ ****************************************************************************/ #include "jsb_global.h" +#include "application/ApplicationManager.h" +#include "base/AutoreleasePool.h" #include "base/CoreStd.h" #include "base/Scheduler.h" #include "base/ThreadPool.h" @@ -32,8 +34,9 @@ #include "gfx-base/GFXDef.h" #include "jsb_conversions.h" #include "network/HttpClient.h" -#include "platform/Application.h" #include "platform/Image.h" +#include "platform/interfaces/modules/ISystem.h" +#include "platform/interfaces/modules/ISystemWindow.h" #include "ui/edit-box/EditBox.h" #include "xxtea/xxtea.h" @@ -308,8 +311,10 @@ static bool jsc_dumpRoot(se::State &s) { //NOLINT SE_BIND_FUNC(jsc_dumpRoot) static bool JSBCore_platform(se::State &s) { //NOLINT - Application::Platform platform = Application::getInstance()->getPlatform(); - s.rval().setInt32(static_cast(platform)); + //Application::Platform platform = CC_CURRENT_ENGINE()->getPlatform(); + cc::BasePlatform::OSType type = + cc::BasePlatform::getPlatform()->getOSType(); + s.rval().setInt32(static_cast(type)); return true; } SE_BIND_FUNC(JSBCore_platform) @@ -326,6 +331,8 @@ static bool JSBCore_os(se::State &s) { //NOLINT os.setString("Windows"); #elif (CC_PLATFORM == CC_PLATFORM_LINUX) os.setString("Linux"); +#elif (CC_PLATFORM == CC_PLATFORM_QNX) + os.setString("Qnx"); #elif (CC_PLATFORM == CC_PLATFORM_MAC_OSX) os.setString("OS X"); #elif (CC_PLATFORM == CC_PLATFORM_OHOS) @@ -338,84 +345,24 @@ static bool JSBCore_os(se::State &s) { //NOLINT SE_BIND_FUNC(JSBCore_os) static bool JSBCore_getCurrentLanguage(se::State &s) { //NOLINT - std::string languageStr; - Application::LanguageType language = Application::getInstance()->getCurrentLanguage(); - switch (language) { - case Application::LanguageType::ENGLISH: - languageStr = "en"; - break; - case Application::LanguageType::CHINESE: - languageStr = "zh"; - break; - case Application::LanguageType::FRENCH: - languageStr = "fr"; - break; - case Application::LanguageType::ITALIAN: - languageStr = "it"; - break; - case Application::LanguageType::GERMAN: - languageStr = "de"; - break; - case Application::LanguageType::SPANISH: - languageStr = "es"; - break; - case Application::LanguageType::DUTCH: - languageStr = "du"; - break; - case Application::LanguageType::RUSSIAN: - languageStr = "ru"; - break; - case Application::LanguageType::KOREAN: - languageStr = "ko"; - break; - case Application::LanguageType::JAPANESE: - languageStr = "ja"; - break; - case Application::LanguageType::HUNGARIAN: - languageStr = "hu"; - break; - case Application::LanguageType::PORTUGUESE: - languageStr = "pt"; - break; - case Application::LanguageType::ARABIC: - languageStr = "ar"; - break; - case Application::LanguageType::NORWEGIAN: - languageStr = "no"; - break; - case Application::LanguageType::POLISH: - languageStr = "pl"; - break; - case Application::LanguageType::TURKISH: - languageStr = "tr"; - break; - case Application::LanguageType::UKRAINIAN: - languageStr = "uk"; - break; - case Application::LanguageType::ROMANIAN: - languageStr = "ro"; - break; - case Application::LanguageType::BULGARIAN: - languageStr = "bg"; - break; - default: - languageStr = "unknown"; - break; - } + ISystem * systemIntf = CC_GET_PLATFORM_INTERFACE(ISystem); + std::string languageStr = systemIntf->getCurrentLanguageToString(); s.rval().setString(languageStr); return true; } SE_BIND_FUNC(JSBCore_getCurrentLanguage) static bool JSBCore_getCurrentLanguageCode(se::State &s) { //NOLINT - std::string language = Application::getInstance()->getCurrentLanguageCode(); + ISystem * systemIntf = CC_GET_PLATFORM_INTERFACE(ISystem); + std::string language = systemIntf->getCurrentLanguageCode(); s.rval().setString(language); return true; } SE_BIND_FUNC(JSBCore_getCurrentLanguageCode) static bool JSB_getOSVersion(se::State &s) { //NOLINT - std::string systemVersion = Application::getInstance()->getSystemVersion(); + ISystem * systemIntf = CC_GET_PLATFORM_INTERFACE(ISystem); + std::string systemVersion = systemIntf->getSystemVersion(); s.rval().setString(systemVersion); return true; } @@ -423,13 +370,13 @@ SE_BIND_FUNC(JSB_getOSVersion) static bool JSB_core_restartVM(se::State &s) { //NOLINT //REFINE: release AudioEngine, waiting HttpClient & WebSocket threads to exit. - Application::getInstance()->restart(); + CC_CURRENT_APPLICATION()->restart(); return true; } SE_BIND_FUNC(JSB_core_restartVM) static bool JSB_closeWindow(se::State &s) { - Application::getInstance()->close(); + CC_CURRENT_APPLICATION()->close(); return true; } SE_BIND_FUNC(JSB_closeWindow) @@ -458,7 +405,8 @@ static bool JSB_setCursorEnabled(se::State &s) { //NOLINT ok &= seval_to_boolean(args[0], &value); SE_PRECONDITION2(ok, false, "Error processing arguments"); - Application::getInstance()->setCursorEnabled(value); + auto *systemWindowIntf = CC_GET_PLATFORM_INTERFACE(ISystemWindow); + systemWindowIntf->setCursorEnabled(value); return true; } SE_BIND_FUNC(JSB_setCursorEnabled) @@ -624,7 +572,7 @@ bool jsb_global_load_image(const std::string &path, const se::Value &callbackVal imgInfo = createImageInfo(img); } - Application::getInstance()->getScheduler()->performFunctionInCocosThread([=]() { + CC_CURRENT_ENGINE()->getScheduler()->performFunctionInCocosThread([=]() { se::AutoHandleScope hs; se::ValueArray seArgs; se::Value dataVal; @@ -721,7 +669,8 @@ static bool JSB_openURL(se::State &s) { //NOLINT std::string url; ok = seval_to_std_string(args[0], &url); SE_PRECONDITION2(ok, false, "url is invalid!"); - Application::getInstance()->openURL(url); + ISystem *systemIntf = CC_GET_PLATFORM_INTERFACE(ISystem); + systemIntf->openURL(url); return true; } @@ -738,7 +687,8 @@ static bool JSB_copyTextToClipboard(se::State &s) { //NOLINT std::string text; ok = seval_to_std_string(args[0], &text); SE_PRECONDITION2(ok, false, "text is invalid!"); - Application::getInstance()->copyTextToClipboard(text); + ISystemWindow *systemWindowIntf = CC_GET_PLATFORM_INTERFACE(ISystemWindow); + systemWindowIntf->copyTextToClipboard(text); return true; } @@ -756,7 +706,7 @@ static bool JSB_setPreferredFramesPerSecond(se::State &s) { //NOLINT ok = seval_to_int32(args[0], &fps); SE_PRECONDITION2(ok, false, "fps is invalid!"); // cc::log("EMPTY IMPLEMENTATION OF jsb.setPreferredFramesPerSecond"); - Application::getInstance()->setPreferredFramesPerSecond(fps); + CC_CURRENT_ENGINE()->setPreferredFramesPerSecond(fps); return true; } diff --git a/native/cocos/bindings/manual/jsb_platform.h b/native/cocos/bindings/manual/jsb_platform.h index f1d293e01a..d2495a14d7 100644 --- a/native/cocos/bindings/manual/jsb_platform.h +++ b/native/cocos/bindings/manual/jsb_platform.h @@ -24,12 +24,12 @@ ****************************************************************************/ #pragma once - +#include #include namespace se { class Object; } -bool register_platform_bindings(se::Object *obj); +bool register_platform_bindings(se::Object *obj); // NOLINT[readability-identifier-naming] const std::unordered_map &getFontFamilyNameMap(); diff --git a/native/cocos/bindings/manual/jsb_platfrom_linux.cpp b/native/cocos/bindings/manual/jsb_platfrom_linux.cpp new file mode 100644 index 0000000000..2ac6b300da --- /dev/null +++ b/native/cocos/bindings/manual/jsb_platfrom_linux.cpp @@ -0,0 +1,87 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "jsb_platform.h" + +#include "cocos/bindings/jswrapper/SeApi.h" +#include "cocos/bindings/manual/jsb_conversions.h" +#include "cocos/bindings/manual/jsb_global_init.h" +#include "cocos/platform/FileUtils.h" + +#include + +using namespace cc; + +static std::unordered_map _fontFamilyNameMap; + +const std::unordered_map &getFontFamilyNameMap() { + return _fontFamilyNameMap; +} + +static bool JSB_loadFont(se::State &s) { + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc >= 1) { + s.rval().setNull(); + + std::string originalFamilyName; + ok &= seval_to_std_string(args[0], &originalFamilyName); + SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: originalFamilyName"); + + std::string source; + ok &= seval_to_std_string(args[1], &source); + SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: source"); + + std::string fontFilePath; + std::regex re("url\\(\\s*'\\s*(.*?)\\s*'\\s*\\)"); + std::match_results results; + if (std::regex_search(source.cbegin(), source.cend(), results, re)) { + fontFilePath = results[1].str(); + } + + fontFilePath = FileUtils::getInstance()->fullPathForFilename(fontFilePath); + if (fontFilePath.empty()) { + SE_LOGE("Font (%s) doesn't exist!", fontFilePath.c_str()); + return true; + } + + // just put the path info, used at CanvasRenderingContext2DImpl::updateFont() + _fontFamilyNameMap.emplace(originalFamilyName, fontFilePath); + + s.rval().setString(originalFamilyName); + + return true; + } + + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(JSB_loadFont) + +bool register_platform_bindings(se::Object *obj) { + __jsbObj->defineFunction("loadFont", _SE(JSB_loadFont)); + return true; +} diff --git a/native/cocos/bindings/manual/jsb_platfrom_qnx.cpp b/native/cocos/bindings/manual/jsb_platfrom_qnx.cpp new file mode 100644 index 0000000000..2ac6b300da --- /dev/null +++ b/native/cocos/bindings/manual/jsb_platfrom_qnx.cpp @@ -0,0 +1,87 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "jsb_platform.h" + +#include "cocos/bindings/jswrapper/SeApi.h" +#include "cocos/bindings/manual/jsb_conversions.h" +#include "cocos/bindings/manual/jsb_global_init.h" +#include "cocos/platform/FileUtils.h" + +#include + +using namespace cc; + +static std::unordered_map _fontFamilyNameMap; + +const std::unordered_map &getFontFamilyNameMap() { + return _fontFamilyNameMap; +} + +static bool JSB_loadFont(se::State &s) { + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc >= 1) { + s.rval().setNull(); + + std::string originalFamilyName; + ok &= seval_to_std_string(args[0], &originalFamilyName); + SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: originalFamilyName"); + + std::string source; + ok &= seval_to_std_string(args[1], &source); + SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: source"); + + std::string fontFilePath; + std::regex re("url\\(\\s*'\\s*(.*?)\\s*'\\s*\\)"); + std::match_results results; + if (std::regex_search(source.cbegin(), source.cend(), results, re)) { + fontFilePath = results[1].str(); + } + + fontFilePath = FileUtils::getInstance()->fullPathForFilename(fontFilePath); + if (fontFilePath.empty()) { + SE_LOGE("Font (%s) doesn't exist!", fontFilePath.c_str()); + return true; + } + + // just put the path info, used at CanvasRenderingContext2DImpl::updateFont() + _fontFamilyNameMap.emplace(originalFamilyName, fontFilePath); + + s.rval().setString(originalFamilyName); + + return true; + } + + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(JSB_loadFont) + +bool register_platform_bindings(se::Object *obj) { + __jsbObj->defineFunction("loadFont", _SE(JSB_loadFont)); + return true; +} diff --git a/native/cocos/bindings/manual/jsb_socketio.cpp b/native/cocos/bindings/manual/jsb_socketio.cpp index 960cd911b0..a4ac511d98 100644 --- a/native/cocos/bindings/manual/jsb_socketio.cpp +++ b/native/cocos/bindings/manual/jsb_socketio.cpp @@ -29,34 +29,33 @@ #include "cocos/bindings/manual/jsb_conversions.h" #include "cocos/bindings/manual/jsb_global.h" -#include "cocos/network/SocketIO.h" +#include "application/ApplicationManager.h" #include "base/UTF8.h" -#include "platform/Application.h" +#include "cocos/network/SocketIO.h" -using namespace cc; -using namespace cc::network; +// using namespace cc; +// using namespace cc::network; -se::Class *__jsb_SocketIO_class = nullptr; +se::Class *__jsb_SocketIO_class = nullptr; // NOLINT -class JSB_SocketIODelegate : public Ref, public SocketIO::SIODelegate { +class JSB_SocketIODelegate : public cc::Ref, public cc::network::SocketIO::SIODelegate { // NOLINT(readability-identifier-naming) public: //c++11 map to callbacks - typedef std::unordered_map JSB_SIOCallbackRegistry; + using JSB_SIOCallbackRegistry = std::unordered_map; - JSB_SocketIODelegate() { - } + JSB_SocketIODelegate() = default; - virtual ~JSB_SocketIODelegate() { + ~JSB_SocketIODelegate() override { CC_LOG_INFO("In the destructor of JSB_SocketIODelegate(%p)", this); } - virtual void onConnect(SIOClient *client) override { + void onConnect(cc::network::SIOClient * /*client*/) override { } - virtual void onMessage(SIOClient *client, const std::string &data) override { + void onMessage(cc::network::SIOClient * /*client*/, const std::string & /*data*/) override { } - virtual void onClose(SIOClient *client) override { + void onClose(cc::network::SIOClient *client) override { // NOLINT CC_LOG_DEBUG("JSB SocketIO::SIODelegate->onClose method called from native"); this->fireEventToScript(client, "disconnect", ""); @@ -72,7 +71,7 @@ public: } } - virtual void onError(SIOClient *client, const std::string &data) override { + void onError(cc::network::SIOClient *client, const std::string &data) override {// NOLINT CC_LOG_DEBUG("JSB SocketIO::SIODelegate->onError method called from native with data: %s", data.c_str()); this->fireEventToScript(client, "error", data); @@ -82,18 +81,20 @@ public: } } - virtual void fireEventToScript(SIOClient *client, const std::string &eventName, const std::string &data) override { + void fireEventToScript(cc::network::SIOClient * client, const std::string & eventName, const std::string & data) override { // NOLINT CC_LOG_DEBUG("JSB SocketIO::SIODelegate->fireEventToScript method called from native with name '%s' data: %s", eventName.c_str(), data.c_str()); se::ScriptEngine::getInstance()->clearException(); se::AutoHandleScope hs; - if (cc::Application::getInstance() == nullptr) + if (!CC_CURRENT_APPLICATION()) { return; + } auto iter = se::NativePtrToObjectMap::find(client); //IDEA: client probably be a new value with the same address as the old one, it may cause undefined result. - if (iter == se::NativePtrToObjectMap::end()) + if (iter == se::NativePtrToObjectMap::end()) { return; + } se::Value dataVal; if (data.empty()) { @@ -102,13 +103,13 @@ public: dataVal.setString(data); } - JSB_SIOCallbackRegistry::iterator it = _eventRegistry.find(eventName); + auto it = _eventRegistry.find(eventName); if (it != _eventRegistry.end()) { const se::ValueArray &cbStruct = it->second; assert(cbStruct.size() == 2); const se::Value &callback = cbStruct[0]; - const se::Value &target = cbStruct[1]; + const se::Value &target = cbStruct[1]; if (callback.isObject() && callback.toObject()->isFunction() && target.isObject()) { se::ValueArray args; args.push_back(dataVal); @@ -134,11 +135,11 @@ private: JSB_SIOCallbackRegistry _eventRegistry; }; -static bool SocketIO_finalize(se::State &s) { - SIOClient *cobj = (SIOClient *)s.nativeThisObject(); +static bool SocketIO_finalize(se::State &s) { // NOLINT(readability-identifier-naming) + auto *cobj = static_cast(s.nativeThisObject()); CC_LOG_INFO("jsbindings: finalizing JS object %p (SocketIO)", cobj); cobj->disconnect(); - JSB_SocketIODelegate *delegate = static_cast(cobj->getDelegate()); + auto *delegate = static_cast(cobj->getDelegate()); if (delegate->getReferenceCount() == 1) { delegate->autorelease(); } else { @@ -147,30 +148,30 @@ static bool SocketIO_finalize(se::State &s) { cobj->release(); return true; } -SE_BIND_FINALIZE_FUNC(SocketIO_finalize) +SE_BIND_FINALIZE_FUNC(SocketIO_finalize) // NOLINT(readability-identifier-naming) -static bool SocketIO_prop_getTag(se::State &s) { - SIOClient *cobj = (SIOClient *)s.nativeThisObject(); +static bool SocketIO_prop_getTag(se::State &s) { // NOLINT(readability-identifier-naming) + auto *cobj = static_cast(s.nativeThisObject()); s.rval().setString(cobj->getTag()); return true; } -SE_BIND_PROP_GET(SocketIO_prop_getTag) +SE_BIND_PROP_GET(SocketIO_prop_getTag) // NOLINT(readability-identifier-naming) -static bool SocketIO_prop_setTag(se::State &s) { - SIOClient *cobj = (SIOClient *)s.nativeThisObject(); +static bool SocketIO_prop_setTag(se::State &s) { // NOLINT(readability-identifier-naming) + auto *cobj = static_cast(s.nativeThisObject()); cobj->setTag(s.args()[0].toString().c_str()); return true; } -SE_BIND_PROP_SET(SocketIO_prop_setTag) +SE_BIND_PROP_SET(SocketIO_prop_setTag) // NOLINT(readability-identifier-naming) -static bool SocketIO_send(se::State &s) { +static bool SocketIO_send(se::State &s) { // NOLINT(readability-identifier-naming) const auto &args = s.args(); - int argc = (int)args.size(); - SIOClient *cobj = (SIOClient *)s.nativeThisObject(); + int argc = static_cast(args.size()); + auto * cobj = static_cast(s.nativeThisObject()); if (argc == 1) { std::string payload; - bool ok = seval_to_std_string(args[0], &payload); + bool ok = seval_to_std_string(args[0], &payload); SE_PRECONDITION2(ok, false, "Converting payload failed!"); cobj->send(payload); @@ -180,15 +181,15 @@ static bool SocketIO_send(se::State &s) { SE_REPORT_ERROR("Wrong number of arguments: %d, expected: %d", argc, 1); return false; } -SE_BIND_FUNC(SocketIO_send) +SE_BIND_FUNC(SocketIO_send) // NOLINT(readability-identifier-naming) -static bool SocketIO_emit(se::State &s) { +static bool SocketIO_emit(se::State &s) { // NOLINT(readability-identifier-naming) const auto &args = s.args(); - int argc = (int)args.size(); - SIOClient *cobj = (SIOClient *)s.nativeThisObject(); + int argc = static_cast(args.size()); + auto * cobj = static_cast(s.nativeThisObject()); if (argc >= 1) { - bool ok = false; + bool ok = false; std::string eventName; ok = seval_to_std_string(args[0], &eventName); SE_PRECONDITION2(ok, false, "Converting eventName failed!"); @@ -213,12 +214,12 @@ static bool SocketIO_emit(se::State &s) { SE_REPORT_ERROR("Wrong number of arguments: %d, expected: %d", argc, 2); return false; } -SE_BIND_FUNC(SocketIO_emit) +SE_BIND_FUNC(SocketIO_emit) // NOLINT(readability-identifier-naming) -static bool SocketIO_disconnect(se::State &s) { +static bool SocketIO_disconnect(se::State &s) { // NOLINT(readability-identifier-naming) const auto &args = s.args(); - int argc = (int)args.size(); - SIOClient *cobj = (SIOClient *)s.nativeThisObject(); + int argc = static_cast(args.size()); + auto * cobj = static_cast(s.nativeThisObject()); if (argc == 0) { cobj->disconnect(); @@ -228,40 +229,40 @@ static bool SocketIO_disconnect(se::State &s) { SE_REPORT_ERROR("Wrong number of arguments: %d, expected: %d", argc, 0); return false; } -SE_BIND_FUNC(SocketIO_disconnect) +SE_BIND_FUNC(SocketIO_disconnect) // NOLINT(readability-identifier-naming) -static bool SocketIO_on(se::State &s) { +static bool SocketIO_on(se::State &s) { // NOLINT(readability-identifier-naming) const auto &args = s.args(); - int argc = (int)args.size(); - SIOClient *cobj = (SIOClient *)s.nativeThisObject(); + int argc = static_cast(args.size()); + auto * cobj = static_cast(s.nativeThisObject()); if (argc == 2) { - bool ok = false; + bool ok = false; std::string eventName; ok = seval_to_std_string(args[0], &eventName); SE_PRECONDITION2(ok, false, "Converting eventName failed!"); CC_LOG_DEBUG("JSB SocketIO eventName to: '%s'", eventName.c_str()); - ((JSB_SocketIODelegate *)cobj->getDelegate())->addEvent(eventName, args[1], se::Value(s.thisObject())); + (static_cast(cobj->getDelegate()))->addEvent(eventName, args[1], se::Value(s.thisObject())); return true; } SE_REPORT_ERROR("Wrong number of arguments: %d, expected: %d", argc, 2); return false; } -SE_BIND_FUNC(SocketIO_on) +SE_BIND_FUNC(SocketIO_on) // NOLINT(readability-identifier-naming) // static -static bool SocketIO_connect(se::State &s) { +static bool SocketIO_connect(se::State &s) { // NOLINT(readability-identifier-naming) const auto &args = s.args(); - int argc = (int)args.size(); + int argc = static_cast(args.size()); CC_LOG_DEBUG("JSB SocketIO.connect method called"); if (argc >= 1 && argc <= 3) { std::string url; std::string caFilePath; - bool ok = false; + bool ok = false; ok = seval_to_std_string(args[0], &url); SE_PRECONDITION2(ok, false, "Error processing arguments"); @@ -286,10 +287,10 @@ static bool SocketIO_connect(se::State &s) { } } - JSB_SocketIODelegate *siodelegate = new (std::nothrow) JSB_SocketIODelegate(); + auto *siodelegate = new (std::nothrow) JSB_SocketIODelegate(); CC_LOG_DEBUG("Calling native SocketIO.connect method"); - SIOClient *ret = SocketIO::connect(url, *siodelegate, caFilePath); + cc::network::SIOClient *ret = cc::network::SocketIO::connect(url, *siodelegate, caFilePath); if (ret != nullptr) { ret->retain(); siodelegate->retain(); @@ -301,21 +302,20 @@ static bool SocketIO_connect(se::State &s) { obj->root(); return true; - } else { - siodelegate->release(); - SE_REPORT_ERROR("SocketIO.connect return nullptr!"); - return false; } + siodelegate->release(); + SE_REPORT_ERROR("SocketIO.connect return nullptr!"); + return false; } SE_REPORT_ERROR("JSB SocketIO.connect: Wrong number of arguments"); return false; } -SE_BIND_FUNC(SocketIO_connect) +SE_BIND_FUNC(SocketIO_connect) // NOLINT(readability-identifier-naming) // static -static bool SocketIO_close(se::State &s) { +static bool SocketIO_close(se::State &s) { // NOLINT(readability-identifier-naming) const auto &args = s.args(); - int argc = (int)args.size(); + int argc = static_cast(args.size()); if (argc == 0) { return true; } @@ -323,7 +323,7 @@ static bool SocketIO_close(se::State &s) { SE_REPORT_ERROR("Wrong number of arguments: %d, expected: %d", argc, 0); return false; } -SE_BIND_FUNC(SocketIO_close) +SE_BIND_FUNC(SocketIO_close) // NOLINT(readability-identifier-naming) bool register_all_socketio(se::Object *obj) { se::Class *cls = se::Class::create("SocketIO", obj, nullptr, nullptr); @@ -338,7 +338,7 @@ bool register_all_socketio(se::Object *obj) { cls->install(); - JSBClassType::registerClass(cls); + JSBClassType::registerClass(cls); se::Value ctorVal; obj->getProperty("SocketIO", &ctorVal); diff --git a/native/cocos/bindings/manual/jsb_websocket.cpp b/native/cocos/bindings/manual/jsb_websocket.cpp index 38f1aa9207..5b447ad3e6 100644 --- a/native/cocos/bindings/manual/jsb_websocket.cpp +++ b/native/cocos/bindings/manual/jsb_websocket.cpp @@ -31,7 +31,7 @@ #include "cocos/bindings/manual/jsb_global.h" #include "base/UTF8.h" - #include "platform/Application.h" + #include "application/ApplicationManager.h" /* [Constructor(in DOMString url, in optional DOMString protocols)] @@ -71,7 +71,7 @@ void JsbWebSocketDelegate::onOpen(cc::network::WebSocket *ws) { se::ScriptEngine::getInstance()->clearException(); se::AutoHandleScope hs; - if (cc::Application::getInstance() == nullptr) { + if (CC_CURRENT_APPLICATION() == nullptr) { return; } @@ -104,7 +104,7 @@ void JsbWebSocketDelegate::onMessage(cc::network::WebSocket *ws, const cc::netwo se::ScriptEngine::getInstance()->clearException(); se::AutoHandleScope hs; - if (cc::Application::getInstance() == nullptr) { + if (CC_CURRENT_APPLICATION() == nullptr) { return; } @@ -155,7 +155,7 @@ void JsbWebSocketDelegate::onClose(cc::network::WebSocket *ws) { se::ScriptEngine::getInstance()->clearException(); se::AutoHandleScope hs; - if (cc::Application::getInstance() == nullptr) { + if (CC_CURRENT_APPLICATION() == nullptr) { return; } @@ -200,7 +200,7 @@ void JsbWebSocketDelegate::onError(cc::network::WebSocket *ws, const cc::network se::ScriptEngine::getInstance()->clearException(); se::AutoHandleScope hs; - if (cc::Application::getInstance() == nullptr) { + if (CC_CURRENT_APPLICATION() == nullptr) { return; } diff --git a/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp b/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp index 584efb30fd..45316df31d 100644 --- a/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp +++ b/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp @@ -41,7 +41,8 @@ #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_conversions.h" #include "cocos/network/HttpClient.h" -#include "platform/Application.h" + +#include "application/ApplicationManager.h" using namespace cc; //NOLINT using namespace cc::network; //NOLINT @@ -226,7 +227,7 @@ XMLHttpRequest::XMLHttpRequest() } XMLHttpRequest::~XMLHttpRequest() { - Application::getInstance()->getScheduler()->unscheduleAllForTarget(this); + CC_CURRENT_ENGINE()->getScheduler()->unscheduleAllForTarget(this); // Avoid HttpClient response call a released object! _httpRequest->setResponseCallback(nullptr); CC_SAFE_RELEASE(_httpRequest); @@ -375,7 +376,7 @@ void XMLHttpRequest::getHeader(const std::string &header) { } void XMLHttpRequest::onResponse(HttpClient * /*client*/, HttpResponse *response) { - Application::getInstance()->getScheduler()->unscheduleAllForTarget(this); + CC_CURRENT_ENGINE()->getScheduler()->unscheduleAllForTarget(this); _isSending = false; if (_isTimeout) { @@ -476,7 +477,7 @@ void XMLHttpRequest::sendRequest() { _isSending = true; _isTimeout = false; if (_timeoutInMilliseconds > 0) { - Application::getInstance()->getScheduler()->schedule([this](float /* dt */) { + CC_CURRENT_ENGINE()->getScheduler()->schedule([this](float /* dt */) { if (ontimeout != nullptr) { ontimeout(); } diff --git a/native/cocos/editor-support/IOBuffer.h b/native/cocos/editor-support/IOBuffer.h index 3d2eb0ac60..1fc392840a 100644 --- a/native/cocos/editor-support/IOBuffer.h +++ b/native/cocos/editor-support/IOBuffer.h @@ -31,6 +31,7 @@ #include #include #include +#include MIDDLEWARE_BEGIN /** diff --git a/native/cocos/editor-support/TypedArrayPool.cpp b/native/cocos/editor-support/TypedArrayPool.cpp index 69887bad4c..5191182f62 100644 --- a/native/cocos/editor-support/TypedArrayPool.cpp +++ b/native/cocos/editor-support/TypedArrayPool.cpp @@ -28,6 +28,7 @@ #include "base/Log.h" #include "base/Macros.h" #include +#include #define POOL_DEBUG 0 @@ -104,7 +105,7 @@ void TypedArrayPool::dump() { } se::Object *TypedArrayPool::pop(arrayType type, std::size_t size) { - auto fitSize = static_cast(ceil(size / float(MIN_TYPE_ARRAY_SIZE)) * MIN_TYPE_ARRAY_SIZE); + auto fitSize = static_cast(std::ceil(size / float(MIN_TYPE_ARRAY_SIZE)) * MIN_TYPE_ARRAY_SIZE); objPool *objPoolPtr = getObjPool(type, fitSize); if (!objPoolPtr->empty()) { diff --git a/native/cocos/engine/BaseEngine.cpp b/native/cocos/engine/BaseEngine.cpp new file mode 100644 index 0000000000..e0db55ac56 --- /dev/null +++ b/native/cocos/engine/BaseEngine.cpp @@ -0,0 +1,40 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "cocos/engine/BaseEngine.h" +#include "cocos/engine/Engine.h" +#include "cocos/platform/BasePlatform.h" +#include "cocos/platform/interfaces/modules/ISystemWindow.h" + +namespace cc { + +BaseEngine::~BaseEngine() = default; + +// static +BaseEngine::Ptr BaseEngine::createEngine() { + return std::make_shared(); +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/engine/BaseEngine.h b/native/cocos/engine/BaseEngine.h new file mode 100644 index 0000000000..55257f5276 --- /dev/null +++ b/native/cocos/engine/BaseEngine.h @@ -0,0 +1,105 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include + +#include "base/Scheduler.h" +#include "base/TypeDef.h" +#include "platform/BasePlatform.h" + +namespace cc { + +class BaseEngine : public std::enable_shared_from_this { +public: + virtual ~BaseEngine(); + using Ptr = std::shared_ptr; + + /** + @brief Get operating system interface template. + */ + template + T* getInterface() const { + BasePlatform* platform = BasePlatform::getPlatform(); + return platform->getInterface(); + } + /** + @brief Create default engine. + */ + static BaseEngine::Ptr createEngine(); + + /** + @brief Initialization engine interface. + */ + virtual int32_t init() = 0; + /** + @brief Run engine main logical interface. + */ + virtual int32_t run() = 0; + /** + @brief Pause engine main logical. + */ + virtual void pause() = 0; + /** + @brief Resume engine main logical. + */ + virtual void resume() = 0; + /** + @brief Restart engine main logical. + */ + virtual int restart() = 0; + /** + @brief Close engine main logical. + */ + virtual void close() = 0; + /** + @brief Gets the total number of frames in the main loop. + */ + virtual uint getTotalFrames() const = 0; + /** + * @brief Sets the preferred frame rate for main loop callback. + * @param fps The preferred frame rate for main loop callback. + */ + virtual void setPreferredFramesPerSecond(int fps) = 0; + + using EventCb = std::function; + /** + @brief Add listening event callback. + */ + virtual void addEventCallback(OSEventType evtype, const EventCb& cb) = 0; + /** + @brief Remove listening event callback. + */ + virtual void removeEventCallback(OSEventType evtype) = 0; + + using SchedulerPtr = std::shared_ptr; + /** + @brief Get engine scheduler. + */ + virtual SchedulerPtr getScheduler() const = 0; +}; + +} // namespace cc diff --git a/native/cocos/engine/Engine.cpp b/native/cocos/engine/Engine.cpp new file mode 100644 index 0000000000..f905f7bd2e --- /dev/null +++ b/native/cocos/engine/Engine.cpp @@ -0,0 +1,354 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "engine/Engine.h" +#include +#include "base/AutoreleasePool.h" +#include "base/Macros.h" +#include "platform/BasePlatform.h" + +#include "cocos/bindings/jswrapper/SeApi.h" +#include "cocos/renderer/GFXDeviceManager.h" +#include "pipeline/RenderPipeline.h" + +#if USE_AUDIO + #include "cocos/audio/include/AudioEngine.h" +#endif + +#if USE_SOCKET + #include "cocos/network/WebSocket.h" +#endif + +#include +#include +#include "application/ApplicationManager.h" +#include "application/BaseApplication.h" +#include "base/Scheduler.h" +#include "cocos/network/HttpClient.h" +#include "platform/interfaces/modules/ISystemWindow.h" + +namespace { + +bool setCanvasCallback(se::Object* /*global*/) { + se::AutoHandleScope scope; + se::ScriptEngine* se = se::ScriptEngine::getInstance(); + auto* window = CC_CURRENT_ENGINE()->getInterface(); + auto handler = window->getWindowHandler(); + auto viewSize = window->getViewSize(); + + std::stringstream ss; + { + ss << "window.innerWidth = " << static_cast(viewSize.x) << ";"; + ss << "window.innerHeight = " << static_cast(viewSize.y) << ";"; + ss << "window.windowHandler = "; + if (sizeof(handler) == 8) { // use bigint + ss << static_cast(handler) << "n;"; + } + if (sizeof(handler) == 4) { + ss << static_cast(handler) << ";"; + } + } + se->evalString(ss.str().c_str()); + + return true; +} + +} // namespace + +namespace cc { + +Engine::Engine() { + _scheduler = std::make_shared(); + FileUtils::getInstance()->addSearchPath("Resources", true); + EventDispatcher::init(); + se::ScriptEngine::getInstance(); +} + +Engine::~Engine() { +#if USE_AUDIO + AudioEngine::end(); +#endif + + pipeline::RenderPipeline::getInstance()->destroy(); + + EventDispatcher::destroy(); + se::ScriptEngine::destroyInstance(); + + gfx::DeviceManager::destroy(); + + BasePlatform* platform = BasePlatform::getPlatform(); + platform->setHandleEventCallback(nullptr); +} + +int32_t Engine::init() { + _scheduler->removeAllFunctionsToBePerformedInCocosThread(); + _scheduler->unscheduleAll(); + + se::ScriptEngine::getInstance()->cleanup(); + + BasePlatform* platform = BasePlatform::getPlatform(); + platform->setHandleEventCallback( + std::bind(&Engine::handleEvent, this, std::placeholders::_1));// NOLINT(modernize-avoid-bind) + + se::ScriptEngine::getInstance()->addPermanentRegisterCallback(setCanvasCallback); + return 0; +} + +int32_t Engine::run() { + BasePlatform* platform = BasePlatform::getPlatform(); + platform->runInPlatformThread([&]() { + tick(); + }); + return 0; +} + +void Engine::pause() { + // TODO(cc) : Follow-up support +} + +void Engine::resume() { + // TODO(cc) : Follow-up support +} + +int Engine::restart() { + _needRestart = true; + return 0; +} + +void Engine::close() { // NOLINT + if (cc::EventDispatcher::initialized()) { + cc::EventDispatcher::dispatchCloseEvent(); + } + + auto* scriptEngine = se::ScriptEngine::getInstance(); + + cc::PoolManager::getInstance()->getCurrentPool()->clear(); +#if USE_AUDIO + cc::AudioEngine::stopAll(); +#endif +//#if USE_SOCKET +// cc::network::WebSocket::closeAllConnections(); +//#endif + cc::network::HttpClient::destroyInstance(); + + _scheduler->removeAllFunctionsToBePerformedInCocosThread(); + _scheduler->unscheduleAll(); + + scriptEngine->cleanup(); + cc::EventDispatcher::destroy(); + + // exit + exit(0); +} + +uint Engine::getTotalFrames() const { + return _totalFrames; +} + +void Engine::setPreferredFramesPerSecond(int fps) { + if (fps == 0) { + return; + } + BasePlatform* platform = BasePlatform::getPlatform(); + platform->setFps(fps); + _prefererredNanosecondsPerFrame = static_cast(1.0 / fps * NANOSECONDS_PER_SECOND); //NOLINT(google-runtime-int) +} + +void Engine::addEventCallback(OSEventType evType, const EventCb& cb) { + _eventCallbacks.insert(std::make_pair(evType, cb)); +} + +void Engine::removeEventCallback(OSEventType evType) { + auto it = _eventCallbacks.find(evType); + if (it != _eventCallbacks.end()) { + _eventCallbacks.erase(it); + return; + } + + // For debugging. + CCASSERT(false, "Interface does not exist"); +} + +void Engine::tick() { + if (_needRestart) { + restartVM(); + _needRestart = false; + } + + static std::chrono::steady_clock::time_point prevTime; + static std::chrono::steady_clock::time_point now; + static float dt = 0.F; + static double dtNS = NANOSECONDS_60FPS; + + ++_totalFrames; + + // iOS/macOS use its own fps limitation algorithm. +#if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_WINDOWS || CC_PLATFORM == CC_PLATFORM_OHOS) + if (dtNS < static_cast(_prefererredNanosecondsPerFrame)) { + std::this_thread::sleep_for( + std::chrono::nanoseconds(_prefererredNanosecondsPerFrame - static_cast(dtNS))); + dtNS = static_cast(_prefererredNanosecondsPerFrame); + } +#endif + + prevTime = std::chrono::steady_clock::now(); + + _scheduler->update(dt); + cc::EventDispatcher::dispatchTickEvent(dt); + + LegacyAutoreleasePool* currentPool = PoolManager::getInstance()->getCurrentPool(); + if (currentPool) { + currentPool->clear(); + } + + now = std::chrono::steady_clock::now(); + dtNS = dtNS * 0.1 + 0.9 * static_cast(std::chrono::duration_cast(now - prevTime).count()); + dt = static_cast(dtNS) / NANOSECONDS_PER_SECOND; +} + +int32_t Engine::restartVM() { + cc::EventDispatcher::dispatchRestartVM(); + + pipeline::RenderPipeline::getInstance()->destroy(); + + auto* scriptEngine = se::ScriptEngine::getInstance(); + + cc::PoolManager::getInstance()->getCurrentPool()->clear(); +#if USE_AUDIO + cc::AudioEngine::stopAll(); +#endif +//#if USE_SOCKET +// cc::network::WebSocket::closeAllConnections(); +//#endif + cc::network::HttpClient::destroyInstance(); + + _scheduler->removeAllFunctionsToBePerformedInCocosThread(); + _scheduler->unscheduleAll(); + + scriptEngine->cleanup(); + cc::EventDispatcher::destroy(); + + // start + cc::EventDispatcher::init(); + CC_CURRENT_APPLICATION()->init(); + + cc::gfx::DeviceManager::addSurfaceEventListener(); + return 0; +} + +bool Engine::handleEvent(const OSEvent& ev) { + bool isHandled = false; + OSEventType type = ev.eventType(); + if (type == OSEventType::TOUCH_OSEVENT) { + cc::EventDispatcher::dispatchTouchEvent(OSEvent::castEvent(ev)); + isHandled = true; + } else if (type == OSEventType::MOUSE_OSEVENT) { + cc::EventDispatcher::dispatchMouseEvent(OSEvent::castEvent(ev)); + isHandled = true; + } else if (type == OSEventType::KEYBOARD_OSEVENT) { + cc::EventDispatcher::dispatchKeyboardEvent(OSEvent::castEvent(ev)); + isHandled = true; + } else if (type == OSEventType::CUSTOM_OSEVENT) { + cc::EventDispatcher::dispatchCustomEvent(OSEvent::castEvent(ev)); + isHandled = true; + } else if (type == OSEventType::WINDOW_OSEVENT) { + isHandled = dispatchWindowEvent(OSEvent::castEvent(ev)); + } else if (type == OSEventType::DEVICE_OSEVENT) { + isHandled = dispatchDeviceEvent(OSEvent::castEvent(ev)); + } + isHandled = dispatchEventToApp(type, ev); + return isHandled; +} + +Engine::SchedulerPtr Engine::getScheduler() const { + return _scheduler; +} + +bool Engine::dispatchDeviceEvent(const DeviceEvent& ev) { // NOLINT(readability-convert-member-functions-to-static) + if (ev.type == DeviceEvent::Type::DEVICE_MEMORY) { + cc::EventDispatcher::dispatchMemoryWarningEvent(); + return true; + } + return false; +} + +bool Engine::dispatchWindowEvent(const WindowEvent& ev) { + bool isHandled = false; + if (ev.type == WindowEvent::Type::SHOW || + ev.type == WindowEvent::Type::RESTORED) { + onResume(); + isHandled = true; + } else if (ev.type == WindowEvent::Type::SIZE_CHANGED || + ev.type == WindowEvent::Type::RESIZED) { + cc::EventDispatcher::dispatchResizeEvent(ev.width, ev.height); + isHandled = true; + } else if (ev.type == WindowEvent::Type::HIDDEN || + ev.type == WindowEvent::Type::MINIMIZED) { + onPause(); + isHandled = true; + } else if (ev.type == WindowEvent::Type::CLOSE) { + onClose(); + isHandled = true; + } else if (ev.type == WindowEvent::Type::QUIT) { + onClose(); + isHandled = true; + } + return isHandled; +} + +bool Engine::dispatchEventToApp(OSEventType type, const OSEvent& ev) { + auto it = _eventCallbacks.find(type); + if (it != _eventCallbacks.end()) { + it->second(ev); + return true; + } + return false; +} + +void Engine::onPause() { + AppEvent appEv; + appEv.type = AppEvent::Type::PAUSE; + dispatchEventToApp(OSEventType::APP_OSEVENT, appEv); + + cc::EventDispatcher::dispatchEnterBackgroundEvent(); +} + +void Engine::onResume() { + AppEvent appEv; + appEv.type = AppEvent::Type::RESUME; + dispatchEventToApp(OSEventType::APP_OSEVENT, appEv); + + cc::EventDispatcher::dispatchEnterForegroundEvent(); +} + +void Engine::onClose() { + AppEvent appEv; + appEv.type = AppEvent::Type::CLOSE; + dispatchEventToApp(OSEventType::APP_OSEVENT, appEv); + + cc::EventDispatcher::dispatchCloseEvent(); +} + +} // namespace cc diff --git a/native/cocos/engine/Engine.h b/native/cocos/engine/Engine.h new file mode 100644 index 0000000000..319ae49d57 --- /dev/null +++ b/native/cocos/engine/Engine.h @@ -0,0 +1,131 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "base/TypeDef.h" +#include "math/Vec2.h" + +#include "bindings/event/EventDispatcher.h" +#include "engine/BaseEngine.h" + +#include +#include + +namespace cc { + +#define NANOSECONDS_PER_SECOND 1000000000 +#define NANOSECONDS_60FPS 16666667L + +class Engine : public BaseEngine { +public: + /** + @brief Constructor of Engine. + */ + Engine(); + /** + @brief Constructor of Engine. + */ + ~Engine() override; + /** + @brief Implement initialization engine. + */ + int32_t init() override; + /** + @brief Implement the main logic of the running engine. + */ + int32_t run() override; + /** + @brief Implement pause engine running. + */ + void pause() override; + /** + @brief Implement resume engine running. + */ + void resume() override; + /** + @brief Implement restart engine running. + */ + int restart() override; + /** + @brief Implement close engine running. + */ + void close() override; + /** + * @brief Sets the preferred frame rate for main loop callback. + * @param fps The preferred frame rate for main loop callback. + */ + void setPreferredFramesPerSecond(int fps) override; + /** + @brief Gets the total number of frames in the main loop. + */ + uint getTotalFrames() const override; + /** + @brief Add Event Listening. + @param evtype:event type. + @param cb:event callback. + */ + void addEventCallback(OSEventType evtype, const EventCb& cb) override; + /** + @brief Remove Event Listening. + @param evtype:event type. + */ + void removeEventCallback(OSEventType evtype) override; + /** + @brief Event handling callback. + @param evtype:event type. + @param evtype:event information. + @return whether it's been handled. + */ + bool handleEvent(const OSEvent& ev); + /** + @brief Get engine scheduler. + */ + SchedulerPtr getScheduler() const override; + +private: + void tick(); + bool dispatchWindowEvent(const WindowEvent& ev); + bool dispatchDeviceEvent(const DeviceEvent& ev); + bool dispatchEventToApp(OSEventType type, const OSEvent& ev); + void onPause(); + void onResume(); + void onClose(); + int32_t restartVM(); + + bool _close{false}; + bool _pause{false}; + bool _resune{false}; + std::shared_ptr _scheduler{nullptr}; + int64_t _prefererredNanosecondsPerFrame{NANOSECONDS_60FPS}; + uint _totalFrames{0}; + cc::Vec2 _viewLogicalSize{0, 0}; + bool _needRestart{false}; + + std::map _eventCallbacks; + CC_DISABLE_COPY_AND_MOVE_SEMANTICS(Engine); +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/main/main-ios.mm b/native/cocos/main/main-ios.mm new file mode 100644 index 0000000000..0bc826ccd7 --- /dev/null +++ b/native/cocos/main/main-ios.mm @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 + +#include "platform/BasePlatform.h" + +int main(int argc, const char * argv[]) { + // cc::BasePlatform* platform = cc::BasePlatform::getPlatform(); + // if (platform->init()) { + // CC_LOG_FATAL("Platform initialization failed"); + // return -1; + // } + // return platform->run(argc, argv); + START_PLATFORM(argc, (const char**)argv); +} + +/* +#import + +int main(int argc, char *argv[]) { + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + int retVal = UIApplicationMain(argc, argv, nil, @"AppDelegate"); + [pool release]; + return retVal; +} + */ diff --git a/native/cocos/main/main-linux.cpp b/native/cocos/main/main-linux.cpp new file mode 100644 index 0000000000..91c465d44a --- /dev/null +++ b/native/cocos/main/main-linux.cpp @@ -0,0 +1,32 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 + +#include "platform/BasePlatform.h" +#include "SDL2/SDL_main.h" + +int main(int argc, char** argv) { + START_PLATFORM(argc, (const char**)argv); +} \ No newline at end of file diff --git a/native/cocos/main/main-mac.mm b/native/cocos/main/main-mac.mm new file mode 100644 index 0000000000..4de010d156 --- /dev/null +++ b/native/cocos/main/main-mac.mm @@ -0,0 +1,31 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 + +#include "platform/BasePlatform.h" + +int main(int argc, const char * argv[]) { + START_PLATFORM(argc, (const char**)argv); +} diff --git a/native/cocos/main/main-qnx.cpp b/native/cocos/main/main-qnx.cpp new file mode 100644 index 0000000000..91c465d44a --- /dev/null +++ b/native/cocos/main/main-qnx.cpp @@ -0,0 +1,32 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 + +#include "platform/BasePlatform.h" +#include "SDL2/SDL_main.h" + +int main(int argc, char** argv) { + START_PLATFORM(argc, (const char**)argv); +} \ No newline at end of file diff --git a/native/cocos/main/main-win32.cpp b/native/cocos/main/main-win32.cpp new file mode 100644 index 0000000000..9911742d79 --- /dev/null +++ b/native/cocos/main/main-win32.cpp @@ -0,0 +1,32 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 + +#include "platform/BasePlatform.h" +#include "sdl2/SDL_main.h" + +int SDL_main(int argc, char** argv) { + START_PLATFORM(argc, (const char**)argv); +} \ No newline at end of file diff --git a/native/cocos/math/Mat4.cpp b/native/cocos/math/Mat4.cpp index 7c7636d5e9..d11bed70fb 100644 --- a/native/cocos/math/Mat4.cpp +++ b/native/cocos/math/Mat4.cpp @@ -104,7 +104,7 @@ void Mat4::createPerspective(float fieldOfView, float aspectRatio, const float minClipZ = -1.0F; const float projectionSignY = 1.0F; - const float f = 1.0F / std::tanf(fieldOfView / 2.0F); + const float f = 1.0F / tanf(fieldOfView / 2.0F); const float nf = 1.0F / (zNearPlane - zFarPlane); const float x = f / aspectRatio; diff --git a/native/cocos/network/Downloader-curl.cpp b/native/cocos/network/Downloader-curl.cpp index 3f46c0e7a2..ea145228a6 100644 --- a/native/cocos/network/Downloader-curl.cpp +++ b/native/cocos/network/Downloader-curl.cpp @@ -29,10 +29,13 @@ #include #include #include +#include +#include #include "base/Scheduler.h" #include "platform/FileUtils.h" -#include "platform/Application.h" +#include "application/ApplicationManager.h" + #include "network/Downloader.h" // **NOTE** @@ -627,7 +630,7 @@ DownloaderCURL::DownloaderCURL(const DownloaderHints &hints) _currTask(nullptr) { DLLOG("Construct DownloaderCURL %p", this); _impl->hints = hints; - _scheduler = Application::getInstance()->getScheduler(); + _scheduler = CC_CURRENT_ENGINE()->getScheduler(); _transferDataToBuffer = [this](void *buf, int64_t len) -> int64_t { DownloadTaskCURL &coTask = *_currTask; diff --git a/native/cocos/network/Downloader-java.cpp b/native/cocos/network/Downloader-java.cpp index 5e5b39e7b1..96b99d4d29 100644 --- a/native/cocos/network/Downloader-java.cpp +++ b/native/cocos/network/Downloader-java.cpp @@ -29,8 +29,7 @@ #include "network/Downloader.h" #include "platform/java/jni/JniHelper.h" #include "platform/java/jni/JniImp.h" - -#include +#include "application/ApplicationManager.h" #include #ifndef JCLS_DOWNLOADER @@ -252,7 +251,7 @@ JNIEXPORT void JNICALL JNI_DOWNLOADER(nativeOnProgress)(JNIEnv * /*env*/, jclass } downloader->onProcessImpl((int)taskId, (int64_t)dl, (int64_t)dlnow, (int64_t)dltotal); }; - cc::Application::getInstance()->getScheduler()->performFunctionInCocosThread(func); + CC_CURRENT_ENGINE()->getScheduler()->performFunctionInCocosThread(func); } JNIEXPORT void JNICALL JNI_DOWNLOADER(nativeOnFinish)(JNIEnv *env, jclass /*clazz*/, jint id, jint taskId, jint errCode, jstring errStr, jbyteArray data) { @@ -286,7 +285,7 @@ JNIEXPORT void JNICALL JNI_DOWNLOADER(nativeOnFinish)(JNIEnv *env, jclass /*claz // success downloader->onFinishImpl((int)taskId, (int)errCode, nullptr, dataTmp); }; - cc::Application::getInstance()->getScheduler()->performFunctionInCocosThread(func); + CC_CURRENT_ENGINE()->getScheduler()->performFunctionInCocosThread(func); } } // extern "C" { diff --git a/native/cocos/network/HttpClient-apple.mm b/native/cocos/network/HttpClient-apple.mm index a89971feb8..2e70b9abb1 100644 --- a/native/cocos/network/HttpClient-apple.mm +++ b/native/cocos/network/HttpClient-apple.mm @@ -34,7 +34,8 @@ #import "network/HttpAsynConnection-apple.h" #include "network/HttpCookie.h" #include "platform/FileUtils.h" -#include "platform/Application.h" +#include "application/ApplicationManager.h" +#include "base/Scheduler.h" namespace cc { @@ -337,7 +338,7 @@ HttpClient::HttpClient() _requestSentinel(new HttpRequest()) { CC_LOG_DEBUG("In the constructor of HttpClient!"); memset(_responseMessage, 0, sizeof(char) * RESPONSE_BUFFER_SIZE); - _scheduler = Application::getInstance()->getScheduler(); + _scheduler = CC_CURRENT_ENGINE()->getScheduler(); increaseThreadCount(); } diff --git a/native/cocos/network/HttpClient-java.cpp b/native/cocos/network/HttpClient-java.cpp index f9dbeea286..10de1d4567 100644 --- a/native/cocos/network/HttpClient-java.cpp +++ b/native/cocos/network/HttpClient-java.cpp @@ -584,7 +584,7 @@ private: // NOLINT(readability-redundant-access-specifiers) // Process Response void HttpClient::processResponse(HttpResponse *response, char *responseMessage) { - auto* request = response->getHttpRequest(); + auto * request = response->getHttpRequest(); HttpRequest::Type requestType = request->getRequestType(); if (HttpRequest::Type::GET != requestType && diff --git a/native/cocos/network/HttpClient.cpp b/native/cocos/network/HttpClient.cpp index 6c63cf214d..3c958ec2f9 100644 --- a/native/cocos/network/HttpClient.cpp +++ b/native/cocos/network/HttpClient.cpp @@ -31,7 +31,7 @@ #include #include #include "platform/FileUtils.h" -#include "platform/Application.h" +#include "application/ApplicationManager.h" #include "platform/StdC.h" #include "base/Log.h" @@ -363,7 +363,7 @@ HttpClient::HttpClient() _requestSentinel(new HttpRequest()) { CC_LOG_DEBUG("In the constructor of HttpClient!"); memset(_responseMessage, 0, RESPONSE_BUFFER_SIZE * sizeof(char)); - _scheduler = Application::getInstance()->getScheduler(); + _scheduler = CC_CURRENT_ENGINE()->getScheduler(); increaseThreadCount(); } diff --git a/native/cocos/network/HttpClient.h b/native/cocos/network/HttpClient.h index 49c4d2e784..b102493ca9 100644 --- a/native/cocos/network/HttpClient.h +++ b/native/cocos/network/HttpClient.h @@ -26,8 +26,7 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef __CCHTTPCLIENT_H__ -#define __CCHTTPCLIENT_H__ +#pragma once #include #include @@ -35,7 +34,6 @@ #include "network/HttpRequest.h" #include "network/HttpResponse.h" #include "network/HttpCookie.h" -#include "base/Scheduler.h" /** * @addtogroup network @@ -43,7 +41,7 @@ */ namespace cc { - +class Scheduler; namespace network { /** Singleton that handles asynchronous http requests. @@ -172,7 +170,7 @@ private: void increaseThreadCount(); void decreaseThreadCountAndMayDeleteThis(); -private: +private: // NOLINT(readability-redundant-access-specifiers) bool _isInited; int _timeoutForConnect; @@ -214,5 +212,3 @@ private: // end group /// @} - -#endif //__CCHTTPCLIENT_H__ diff --git a/native/cocos/network/HttpCookie.cpp b/native/cocos/network/HttpCookie.cpp index 4323d7154c..e200dce638 100644 --- a/native/cocos/network/HttpCookie.cpp +++ b/native/cocos/network/HttpCookie.cpp @@ -25,9 +25,10 @@ ****************************************************************************/ #include "network/HttpCookie.h" -#include "platform/FileUtils.h" +#include +#include #include -#include +#include "platform/FileUtils.h" void HttpCookie::readFile() { std::string inString = cc::FileUtils::getInstance()->getStringFromFile(_cookieFileName); @@ -36,31 +37,34 @@ void HttpCookie::readFile() { cookiesVec.clear(); std::stringstream stream(inString); - std::string item; + std::string item; while (std::getline(stream, item, '\n')) { cookiesVec.push_back(item); } - if (cookiesVec.empty()) + if (cookiesVec.empty()) { return; + } _cookies.clear(); for (auto &cookie : cookiesVec) { - if (cookie.length() == 0) + if (cookie.length() == 0) { continue; + } if (cookie.find("#HttpOnly_") != std::string::npos) { cookie = cookie.substr(10); } - if (cookie.at(0) == '#') + if (cookie.at(0) == '#') { continue; + } - CookiesInfo co; - std::stringstream streamInfo(cookie); + CookiesInfo co; + std::stringstream streamInfo(cookie); std::vector elems; - std::string elemsItem; + std::string elemsItem; while (std::getline(streamInfo, elemsItem, '\t')) { elems.push_back(elemsItem); @@ -70,12 +74,12 @@ void HttpCookie::readFile() { if (co.domain.at(0) == '.') { co.domain = co.domain.substr(1); } - co.tailmatch = strcmp("TRUE", elems[1].c_str()) ? true : false; - co.path = elems[2]; - co.secure = strcmp("TRUE", elems[3].c_str()) ? true : false; - co.expires = elems[4]; - co.name = elems[5]; - co.value = elems[6]; + co.tailmatch = (strcmp("TRUE", elems[1].c_str()) != 0); + co.path = elems[2]; + co.secure = (strcmp("TRUE", elems[3].c_str()) != 0); + co.expires = elems[4]; + co.name = elems[5]; + co.value = elems[6]; _cookies.push_back(co); } } @@ -86,18 +90,19 @@ const std::vector *HttpCookie::getCookies() const { } const CookiesInfo *HttpCookie::getMatchCookie(const std::string &url) const { - for (auto &cookie : _cookies) { - if (url.find(cookie.domain) != std::string::npos) + for (const auto &cookie : _cookies) { + if (url.find(cookie.domain) != std::string::npos) { return &cookie; + } } return nullptr; } void HttpCookie::updateOrAddCookie(CookiesInfo *cookie) { - for (auto &_cookie : _cookies) { - if (cookie->domain == _cookie.domain) { - _cookie = *cookie; + for (auto &iter : _cookies) { + if (cookie->domain == iter.domain) { + iter = *cookie; return; } } @@ -107,11 +112,12 @@ void HttpCookie::updateOrAddCookie(CookiesInfo *cookie) { void HttpCookie::writeFile() { FILE *out; out = fopen(_cookieFileName.c_str(), "w"); - fputs("# Netscape HTTP Cookie File\n" - "# http://curl.haxx.se/docs/http-cookies.html\n" - "# This file was generated by cocos2d-x! Edit at your own risk.\n" - "# Test cocos2d-x cookie write.\n\n", - out); + fputs( + "# Netscape HTTP Cookie File\n" + "# http://curl.haxx.se/docs/http-cookies.html\n" + "# This file was generated by cocos2d-x! Edit at your own risk.\n" + "# Test cocos2d-x cookie write.\n\n", + out); std::string line; for (auto &cookie : _cookies) { diff --git a/native/cocos/network/SocketIO.cpp b/native/cocos/network/SocketIO.cpp index 28324a0fe6..3192aac380 100644 --- a/native/cocos/network/SocketIO.cpp +++ b/native/cocos/network/SocketIO.cpp @@ -35,7 +35,7 @@ #include "network/HttpClient.h" #include "network/Uri.h" #include "network/WebSocket.h" -#include "platform/Application.h" +#include "application/ApplicationManager.h" #include "json/document-wrapper.h" #include "json/rapidjson.h" @@ -372,7 +372,7 @@ void SIOClientImpl::handshake() { request->setUrl(pre.str()); request->setRequestType(HttpRequest::Type::GET); - request->setResponseCallback([this](auto &&pH1, auto &&pH2) { handshakeResponse(std::forward(pH1), std::forward(pH2)); }); + request->setResponseCallback([this](auto &&pH1, auto &&pH2) { this->handshakeResponse(std::forward(pH1), std::forward(pH2)); }); request->setTag("handshake"); CC_LOG_INFO("SIOClientImpl::handshake() waiting"); @@ -545,7 +545,7 @@ void SIOClientImpl::disconnect() { _ws->send(s); } - Application::getInstance()->getScheduler()->unscheduleAllForTarget(this); + CC_CURRENT_ENGINE()->getScheduler()->unscheduleAllForTarget(this); _connected = false; @@ -654,7 +654,7 @@ void SIOClientImpl::onOpen(WebSocket * /*ws*/) { _ws->send(s); } - Application::getInstance()->getScheduler()->schedule([this](auto &&pH1) { heartbeat(std::forward(pH1)); }, this, (static_cast(_heartbeat) * .9F), false, "heartbeat"); + CC_CURRENT_ENGINE()->getScheduler()->schedule([this](auto &&pH1) { this->heartbeat(std::forward(pH1)); }, this, (static_cast(_heartbeat) * .9F), false, "heartbeat"); for (auto &client : _clients) { client.second->onOpen(); @@ -881,8 +881,8 @@ void SIOClientImpl::onClose(WebSocket * /*ws*/) { } // discard this client _connected = false; - if (Application::getInstance()) { - Application::getInstance()->getScheduler()->unscheduleAllForTarget(this); + if (CC_CURRENT_APPLICATION() != nullptr) { + CC_CURRENT_APPLICATION()->getEngine()->getScheduler()->unscheduleAllForTarget(this); } SocketIO::getInstance()->removeSocket(_uri.getAuthority()); diff --git a/native/cocos/network/SocketIO.h b/native/cocos/network/SocketIO.h index 7744085ede..4ba4a727da 100644 --- a/native/cocos/network/SocketIO.h +++ b/native/cocos/network/SocketIO.h @@ -152,8 +152,8 @@ private: friend class SIOClientImpl; - DISABLE_COPY_SEMANTICS(SocketIO) - DISABLE_MOVE_SEMANTICS(SocketIO) + CC_DISABLE_COPY_SEMANTICS(SocketIO) + CC_DISABLE_MOVE_SEMANTICS(SocketIO) }; //c++11 style callbacks entities will be created using CC_CALLBACK (which uses std::bind) diff --git a/native/cocos/network/WebSocket-libwebsockets.cpp b/native/cocos/network/WebSocket-libwebsockets.cpp index 441cb09115..36247bb2f0 100644 --- a/native/cocos/network/WebSocket-libwebsockets.cpp +++ b/native/cocos/network/WebSocket-libwebsockets.cpp @@ -35,7 +35,7 @@ #include "uv.h" // clang-format on -#if __OHOS__ +#if __OHOS__ || __LINUX__ || __QNX__ #include "libwebsockets.h" #else #include "websockets/libwebsockets.h" @@ -56,7 +56,8 @@ #include "base/Scheduler.h" #include "network/Uri.h" #include "network/WebSocket.h" -#include "platform/Application.h" +#include "application/ApplicationManager.h" + #include "platform/FileUtils.h" #include "platform/StdC.h" @@ -140,7 +141,7 @@ static void wsLog(const char *format, ...) { } #else - #define WS_LOG printf + #define wsLog printf //NOLINT #endif #define DO_QUOTEME(x) #x @@ -519,7 +520,9 @@ void WsThreadHelper::wsThreadEntryFunc() const { } void WsThreadHelper::sendMessageToCocosThread(const std::function &cb) { - cc::Application::getInstance()->getScheduler()->performFunctionInCocosThread(cb); + if (CC_CURRENT_APPLICATION() != nullptr) { + CC_CURRENT_APPLICATION()->getEngine()->getScheduler()->performFunctionInCocosThread(cb); + } } void WsThreadHelper::sendMessageToWebSocketThread(WsMessage *msg) { diff --git a/native/cocos/network/WebSocketServer.cpp b/native/cocos/network/WebSocketServer.cpp index 4a86cdfeed..4517d5a5c2 100644 --- a/native/cocos/network/WebSocketServer.cpp +++ b/native/cocos/network/WebSocketServer.cpp @@ -32,7 +32,7 @@ #include #include "cocos/network/WebSocketServer.h" - #include "cocos/platform/Application.h" + #include "cocos/application/ApplicationManager.h" #include "cocos/base/Scheduler.h" #include "cocos/base/Log.h" @@ -97,10 +97,10 @@ void schedule_task_into_server_thread_task_queue(uv_async_t *asyn, std::function namespace cc { namespace network { - + #define RUN_IN_GAMETHREAD(task) \ do { \ - cc::Application::getInstance()->getScheduler()->performFunctionInCocosThread([=]() { \ + CC_CURRENT_ENGINE()->getScheduler()->performFunctionInCocosThread([=]() { \ task; \ }); \ } while (0) diff --git a/native/cocos/platform/Application.h b/native/cocos/platform/Application.h deleted file mode 100644 index 4cfb0d2a63..0000000000 --- a/native/cocos/platform/Application.h +++ /dev/null @@ -1,177 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - 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. -****************************************************************************/ - -#pragma once - -#include -#include -#include // // std::this_thread::sleep_for -#include "base/Macros.h" - -#include "base/AutoreleasePool.h" -#include "base/Scheduler.h" -#include "base/TypeDef.h" -#include "bindings/event/EventDispatcher.h" -#include "math/Vec2.h" - -#define NANOSECONDS_PER_SECOND 1000000000 -#define NANOSECONDS_60FPS 16666667L - -namespace cc { -/** - * @addtogroup platform - * @{ - */ - -class CC_DLL Application { -public: - /** Since WINDOWS and ANDROID are defined as macros, we could not just use these keywords in enumeration(Platform). - * Therefore, 'OS_' prefix is added to avoid conflicts with the definitions of system macros. - */ - enum class Platform { - WINDOWS, /**< Windows */ - LINUX, /**< Linux */ - MAC, /**< Mac OS X*/ - ANDROIDOS, /**< Android, because ANDROID is a macro, so use ANDROIDOS instead */ - IPHONE, /**< iPhone */ - IPAD, /**< iPad */ - OHOS, /**< Open Harmony OS> */ - }; - - enum class LanguageType { - ENGLISH = 0, - CHINESE, - FRENCH, - ITALIAN, - GERMAN, - SPANISH, - DUTCH, - RUSSIAN, - KOREAN, - JAPANESE, - HUNGARIAN, - PORTUGUESE, - ARABIC, - NORWEGIAN, - POLISH, - TURKISH, - UKRAINIAN, - ROMANIAN, - BULGARIAN - }; - - // This class is useful for internal usage. - static Application *getInstance() { return Application::instance; } - - Application(int width, int height); - virtual ~Application(); - - virtual bool init(); - virtual void onPause(); - virtual void onResume(); - virtual void onClose(); - - void restart() { _needRestart = true; } - void tick(); - void restartVM(); - - inline std::shared_ptr getScheduler() const { return Application::scheduler; } //NOLINT(readability-convert-member-functions-to-static) - void close(); - - /** - * @brief Sets the preferred frame rate for main loop callback. - * @param fps The preferred frame rate for main loop callback. - */ - void setPreferredFramesPerSecond(int fps); - - /** - * @brief Get the preferred frame rate for main loop callback. - */ - inline int getPreferredFramesPerSecond() const { return _fps; } - - inline uint getTotalFrames() const { return _totalFrames; } - - /** - @brief Get current language config. - @return Current language config. - */ - LanguageType getCurrentLanguage() const; - - /** - @brief Get current language iso 639-1 code. - @return Current language iso 639-1 code. - */ - std::string getCurrentLanguageCode() const; - - /** - @brief Get current display stats. - @return bool, is displaying stats or not. - */ - bool isDisplayStats(); - - /** - @brief set display stats information. - */ - void setDisplayStats(bool isShow); - - /** - @brief enable/disable(lock) the cursor, default is enabled - */ - void setCursorEnabled(bool value); - - /** - @brief Get target platform. - */ - Platform getPlatform() const; - - /** - @brief Open url in default browser. - @param String with url to open. - @return True if the resource located by the URL was successfully opened; otherwise false. - */ - bool openURL(const std::string &url); - - void copyTextToClipboard(const std::string &text); - - std::string getSystemVersion(); - - // return size in logical pixel unit. - inline const cc::Vec2 &getViewLogicalSize() const { return _viewLogicalSize; } - -private: - static Application * instance; - static std::shared_ptr scheduler; - int _fps = 60; - int64_t _prefererredNanosecondsPerFrame = NANOSECONDS_60FPS; - uint _totalFrames = 0; - cc::Vec2 _viewLogicalSize; - bool _needRestart = false; -}; - -// end of platform group -/** @} */ - -} // namespace cc diff --git a/native/cocos/platform/BasePlatform.cpp b/native/cocos/platform/BasePlatform.cpp new file mode 100644 index 0000000000..cff2c0c6ef --- /dev/null +++ b/native/cocos/platform/BasePlatform.cpp @@ -0,0 +1,65 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/BasePlatform.h" +#if (CC_PLATFORM == CC_PLATFORM_WINDOWS) + #include "platform/win32/WindowsPlatform.h" +#elif (CC_PLATFORM == CC_PLATFORM_ANDROID) + #include "platform/android/AndroidPlatform.h" +#elif (CC_PLATFORM == CC_PLATFORM_OHOS) + #include "platform/ohos/OhosPlatform.h" +#elif (CC_PLATFORM == CC_PLATFORM_MAC_OSX) + #include "platform/mac/MacPlatform.h" +#elif (CC_PLATFORM == CC_PLATFORM_MAC_IOS) + #include "platform/ios/IOSPlatform.h" +#elif (CC_PLATFORM == CC_PLATFORM_LINUX) + #include "platform/linux/LinuxPlatform.h" +#elif (CC_PLATFORM == CC_PLATFORM_QNX) + #include "platform/qnx/QnxPlatform.h" +#endif + +namespace cc { +BasePlatform::BasePlatform() = default; +BasePlatform::~BasePlatform() = default; + +BasePlatform* BasePlatform::getPlatform() { +#if (CC_PLATFORM == CC_PLATFORM_WINDOWS) + static WindowsPlatform platform; +#elif (CC_PLATFORM == CC_PLATFORM_ANDROID) + static AndroidPlatform platform; +#elif (CC_PLATFORM == CC_PLATFORM_OHOS) + static OhosPlatform platform; +#elif (CC_PLATFORM == CC_PLATFORM_MAC_OSX) + static MacPlatform platform; +#elif (CC_PLATFORM == CC_PLATFORM_MAC_IOS) + static IOSPlatform platform; +#elif (CC_PLATFORM == CC_PLATFORM_LINUX) + static LinuxPlatform platform; +#elif (CC_PLATFORM == CC_PLATFORM_QNX) + static QnxPlatform platform; +#endif + return &platform; +} +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/BasePlatform.h b/native/cocos/platform/BasePlatform.h new file mode 100644 index 0000000000..51117ced01 --- /dev/null +++ b/native/cocos/platform/BasePlatform.h @@ -0,0 +1,172 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "base/Log.h" +#include "base/Macros.h" + +#include "bindings/event/EventDispatcher.h" +#include "platform/interfaces/modules/ISystem.h" + +#include +#include +#include + +namespace cc { + +class OSInterface; + +class BasePlatform { +public: + BasePlatform(); + /** + * @brief Destructor of AbstratctPlatform. + */ + virtual ~BasePlatform(); + /** + * @brief Get default system platform. + */ + static BasePlatform* getPlatform(); + /** + * @brief Initialize system platform. + */ + virtual int32_t init() = 0; + /** + * @brief Run system platform. + */ + virtual int32_t run(int argc, const char** argv) = 0; + /** + * @brief Main business logic. + */ + virtual int32_t loop() = 0; + + /** + * @brief Polling event. + */ + virtual void pollEvent() = 0; + + /** + * @brief Get target system type. + */ + using OSType = ISystem::OSType; + + virtual OSType getOSType() const = 0; + + /** + * @brief Set event handling callback function. + */ + using HandleEventCallback = std::function; + + virtual void setHandleEventCallback(HandleEventCallback cb) = 0; + + /** + * @brief Set default event handling callback function. + */ + virtual void setHandleDefaultEventCallback(HandleEventCallback cb) = 0; + /** + * @brief Default event handling. + */ + virtual void handleDefaultEvent(const OSEvent& ev) = 0; + /** + * @brief Get the SDK version for Android.Other systems also have sdk versions, + but they are not currently used. + */ + virtual int getSdkVersion() const = 0; + /** + * @brief Run the task in the platform thread, + * @brief most platforms are the main thread, android is the non-main thread + * @param task : Tasks running in platform threads + * @param fps : Task call frequency + */ + using ThreadCallback = std::function; + virtual void runInPlatformThread(const ThreadCallback& task) = 0; + /** + * @brief Get task call frequency. + */ + virtual int32_t getFps() const = 0; + /** + * @brief Set task call frequency. + */ + virtual void setFps(int32_t fps) = 0; + + /** + * @brief Get target system interface(Non thread safe.). + */ + template + std::enable_if_t::value, T*> + getInterface() const { + for (const auto& it : _osInterfaces) { + T* intf = dynamic_cast(it.get()); + if (intf) { + return intf; + } + } + CCASSERT(false, "Interface does not exist"); + return nullptr; + } + + /** + * @brief Registration system interface. + */ + bool registerInterface(const OSInterface::Ptr& osInterface) { + CCASSERT(osInterface != nullptr, "Invalid interface pointer"); + auto it = std::find(_osInterfaces.begin(), _osInterfaces.end(), osInterface); + if (it != _osInterfaces.end()) { + CC_LOG_WARNING("Duplicate registration interface"); + return false; + } + _osInterfaces.push_back(osInterface); + return true; + } + /** + * @brief Unregistration system interface. + */ + void unregisterInterface(const OSInterface::Ptr& osInterface) { + CCASSERT(osInterface != nullptr, "Invalid interface pointer"); + auto it = std::find(_osInterfaces.begin(), _osInterfaces.end(), osInterface); + if (it != _osInterfaces.end()) { + CC_LOG_WARNING("Interface is not registrated"); + return; + } + _osInterfaces.erase(it); + } + +private: + + std::vector _osInterfaces; + CC_DISABLE_COPY_AND_MOVE_SEMANTICS(BasePlatform); +}; +} // namespace cc + +#define START_PLATFORM(argc, argv) \ + do { \ + cc::BasePlatform* platform = cc::BasePlatform::getPlatform(); \ + if (platform->init()) { \ + CC_LOG_FATAL("Platform initialization failed"); \ + return -1; \ + } \ + return platform->run(argc, argv); \ + } while (0) \ No newline at end of file diff --git a/native/cocos/platform/FileUtils.cpp b/native/cocos/platform/FileUtils.cpp index d06709b559..88ce89cfe8 100644 --- a/native/cocos/platform/FileUtils.cpp +++ b/native/cocos/platform/FileUtils.cpp @@ -1,6 +1,4 @@ /**************************************************************************** - Copyright (c) 2010-2013 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -39,6 +37,7 @@ #include #include +#include #ifdef MINIZIP_FROM_SYSTEM #include diff --git a/native/cocos/platform/FileUtils.h b/native/cocos/platform/FileUtils.h index 9d7348d696..e9aa1603ff 100644 --- a/native/cocos/platform/FileUtils.h +++ b/native/cocos/platform/FileUtils.h @@ -1,6 +1,4 @@ /**************************************************************************** - Copyright (c) 2010-2013 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. http://www.cocos.com diff --git a/native/cocos/platform/IEventDispatch.h b/native/cocos/platform/IEventDispatch.h new file mode 100644 index 0000000000..afade1349a --- /dev/null +++ b/native/cocos/platform/IEventDispatch.h @@ -0,0 +1,47 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "bindings/event/EventDispatcher.h" + +namespace cc { +class IEventDispatch { +public: + /** + * Destructor of EventDispatchInterface. + */ + virtual ~IEventDispatch() = default; + /** + * Dispatch event interface. + */ + virtual void dispatchEvent(const OSEvent& ev) = 0; + /** + * Dispatch touch event interface. + */ + virtual void dispatchTouchEvent(const OSEvent& ev) = 0; +}; + +} // namespace cc diff --git a/native/cocos/platform/Image.cpp b/native/cocos/platform/Image.cpp index f748b2607f..40a5b33a8b 100644 --- a/native/cocos/platform/Image.cpp +++ b/native/cocos/platform/Image.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include "base/Config.h" // CC_USE_JPEG, CC_USE_WEBP #if CC_USE_JPEG @@ -42,7 +43,7 @@ extern "C" { #if CC_USE_PNG - #if __OHOS__ + #if __OHOS__ || __LINUX__ || __QNX__ #include "png.h" #else #include "png/png.h" diff --git a/native/cocos/platform/UniversalPlatform.cpp b/native/cocos/platform/UniversalPlatform.cpp new file mode 100644 index 0000000000..87d0e34cc7 --- /dev/null +++ b/native/cocos/platform/UniversalPlatform.cpp @@ -0,0 +1,133 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/UniversalPlatform.h" + +#include "platform/interfaces/OSInterface.h" + +#include "platform/interfaces/modules/IAccelerometer.h" +#include "platform/interfaces/modules/IBattery.h" +#include "platform/interfaces/modules/INetwork.h" +#include "platform/interfaces/modules/IScreen.h" +#include "platform/interfaces/modules/ISystem.h" +#include "platform/interfaces/modules/ISystemWindow.h" +#include "platform/interfaces/modules/IVibrator.h" + +extern int cocos_main(int argc, const char** argv); // NOLINT(readability-identifier-naming) +extern void cocos_destory(); // NOLINT(readability-identifier-naming) + +namespace cc { +UniversalPlatform::OSType UniversalPlatform::getOSType() const { + return getInterface()->getOSType(); +} + +void UniversalPlatform::dispatchEvent(const OSEvent& ev) { + bool isHandled = false; + if (_handleEventCallback) { + isHandled = (_handleEventCallback)(ev); + } + if (isHandled) { + return; + } + if (_handleDefaultEventCallback) { + isHandled = (_handleDefaultEventCallback)(ev); + } + if (!isHandled) { + handleDefaultEvent(ev); + } +} + +void UniversalPlatform::dispatchTouchEvent(const OSEvent& ev) { +} + +void UniversalPlatform::handleDefaultEvent(const OSEvent& ev) { + // TODO(cc) : Follow-up support +} + +void UniversalPlatform::setHandleEventCallback(HandleEventCallback cb) { + _handleEventCallback = cb; +} + +void UniversalPlatform::setHandleDefaultEventCallback(HandleEventCallback cb) { + _handleDefaultEventCallback = cb; +} + +int32_t UniversalPlatform::init() { + registerInterface(ISystemWindow::createSystemWindowInterface()); + registerInterface(ISystem::createSystemInterface()); + registerInterface(INetwork::createNetworkInterface()); + registerInterface(IScreen::createScreenInterface()); + registerInterface(IBattery::createBatteryInterface()); + registerInterface(IVibrator::createVibratorInterface()); + registerInterface(IAccelerometer::createAccelerometerInterface()); + return 0; +} + +int32_t UniversalPlatform::run(int argc, const char** argv) { + if (cocos_main(argc, argv) != 0) { + return -1; + } + return loop(); +} + +int UniversalPlatform::getSdkVersion() const { + return 0; +} + +void UniversalPlatform::runInPlatformThread(const ThreadCallback& task) { + _mainTask = task; +} + +void UniversalPlatform::runTask() { + if (_mainTask) { + _mainTask(); + } +} + +int32_t UniversalPlatform::getFps() const { + return _fps; +} + +void UniversalPlatform::setFps(int32_t fps) { + _fps = fps; +} + +void UniversalPlatform::pollEvent() { +} + +void UniversalPlatform::onPause() { +} + +void UniversalPlatform::onResume() { +} + +void UniversalPlatform::onClose() { +} + +void UniversalPlatform::onDestory() { + cocos_destory(); +} + +} // namespace cc diff --git a/native/cocos/platform/UniversalPlatform.h b/native/cocos/platform/UniversalPlatform.h new file mode 100644 index 0000000000..0386dffb99 --- /dev/null +++ b/native/cocos/platform/UniversalPlatform.h @@ -0,0 +1,118 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/BasePlatform.h" +#include "platform/IEventDispatch.h" + +namespace cc { +class UniversalPlatform : public BasePlatform, public IEventDispatch { +public: + /** + * @brief Implement basic platform initialization. + */ + int32_t init() override; + /** + * @brief Start base platform initialization. + */ + int32_t run(int argc, const char** argv) override; + + /** + * @brief Get targe platform type. + */ + OSType getOSType() const override; + /** + * @brief Set the event handling callback. + */ + void setHandleEventCallback(HandleEventCallback cb) override; + /** + * @brief Set the event to handle callbacks by default. + */ + void setHandleDefaultEventCallback(HandleEventCallback cb) override; + /** + * @brief Implement dispatch event interface. + */ + void dispatchEvent(const OSEvent& ev) override; + /** + * @brief Implement dispatch touch event interface. + */ + void dispatchTouchEvent(const OSEvent& ev) override; + /** + * @brief Implement handle default event interface. + */ + void handleDefaultEvent(const OSEvent& ev) override; + /** + * @brief Get the SDK version for Android.Other systems also have sdk versions, + but they are not currently used. + */ + int getSdkVersion() const override; + /** + * @brief Polling event + */ + void pollEvent() override; + /** + * @brief Run the task in the platform thread, + * @brief most platforms are the main thread, android is the non-main thread + * @param task : Tasks running in platform threads + */ + void runInPlatformThread(const ThreadCallback& task) override; + /** + * @brief Get task call frequency. + */ + int32_t getFps() const override; + /** + * @brief Set task call frequency. + */ + void setFps(int32_t fps) override; + + virtual void runTask(); + /** + * @brief Processing pause message + */ + virtual void onPause(); + /** + * @brief Processing resume message + */ + virtual void onResume(); + /** + * @brief Processing close message + */ + virtual void onClose(); + /** + * @brief Processing destroy message + */ + virtual void onDestory(); + +private: + ThreadCallback _mainTask{nullptr}; + + int32_t _fps{60}; + + HandleEventCallback _handleEventCallback{nullptr}; + HandleEventCallback _handleDefaultEventCallback{nullptr}; +}; + +} // namespace cc diff --git a/native/cocos/platform/android/AndroidPlatform.cpp b/native/cocos/platform/android/AndroidPlatform.cpp new file mode 100644 index 0000000000..2672ee5a05 --- /dev/null +++ b/native/cocos/platform/android/AndroidPlatform.cpp @@ -0,0 +1,79 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 + +#include "platform/android/AndroidPlatform.h" +#include "platform/java/jni/glue/JniNativeGlue.h" + +namespace cc { +AndroidPlatform::AndroidPlatform() { + _jniNativeGlue = JNI_NATIVE_GLUE(); +} + +int AndroidPlatform::getSdkVersion() const { + return _jniNativeGlue->getSdkVersion(); +} + +int32_t AndroidPlatform::run(int argc, const char** argv) { + std::thread mainLogicThread([this, argc, argv]() { + waitWindowInitialized(); + UniversalPlatform::run(argc, argv); + onDestory(); + }); + mainLogicThread.detach(); + _jniNativeGlue->waitRunning(); + return 0; +} + +void AndroidPlatform::waitWindowInitialized() { + _jniNativeGlue->setRunning(true); + while (_jniNativeGlue->isRunning()) { + pollEvent(); + NativeWindowType* wndHandle = _jniNativeGlue->getWindowHandler(); + if (wndHandle != nullptr) { + break; + } + //std::this_thread::sleep_for(std::chrono::nanoseconds(100)); + } + _jniNativeGlue->setEventDispatch(this); +} + +int32_t AndroidPlatform::loop() { + while (_jniNativeGlue->isRunning()) { + pollEvent(); + runTask(); + } + return 0; +} + +void AndroidPlatform::pollEvent() { + _jniNativeGlue->execCommand(); + if (!_jniNativeGlue->isPause()) { + std::this_thread::yield(); + } + _jniNativeGlue->flushTasksOnGameThread(); +} + +}; // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/apple/Device-apple.mm b/native/cocos/platform/android/AndroidPlatform.h similarity index 70% rename from native/cocos/platform/apple/Device-apple.mm rename to native/cocos/platform/android/AndroidPlatform.h index 8ad0a32d59..8b2e95039f 100644 --- a/native/cocos/platform/apple/Device-apple.mm +++ b/native/cocos/platform/android/AndroidPlatform.h @@ -1,6 +1,4 @@ /**************************************************************************** - Copyright (c) 2010-2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -25,25 +23,23 @@ THE SOFTWARE. ****************************************************************************/ -#include "platform/apple/Device-apple.h" -#include "platform/Application.h" +#pragma once -#if CC_PLATFORM == CC_PLATFORM_MAC_OSX - #import -#endif -#if CC_PLATFORM == CC_PLATFORM_MAC_IOS - #import -#endif +#include "platform/UniversalPlatform.h" namespace cc { +class JniNativeGlue; +class AndroidPlatform : public UniversalPlatform { +public: + AndroidPlatform(); + void pollEvent() override; + int32_t run(int argc, const char** argv) override; + int getSdkVersion() const override; + int32_t loop() override; -float Device::getDevicePixelRatio() { -#if (CC_PLATFORM == CC_PLATFORM_MAC_OSX) - return [[[[NSApplication sharedApplication] delegate] getWindow] backingScaleFactor]; - ; -#else - return [[UIScreen mainScreen] nativeScale]; -#endif //CC_USE_METAL -} +private: + void waitWindowInitialized(); -} // namespace cc + JniNativeGlue* _jniNativeGlue; +}; +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/android/Application-android.cpp b/native/cocos/platform/android/Application-android.cpp deleted file mode 100644 index 1c7a2f0763..0000000000 --- a/native/cocos/platform/android/Application-android.cpp +++ /dev/null @@ -1,225 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - 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 -#include -#include -#include "audio/include/AudioEngine.h" -#include "base/Scheduler.h" -#include "cocos/bindings/event/EventDispatcher.h" -#include "cocos/bindings/jswrapper/SeApi.h" -#include "platform/Application.h" -#include "platform/android/jni/JniCocosActivity.h" -#include "platform/java/jni/JniHelper.h" -#include "platform/java/jni/JniImp.h" - -#include "pipeline/Define.h" -#include "pipeline/RenderPipeline.h" -#include "renderer/GFXDeviceManager.h" - -#define LOG_APP_TAG "Application_android Debug" -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_APP_TAG, __VA_ARGS__) - -// IDEA: using ndk-r10c will cause the next function could not be found. It may be a bug of ndk-r10c. -// Here is the workaround method to fix the problem. -#ifdef __aarch64__ -extern "C" size_t __ctype_get_mb_cur_max(void) { //NOLINT - return (size_t)sizeof(wchar_t); -} -#endif - -namespace cc { - -namespace { - -bool setCanvasCallback(se::Object * /*global*/) { - auto viewLogicalSize = cc::Application::getInstance()->getViewLogicalSize(); - se::AutoHandleScope scope; - se::ScriptEngine * se = se::ScriptEngine::getInstance(); - std::stringstream ss; - { - auto windowPtr = reinterpret_cast(cc::cocosApp.window); - ss << "window.innerWidth = " << static_cast(viewLogicalSize.x) << ";"; - ss << "window.innerHeight = " << static_cast(viewLogicalSize.y) << ";"; - ss << "window.windowHandler = "; - if (sizeof(windowPtr) == 8) { // use bigint - ss << static_cast(windowPtr) << "n;"; - } - if (sizeof(windowPtr) == 4) { - ss << static_cast(windowPtr) << ";"; - } - } - se->evalString(ss.str().c_str()); - - return true; -} - -} // namespace - -Application * Application::instance = nullptr; -std::shared_ptr Application::scheduler = nullptr; - -Application::Application(int width, int height) { - Application::instance = this; - scheduler = std::make_shared(); - _viewLogicalSize.x = static_cast(width); - _viewLogicalSize.y = static_cast(height); -} - -Application::~Application() { -#if USE_AUDIO - AudioEngine::end(); -#endif - - Application::getInstance()->onClose(); - if (EventDispatcher::initialized()) { - EventDispatcher::dispatchCloseEvent(); - } - - pipeline::RenderPipeline::getInstance()->destroy(); - - EventDispatcher::destroy(); - se::ScriptEngine::destroyInstance(); - - gfx::DeviceManager::destroy(); - - Application::instance = nullptr; -} - -bool Application::init() { - se::ScriptEngine *se = se::ScriptEngine::getInstance(); - se->addRegisterCallback(setCanvasCallback); - - EventDispatcher::init(); - - return true; -} - -void Application::onPause() { -} - -void Application::onResume() { -} - -void Application::onClose() { -} - -void Application::setPreferredFramesPerSecond(int fps) { - if (fps == 0) { - return; - } - - _fps = fps; - _prefererredNanosecondsPerFrame = static_cast(1.0 / _fps * NANOSECONDS_PER_SECOND); -} - -std::string Application::getCurrentLanguageCode() const { // NOLINT - return getCurrentLanguageCodeJNI(); -} - -bool Application::isDisplayStats() { //NOLINT - se::AutoHandleScope hs; - se::Value ret; - char commandBuf[100] = "cc.debug.isDisplayStats();"; - se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret); - return ret.toBoolean(); -} - -void Application::setDisplayStats(bool isShow) { // NOLINT - se::AutoHandleScope hs; - char commandBuf[100] = {0}; - sprintf(commandBuf, "cc.debug.setDisplayStats(%s);", isShow ? "true" : "false"); - se::ScriptEngine::getInstance()->evalString(commandBuf); -} - -void Application::setCursorEnabled(bool value) { -} - -Application::LanguageType Application::getCurrentLanguage() const { // NOLINT - std::string languageName = getCurrentLanguageJNI(); - const char * pLanguageName = languageName.c_str(); - LanguageType ret = LanguageType::ENGLISH; - - if (0 == strcmp("zh", pLanguageName)) { - ret = LanguageType::CHINESE; - } else if (0 == strcmp("en", pLanguageName)) { - ret = LanguageType::ENGLISH; - } else if (0 == strcmp("fr", pLanguageName)) { - ret = LanguageType::FRENCH; - } else if (0 == strcmp("it", pLanguageName)) { - ret = LanguageType::ITALIAN; - } else if (0 == strcmp("de", pLanguageName)) { - ret = LanguageType::GERMAN; - } else if (0 == strcmp("es", pLanguageName)) { - ret = LanguageType::SPANISH; - } else if (0 == strcmp("ru", pLanguageName)) { - ret = LanguageType::RUSSIAN; - } else if (0 == strcmp("nl", pLanguageName)) { - ret = LanguageType::DUTCH; - } else if (0 == strcmp("ko", pLanguageName)) { - ret = LanguageType::KOREAN; - } else if (0 == strcmp("ja", pLanguageName)) { - ret = LanguageType::JAPANESE; - } else if (0 == strcmp("hu", pLanguageName)) { - ret = LanguageType::HUNGARIAN; - } else if (0 == strcmp("pt", pLanguageName)) { - ret = LanguageType::PORTUGUESE; - } else if (0 == strcmp("ar", pLanguageName)) { - ret = LanguageType::ARABIC; - } else if (0 == strcmp("nb", pLanguageName)) { - ret = LanguageType::NORWEGIAN; - } else if (0 == strcmp("pl", pLanguageName)) { - ret = LanguageType::POLISH; - } else if (0 == strcmp("tr", pLanguageName)) { - ret = LanguageType::TURKISH; - } else if (0 == strcmp("uk", pLanguageName)) { - ret = LanguageType::UKRAINIAN; - } else if (0 == strcmp("ro", pLanguageName)) { - ret = LanguageType::ROMANIAN; - } else if (0 == strcmp("bg", pLanguageName)) { - ret = LanguageType::BULGARIAN; - } - return ret; -} - -Application::Platform Application::getPlatform() const { // NOLINT - return Platform::ANDROIDOS; -} - -bool Application::openURL(const std::string &url) { // NOLINT - return openURLJNI(url); -} - -void Application::copyTextToClipboard(const std::string &text) { // NOLINT - copyTextToClipboardJNI(text); -} - -std::string Application::getSystemVersion() { // NOLINT - return getSystemVersionJNI(); -} - -} // namespace cc diff --git a/native/cocos/platform/android/View.cpp b/native/cocos/platform/android/View.cpp deleted file mode 100644 index 1815ffd4f8..0000000000 --- a/native/cocos/platform/android/View.cpp +++ /dev/null @@ -1,182 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - 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 "View.h" -#include -#include "cocos/bindings/event/CustomEventTypes.h" -#include "cocos/bindings/event/EventDispatcher.h" -#include "platform/Application.h" -#include "platform/android/jni/JniCocosActivity.h" - -namespace { -struct cc::TouchEvent touchEvent; -struct cc::KeyboardEvent keyboardEvent; - -// key values in web, refer to http://docs.cocos.com/creator/api/en/enums/KEY.html -std::unordered_map keyCodeMap = { - {AKEYCODE_BACK, 6}, - {AKEYCODE_ENTER, 13}, - {AKEYCODE_MENU, 18}, - {AKEYCODE_DPAD_UP, 1003}, - {AKEYCODE_DPAD_DOWN, 1004}, - {AKEYCODE_DPAD_LEFT, 1000}, - {AKEYCODE_DPAD_RIGHT, 1001}, - {AKEYCODE_DPAD_CENTER, 1005}}; - -void dispatchTouchEvent(int index, AInputEvent *event, cc::TouchEvent *touchEvent) { - int pointerID = AMotionEvent_getPointerId(event, index); - touchEvent->touches.emplace_back(AMotionEvent_getX(event, index), // x - AMotionEvent_getY(event, index), // y - pointerID); - - cc::EventDispatcher::dispatchTouchEvent(*touchEvent); - touchEvent->touches.clear(); -} - -void dispatchTouchEvents(AInputEvent *event, cc::TouchEvent *touchEvent) { - size_t pointerCount = AMotionEvent_getPointerCount(event); - for (size_t i = 0; i < pointerCount; ++i) { - touchEvent->touches.emplace_back(AMotionEvent_getX(event, i), - AMotionEvent_getY(event, i), - AMotionEvent_getPointerId(event, i)); - } - - cc::EventDispatcher::dispatchTouchEvent(*touchEvent); - touchEvent->touches.clear(); -} -} // namespace - -namespace cc { - -void View::engineHandleCmd(int cmd) { - static bool isWindowInitialized = false; - // Handle CMD here if needed. - switch (cmd) { - case APP_CMD_INIT_WINDOW: { - if (!isWindowInitialized) { - isWindowInitialized = true; - return; - } - cc::CustomEvent event; - event.name = EVENT_RECREATE_WINDOW; - event.args->ptrVal = cocosApp.window; - cc::EventDispatcher::dispatchCustomEvent(event); - } break; - case APP_CMD_TERM_WINDOW: { - cc::CustomEvent event; - event.name = EVENT_DESTROY_WINDOW; - event.args->ptrVal = cocosApp.window; - cc::EventDispatcher::dispatchCustomEvent(event); - } break; - case APP_CMD_RESUME: - if (Application::getInstance()) { - Application::getInstance()->onResume(); - } - break; - case APP_CMD_PAUSE: - if (Application::getInstance()) { - Application::getInstance()->onPause(); - } - break; - case APP_CMD_LOW_MEMORY: - cc::EventDispatcher::dispatchMemoryWarningEvent(); - break; - default: - break; - } -} - -/** - * Process the next input event. - */ -int32_t View::engineHandleInput(struct android_app * /*app*/, AInputEvent *event) { - int type = AInputEvent_getType(event); - - if (type == AINPUT_EVENT_TYPE_KEY) { - int action = AKeyEvent_getAction(event); - if (action == AKEY_EVENT_ACTION_MULTIPLE) { - return 0; - } - - int keyCode = AKeyEvent_getKeyCode(event); - if (keyCodeMap.count(keyCode) > 0) { - keyCode = keyCodeMap[keyCode]; - } else { - keyCode = 0; - } - - keyboardEvent.key = keyCode; - keyboardEvent.action = action == AKEY_EVENT_ACTION_DOWN - ? cc::KeyboardEvent::Action::RELEASE - : cc::KeyboardEvent::Action::PRESS; - cc::EventDispatcher::dispatchKeyboardEvent(keyboardEvent); - - return 1; - } - if (type == AINPUT_EVENT_TYPE_MOTION) { - int action = AMotionEvent_getAction(event); - - switch (action & AMOTION_EVENT_ACTION_MASK) { - case AMOTION_EVENT_ACTION_DOWN: - touchEvent.type = cc::TouchEvent::Type::BEGAN; - dispatchTouchEvent(0, event, &touchEvent); - break; - case AMOTION_EVENT_ACTION_POINTER_DOWN: - touchEvent.type = cc::TouchEvent::Type::BEGAN; - dispatchTouchEvent((action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT, - event, - &touchEvent); - break; - case AMOTION_EVENT_ACTION_UP: - touchEvent.type = cc::TouchEvent::Type::ENDED; - dispatchTouchEvent(0, event, &touchEvent); - break; - case AMOTION_EVENT_ACTION_POINTER_UP: - touchEvent.type = cc::TouchEvent::Type::ENDED; - dispatchTouchEvent((action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT, - event, - &touchEvent); - break; - case AMOTION_EVENT_ACTION_MOVE: - touchEvent.type = cc::TouchEvent::Type::MOVED; - dispatchTouchEvents(event, &touchEvent); - break; - case AMOTION_EVENT_ACTION_CANCEL: - touchEvent.type = cc::TouchEvent::Type::CANCELLED; - dispatchTouchEvents(event, &touchEvent); - break; - default: - return 0; - } - - return 1; - } - - return 0; -} - -} // namespace cc diff --git a/native/cocos/platform/android/jni/JniCocosActivity.cpp b/native/cocos/platform/android/jni/JniCocosActivity.cpp index cc9e3ddfe5..9bcae2d1d5 100644 --- a/native/cocos/platform/android/jni/JniCocosActivity.cpp +++ b/native/cocos/platform/android/jni/JniCocosActivity.cpp @@ -33,192 +33,35 @@ #include #include #include -#include "platform/Application.h" + #include "platform/android/FileUtils-android.h" -#include "platform/android/View.h" #include "platform/java/jni/JniHelper.h" +#include "platform/java/jni/glue/JniNativeGlue.h" -#define LOGV(...) __android_log_print(ANDROID_LOG_INFO, "CocosActivity JNI", __VA_ARGS__) - -cc::Application *cocos_main(int, int) __attribute__((weak)); //NOLINT - -namespace cc { -CocosApp cocosApp; -} - -namespace { -int messagePipe[2]; -int pipeRead = 0; -int pipeWrite = 0; -cc::Application *game = nullptr; - -void createGame(ANativeWindow *window) { - int width = ANativeWindow_getWidth(window); - int height = ANativeWindow_getHeight(window); - game = cocos_main(width, height); - game->init(); -} - -void writeCommand(int8_t cmd) { - write(pipeWrite, &cmd, sizeof(cmd)); -} - -int readCommand(int8_t &cmd) { - return read(pipeRead, &cmd, sizeof(cmd)); -} - -void handlePauseResume(int8_t cmd) { - LOGV("appState=%d", cmd); - std::unique_lock lk(cc::cocosApp.mutex); - cc::cocosApp.appState = static_cast(cmd); - lk.unlock(); - cc::cocosApp.cond.notify_all(); -} - -void preExecCmd(int8_t cmd) { - switch (cmd) { - case APP_CMD_INIT_WINDOW: { - LOGV("APP_CMD_INIT_WINDOW"); - std::unique_lock lk(cc::cocosApp.mutex); - cc::cocosApp.window = cc::cocosApp.pendingWindow; - lk.unlock(); - cc::cocosApp.cond.notify_all(); - cc::cocosApp.animating = true; - - if (!game) { - createGame(cc::cocosApp.window); - } - } break; - case APP_CMD_TERM_WINDOW: - LOGV("APP_CMD_TERM_WINDOW"); - cc::cocosApp.animating = false; - cc::cocosApp.cond.notify_all(); - break; - case APP_CMD_RESUME: - LOGV("APP_CMD_RESUME"); - handlePauseResume(cmd); - break; - case APP_CMD_PAUSE: - LOGV("APP_CMD_PAUSE"); - handlePauseResume(cmd); - break; - case APP_CMD_DESTROY: - LOGV("APP_CMD_DESTROY"); - cc::cocosApp.destroyRequested = true; - break; - default: - break; - } -} - -void postExecCmd(int8_t cmd) { - switch (cmd) { - case APP_CMD_TERM_WINDOW: { - std::unique_lock lk(cc::cocosApp.mutex); - cc::cocosApp.window = nullptr; - lk.unlock(); - cc::cocosApp.cond.notify_all(); - } break; - default: - break; - } -} - -void glThreadEntry() { - std::unique_lock lk(cc::cocosApp.mutex); - cc::cocosApp.running = true; - lk.unlock(); - cc::cocosApp.cond.notify_all(); - - int8_t cmd = 0; - while (true) { - if (readCommand(cmd) > 0) { - preExecCmd(cmd); - cc::View::engineHandleCmd(cmd); - postExecCmd(cmd); - } - - if (!cc::cocosApp.animating || APP_CMD_PAUSE == cc::cocosApp.appState) { - std::this_thread::yield(); - } - - if (game && cc::cocosApp.animating) { - // Handle java events send by UI thread. Input events are handled here too. - cc::JniHelper::callStaticVoidMethod("com.cocos.lib.CocosHelper", - "flushTasksOnGameThread"); - game->tick(); - } - if (cc::cocosApp.destroyRequested) break; - } - - close(pipeRead); - close(pipeWrite); - - delete game; - game = nullptr; -} - -void setWindow(ANativeWindow *window) { - std::unique_lock lk(cc::cocosApp.mutex); - if (cc::cocosApp.pendingWindow) { - writeCommand(APP_CMD_TERM_WINDOW); - } - cc::cocosApp.pendingWindow = window; - if (window) { - writeCommand(APP_CMD_INIT_WINDOW); - } - while (cc::cocosApp.window != cc::cocosApp.pendingWindow) { - cc::cocosApp.cond.wait(lk); - } -} - -void setAppState(int8_t cmd) { - std::unique_lock lk(cc::cocosApp.mutex); - writeCommand(cmd); - while (cc::cocosApp.appState != cmd) { - cc::cocosApp.cond.wait(lk); - } -} -} // namespace extern "C" { //NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onCreateNative(JNIEnv *env, jobject obj, jobject activity, jobject assetMgr, jstring obbPath, jint sdkVersion) { - if (cc::cocosApp.running) { + if (JNI_NATIVE_GLUE()->isRunning()) { return; } - - cc::cocosApp.sdkVersion = sdkVersion; + JNI_NATIVE_GLUE()->setSdkVersion(sdkVersion); cc::JniHelper::init(env, activity); - cc::cocosApp.obbPath = cc::JniHelper::jstring2string(obbPath); - cc::cocosApp.assetManager = AAssetManager_fromJava(env, assetMgr); - cc::FileUtilsAndroid::setassetmanager(cc::cocosApp.assetManager); - - if (pipe(messagePipe)) { - LOGV("Can not create pipe: %s", strerror(errno)); - } - pipeRead = messagePipe[0]; - pipeWrite = messagePipe[1]; - if (fcntl(pipeRead, F_SETFL, O_NONBLOCK) < 0) { - LOGV("Can not make pipe read to non blocking mode."); - } - - std::thread glThread(glThreadEntry); - glThread.detach(); - - std::unique_lock lk(cc::cocosApp.mutex); - while (!cc::cocosApp.running) { - cc::cocosApp.cond.wait(lk); - } + JNI_NATIVE_GLUE()->setObbPath(cc::JniHelper::jstring2string(obbPath)); + JNI_NATIVE_GLUE()->setResourceManager(AAssetManager_fromJava(env, assetMgr)); + cc::FileUtilsAndroid::setassetmanager(AAssetManager_fromJava(env, assetMgr)); + JNI_NATIVE_GLUE()->start(0, nullptr); } + //NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onSurfaceCreatedNative(JNIEnv *env, jobject obj, jobject surface) { - setWindow(ANativeWindow_fromSurface(env, surface)); + JNI_NATIVE_GLUE()->setWindowHandler(ANativeWindow_fromSurface(env, surface)); } + //NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onStartNative(JNIEnv *env, jobject obj) { - setAppState(APP_CMD_RESUME); + JNI_NATIVE_GLUE()->onResume(); } //NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onPauseNative(JNIEnv *env, jobject obj) { @@ -228,11 +71,11 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onResumeNative(JNIEnv *e } //NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onStopNative(JNIEnv *env, jobject obj) { - setAppState(APP_CMD_PAUSE); + JNI_NATIVE_GLUE()->onPause(); } //NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onLowMemoryNative(JNIEnv *env, jobject obj) { - writeCommand(APP_CMD_LOW_MEMORY); + JNI_NATIVE_GLUE()->onLowMemory(); } //NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onWindowFocusChangedNative(JNIEnv *env, jobject obj, jboolean has_focus) { @@ -242,6 +85,6 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onSurfaceChangedNative(J } //NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onSurfaceDestroyNative(JNIEnv *env, jobject obj) { - setWindow(nullptr); + JNI_NATIVE_GLUE()->setWindowHandler(nullptr); } } diff --git a/native/cocos/platform/android/jni/JniCocosActivity.h b/native/cocos/platform/android/jni/JniCocosActivity.h index 22b45e4c99..a7cc3204a5 100644 --- a/native/cocos/platform/android/jni/JniCocosActivity.h +++ b/native/cocos/platform/android/jni/JniCocosActivity.h @@ -25,31 +25,8 @@ #pragma once -#include -#include -#include -#include -#include - -namespace cc { - -struct CocosApp { - AAssetManager *assetManager = nullptr; - ANativeWindow *window = nullptr; - std::string obbPath; - int sdkVersion = 0; - - std::mutex mutex; - std::condition_variable cond; - ANativeWindow *pendingWindow = nullptr; - bool destroyRequested = false; - bool animating = true; - bool running = false; - - // Current state of the app. May be either APP_CMD_RESUME, APP_CMD_PAUSE. - int appState = 0; -}; - -extern CocosApp cocosApp; - -} // namespace cc +//#include +//#include +//#include +//#include +//#include \ No newline at end of file diff --git a/native/cocos/platform/android/jni/JniCocosSurfaceView.cpp b/native/cocos/platform/android/jni/JniCocosSurfaceView.cpp index fe2aaafc5e..2d140ad230 100644 --- a/native/cocos/platform/android/jni/JniCocosSurfaceView.cpp +++ b/native/cocos/platform/android/jni/JniCocosSurfaceView.cpp @@ -25,15 +25,19 @@ #include #include #include -#include "platform/Application.h" -#include "platform/java/jni/JniHelper.h" +#include "platform/BasePlatform.h" +#include "platform/java/jni/glue/JniNativeGlue.h" -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, "JniCocosSurfaceView JNI", __VA_ARGS__) +//#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, "JniCocosSurfaceView JNI", __VA_ARGS__) extern "C" { //NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosSurfaceView_nativeOnSizeChanged(JNIEnv *env, jobject thiz, jint width, jint height) { - cc::EventDispatcher::dispatchResizeEvent(width, height); + cc::WindowEvent ev; + ev.type = cc::WindowEvent::Type::SIZE_CHANGED; + ev.width = width; + ev.height = height; + JNI_NATIVE_GLUE()->dispatchEvent(ev); } } diff --git a/native/cocos/platform/android/modules/Screen.cpp b/native/cocos/platform/android/modules/Screen.cpp new file mode 100644 index 0000000000..2bcdd9385c --- /dev/null +++ b/native/cocos/platform/android/modules/Screen.cpp @@ -0,0 +1,47 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/android/modules/Screen.h" +#include +#include +#include +#include "platform/java/jni/JniHelper.h" + +namespace cc { + +int Screen::getDPI() const { + static int dpi = -1; + if (dpi == -1) { + AConfiguration *config = AConfiguration_new(); + //AConfiguration_fromAssetManager(config, cocosApp.assetManager); + int32_t density = AConfiguration_getDensity(config); + AConfiguration_delete(config); + const int stdDpi = 160; + dpi = density * stdDpi; + } + return dpi; +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/apple/Device-apple.h b/native/cocos/platform/android/modules/Screen.h similarity index 87% rename from native/cocos/platform/apple/Device-apple.h rename to native/cocos/platform/android/modules/Screen.h index adfe053f1e..7a8c22c529 100644 --- a/native/cocos/platform/apple/Device-apple.h +++ b/native/cocos/platform/android/modules/Screen.h @@ -1,6 +1,4 @@ /**************************************************************************** - Copyright (c) 2010-2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -25,9 +23,15 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef CCDevice_apple_hpp -#define CCDevice_apple_hpp +#pragma once -#include "platform/Device.h" +#include "platform/java/modules/CommonScreen.h" -#endif /* CCDevice_apple_hpp */ +namespace cc { + +class Screen : public CommonScreen { +public: + int getDPI() const override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/templates/windows/main.h b/native/cocos/platform/android/modules/System.cpp similarity index 76% rename from native/templates/windows/main.h rename to native/cocos/platform/android/modules/System.cpp index 458f7687b4..04b91eb6ba 100644 --- a/native/templates/windows/main.h +++ b/native/cocos/platform/android/modules/System.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -21,17 +21,19 @@ 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 __MAIN_H__ -#define __MAIN_H__ +#include "platform/android/modules/System.h" -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers -// Windows Header Files: -#include +namespace cc { +System::System() = default; -// C RunTime Header Files -#include "StdC.h" +System::~System() = default; -#endif // __WINMAIN_H__ +System::OSType System::getOSType() const { + return OSType::ANDROIDOS; +} + + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/android/modules/System.h b/native/cocos/platform/android/modules/System.h new file mode 100644 index 0000000000..e57753398a --- /dev/null +++ b/native/cocos/platform/android/modules/System.h @@ -0,0 +1,41 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/java/modules/CommonSystem.h" + +namespace cc { + +class System : public CommonSystem { +public: + System(); + ~System() override; + + OSType getOSType() const override; +private: +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/apple/JsbBridge.mm b/native/cocos/platform/apple/JsbBridge.mm index 702ef0f3b8..b335947f08 100644 --- a/native/cocos/platform/apple/JsbBridge.mm +++ b/native/cocos/platform/apple/JsbBridge.mm @@ -25,7 +25,6 @@ #import #include -#include #include "JsbBridge.h" #include "cocos/bindings/manual/JavaScriptObjCBridge.h" diff --git a/native/cocos/platform/ios/Reachability.cpp b/native/cocos/platform/apple/Reachability.cpp similarity index 100% rename from native/cocos/platform/ios/Reachability.cpp rename to native/cocos/platform/apple/Reachability.cpp diff --git a/native/cocos/platform/ios/Reachability.h b/native/cocos/platform/apple/Reachability.h similarity index 100% rename from native/cocos/platform/ios/Reachability.h rename to native/cocos/platform/apple/Reachability.h diff --git a/native/cocos/platform/apple/modules/CanvasRenderingContext2DDelegate.h b/native/cocos/platform/apple/modules/CanvasRenderingContext2DDelegate.h new file mode 100644 index 0000000000..da7cd5f56a --- /dev/null +++ b/native/cocos/platform/apple/modules/CanvasRenderingContext2DDelegate.h @@ -0,0 +1,83 @@ +/**************************************************************************** + Copyright (c) 2018-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h" + +#include "base/csscolorparser.h" +#include "bindings/jswrapper/config.h" +#include "math/Math.h" + +#ifdef __OBJC__ +@class CanvasRenderingContext2DDelegateImpl; +#else +class CanvasRenderingContext2DDelegateImpl; +#endif + +namespace cc { + +class CanvasRenderingContext2DDelegate : public ICanvasRenderingContext2D::Delegate { +public: + using Size = std::array; + CanvasRenderingContext2DDelegate(); + ~CanvasRenderingContext2DDelegate() override; + + void recreateBuffer(float w, float h) override; + void beginPath() override; + void closePath() override; + void moveTo(float x, float y) override; + void lineTo(float x, float y) override; + void stroke() override; + void saveContext() override; + void restoreContext() override; + void clearRect(float /*x*/, float /*y*/, float w, float h) override; + void fill() override; + void setLineCap(const std::string &lineCap) override; + void setLineJoin(const std::string &lineJoin) override; + void rect(float x, float y, float w, float h) override; + void fillRect(float x, float y, float w, float h) override; + void fillText(const std::string &text, float x, float y, float /*maxWidth*/) override; + void strokeText(const std::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; + Size measureText(const std::string &text) override; + void updateFont(const std::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; + void setTextAlign(CanvasTextAlign align) override; + void setTextBaseline(CanvasTextBaseline baseline) override; + void setFillStyle(float r, float g, float b, float a) override; + void setStrokeStyle(float r, float g, float b, float a) override; + void setLineWidth(float lineWidth) override; + const cc::Data &getDataRef() const override; + void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; + +private: + void fillData(); + void unMultiplyAlpha(unsigned char *ptr, ssize_t size) const ; + +public: +private: + CanvasRenderingContext2DDelegateImpl *_impl; +}; + +} // namespace cc diff --git a/native/cocos/platform/apple/CanvasRenderingContext2D-apple.mm b/native/cocos/platform/apple/modules/CanvasRenderingContext2DDelegate.mm similarity index 61% rename from native/cocos/platform/apple/CanvasRenderingContext2D-apple.mm rename to native/cocos/platform/apple/modules/CanvasRenderingContext2DDelegate.mm index 83a1bdc800..b315a63e02 100644 --- a/native/cocos/platform/apple/CanvasRenderingContext2D-apple.mm +++ b/native/cocos/platform/apple/modules/CanvasRenderingContext2DDelegate.mm @@ -23,11 +23,12 @@ THE SOFTWARE. ****************************************************************************/ -#include "platform/CanvasRenderingContext2D.h" -#include "base/csscolorparser.h" +#include "platform/apple/modules/CanvasRenderingContext2DDelegate.h" #include "base/UTF8.h" +#include "base/csscolorparser.h" #include "math/Math.h" + #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_platform.h" @@ -49,29 +50,18 @@ #endif -#include #include -enum class CanvasTextAlign { - LEFT, - CENTER, - RIGHT -}; +#include -enum class CanvasTextBaseline { - TOP, - MIDDLE, - BOTTOM, - ALPHABETIC -}; -@interface CanvasRenderingContext2DImpl : NSObject { - NSFont *_font; +@interface CanvasRenderingContext2DDelegateImpl : NSObject { + NSFont * _font; NSMutableDictionary *_tokenAttributesDict; - NSString *_fontName; - CGFloat _fontSize; - CGFloat _width; - CGFloat _height; - CGContextRef _context; + NSString * _fontName; + CGFloat _fontSize; + CGFloat _width; + CGFloat _height; + CGContextRef _context; #if CC_PLATFORM == CC_PLATFORM_MAC_OSX NSGraphicsContext *_currentGraphicsContext; @@ -81,47 +71,47 @@ enum class CanvasTextBaseline { #endif CGColorSpaceRef _colorSpace; - cc::Data _imageData; - NSBezierPath *_path; + cc::Data _imageData; + NSBezierPath * _path; - CanvasTextAlign _textAlign; - CanvasTextBaseline _textBaseLine; + CanvasTextAlign _textAlign; + CanvasTextBaseline _textBaseLine; std::array _fillStyle; std::array _strokeStyle; - float _lineWidth; - bool _bold; + float _lineWidth; + bool _bold; } -@property (nonatomic, strong) NSFont *font; +@property (nonatomic, strong) NSFont * font; @property (nonatomic, strong) NSMutableDictionary *tokenAttributesDict; -@property (nonatomic, strong) NSString *fontName; -@property (nonatomic, assign) CanvasTextAlign textAlign; -@property (nonatomic, assign) CanvasTextBaseline textBaseLine; -@property (nonatomic, assign) float lineWidth; +@property (nonatomic, strong) NSString * fontName; +@property (nonatomic, assign) CanvasTextAlign textAlign; +@property (nonatomic, assign) CanvasTextBaseline textBaseLine; +@property (nonatomic, assign) float lineWidth; @end -@implementation CanvasRenderingContext2DImpl +@implementation CanvasRenderingContext2DDelegateImpl -@synthesize font = _font; +@synthesize font = _font; @synthesize tokenAttributesDict = _tokenAttributesDict; -@synthesize fontName = _fontName; -@synthesize textAlign = _textAlign; -@synthesize textBaseLine = _textBaseLine; -@synthesize lineWidth = _lineWidth; +@synthesize fontName = _fontName; +@synthesize textAlign = _textAlign; +@synthesize textBaseLine = _textBaseLine; +@synthesize lineWidth = _lineWidth; - (id)init { if (self = [super init]) { - _lineWidth = 0; - _textAlign = CanvasTextAlign::LEFT; + _lineWidth = 0; + _textAlign = CanvasTextAlign::LEFT; _textBaseLine = CanvasTextBaseline::BOTTOM; _width = _height = 0; - _context = nil; - _colorSpace = nil; + _context = nil; + _colorSpace = nil; #if CC_PLATFORM == CC_PLATFORM_MAC_OSX _currentGraphicsContext = nil; - _oldGraphicsContext = nil; + _oldGraphicsContext = nil; #endif _path = [NSBezierPath bezierPath]; [_path retain]; @@ -132,9 +122,9 @@ enum class CanvasTextBaseline { } - (void)dealloc { - self.font = nil; + self.font = nil; self.tokenAttributesDict = nil; - self.fontName = nil; + self.fontName = nil; CGColorSpaceRelease(_colorSpace); // release the context CGContextRelease(_context); @@ -163,7 +153,7 @@ enum class CanvasTextBaseline { if (font == nil) { const auto &familyMap = getFontFamilyNameMap(); - auto iter = familyMap.find([_fontName UTF8String]); + auto iter = familyMap.find([_fontName UTF8String]); if (iter != familyMap.end()) { font = [[NSFontManager sharedFontManager] fontWithFamily:[NSString stringWithUTF8String:iter->second.c_str()] @@ -216,13 +206,13 @@ enum class CanvasTextBaseline { - (void)updateFontWithName:(NSString *)fontName fontSize:(CGFloat)fontSize bold:(bool)bold { _fontSize = fontSize; - _bold = bold; + _bold = bold; self.fontName = fontName; - self.font = [self _createSystemFont]; + self.font = [self _createSystemFont]; NSMutableParagraphStyle *paragraphStyle = [[[NSMutableParagraphStyle alloc] init] autorelease]; - paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; + paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; [paragraphStyle setAlignment:NSTextAlignmentCenter]; // color @@ -240,9 +230,9 @@ enum class CanvasTextBaseline { - (void)recreateBufferWithWidth:(NSInteger)width height:(NSInteger)height { _width = width = width > 0 ? width : 1; - _height = height = height > 0 ? height : 1; - NSUInteger textureSize = width * height * 4; - unsigned char *data = (unsigned char *)malloc(sizeof(unsigned char) * textureSize); + _height = height = height > 0 ? height : 1; + NSUInteger textureSize = width * height * 4; + unsigned char *data = (unsigned char *)malloc(sizeof(unsigned char) * textureSize); memset(data, 0, textureSize); _imageData.fastSet(data, textureSize); @@ -260,7 +250,7 @@ enum class CanvasTextBaseline { // draw text _colorSpace = CGColorSpaceCreateDeviceRGB(); - _context = CGBitmapContextCreate(data, + _context = CGBitmapContextCreate(data, width, height, 8, @@ -285,17 +275,16 @@ enum class CanvasTextBaseline { } - (NSSize)measureText:(NSString *)text { - NSAttributedString *stringWithAttributes = [[[NSAttributedString alloc] initWithString:text attributes:_tokenAttributesDict] autorelease]; NSSize textRect = NSZeroSize; - textRect.width = CGFLOAT_MAX; + textRect.width = CGFLOAT_MAX; textRect.height = CGFLOAT_MAX; NSSize dim = [stringWithAttributes boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin)context:nil].size; - dim.width = ceilf(dim.width); + dim.width = ceilf(dim.width); dim.height = ceilf(dim.height); return dim; @@ -347,7 +336,7 @@ enum class CanvasTextBaseline { NSPoint drawPoint = [self convertDrawPoint:NSMakePoint(x, y) text:text]; NSMutableParagraphStyle *paragraphStyle = [[[NSMutableParagraphStyle alloc] init] autorelease]; - paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; + paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; [_tokenAttributesDict removeObjectForKey:NSStrokeColorAttributeName]; @@ -380,7 +369,7 @@ enum class CanvasTextBaseline { NSPoint drawPoint = [self convertDrawPoint:NSMakePoint(x, y) text:text]; NSMutableParagraphStyle *paragraphStyle = [[[NSMutableParagraphStyle alloc] init] autorelease]; - paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; + paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; [_tokenAttributesDict removeObjectForKey:NSForegroundColorAttributeName]; @@ -435,9 +424,9 @@ enum class CanvasTextBaseline { if (_imageData.isNull()) return; - rect.origin.x = floor(rect.origin.x); - rect.origin.y = floor(rect.origin.y); - rect.size.width = floor(rect.size.width); + rect.origin.x = floor(rect.origin.x); + rect.origin.y = floor(rect.origin.y); + rect.size.width = floor(rect.size.width); rect.size.height = floor(rect.size.height); if (rect.origin.x < 0) rect.origin.x = 0; @@ -528,98 +517,81 @@ enum class CanvasTextBaseline { @end namespace cc { - -CanvasGradient::CanvasGradient() { - SE_LOGD("CanvasGradient constructor: %p\n", this); +CanvasRenderingContext2DDelegate::CanvasRenderingContext2DDelegate() { + _impl = [[CanvasRenderingContext2DDelegateImpl alloc] init]; } -CanvasGradient::~CanvasGradient() { - SE_LOGD("CanvasGradient destructor: %p\n", this); -} - -void CanvasGradient::addColorStop(float offset, const std::string &color) { - SE_LOGD("CanvasGradient::addColorStop: %p\n", this); -} - -// CanvasRenderingContext2D - -namespace { -#define CLAMP(V, HI) std::min((V), (HI)) -void unMultiplyAlpha(unsigned char *ptr, ssize_t size) { - float alpha; - for (int i = 0; i < size; i += 4) { - alpha = (float)ptr[i + 3]; - if (alpha > 0) { - ptr[i] = CLAMP((int)((float)ptr[i] / alpha * 255), 255); - ptr[i + 1] = CLAMP((int)((float)ptr[i + 1] / alpha * 255), 255); - ptr[i + 2] = CLAMP((int)((float)ptr[i + 2] / alpha * 255), 255); - } - } -} -} // namespace - -#define SEND_DATA_TO_JS(CB, IMPL) \ - if (CB) { \ - Data data([IMPL getDataRef]); \ - unMultiplyAlpha(data.getBytes(), data.getSize()); \ - CB(data); \ - } - -CanvasRenderingContext2D::CanvasRenderingContext2D(float width, float height) -: _width(width), - _height(height) { - // SE_LOGD("CanvasRenderingContext2D constructor: %p, width: %f, height: %f\n", this, width, height); - _impl = [[CanvasRenderingContext2DImpl alloc] init]; -} - -CanvasRenderingContext2D::~CanvasRenderingContext2D() { - // SE_LOGD("CanvasRenderingContext2D destructor: %p\n", this); +CanvasRenderingContext2DDelegate::~CanvasRenderingContext2DDelegate() { [_impl release]; } -void CanvasRenderingContext2D::recreateBufferIfNeeded() { - if (_isBufferSizeDirty) { - _isBufferSizeDirty = false; - // SE_LOGD("CanvasRenderingContext2D::recreateBufferIfNeeded %p, w: %f, h:%f\n", this, __width, __height); - [_impl recreateBufferWithWidth:_width height:_height]; - SEND_DATA_TO_JS(_canvasBufferUpdatedCB, _impl); - } +void CanvasRenderingContext2DDelegate::recreateBuffer(float w, float h) { + [_impl recreateBufferWithWidth:w height:h]; } -void CanvasRenderingContext2D::clearRect(float x, float y, float width, float height) { - // SE_LOGD("CanvasGradient::clearRect: %p, %f, %f, %f, %f\n", this, x, y, width, height); - recreateBufferIfNeeded(); - [_impl clearRect:CGRectMake(x, y, width, height)]; +const cc::Data &CanvasRenderingContext2DDelegate::getDataRef() const { + static Data data; + data = [_impl getDataRef]; + unMultiplyAlpha(data.getBytes(), data.getSize()); + return data; } -void CanvasRenderingContext2D::fillRect(float x, float y, float width, float height) { - recreateBufferIfNeeded(); - [_impl fillRect:CGRectMake(x, y, width, height)]; - SEND_DATA_TO_JS(_canvasBufferUpdatedCB, _impl); +void CanvasRenderingContext2DDelegate::beginPath() { + [_impl beginPath]; } -void CanvasRenderingContext2D::fillText(const std::string &text, float x, float y, float maxWidth) { - // SE_LOGD("CanvasRenderingContext2D(%p)::fillText: %s, %f, %f, %f\n", this, text.c_str(), x, y, maxWidth); - if (text.empty()) - return; +void CanvasRenderingContext2DDelegate::closePath() { +} - recreateBufferIfNeeded(); +void CanvasRenderingContext2DDelegate::moveTo(float x, float y) { + [_impl moveToX:x y:y]; +} +void CanvasRenderingContext2DDelegate::lineTo(float x, float y) { + [_impl lineToX:x y:y]; +} + +void CanvasRenderingContext2DDelegate::stroke() { + [_impl stroke]; +} + +void CanvasRenderingContext2DDelegate::saveContext() { + [_impl saveContext]; +} + +void CanvasRenderingContext2DDelegate::restoreContext() { + [_impl restoreContext]; +} + +void CanvasRenderingContext2DDelegate::clearRect(float x, float y, float w, float h) { + [_impl clearRect:CGRectMake(x, y, w, h)]; +} + +void CanvasRenderingContext2DDelegate::fill() { +} + +void CanvasRenderingContext2DDelegate::setLineCap(const std::string &lineCap) { +} + +void CanvasRenderingContext2DDelegate::setLineJoin(const std::string &lineJoin) { +} + +void CanvasRenderingContext2DDelegate::rect(float x, float y, float w, float h) { +} + +void CanvasRenderingContext2DDelegate::fillRect(float x, float y, float w, float h) { + [_impl fillRect:CGRectMake(x, y, w, h)]; +} + +void CanvasRenderingContext2DDelegate::fillText(const std::string &text, float x, float y, float maxWidth) { [_impl fillText:[NSString stringWithUTF8String:text.c_str()] x:x y:y maxWidth:maxWidth]; - SEND_DATA_TO_JS(_canvasBufferUpdatedCB, _impl); } -void CanvasRenderingContext2D::strokeText(const std::string &text, float x, float y, float maxWidth) { - // SE_LOGD("CanvasRenderingContext2D(%p)::strokeText: %s, %f, %f, %f\n", this, text.c_str(), x, y, maxWidth); - if (text.empty()) - return; - recreateBufferIfNeeded(); - +void CanvasRenderingContext2DDelegate::strokeText(const std::string &text, float x, float y, float maxWidth) { [_impl strokeText:[NSString stringWithUTF8String:text.c_str()] x:x y:y maxWidth:maxWidth]; - SEND_DATA_TO_JS(_canvasBufferUpdatedCB, _impl); } -cc::Size CanvasRenderingContext2D::measureText(const std::string &text) { +CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::measureText(const std::string &text) { NSString *str = [NSString stringWithUTF8String:text.c_str()]; if (str == nil) { std::string textNew; @@ -627,174 +599,51 @@ cc::Size CanvasRenderingContext2D::measureText(const std::string &text) { str = [NSString stringWithUTF8String:textNew.c_str()]; } CGSize size = [_impl measureText:str]; - return cc::Size(size.width, size.height); + return CanvasRenderingContext2DDelegate::Size{(float)size.width, (float)size.height}; } -CanvasGradient *CanvasRenderingContext2D::createLinearGradient(float x0, float y0, float x1, float y1) { - return nullptr; +void CanvasRenderingContext2DDelegate::updateFont(const std::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) { + CGFloat gfloatFontSize = fontSize; + [_impl updateFontWithName:[NSString stringWithUTF8String:fontName.c_str()] fontSize:gfloatFontSize bold:bold]; } -void CanvasRenderingContext2D::save() { - [_impl saveContext]; +void CanvasRenderingContext2DDelegate::setTextAlign(CanvasTextAlign align) { + _impl.textAlign = align; } -void CanvasRenderingContext2D::beginPath() { - [_impl beginPath]; +void CanvasRenderingContext2DDelegate::setTextBaseline(CanvasTextBaseline baseline) { + _impl.textBaseLine = baseline; } -void CanvasRenderingContext2D::closePath() { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); +void CanvasRenderingContext2DDelegate::setFillStyle(float r, float g, float b, float a) { + [_impl setFillStyleWithRed:r green:g blue:b alpha:a]; } -void CanvasRenderingContext2D::moveTo(float x, float y) { - [_impl moveToX:x y:y]; +void CanvasRenderingContext2DDelegate::setStrokeStyle(float r, float g, float b, float a) { + [_impl setStrokeStyleWithRed:r green:g blue:b alpha:a]; } -void CanvasRenderingContext2D::lineTo(float x, float y) { - [_impl lineToX:x y:y]; +void CanvasRenderingContext2DDelegate::setLineWidth(float lineWidth) { + _impl.lineWidth = lineWidth; } -void CanvasRenderingContext2D::stroke() { - [_impl stroke]; - SEND_DATA_TO_JS(_canvasBufferUpdatedCB, _impl); +void CanvasRenderingContext2DDelegate::fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) { } -void CanvasRenderingContext2D::fill() { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); +void CanvasRenderingContext2DDelegate::fillData() { } -void CanvasRenderingContext2D::rect(float x, float y, float w, float h) { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::restore() { - [_impl restoreContext]; -} - -void CanvasRenderingContext2D::setCanvasBufferUpdatedCallback(const CanvasBufferUpdatedCallback &cb) { - _canvasBufferUpdatedCB = cb; - recreateBufferIfNeeded(); -} - -void CanvasRenderingContext2D::setWidth(float width) { - // SE_LOGD("CanvasRenderingContext2D::set__width: %f\n", width); - if (math::IsEqualF(width, _width)) return; - _width = width; - _isBufferSizeDirty = true; - recreateBufferIfNeeded(); -} - -void CanvasRenderingContext2D::setHeight(float height) { - // SE_LOGD("CanvasRenderingContext2D::set__height: %f\n", height); - if (math::IsEqualF(height, _height)) return; - _height = height; - _isBufferSizeDirty = true; - recreateBufferIfNeeded(); -} - -void CanvasRenderingContext2D::setLineWidth(float lineWidth) { - _lineWidth = lineWidth; - _impl.lineWidth = _lineWidth; -} - -void CanvasRenderingContext2D::setLineCap(const std::string &lineCap) { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::setLineJoin(const std::string &lineJoin) { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::setFont(const std::string &font) { - if (_font != font) { - _font = font; - - std::string boldStr; - std::string fontName = "Arial"; - std::string fontSizeStr = "30"; - - // support get font name from `60px American` or `60px "American abc-abc_abc"` - std::regex re("(bold)?\\s*((\\d+)([\\.]\\d+)?)px\\s+([\\w-]+|\"[\\w -]+\"$)"); - std::match_results results; - if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) { - boldStr = results[1].str(); - fontSizeStr = results[2].str(); - fontName = results[5].str(); +#define CLAMP(V, HI) std::min((V), (HI)) +void CanvasRenderingContext2DDelegate::unMultiplyAlpha(unsigned char *ptr, ssize_t size) const { + float alpha; + for (int i = 0; i < size; i += 4) { + alpha = (float)ptr[i + 3]; + if (alpha > 0) { + ptr[i] = CLAMP((int)((float)ptr[i] / alpha * 255), 255); + ptr[i + 1] = CLAMP((int)((float)ptr[i + 1] / alpha * 255), 255); + ptr[i + 2] = CLAMP((int)((float)ptr[i + 2] / alpha * 255), 255); } - - CGFloat fontSize = atof(fontSizeStr.c_str()); - [_impl updateFontWithName:[NSString stringWithUTF8String:fontName.c_str()] fontSize:fontSize bold:!boldStr.empty()]; } } -void CanvasRenderingContext2D::setTextAlign(const std::string &textAlign) { - // SE_LOGD("CanvasRenderingContext2D::set_textAlign: %s\n", textAlign.c_str()); - if (textAlign == "left") { - _impl.textAlign = CanvasTextAlign::LEFT; - } else if (textAlign == "center" || textAlign == "middle") { - _impl.textAlign = CanvasTextAlign::CENTER; - } else if (textAlign == "right") { - _impl.textAlign = CanvasTextAlign::RIGHT; - } else { - assert(false); - } -} - -void CanvasRenderingContext2D::setTextBaseline(const std::string &textBaseline) { - // SE_LOGD("CanvasRenderingContext2D::set_textBaseline: %s\n", textBaseline.c_str()); - if (textBaseline == "top") { - _impl.textBaseLine = CanvasTextBaseline::TOP; - } else if (textBaseline == "middle") { - _impl.textBaseLine = CanvasTextBaseline::MIDDLE; - } else if (textBaseline == "bottom") //REFINE:, how to deal with alphabetic, currently we handle it as bottom mode. - { - _impl.textBaseLine = CanvasTextBaseline::BOTTOM; - } else if (textBaseline == "alphabetic") { - _impl.textBaseLine = CanvasTextBaseline::ALPHABETIC; - } else { - assert(false); - } -} - -void CanvasRenderingContext2D::setFillStyle(const std::string &fillStyle) { - CSSColorParser::Color color = CSSColorParser::parse(fillStyle); - [_impl setFillStyleWithRed:color.r / 255.0f green:color.g / 255.0f blue:color.b / 255.0f alpha:color.a]; - // SE_LOGD("CanvasRenderingContext2D::set_fillStyle: %s, (%d, %d, %d, %f)\n", fillStyle.c_str(), color.r, color.g, color.b, color.a); -} - -void CanvasRenderingContext2D::setStrokeStyle(const std::string &strokeStyle) { - CSSColorParser::Color color = CSSColorParser::parse(strokeStyle); - [_impl setStrokeStyleWithRed:color.r / 255.0f green:color.g / 255.0f blue:color.b / 255.0f alpha:color.a]; -} - -void CanvasRenderingContext2D::setGlobalCompositeOperation(const std::string &globalCompositeOperation) { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -// transform - -void CanvasRenderingContext2D::translate(float x, float y) { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::scale(float x, float y) { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::rotate(float angle) { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::transform(float a, float b, float c, float d, float e, float f) { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::setTransform(float a, float b, float c, float d, float e, float f) { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - } // namespace cc diff --git a/native/cocos/platform/interfaces/OSInterface.cpp b/native/cocos/platform/interfaces/OSInterface.cpp new file mode 100644 index 0000000000..67c593d969 --- /dev/null +++ b/native/cocos/platform/interfaces/OSInterface.cpp @@ -0,0 +1,50 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/interfaces/OSInterface.h" +#include "platform/IEventDispatch.h" + +namespace cc { + +OSInterface::OSInterface() +: OSInterface(nullptr) { +} + +OSInterface::OSInterface(IEventDispatch* evDispatchInterface) +: _evDispatchInterface(evDispatchInterface) { +} + +void OSInterface::dispatchEvent(const OSEvent& ev) { + if (_evDispatchInterface) { + _evDispatchInterface->dispatchEvent(ev); + } +} + +void OSInterface::dispatchTouchEvent(const OSEvent& ev) { + if (_evDispatchInterface) { + _evDispatchInterface->dispatchTouchEvent(ev); + } +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/interfaces/OSInterface.h b/native/cocos/platform/interfaces/OSInterface.h new file mode 100644 index 0000000000..6ec9e03b59 --- /dev/null +++ b/native/cocos/platform/interfaces/OSInterface.h @@ -0,0 +1,76 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include +#include +#include "base/Macros.h" +#include "bindings/event/EventDispatcher.h" + + +namespace cc { +class IEventDispatch; + +class OSInterface { +public: + using Ptr = std::shared_ptr; + /** + @brief Constructor of OSAbstractInterface. + */ + explicit OSInterface(); + /** + @brief Constructor of OSAbstractInterface. + */ + explicit OSInterface(IEventDispatch*); + /** + @brief Destructor of OSAbstractInterface. + */ + virtual ~OSInterface() = default; + + /** + @brief Dispatch event. + @param type : event type + @param type : event information + */ + void dispatchEvent(const OSEvent& ev); + /** + @brief Dispatch touch event. + @param type : event type + */ + void dispatchTouchEvent(const OSEvent& ev); + + //enum class InterfaceType { + //}; + +protected: + // InterfaceType _type; + IEventDispatch* _evDispatchInterface{nullptr}; + +private: + CC_DISABLE_COPY_AND_MOVE_SEMANTICS(OSInterface); +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/interfaces/OSInterfaceManager.cpp b/native/cocos/platform/interfaces/OSInterfaceManager.cpp new file mode 100644 index 0000000000..e69de29bb2 diff --git a/native/cocos/platform/interfaces/OSInterfaceManager.h b/native/cocos/platform/interfaces/OSInterfaceManager.h new file mode 100644 index 0000000000..cae284065f --- /dev/null +++ b/native/cocos/platform/interfaces/OSInterfaceManager.h @@ -0,0 +1,37 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +namespace cc { + +class OSInterfaceManager { +public: + virtual ~OSInterfaceManager() = default; + +private: +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/interfaces/modules/Device.cpp b/native/cocos/platform/interfaces/modules/Device.cpp new file mode 100644 index 0000000000..e9354f2064 --- /dev/null +++ b/native/cocos/platform/interfaces/modules/Device.cpp @@ -0,0 +1,84 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/interfaces/modules/Device.h" + +#include "application/ApplicationManager.h" +#include "platform/interfaces/modules/IAccelerometer.h" +#include "platform/interfaces/modules/IBattery.h" +#include "platform/interfaces/modules/INetwork.h" +#include "platform/interfaces/modules/IScreen.h" +#include "platform/interfaces/modules/IVibrator.h" + +namespace cc { + +int Device::getDPI() { + return CC_GET_PLATFORM_INTERFACE(IScreen)->getDPI(); +} + +float Device::getDevicePixelRatio() { + return CC_GET_PLATFORM_INTERFACE(IScreen)->getDevicePixelRatio(); +} + +void Device::setKeepScreenOn(bool keepScreenOn) { + return CC_GET_PLATFORM_INTERFACE(IScreen)->setKeepScreenOn(keepScreenOn); +} + +void Device::setAccelerometerEnabled(bool isEnabled) { + return CC_GET_PLATFORM_INTERFACE(IAccelerometer)->setAccelerometerEnabled(isEnabled); +} + +void Device::setAccelerometerInterval(float interval) { + return CC_GET_PLATFORM_INTERFACE(IAccelerometer)->setAccelerometerInterval(interval); +} + +const IAccelerometer::MotionValue &Device::getDeviceMotionValue() { + return CC_GET_PLATFORM_INTERFACE(IAccelerometer)->getDeviceMotionValue(); +} + +IScreen::Orientation Device::getDeviceOrientation() { + return CC_GET_PLATFORM_INTERFACE(IScreen)->getDeviceOrientation(); +} + +std::string Device::getDeviceModel() { + return CC_GET_PLATFORM_INTERFACE(ISystem)->getDeviceModel(); +} + +void Device::vibrate(float duration) { + return CC_GET_PLATFORM_INTERFACE(IVibrator)->vibrate(duration); +} + +float Device::getBatteryLevel() { + return CC_GET_PLATFORM_INTERFACE(IBattery)->getBatteryLevel(); +} + +INetwork::NetworkType Device::getNetworkType() { + return CC_GET_PLATFORM_INTERFACE(INetwork)->getNetworkType(); +} + +Vec4 Device::getSafeAreaEdge() { + return CC_GET_PLATFORM_INTERFACE(IScreen)->getSafeAreaEdge(); +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/Device.h b/native/cocos/platform/interfaces/modules/Device.h similarity index 90% rename from native/cocos/platform/Device.h rename to native/cocos/platform/interfaces/modules/Device.h index e6289419c1..239f7900c6 100644 --- a/native/cocos/platform/Device.h +++ b/native/cocos/platform/interfaces/modules/Device.h @@ -25,13 +25,15 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef __CCDEVICE_H__ -#define __CCDEVICE_H__ +#pragma once #include "base/Data.h" #include "base/Macros.h" #include "math/Vec4.h" +#include "platform/interfaces/modules/IAccelerometer.h" +#include "platform/interfaces/modules/INetwork.h" +#include "platform/interfaces/modules/IScreen.h" namespace cc { @@ -94,12 +96,12 @@ public: /** * Gets the motion value of current device. */ - static const MotionValue &getDeviceMotionValue(); + static const IAccelerometer::MotionValue &getDeviceMotionValue(); /** * Gets the orientation of device. */ - static Orientation getDeviceOrientation(); + static IScreen::Orientation getDeviceOrientation(); /** * Gets device model information. @@ -128,13 +130,7 @@ public: */ static float getBatteryLevel(); - enum class NetworkType { - NONE, - LAN, - WWAN - }; - - static NetworkType getNetworkType(); + static INetwork::NetworkType getNetworkType(); /* * Gets the SafeArea edge. @@ -144,8 +140,7 @@ public: private: Device(); - DISABLE_COPY_SEMANTICS(Device) - DISABLE_MOVE_SEMANTICS(Device) + CC_DISABLE_COPY_AND_MOVE_SEMANTICS(Device) }; // end group @@ -153,4 +148,3 @@ private: } // namespace cc -#endif /* __CCDEVICE_H__ */ diff --git a/native/cocos/platform/interfaces/modules/IAccelerometer.cpp b/native/cocos/platform/interfaces/modules/IAccelerometer.cpp new file mode 100644 index 0000000000..712ec849df --- /dev/null +++ b/native/cocos/platform/interfaces/modules/IAccelerometer.cpp @@ -0,0 +1,49 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/interfaces/modules/IAccelerometer.h" + +#if (CC_PLATFORM == CC_PLATFORM_WINDOWS) + #include "platform/win32/modules/Accelerometer.h" +#elif (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) + #include "platform/java/modules/Accelerometer.h" +#elif (CC_PLATFORM == CC_PLATFORM_MAC_OSX) + #include "platform/mac/modules/Accelerometer.h" +#elif (CC_PLATFORM == CC_PLATFORM_MAC_IOS) + #include "platform/ios/modules/Accelerometer.h" +#elif (CC_PLATFORM == CC_PLATFORM_LINUX) + #include "platform/linux/modules/Accelerometer.h" +#elif (CC_PLATFORM == CC_PLATFORM_QNX) + #include "platform/qnx/modules/Accelerometer.h" +#endif + +namespace cc { + +// static +OSInterface::Ptr IAccelerometer::createAccelerometerInterface() { + return std::make_shared(); +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/interfaces/modules/IAccelerometer.h b/native/cocos/platform/interfaces/modules/IAccelerometer.h new file mode 100644 index 0000000000..61c55fcfea --- /dev/null +++ b/native/cocos/platform/interfaces/modules/IAccelerometer.h @@ -0,0 +1,70 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/OSInterface.h" + +namespace cc { + +class IAccelerometer : public OSInterface { +public: + struct MotionValue { + float accelerationX = 0.0F; + float accelerationY = 0.0F; + float accelerationZ = 0.0F; + + float accelerationIncludingGravityX = 0.0F; + float accelerationIncludingGravityY = 0.0F; + float accelerationIncludingGravityZ = 0.0F; + + float rotationRateAlpha = 0.0F; + float rotationRateBeta = 0.0F; + float rotationRateGamma = 0.0F; + }; + + /** + * To enable or disable accelerometer. + */ + virtual void setAccelerometerEnabled(bool isEnabled) = 0; + + /** + * Sets the interval of accelerometer. + */ + virtual void setAccelerometerInterval(float interval) = 0; + + /** + * Gets the motion value of current device. + */ + virtual const MotionValue &getDeviceMotionValue() = 0; + /** + @brief Create default accelerometer interface. + @return accelerometer interface. + */ + static OSInterface::Ptr createAccelerometerInterface(); +private: +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/interfaces/modules/IBattery.cpp b/native/cocos/platform/interfaces/modules/IBattery.cpp new file mode 100644 index 0000000000..306f26dd43 --- /dev/null +++ b/native/cocos/platform/interfaces/modules/IBattery.cpp @@ -0,0 +1,49 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/interfaces/modules/IBattery.h" + +#if (CC_PLATFORM == CC_PLATFORM_WINDOWS) + #include "platform/win32/modules/Battery.h" +#elif (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) + #include "platform/java/modules/Battery.h" +#elif (CC_PLATFORM == CC_PLATFORM_MAC_OSX) + #include "platform/mac/modules/Battery.h" +#elif (CC_PLATFORM == CC_PLATFORM_MAC_IOS) + #include "platform/ios/modules/Battery.h" +#elif (CC_PLATFORM == CC_PLATFORM_LINUX) + #include "platform/linux/modules/Battery.h" +#elif (CC_PLATFORM == CC_PLATFORM_QNX) + #include "platform/qnx/modules/Battery.h" +#endif + +namespace cc { + +// static +OSInterface::Ptr IBattery::createBatteryInterface() { + return std::make_shared(); +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/interfaces/modules/IBattery.h b/native/cocos/platform/interfaces/modules/IBattery.h new file mode 100644 index 0000000000..821119391c --- /dev/null +++ b/native/cocos/platform/interfaces/modules/IBattery.h @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/OSInterface.h" + +namespace cc { + +class IBattery : public OSInterface { +public: + /** + * Gets battery level, only avaiable on iOS and Android. + * @return 0.0 ~ 1.0 + */ + virtual float getBatteryLevel() const = 0; + /** + @brief Create default battery interface. + @return battery interface. + */ + static OSInterface::Ptr createBatteryInterface(); + +private: +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/interfaces/modules/INetwork.cpp b/native/cocos/platform/interfaces/modules/INetwork.cpp new file mode 100644 index 0000000000..e37be1c470 --- /dev/null +++ b/native/cocos/platform/interfaces/modules/INetwork.cpp @@ -0,0 +1,49 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/interfaces/modules/INetwork.h" + +#if (CC_PLATFORM == CC_PLATFORM_WINDOWS) + #include "platform/win32/modules/Network.h" +#elif (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) + #include "platform/java/modules/Network.h" +#elif (CC_PLATFORM == CC_PLATFORM_MAC_OSX) + #include "platform/mac/modules/Network.h" +#elif (CC_PLATFORM == CC_PLATFORM_MAC_IOS) + #include "platform/ios/modules/Network.h" +#elif (CC_PLATFORM == CC_PLATFORM_LINUX) + #include "platform/linux/modules/Network.h" +#elif (CC_PLATFORM == CC_PLATFORM_QNX) + #include "platform/qnx/modules/Network.h" +#endif + +namespace cc { + +// static +OSInterface::Ptr INetwork::createNetworkInterface() { + return std::make_shared(); +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/interfaces/modules/INetwork.h b/native/cocos/platform/interfaces/modules/INetwork.h new file mode 100644 index 0000000000..d19e64fa76 --- /dev/null +++ b/native/cocos/platform/interfaces/modules/INetwork.h @@ -0,0 +1,49 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/OSInterface.h" + +namespace cc { + +class INetwork : public OSInterface { +public: + enum class NetworkType { + NONE, + LAN, + WWAN + }; + virtual NetworkType getNetworkType() const = 0; + /** + @brief Create default network interface. + @return network interface. + */ + static OSInterface::Ptr createNetworkInterface(); + +private: +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/interfaces/modules/IScreen.cpp b/native/cocos/platform/interfaces/modules/IScreen.cpp new file mode 100644 index 0000000000..0f5078b9b9 --- /dev/null +++ b/native/cocos/platform/interfaces/modules/IScreen.cpp @@ -0,0 +1,51 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/interfaces/modules/IScreen.h" + +#if (CC_PLATFORM == CC_PLATFORM_WINDOWS) + #include "platform/win32/modules/Screen.h" +#elif (CC_PLATFORM == CC_PLATFORM_ANDROID) + #include "platform/android/modules/Screen.h" +#elif (CC_PLATFORM == CC_PLATFORM_OHOS) + #include "platform/ohos/modules/Screen.h" +#elif (CC_PLATFORM == CC_PLATFORM_MAC_OSX) + #include "platform/mac/modules/Screen.h" +#elif (CC_PLATFORM == CC_PLATFORM_MAC_IOS) + #include "platform/ios/modules/Screen.h" +#elif (CC_PLATFORM == CC_PLATFORM_LINUX) + #include "platform/linux/modules/Screen.h" +#elif (CC_PLATFORM == CC_PLATFORM_QNX) + #include "platform/qnx/modules/Screen.h" +#endif + +namespace cc { + +// static +OSInterface::Ptr IScreen::createScreenInterface() { + return std::make_shared(); +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/interfaces/modules/IScreen.h b/native/cocos/platform/interfaces/modules/IScreen.h new file mode 100644 index 0000000000..723dfd7860 --- /dev/null +++ b/native/cocos/platform/interfaces/modules/IScreen.h @@ -0,0 +1,73 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "math/Vec4.h" +#include "platform/interfaces/OSInterface.h" + +namespace cc { +class IScreen : public OSInterface { +public: + virtual int getDPI() const = 0; + virtual float getDevicePixelRatio() const = 0; + + // https://developer.mozilla.org/en-US/docs/Web/API/Window/orientation + enum class Orientation { + PORTRAIT = 0, + LANDSCAPE_LEFT = -90, + PORTRAIT_UPSIDE_DOWN = 180, + LANDSCAPE_RIGHT = 90 + }; + virtual Orientation getDeviceOrientation() const = 0; + + /** + @brief Get current display stats. + @return bool, is displaying stats or not. + */ + virtual bool isDisplayStats() = 0; + + /** + @brief set display stats information. + */ + virtual void setDisplayStats(bool isShow) = 0; + + /** + * Controls whether the screen should remain on. + * + * @param keepScreenOn One flag indicating that the screen should remain on. + */ + virtual void setKeepScreenOn(bool keepScreenOn) = 0; + + virtual Vec4 getSafeAreaEdge() const = 0; + /** + @brief Create default screen interface. + @return screen interface. + */ + static OSInterface::Ptr createScreenInterface(); + +private: +}; +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/interfaces/modules/ISystem.cpp b/native/cocos/platform/interfaces/modules/ISystem.cpp new file mode 100644 index 0000000000..b4f3cea001 --- /dev/null +++ b/native/cocos/platform/interfaces/modules/ISystem.cpp @@ -0,0 +1,118 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/interfaces/modules/ISystem.h" + +#if (CC_PLATFORM == CC_PLATFORM_WINDOWS) + #include "platform/win32/modules/System.h" +#elif (CC_PLATFORM == CC_PLATFORM_ANDROID) + #include "platform/android/modules/System.h" +#elif (CC_PLATFORM == CC_PLATFORM_OHOS) + #include "platform/ohos/modules/System.h" +#elif (CC_PLATFORM == CC_PLATFORM_MAC_OSX) + #include "platform/mac/modules/System.h" +#elif (CC_PLATFORM == CC_PLATFORM_MAC_IOS) + #include "platform/ios/modules/System.h" +#elif (CC_PLATFORM == CC_PLATFORM_LINUX) + #include "platform/linux/modules/System.h" +#elif (CC_PLATFORM == CC_PLATFORM_QNX) + #include "platform/qnx/modules/System.h" +#endif + +namespace cc { +ISystem::~ISystem() = default; + +ISystem::Ptr ISystem::createSystemInterface() { + return std::make_shared(); +} + +std::string ISystem::getCurrentLanguageToString() { + LanguageType language = getCurrentLanguage(); + std::string languageStr = ""; // NOLINT + switch (language) { + case ISystem::LanguageType::ENGLISH: + languageStr = "en"; + break; + case ISystem::LanguageType::CHINESE: + languageStr = "zh"; + break; + case ISystem::LanguageType::FRENCH: + languageStr = "fr"; + break; + case ISystem::LanguageType::ITALIAN: + languageStr = "it"; + break; + case ISystem::LanguageType::GERMAN: + languageStr = "de"; + break; + case ISystem::LanguageType::SPANISH: + languageStr = "es"; + break; + case ISystem::LanguageType::DUTCH: + languageStr = "du"; + break; + case ISystem::LanguageType::RUSSIAN: + languageStr = "ru"; + break; + case ISystem::LanguageType::KOREAN: + languageStr = "ko"; + break; + case ISystem::LanguageType::JAPANESE: + languageStr = "ja"; + break; + case ISystem::LanguageType::HUNGARIAN: + languageStr = "hu"; + break; + case ISystem::LanguageType::PORTUGUESE: + languageStr = "pt"; + break; + case ISystem::LanguageType::ARABIC: + languageStr = "ar"; + break; + case ISystem::LanguageType::NORWEGIAN: + languageStr = "no"; + break; + case ISystem::LanguageType::POLISH: + languageStr = "pl"; + break; + case ISystem::LanguageType::TURKISH: + languageStr = "tr"; + break; + case ISystem::LanguageType::UKRAINIAN: + languageStr = "uk"; + break; + case ISystem::LanguageType::ROMANIAN: + languageStr = "ro"; + break; + case ISystem::LanguageType::BULGARIAN: + languageStr = "bg"; + break; + default: + languageStr = "unknown"; + break; + } + return languageStr; +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/interfaces/modules/ISystem.h b/native/cocos/platform/interfaces/modules/ISystem.h new file mode 100644 index 0000000000..b0075ebb56 --- /dev/null +++ b/native/cocos/platform/interfaces/modules/ISystem.h @@ -0,0 +1,96 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/OSInterface.h" + +#include + +namespace cc { + +class ISystem : public OSInterface { +public: + ~ISystem() override; + enum class LanguageType { + ENGLISH = 0, + CHINESE, + FRENCH, + ITALIAN, + GERMAN, + SPANISH, + DUTCH, + RUSSIAN, + KOREAN, + JAPANESE, + HUNGARIAN, + PORTUGUESE, + ARABIC, + NORWEGIAN, + POLISH, + TURKISH, + UKRAINIAN, + ROMANIAN, + BULGARIAN + }; + enum class OSType { + WINDOWS, /**< Windows */ + LINUX, /**< Linux */ + MAC, /**< Mac OS X*/ + ANDROIDOS, /**< Android, because ANDROID is a macro, so use ANDROIDOS instead */ + IPHONE, /**< iPhone */ + IPAD, /**< iPad */ + OHOS, /**< Open Harmony OS> */ + QNX, /**< QNX */ + }; + /** + @brief Get target system type. + */ + virtual OSType getOSType() const = 0; + + // + virtual std::string getDeviceModel() const = 0; + virtual LanguageType getCurrentLanguage() const = 0; + virtual std::string getCurrentLanguageCode() const = 0; + virtual std::string getSystemVersion() const = 0; + + virtual std::string getCurrentLanguageToString(); + + /** + @brief Open url in default browser. + @param String with url to open. + @return True if the resource located by the URL was successfully opened; otherwise false. + */ + virtual bool openURL(const std::string& url) = 0; + /** + @brief Create default sytem interface. + @return sytem interface. + */ + static OSInterface::Ptr createSystemInterface(); + +private: +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/interfaces/modules/ISystemWindow.cpp b/native/cocos/platform/interfaces/modules/ISystemWindow.cpp new file mode 100644 index 0000000000..7fe7632f2c --- /dev/null +++ b/native/cocos/platform/interfaces/modules/ISystemWindow.cpp @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/interfaces/modules/ISystemWindow.h" +#if (CC_PLATFORM == CC_PLATFORM_WINDOWS) + #include "platform/win32/modules/SystemWindow.h" +#elif (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) + #include "platform/java/modules/SystemWindow.h" +#elif (CC_PLATFORM == CC_PLATFORM_MAC_OSX) + #include "platform/mac/modules/SystemWindow.h" +#elif (CC_PLATFORM == CC_PLATFORM_MAC_IOS) + #include "platform/ios/modules/SystemWindow.h" +#elif (CC_PLATFORM == CC_PLATFORM_LINUX) + #include "platform/linux/modules/SystemWindow.h" +#elif (CC_PLATFORM == CC_PLATFORM_QNX) + #include "platform/qnx/modules/SystemWindow.h" +#endif + +namespace cc { + +// static +OSInterface::Ptr ISystemWindow::createSystemWindowInterface() { + return std::make_shared(); +} + +} // namespace cc diff --git a/native/cocos/platform/interfaces/modules/ISystemWindow.h b/native/cocos/platform/interfaces/modules/ISystemWindow.h new file mode 100644 index 0000000000..7428ed3780 --- /dev/null +++ b/native/cocos/platform/interfaces/modules/ISystemWindow.h @@ -0,0 +1,94 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/OSInterface.h" +#include "math/Vec2.h" +#include +#include + +namespace cc { + +class ISystemWindow : public OSInterface { +public: + using Size = cc::Vec2; + using WindowFlags = enum { + /* !!! FIXME: change this to name = (1<(); +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/interfaces/modules/IVibrator.h b/native/cocos/platform/interfaces/modules/IVibrator.h new file mode 100644 index 0000000000..3e8a5842f0 --- /dev/null +++ b/native/cocos/platform/interfaces/modules/IVibrator.h @@ -0,0 +1,51 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/OSInterface.h" + +namespace cc { + +class IVibrator : public OSInterface { +public: + IVibrator() = default; + /** + * Vibrate for the specified amount of time. + * If vibrate is not supported, then invoking this method has no effect. + * Some platforms limit to a maximum duration of 5 seconds. + * Duration is ignored on iOS due to API limitations. + * @param duration The duration in seconds. + */ + virtual void vibrate(float duration) = 0; + + /** + * @brief Create default Vibrator interface. + * @return Vibrator interface. + */ + static OSInterface::Ptr createVibratorInterface(); +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp b/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp new file mode 100644 index 0000000000..3d9d136b7a --- /dev/null +++ b/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp @@ -0,0 +1,470 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/interfaces/modules/canvas/CanvasRenderingContext2D.h" + +#include +#include +#include +#include "base/csscolorparser.h" +#include "cocos/bindings/jswrapper/SeApi.h" +#include "cocos/bindings/manual/jsb_platform.h" +#include "math/Math.h" +#include "platform/FileUtils.h" + +#if (CC_PLATFORM == CC_PLATFORM_WINDOWS) + #include "platform/win32/modules/CanvasRenderingContext2DDelegate.h" +#elif (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) + #include "platform/java/modules/CanvasRenderingContext2DDelegate.h" +#elif (CC_PLATFORM == CC_PLATFORM_MAC_OSX || CC_PLATFORM == CC_PLATFORM_MAC_IOS) + #include "platform/apple/modules/CanvasRenderingContext2DDelegate.h" +#elif (CC_PLATFORM == CC_PLATFORM_LINUX) + #include "platform/linux/modules/CanvasRenderingContext2DDelegate.h" +#elif (CC_PLATFORM == CC_PLATFORM_QNX) + #include "platform/qnx/modules/CanvasRenderingContext2DDelegate.h" +#endif + +using Vec2 = std::array; +using Color4F = std::array; + +namespace { +void fillRectWithColor(uint8_t *buf, uint32_t totalWidth, uint32_t totalHeight, uint32_t x, uint32_t y, uint32_t width, uint32_t height, uint8_t r, uint8_t g, uint8_t b, uint8_t a) { + assert(x + width <= totalWidth); + assert(y + height <= totalHeight); + + uint32_t y0 = y; + uint32_t y1 = y + height; + uint8_t *p; + for (uint32_t offsetY = y0; offsetY < y1; ++offsetY) { + for (uint32_t offsetX = x; offsetX < (x + width); ++offsetX) { + p = buf + (totalWidth * offsetY + offsetX) * 4; + *p++ = r; + *p++ = g; + *p++ = b; + *p++ = a; + } + } +} +} // namespace + +namespace cc { +//using Size = std::array; +CanvasGradient::CanvasGradient() = default; + +CanvasGradient::~CanvasGradient() = default; + +void CanvasGradient::addColorStop(float offset, const std::string &color) { + //SE_LOGD("CanvasGradient::addColorStop: %p\n", this); +} + +// CanvasRenderingContext2D + +CanvasRenderingContext2D::CanvasRenderingContext2D(float width, float height) +: _width(width), + _height(height) { + _delegate = new CanvasRenderingContext2DDelegate(); + //SE_LOGD("CanvasRenderingContext2D constructor: %p, width: %f, height: %f\n", this, width, height); +} + +CanvasRenderingContext2D::~CanvasRenderingContext2D() { + delete _delegate; +} + +void CanvasRenderingContext2D::clearRect(float x, float y, float width, float height) { + //SE_LOGD("CanvasRenderingContext2D::clearRect: %p, %f, %f, %f, %f\n", this, x, y, width, height); + recreateBufferIfNeeded(); + _delegate->clearRect(x, y, width, height); +} + +void CanvasRenderingContext2D::fillRect(float x, float y, float width, float height) { + recreateBufferIfNeeded(); + _delegate->fillRect(x, y, width, height); + + if (_canvasBufferUpdatedCB != nullptr) { + _canvasBufferUpdatedCB(_delegate->getDataRef()); + } +} + +void CanvasRenderingContext2D::fillText(const std::string &text, float x, float y, float maxWidth) { + //SE_LOGD("CanvasRenderingContext2D::fillText: %s, offset: (%f, %f), %f\n", text.c_str(), x, y, maxWidth); + if (text.empty()) { + return; + } + + recreateBufferIfNeeded(); + + _delegate->fillText(text, x, y, maxWidth); + if (_canvasBufferUpdatedCB != nullptr) { + _canvasBufferUpdatedCB(_delegate->getDataRef()); + } +} + +void CanvasRenderingContext2D::strokeText(const std::string &text, float x, float y, float maxWidth) { + //SE_LOGD("CanvasRenderingContext2D::strokeText: %s, %f, %f, %f\n", text.c_str(), x, y, maxWidth); + if (text.empty()) { + return; + } + + recreateBufferIfNeeded(); + + _delegate->strokeText(text, x, y, maxWidth); + + if (_canvasBufferUpdatedCB != nullptr) { + _canvasBufferUpdatedCB(_delegate->getDataRef()); + } +} + +cc::Size CanvasRenderingContext2D::measureText(const std::string &text) { + //SE_LOGD("CanvasRenderingContext2D::measureText: %s\n", text.c_str()); + auto s = _delegate->measureText(text); + return cc::Size(s[0], s[1]); +} + +ICanvasGradient *CanvasRenderingContext2D::createLinearGradient(float /*x0*/, float /*y0*/, float /*x1*/, float /*y1*/) { + return nullptr; +} + +void CanvasRenderingContext2D::save() { + //SE_LOGD("CanvasRenderingContext2D::save\n"); + _delegate->saveContext(); +} + +void CanvasRenderingContext2D::beginPath() { + //SE_LOGD("\n-----------begin------------------\nCanvasRenderingContext2D::beginPath\n"); + _delegate->beginPath(); +} + +void CanvasRenderingContext2D::closePath() { + //SE_LOGD("CanvasRenderingContext2D::closePath\n"); + _delegate->closePath(); +} + +void CanvasRenderingContext2D::moveTo(float x, float y) { + //SE_LOGD("CanvasRenderingContext2D::moveTo\n"); + _delegate->moveTo(x, y); +} + +void CanvasRenderingContext2D::lineTo(float x, float y) { + //SE_LOGD("CanvasRenderingContext2D::lineTo\n"); + _delegate->lineTo(x, y); +} + +void CanvasRenderingContext2D::stroke() { + //SE_LOGD("CanvasRenderingContext2D::stroke\n"); + _delegate->stroke(); + + if (_canvasBufferUpdatedCB != nullptr) { + _canvasBufferUpdatedCB(_delegate->getDataRef()); + } +} + +void CanvasRenderingContext2D::restore() { + //SE_LOGD("CanvasRenderingContext2D::restore\n"); + _delegate->restoreContext(); +} + +void CanvasRenderingContext2D::setCanvasBufferUpdatedCallback(const CanvasBufferUpdatedCallback &cb) { + _canvasBufferUpdatedCB = cb; + recreateBufferIfNeeded(); +} + +void CanvasRenderingContext2D::setWidth(float width) { + //SE_LOGD("CanvasRenderingContext2D::set__width: %f\n", width); + if (math::IsEqualF(width, _width)) return; + _width = width; + _isBufferSizeDirty = true; + recreateBufferIfNeeded(); +} + +void CanvasRenderingContext2D::setHeight(float height) { + //SE_LOGD("CanvasRenderingContext2D::set__height: %f\n", height); + if (math::IsEqualF(height, _height)) return; + _height = height; + _isBufferSizeDirty = true; + recreateBufferIfNeeded(); +} + +void CanvasRenderingContext2D::setLineWidth(float lineWidth) { + //SE_LOGD("CanvasRenderingContext2D::set_lineWidth %d\n", lineWidth); + _lineWidth = lineWidth; + _delegate->setLineWidth(lineWidth); +} + +void CanvasRenderingContext2D::setLineCap(const std::string &lineCap) { + //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); +#if CC_PLATFORM == CC_PLATFORM_WINDOWS + +#elif CC_PLATFORM == CC_PLATFORM_ANDROID + if (lineCap.empty()) return; + _delegate->setLineCap(lineCap); +#endif +} + +void CanvasRenderingContext2D::setLineJoin(const std::string &lineJoin) { + //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); + _delegate->setLineJoin(lineJoin); +} + +void CanvasRenderingContext2D::fill() { + // SE_LOGE("%s isn't implemented!\n", __FUNCTION__); +#if CC_PLATFORM == CC_PLATFORM_WINDOWS + +#elif CC_PLATFORM == CC_PLATFORM_ANDROID + _delegate->fill(); + + if (_canvasBufferUpdatedCB != nullptr) { + _canvasBufferUpdatedCB(_delegate->getDataRef()); + } +#endif +} + +void CanvasRenderingContext2D::rect(float x, float y, float w, float h) { +#if CC_PLATFORM == CC_PLATFORM_WINDOWS + // SE_LOGE("%s isn't implemented!\n", __FUNCTION__); +#elif CC_PLATFORM == CC_PLATFORM_ANDROID + // SE_LOGD("CanvasRenderingContext2D::rect: %p, %f, %f, %f, %f\n", this, x, y, width, height); + recreateBufferIfNeeded(); + _delegate->rect(x, y, w, h); +#endif +} + +void CanvasRenderingContext2D::setFont(const std::string &font) { +#if CC_PLATFORM == CC_PLATFORM_WINDOWS + if (_font != font) { + _font = font; + + std::string boldStr; + std::string fontName = "Arial"; + std::string fontSizeStr = "30"; + + // support get font name from `60px American` or `60px "American abc-abc_abc"` + std::regex re("(bold)?\\s*((\\d+)([\\.]\\d+)?)px\\s+([\\w-]+|\"[\\w -]+\"$)"); + std::match_results results; + if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) { + boldStr = results[1].str(); + fontSizeStr = results[2].str(); + fontName = results[5].str(); + } + + auto fontSize = static_cast(atof(fontSizeStr.c_str())); + //SE_LOGD("CanvasRenderingContext2D::set_font: %s, Size: %f, isBold: %b\n", fontName.c_str(), fontSize, !boldStr.empty()); + _delegate->updateFont(fontName, fontSize, !boldStr.empty(), false, false, false); + } +#elif CC_PLATFORM == CC_PLATFORM_QNX + if (_font != font) { + _font = font; + + std::string boldStr; + std::string fontName = "Arial"; + std::string fontSizeStr = "30"; + + // support get font name from `60px American` or `60px "American abc-abc_abc"` + std::regex re("(bold)?\\s*((\\d+)([\\.]\\d+)?)px\\s+([\\w-]+|\"[\\w -]+\"$)"); + std::match_results results; + if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) { + boldStr = results[1].str(); + fontSizeStr = results[2].str(); + fontName = results[5].str(); + } + bool isItalic = font.find("italic", 0) != std::string::npos; + auto fontSize = static_cast(atof(fontSizeStr.c_str())); + //SE_LOGD("CanvasRenderingContext2D::set_font: %s, Size: %f, isBold: %b\n", fontName.c_str(), fontSize, !boldStr.empty()); + _delegate->updateFont(fontName, fontSize, !boldStr.empty(), isItalic, false, false); + } +#elif CC_PLATFORM == CC_PLATFORM_LINUX + if (_font != font) { + _font = font; + + std::string fontName = "sans-serif"; + std::string fontSizeStr = "30"; + std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))"); + std::match_results results; + if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) { + fontSizeStr = results[2].str(); + // support get font name from `60px American` or `60px "American abc-abc_abc"` + // support get font name contain space,example `times new roman` + // if regex rule that does not conform to the rules,such as Chinese,it defaults to sans-serif + std::match_results fontResults; + std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))"); + std::string tmp(results[4].str()); + if (std::regex_match(tmp, fontResults, fontRe)) { + //fontName = results[4].str(); + } + } + + bool isBold = font.find("bold", 0) != std::string::npos; + bool isItalic = font.find("italic", 0) != std::string::npos; + float fontSize = static_cast(atof(fontSizeStr.c_str())); + //SE_LOGD("CanvasRenderingContext2D::set_font: %s, Size: %f, isBold: %b\n", fontName.c_str(), fontSize, !boldStr.empty()); + _delegate->updateFont(fontName, fontSize, isBold, isItalic, false, false); + } +#elif CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS + if (_font != font) { + _font = font; + std::string fontName = "sans-serif"; + std::string fontSizeStr = "30"; + std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))"); + std::match_results results; + if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) { + fontSizeStr = results[2].str(); + // support get font name from `60px American` or `60px "American abc-abc_abc"` + // support get font name contain space,example `times new roman` + // if regex rule that does not conform to the rules,such as Chinese,it defaults to sans-serif + std::match_results fontResults; + std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))"); + std::string tmp(results[4].str()); + if (std::regex_match(tmp, fontResults, fontRe)) { + fontName = results[4].str(); + } + } + + double fontSize = atof(fontSizeStr.c_str()); + bool isBold = font.find("bold", 0) != std::string::npos; + bool isItalic = font.find("italic", 0) != std::string::npos; + bool isSmallCaps = font.find("small-caps", 0) != std::string::npos; + bool isOblique = font.find("oblique", 0) != std::string::npos; + //font-style: italic, oblique, normal + //font-weight: normal, bold + //font-variant: normal, small-caps + _delegate->updateFont(fontName, static_cast(fontSize), isBold, isItalic, isOblique, isSmallCaps); + } +#elif CC_PLATFORM == CC_PLATFORM_MAC_OSX || CC_PLATFORM == CC_PLATFORM_MAC_IOS + if (_font != font) { + _font = font; + + std::string boldStr; + std::string fontName = "Arial"; + std::string fontSizeStr = "30"; + + // support get font name from `60px American` or `60px "American abc-abc_abc"` + std::regex re("(bold)?\\s*((\\d+)([\\.]\\d+)?)px\\s+([\\w-]+|\"[\\w -]+\"$)"); + std::match_results results; + if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) { + boldStr = results[1].str(); + fontSizeStr = results[2].str(); + fontName = results[5].str(); + } + float fontSize = atof(fontSizeStr.c_str()); + bool isBold = !boldStr.empty(); + _delegate->updateFont(fontName, static_cast(fontSize), isBold, false, false, false); + } +#endif +} + +void CanvasRenderingContext2D::setTextAlign(const std::string &textAlign) { + //SE_LOGD("CanvasRenderingContext2D::set_textAlign: %s\n", textAlign.c_str()); + if (textAlign == "left") { + _delegate->setTextAlign(CanvasTextAlign::LEFT); + } else if (textAlign == "center" || textAlign == "middle") { + _delegate->setTextAlign(CanvasTextAlign::CENTER); + } else if (textAlign == "right") { + _delegate->setTextAlign(CanvasTextAlign::RIGHT); + } else { + assert(false); + } +} + +void CanvasRenderingContext2D::setTextBaseline(const std::string &textBaseline) { + //SE_LOGD("CanvasRenderingContext2D::set_textBaseline: %s\n", textBaseline.c_str()); + if (textBaseline == "top") { + _delegate->setTextBaseline(CanvasTextBaseline::TOP); + } else if (textBaseline == "middle") { + _delegate->setTextBaseline(CanvasTextBaseline::MIDDLE); + } else if (textBaseline == "bottom") //REFINE:, how to deal with alphabetic, currently we handle it as bottom mode. + { + _delegate->setTextBaseline(CanvasTextBaseline::BOTTOM); + } else if (textBaseline == "alphabetic") { + _delegate->setTextBaseline(CanvasTextBaseline::ALPHABETIC); + } else { + assert(false); + } +} + +void CanvasRenderingContext2D::setFillStyle(const std::string &fillStyle) { + CSSColorParser::Color color = CSSColorParser::parse(fillStyle); + _delegate->setFillStyle(static_cast(color.r) / 255.0F, + static_cast(color.g) / 255.0F, + static_cast(color.b) / 255.0F, + color.a); + //SE_LOGD("CanvasRenderingContext2D::set_fillStyle: %s, (%d, %d, %d, %f)\n", fillStyle.c_str(), color.r, color.g, color.b, color.a); +} + +void CanvasRenderingContext2D::setStrokeStyle(const std::string &strokeStyle) { + CSSColorParser::Color color = CSSColorParser::parse(strokeStyle); + _delegate->setStrokeStyle(static_cast(color.r) / 255.0F, + static_cast(color.g) / 255.0F, + static_cast(color.b) / 255.0F, + color.a); +} + +void CanvasRenderingContext2D::setGlobalCompositeOperation(const std::string &globalCompositeOperation) { + //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); +} + +void CanvasRenderingContext2D::fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) { + //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); +#if CC_PLATFORM == CC_PLATFORM_WINDOWS +#elif CC_PLATFORM == CC_PLATFORM_ANDROID + _delegate->fillImageData(imageData, imageWidth, imageHeight, offsetX, offsetY); + if (_canvasBufferUpdatedCB != nullptr) { + _canvasBufferUpdatedCB(_delegate->getDataRef()); + } +#endif +} +// transform +//REFINE: + +void CanvasRenderingContext2D::translate(float x, float y) { + //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); +} + +void CanvasRenderingContext2D::scale(float x, float y) { + //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); +} + +void CanvasRenderingContext2D::rotate(float angle) { + //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); +} + +void CanvasRenderingContext2D::transform(float a, float b, float c, float d, float e, float f) { + //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); +} + +void CanvasRenderingContext2D::setTransform(float a, float b, float c, float d, float e, float f) { + //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); +} + +void CanvasRenderingContext2D::recreateBufferIfNeeded() { + if (_isBufferSizeDirty) { + _isBufferSizeDirty = false; + //SE_LOGD("Recreate buffer %p, w: %f, h:%f\n", this, __width, __height); + _delegate->recreateBuffer(_width, _height); + if (_canvasBufferUpdatedCB != nullptr) { + _canvasBufferUpdatedCB(_delegate->getDataRef()); + } + } +} + +} // namespace cc diff --git a/native/cocos/platform/CanvasRenderingContext2D.h b/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.h similarity index 51% rename from native/cocos/platform/CanvasRenderingContext2D.h rename to native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.h index de76281b7d..dcbef5589d 100644 --- a/native/cocos/platform/CanvasRenderingContext2D.h +++ b/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.h @@ -25,111 +25,98 @@ #pragma once -#include "base/Macros.h" -#include "base/Data.h" -#include "math/Geometry.h" - -#include - -#ifndef OBJC_CLASS - #ifdef __OBJC__ - #define OBJC_CLASS(name) @class name - #else - #define OBJC_CLASS(name) class name - #endif -#endif // OBJC_CLASS - -OBJC_CLASS(CanvasRenderingContext2DImpl); +#include "platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h" namespace cc { -class CC_DLL CanvasGradient { +class CanvasGradient : public ICanvasGradient { public: CanvasGradient(); - ~CanvasGradient(); // NOLINT(performance-trivially-destructible) - void addColorStop(float offset, const std::string &color); + ~CanvasGradient() override; // NOLINT(performance-trivially-destructible) + void addColorStop(float offset, const std::string &color) override; }; -class CC_DLL CanvasRenderingContext2D { +class CanvasRenderingContext2D : public ICanvasRenderingContext2D { public: CanvasRenderingContext2D(float width, float height); - ~CanvasRenderingContext2D(); + ~CanvasRenderingContext2D() override; // Rect - void rect(float x, float y, float width, float height); - void clearRect(float x, float y, float width, float height); - void fillRect(float x, float y, float width, float height); + void rect(float x, float y, float width, float height) override; + void clearRect(float x, float y, float width, float height) override; + void fillRect(float x, float y, float width, float height) override; - void fillText(const std::string &text, float x, float y, float maxWidth = -1.0F); - void strokeText(const std::string &text, float x, float y, float maxWidth = -1.0F); - Size measureText(const std::string &text); - CanvasGradient *createLinearGradient(float x0, float y0, float x1, float y1); - void save(); + void fillText(const std::string &text, float x, float y, float maxWidth) override; + void strokeText(const std::string &text, float x, float y, float maxWidth) override; + Size measureText(const std::string &text) override; + ICanvasGradient *createLinearGradient(float x0, float y0, float x1, float y1) override; + void save() override; // Paths - void beginPath(); - void closePath(); - void moveTo(float x, float y); - void lineTo(float x, float y); - void fill(); - void stroke(); - void restore(); + void beginPath() override; + void closePath() override; + void moveTo(float x, float y) override; + void lineTo(float x, float y) override; + void fill() override; + void stroke() override; + void restore() override; // callback using CanvasBufferUpdatedCallback = std::function; - void setCanvasBufferUpdatedCallback(const CanvasBufferUpdatedCallback &cb); + void setCanvasBufferUpdatedCallback(const CanvasBufferUpdatedCallback &cb) override; // functions for properties - void setWidth(float width); - void setHeight(float height); - void setLineWidth(float lineWidth); - void setLineJoin(const std::string &lineJoin); - void setLineCap(const std::string &lineCap); - void setFont(const std::string &font); - void setTextAlign(const std::string &textAlign); - void setTextBaseline(const std::string &textBaseline); - void setFillStyle(const std::string &fillStyle); - void setStrokeStyle(const std::string &strokeStyle); - void setGlobalCompositeOperation(const std::string &globalCompositeOperation); + void setWidth(float width) override; + void setHeight(float height) override; + void setLineWidth(float lineWidth) override; + void setLineJoin(const std::string &lineJoin) override; + void setLineCap(const std::string &lineCap) override; + void setFont(const std::string &font) override; + void setTextAlign(const std::string &textAlign) override; + void setTextBaseline(const std::string &textBaseline) override; + void setFillStyle(const std::string &fillStyle) override; + void setStrokeStyle(const std::string &strokeStyle) override; + void setGlobalCompositeOperation(const std::string &globalCompositeOperation) override; // fill image data into Context2D - void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY); + void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; // transform - void translate(float x, float y); - void scale(float x, float y); - void rotate(float angle); + void translate(float x, float y) override; + void scale(float x, float y) override; + void rotate(float angle) override; - void transform(float a, float b, float c, float d, float e, float f); - void setTransform(float a, float b, float c, float d, float e, float f); + void transform(float a, float b, float c, float d, float e, float f) override; + void setTransform(float a, float b, float c, float d, float e, float f) override; private: - void recreateBufferIfNeeded(); + void recreateBufferIfNeeded() override; public: - float _width = 0.0F; + float _width = 0.0F; float _height = 0.0F; // Line styles - float _lineWidth = 1.0F; - std::string _lineJoin = "miter"; - std::string _lineCap = "butt"; + float _lineWidth = 1.0F; + std::string _lineJoin = "miter"; + std::string _lineCap = "butt"; // Text styles - std::string _font = "10px sans-serif"; - std::string _textAlign = "start"; + std::string _font = "10px sans-serif"; + std::string _textAlign = "start"; std::string _textBaseline = "alphabetic"; // Fill and stroke styles std::string _fillStyle = "#000"; - + std::string _strokeStyle = "#000"; // Compositing std::string _globalCompositeOperation = "source-over"; private: + ICanvasRenderingContext2D::Delegate *_delegate; + CanvasBufferUpdatedCallback _canvasBufferUpdatedCB = nullptr; - CanvasRenderingContext2DImpl *_impl = nullptr; bool _isBufferSizeDirty = true; }; diff --git a/native/cocos/platform/interfaces/modules/canvas/ICanvasRenderingContext2D.cpp b/native/cocos/platform/interfaces/modules/canvas/ICanvasRenderingContext2D.cpp new file mode 100644 index 0000000000..4312d2380e --- /dev/null +++ b/native/cocos/platform/interfaces/modules/canvas/ICanvasRenderingContext2D.cpp @@ -0,0 +1,34 @@ +/**************************************************************************** + Copyright (c) 2018-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h" +#include "platform/interfaces/modules/canvas/CanvasRenderingContext2D.h" + +namespace cc { + +//OSInterface::Ptr ICanvasRenderingContext2D::getInterface() { +// return std::make_shared(float(0), float(0)); +//} + +} // namespace cc diff --git a/native/cocos/platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h b/native/cocos/platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h new file mode 100644 index 0000000000..bdb647be32 --- /dev/null +++ b/native/cocos/platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h @@ -0,0 +1,148 @@ +/**************************************************************************** + Copyright (c) 2018-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/OSInterface.h" + +#include "base/Data.h" +#include "math/Geometry.h" + +#include + +enum class CanvasTextAlign { + LEFT, + CENTER, + RIGHT +}; + +enum class CanvasTextBaseline { + TOP, + MIDDLE, + BOTTOM, + ALPHABETIC +}; + +namespace cc { + +//class CanvasGradient { +//public: +// CanvasGradient(); +// ~CanvasGradient(); // NOLINT(performance-trivially-destructible) +// void addColorStop(float offset, const std::string &color); +//}; + +class ICanvasGradient { +public: + ICanvasGradient() = default; + virtual ~ICanvasGradient() = default; // NOLINT(performance-trivially-destructible) + virtual void addColorStop(float offset, const std::string &color) = 0; +}; + +class ICanvasRenderingContext2D : public OSInterface { +public: + class Delegate { + public: + using Size = std::array; + virtual ~Delegate() = default; + virtual void recreateBuffer(float w, float h) = 0; + virtual void beginPath() = 0; + virtual void closePath() = 0; + virtual void moveTo(float x, float y) = 0; + virtual void lineTo(float x, float y) = 0; + virtual void stroke() = 0; + virtual void saveContext() = 0; + virtual void restoreContext() = 0; + virtual void clearRect(float /*x*/, float /*y*/, float w, float h) = 0; + virtual void fill() = 0; + virtual void rect(float x, float y, float w, float h) = 0; + virtual void setLineCap(const std::string &lineCap) = 0; + virtual void setLineJoin(const std::string &lineCap) = 0; + virtual void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) = 0; + virtual void fillRect(float x, float y, float w, float h) = 0; + virtual void fillText(const std::string &text, float x, float y, float /*maxWidth*/) = 0; + virtual void strokeText(const std::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) = 0; + virtual Size measureText(const std::string &text) = 0; + virtual void updateFont(const std::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) = 0; + virtual void setTextAlign(CanvasTextAlign align) = 0; + virtual void setTextBaseline(CanvasTextBaseline baseline) = 0; + virtual void setFillStyle(float r, float g, float b, float a) = 0; + virtual void setStrokeStyle(float r, float g, float b, float a) = 0; + virtual void setLineWidth(float lineWidth) = 0; + virtual const cc::Data &getDataRef() const = 0; + }; + //static OSInterface::Ptr getInterface(); + // Rect + virtual void rect(float x, float y, float width, float height) = 0; + virtual void clearRect(float x, float y, float width, float height) = 0; + virtual void fillRect(float x, float y, float width, float height) = 0; + + virtual void fillText(const std::string &text, float x, float y, float maxWidth) = 0; + virtual void strokeText(const std::string &text, float x, float y, float maxWidth) = 0; + virtual Size measureText(const std::string &text) = 0; + virtual ICanvasGradient *createLinearGradient(float x0, float y0, float x1, float y1) = 0; + virtual void save() = 0; + // Paths + virtual void beginPath() = 0; + virtual void closePath() = 0; + virtual void moveTo(float x, float y) = 0; + virtual void lineTo(float x, float y) = 0; + virtual void fill() = 0; + virtual void stroke() = 0; + virtual void restore() = 0; + + // callback + using CanvasBufferUpdatedCallback = std::function; + virtual void setCanvasBufferUpdatedCallback(const CanvasBufferUpdatedCallback &cb) = 0; + + // functions for properties + virtual void setWidth(float width) = 0; + virtual void setHeight(float height) = 0; + virtual void setLineWidth(float lineWidth) = 0; + virtual void setLineJoin(const std::string &lineJoin) = 0; + virtual void setLineCap(const std::string &lineCap) = 0; + virtual void setFont(const std::string &font) = 0; + virtual void setTextAlign(const std::string &textAlign) = 0; + virtual void setTextBaseline(const std::string &textBaseline) = 0; + virtual void setFillStyle(const std::string &fillStyle) = 0; + virtual void setStrokeStyle(const std::string &strokeStyle) = 0; + virtual void setGlobalCompositeOperation(const std::string &globalCompositeOperation) = 0; + + // fill image data into Context2D + virtual void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) = 0; + + // transform + virtual void translate(float x, float y) = 0; + virtual void scale(float x, float y) = 0; + virtual void rotate(float angle) = 0; + + virtual void transform(float a, float b, float c, float d, float e, float f) = 0; + virtual void setTransform(float a, float b, float c, float d, float e, float f) = 0; + +private: + virtual void recreateBufferIfNeeded() = 0; +}; + +} // namespace cc diff --git a/native/templates/ios/AppDelegate.h b/native/cocos/platform/ios/AppDelegate.h similarity index 96% rename from native/templates/ios/AppDelegate.h rename to native/cocos/platform/ios/AppDelegate.h index cd3334e52d..33e29b6a04 100644 --- a/native/templates/ios/AppDelegate.h +++ b/native/cocos/platform/ios/AppDelegate.h @@ -32,6 +32,7 @@ } @property(nonatomic, readonly) ViewController* viewController; +int runUIAppicationMain(int argc, const char** argv); @end diff --git a/native/templates/ios/AppDelegate.mm b/native/cocos/platform/ios/AppDelegate.mm similarity index 79% rename from native/templates/ios/AppDelegate.mm rename to native/cocos/platform/ios/AppDelegate.mm index bbb50c011e..753036a497 100644 --- a/native/templates/ios/AppDelegate.mm +++ b/native/cocos/platform/ios/AppDelegate.mm @@ -23,16 +23,17 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "AppDelegate.h" +#import "platform/ios/AppDelegate.h" #import "ViewController.h" -#include "platform/ios/View.h" +#import "platform/ios/View.h" -#include "Game.h" -#include "SDKWrapper.h" +#include "platform/ios/IOSPlatform.h" +#include "platform/ios/service/SDKWrapper.h" @implementation AppDelegate -Game * game = nullptr; +cc::IOSPlatform *_platform = nullptr; + @synthesize window; #pragma mark - @@ -51,12 +52,12 @@ Game * game = nullptr; _viewController.view.multipleTouchEnabled = true; [self.window setRootViewController:_viewController]; - // cocos2d application instance - game = new Game(bounds.size.width, bounds.size.height); - game->init(); - [self.window makeKeyAndVisible]; + _platform = dynamic_cast(cc::BasePlatform::getPlatform()); + CCASSERT(_platform != nullptr, "Platform pointer can't be null"); + _platform->loop(); + return YES; } @@ -66,7 +67,7 @@ Game * game = nullptr; Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. */ [[SDKWrapper shared] applicationWillResignActive:application]; - game->onPause(); + _platform->onPause(); } - (void)applicationDidBecomeActive:(UIApplication *)application { @@ -74,7 +75,7 @@ Game * game = nullptr; Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. */ [[SDKWrapper shared] applicationDidBecomeActive:application]; - game->onResume(); + _platform->onResume(); } - (void)applicationDidEnterBackground:(UIApplication *)application { @@ -93,10 +94,14 @@ Game * game = nullptr; } - (void)applicationWillTerminate:(UIApplication *)application { - game->onClose(); + _platform->onClose(); + _platform->onDestory(); + _platform = nullptr; [[SDKWrapper shared] applicationWillTerminate:application]; - delete game; - game = nullptr; +} + +- (void)dispatchEvent:(const cc::OSEvent &)ev { + _platform->dispatchEvent(ev); } #pragma mark - @@ -104,7 +109,21 @@ Game * game = nullptr; - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { [[SDKWrapper shared] applicationDidReceiveMemoryWarning:application]; - cc::EventDispatcher::dispatchMemoryWarningEvent(); + cc::DeviceEvent ev; + ev.type = cc::DeviceEvent::Type::DEVICE_MEMORY; + _platform->dispatchEvent(ev); } +// We must put UIApplicationMain in the same file as AppDelegate, +// otherwise there will be instances where AppDelegate cannot be found at runtime. +// Reference SDL implementation +int runUIAppicationMain(int argc, const char** argv) { + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + int retVal = UIApplicationMain(argc, (char**)argv, nil, @"AppDelegate"); + [pool release]; + return retVal; +} + + + @end diff --git a/native/cocos/platform/ios/IOSPlatform.h b/native/cocos/platform/ios/IOSPlatform.h new file mode 100644 index 0000000000..e0a5fd4ab2 --- /dev/null +++ b/native/cocos/platform/ios/IOSPlatform.h @@ -0,0 +1,63 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/UniversalPlatform.h" + +namespace cc { + +class IOSPlatform : public UniversalPlatform { +public: + IOSPlatform() = default; + /** + * @brief Destructor of WindowPlatform. + */ + ~IOSPlatform() override; + /** + * @brief Implementation of Windows platform initialization. + */ + int32_t init() override; + + /** + * @brief Start base platform initialization. + */ + int32_t run(int argc, const char** argv) override; + /** + * @brief Implement the main logic of the base platform. + */ + int32_t loop() override; + + void setFps(int32_t fps) override; + int32_t getFps() const override; + + void onPause() override; + void onResume() override; + void onClose() override; +private: + ThreadCallback _cb; +}; + +} // namespace cc diff --git a/native/cocos/platform/ios/IOSPlatform.mm b/native/cocos/platform/ios/IOSPlatform.mm new file mode 100644 index 0000000000..7d6c76ef97 --- /dev/null +++ b/native/cocos/platform/ios/IOSPlatform.mm @@ -0,0 +1,138 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/ios/IOSPlatform.h" +#include "platform/interfaces/OSInterface.h" +#include "platform/interfaces/modules/ISystemWindow.h" + +#import +#import "platform/ios/AppDelegate.h" + +extern int cocos_main(int argc, const char** argv); + +@interface MyTimer : NSObject { + cc::IOSPlatform *_platform; + CADisplayLink * _displayLink; + int _fps; +} +- (instancetype)initWithApp:(cc::IOSPlatform *)platform fps:(int)fps; +- (void)start; +- (void)changeFPS:(int)fps; +- (void)pause; +- (void)resume; +@end + +@implementation MyTimer + +- (instancetype)initWithApp:(cc::IOSPlatform *)platform fps:(int)fps { + if (self = [super init]) { + _fps = fps; + _platform = platform; + _displayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(renderScene:)]; + _displayLink.preferredFramesPerSecond = _fps; + } + return self; +} + +- (void)start { + [_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; +} + +- (void)pause { + _displayLink.paused = TRUE; +} + +- (void)resume { + _displayLink.paused = FALSE; +} + +- (void)changeFPS:(int)fps { + _displayLink.preferredFramesPerSecond = fps; +} + +- (int)getFPS { + return (int)_displayLink.preferredFramesPerSecond; +} + +- (void)renderScene:(id)sender { + _platform->runTask(); +} + +@end + +namespace { +MyTimer *_timer; +} + +namespace cc { + +IOSPlatform::~IOSPlatform() = default; + +int32_t IOSPlatform::init() { + _timer = [[MyTimer alloc] initWithApp:this fps:60]; + return UniversalPlatform::init(); +} + +int32_t IOSPlatform::loop() { + cocos_main(0, nullptr); + [_timer start]; + return 0; +} + +int32_t IOSPlatform::run(int argc, const char** argv) { + return runUIAppicationMain(argc, argv); +} + +void IOSPlatform::setFps(int32_t fps) { + [_timer changeFPS:fps]; +} + +int32_t IOSPlatform::getFps() const { + return [_timer getFPS]; +} + +void IOSPlatform::onPause() { + [_timer pause]; + + cc::WindowEvent ev; + ev.type = cc::WindowEvent::Type::HIDDEN; + dispatchEvent(ev); +} + +void IOSPlatform::onResume() { + [_timer resume]; + + cc::WindowEvent ev; + ev.type = cc::WindowEvent::Type::SHOW; + dispatchEvent(ev); +} + +void IOSPlatform::onClose() { + cc::WindowEvent ev; + ev.type = cc::WindowEvent::Type::CLOSE; + dispatchEvent(ev); +} + +} // namespace cc diff --git a/native/cocos/platform/ios/View.mm b/native/cocos/platform/ios/View.mm index 7ca048bca6..8f30ca881a 100644 --- a/native/cocos/platform/ios/View.mm +++ b/native/cocos/platform/ios/View.mm @@ -24,24 +24,17 @@ ****************************************************************************/ #import "View.h" +#import "platform/ios/AppDelegate.h" + #include #include "bindings/event/EventDispatcher.h" -#include "platform/Application.h" namespace { -void dispatchEvents(cc::TouchEvent &touchEvent, NSSet *touches) { - for (UITouch *touch in touches) { - touchEvent.touches.push_back({static_cast([touch locationInView:[touch view]].x), - static_cast([touch locationInView:[touch view]].y), - static_cast((intptr_t)touch)}); - } - cc::EventDispatcher::dispatchTouchEvent(touchEvent); - touchEvent.touches.clear(); -} } // namespace @implementation View { cc::TouchEvent _touchEvent; + AppDelegate* _delegate; } @synthesize preventTouch; @@ -56,7 +49,18 @@ void dispatchEvents(cc::TouchEvent &touchEvent, NSSet *touches) { } #endif +- (void)dispatchEvents:(cc::TouchEvent &)touchEvent withEvent:(NSSet*) touches { + for (UITouch *touch in touches) { + touchEvent.touches.push_back({static_cast([touch locationInView:[touch view]].x), + static_cast([touch locationInView:[touch view]].y), + static_cast((intptr_t)touch)}); + } + [_delegate dispatchEvent:touchEvent]; + touchEvent.touches.clear(); +} + - (id)initWithFrame:(CGRect)frame { + _delegate = [[UIApplication sharedApplication] delegate]; #ifdef CC_USE_METAL if (self = [super initWithFrame:frame]) { self.preventTouch = FALSE; @@ -85,7 +89,7 @@ void dispatchEvents(cc::TouchEvent &touchEvent, NSSet *touches) { return; _touchEvent.type = cc::TouchEvent::Type::BEGAN; - dispatchEvents(_touchEvent, touches); + [self dispatchEvents:_touchEvent withEvent:touches]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { @@ -93,7 +97,7 @@ void dispatchEvents(cc::TouchEvent &touchEvent, NSSet *touches) { return; _touchEvent.type = cc::TouchEvent::Type::MOVED; - dispatchEvents(_touchEvent, touches); + [self dispatchEvents:_touchEvent withEvent:touches]; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { @@ -101,7 +105,7 @@ void dispatchEvents(cc::TouchEvent &touchEvent, NSSet *touches) { return; _touchEvent.type = cc::TouchEvent::Type::ENDED; - dispatchEvents(_touchEvent, touches); + [self dispatchEvents:_touchEvent withEvent:touches]; } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { @@ -109,7 +113,7 @@ void dispatchEvents(cc::TouchEvent &touchEvent, NSSet *touches) { return; _touchEvent.type = cc::TouchEvent::Type::CANCELLED; - dispatchEvents(_touchEvent, touches); + [self dispatchEvents:_touchEvent withEvent:touches]; } - (void)setPreventTouchEvent:(BOOL)flag { diff --git a/native/templates/ios/ViewController.h b/native/cocos/platform/ios/ViewController.h similarity index 100% rename from native/templates/ios/ViewController.h rename to native/cocos/platform/ios/ViewController.h diff --git a/native/templates/ios/ViewController.mm b/native/cocos/platform/ios/ViewController.mm similarity index 71% rename from native/templates/ios/ViewController.mm rename to native/cocos/platform/ios/ViewController.mm index 08c0262fcf..f3e4ef6d3d 100644 --- a/native/templates/ios/ViewController.mm +++ b/native/cocos/platform/ios/ViewController.mm @@ -25,18 +25,25 @@ ****************************************************************************/ #import "ViewController.h" #include "cocos/bindings/event/EventDispatcher.h" -#include "cocos/platform/Device.h" +#include "platform/IEventDispatch.h" +#include "platform/interfaces/modules/IScreen.h" +#include "platform/BasePlatform.h" + +#import "platform/ios/AppDelegate.h" +//#include "cocos/platform/Device.h" namespace { - cc::Device::Orientation _lastOrientation; +// cc::Device::Orientation _lastOrientation; } @interface ViewController () - + @end @implementation ViewController +cc::IScreen::Orientation _lastOrientation; + - (BOOL) shouldAutorotate { return YES; } @@ -52,28 +59,34 @@ namespace { } - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator { - cc::Device::Orientation orientation = _lastOrientation; + cc::IScreen::Orientation orientation = _lastOrientation; // reference: https://developer.apple.com/documentation/uikit/uiinterfaceorientation?language=objc // UIInterfaceOrientationLandscapeRight = UIDeviceOrientationLandscapeLeft // UIInterfaceOrientationLandscapeLeft = UIDeviceOrientationLandscapeRight switch ([UIDevice currentDevice].orientation) { case UIDeviceOrientationPortrait: - orientation = cc::Device::Orientation::PORTRAIT; + orientation = cc::IScreen::Orientation::PORTRAIT; break; case UIDeviceOrientationLandscapeRight: - orientation = cc::Device::Orientation::LANDSCAPE_LEFT; + orientation = cc::IScreen::Orientation::LANDSCAPE_LEFT; break; case UIDeviceOrientationPortraitUpsideDown: - orientation = cc::Device::Orientation::PORTRAIT_UPSIDE_DOWN; + orientation = cc::IScreen::Orientation::PORTRAIT_UPSIDE_DOWN; break; case UIDeviceOrientationLandscapeLeft: - orientation = cc::Device::Orientation::LANDSCAPE_RIGHT; + orientation = cc::IScreen::Orientation::LANDSCAPE_RIGHT; break; default: break; } if (_lastOrientation != orientation) { - cc::EventDispatcher::dispatchOrientationChangeEvent((int) orientation); + cc::DeviceEvent ev; + cc::BasePlatform* platform = cc::BasePlatform::getPlatform(); + cc::IScreen* screenIntf = platform->getInterface(); + ev.type = cc::DeviceEvent::Type::DEVICE_ORIENTATION; + ev.args[0].intVal = static_cast(screenIntf->getDeviceOrientation()); + AppDelegate* delegate = [[UIApplication sharedApplication] delegate]; + [delegate dispatchEvent:ev]; _lastOrientation = orientation; } } diff --git a/native/templates/windows/main.cpp b/native/cocos/platform/ios/modules/Accelerometer.h similarity index 65% rename from native/templates/windows/main.cpp rename to native/cocos/platform/ios/modules/Accelerometer.h index 150246e7c3..b32b67dfda 100644 --- a/native/templates/windows/main.cpp +++ b/native/cocos/platform/ios/modules/Accelerometer.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -21,34 +21,30 @@ 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 "main.h" -#include "AppDelegate.h" -#include "sdl2/SDL.h" +#pragma once -using namespace cc; +#include "platform/interfaces/modules/IAccelerometer.h" -// uncomment below line, open debug console -// #define USE_WIN32_CONSOLE +namespace cc { -int SDL_main(int argc, char *argv[]) -{ +class Accelerometer : public IAccelerometer { +public: + /** + * @brief To enable or disable accelerometer. + */ + void setAccelerometerEnabled(bool isEnabled) override; -#ifdef USE_WIN32_CONSOLE - AllocConsole(); - freopen("CONIN$", "r", stdin); - freopen("CONOUT$", "w", stdout); - freopen("CONOUT$", "w", stderr); -#endif + /** + * @brief Sets the interval of accelerometer. + */ + void setAccelerometerInterval(float interval) override; - // create the application instance - AppDelegate app("Cocos3D Game", 960, 640); - app.start(); + /** + * @brief Gets the motion value of current device. + */ + const MotionValue &getDeviceMotionValue() override; +}; -#ifdef USE_WIN32_CONSOLE - FreeConsole(); -#endif - - return 0; -} +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/ios/Device-ios.mm b/native/cocos/platform/ios/modules/Accelerometer.mm similarity index 50% rename from native/cocos/platform/ios/Device-ios.mm rename to native/cocos/platform/ios/modules/Accelerometer.mm index 1ea056b5df..437db24834 100644 --- a/native/cocos/platform/ios/Device-ios.mm +++ b/native/cocos/platform/ios/modules/Accelerometer.mm @@ -1,7 +1,5 @@ /**************************************************************************** - Copyright (c) 2010-2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -25,29 +23,22 @@ THE SOFTWARE. ****************************************************************************/ -#include "Application.h" -#include "platform/Device.h" - -// Vibrate -#import -#include "platform/apple/Device-apple.h" -#include "Reachability.h" - +#include "platform/ios/modules/Accelerometer.h" #import // Accelerometer -#import #include +#import #include -#include +#include "platform/interfaces/modules/IAccelerometer.h" -static const float g = 9.80665; +static const float g = 9.80665; static const float radToDeg = (180 / M_PI); @interface CCMotionDispatcher : NSObject { - CMMotionManager *_motionManager; - cc::Device::MotionValue _motionValue; - float _interval; // unit: seconds - bool _enabled; + CMMotionManager * _motionManager; + cc::IAccelerometer::MotionValue _motionValue; + float _interval; // unit: seconds + bool _enabled; } + (id)sharedMotionDispatcher; @@ -71,8 +62,8 @@ static CCMotionDispatcher *__motionDispatcher = nullptr; - (id)init { if ((self = [super init])) { - _enabled = false; - _interval = 1.0f / 60.0f; + _enabled = false; + _interval = 1.0f / 60.0f; _motionManager = [[CMMotionManager alloc] init]; } return self; @@ -124,10 +115,9 @@ static CCMotionDispatcher *__motionDispatcher = nullptr; } } -- (const cc::Device::MotionValue &)getMotionValue { - +- (const cc::IAccelerometer::MotionValue &)getMotionValue { if (_motionManager.isDeviceMotionAvailable) { - CMDeviceMotion *motion = _motionManager.deviceMotion; + CMDeviceMotion *motion = _motionManager.deviceMotion; _motionValue.accelerationX = motion.userAcceleration.x * g; _motionValue.accelerationY = motion.userAcceleration.y * g; _motionValue.accelerationZ = motion.userAcceleration.z * g; @@ -137,10 +127,10 @@ static CCMotionDispatcher *__motionDispatcher = nullptr; _motionValue.accelerationIncludingGravityZ = (motion.userAcceleration.z + motion.gravity.z) * g; _motionValue.rotationRateAlpha = motion.rotationRate.x * radToDeg; - _motionValue.rotationRateBeta = motion.rotationRate.y * radToDeg; + _motionValue.rotationRateBeta = motion.rotationRate.y * radToDeg; _motionValue.rotationRateGamma = motion.rotationRate.z * radToDeg; } else { - CMAccelerometerData *acc = _motionManager.accelerometerData; + CMAccelerometerData *acc = _motionManager.accelerometerData; _motionValue.accelerationIncludingGravityX = acc.acceleration.x * g; _motionValue.accelerationIncludingGravityY = acc.acceleration.y * g; _motionValue.accelerationIncludingGravityZ = acc.acceleration.z * g; @@ -154,41 +144,13 @@ static CCMotionDispatcher *__motionDispatcher = nullptr; // namespace cc { - -int Device::getDPI() { - static int dpi = -1; - - if (dpi == -1) { - float scale = 1.0f; - - if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { - scale = [[UIScreen mainScreen] scale]; - } - - if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { - dpi = 132 * scale; - } else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) { - dpi = 163 * scale; - } else { - dpi = 160 * scale; - } - } - return dpi; +void Accelerometer::setAccelerometerEnabled(bool isEnabled) { } -void Device::setAccelerometerEnabled(bool isEnabled) { -#if !defined(CC_TARGET_OS_TVOS) - [[CCMotionDispatcher sharedMotionDispatcher] setMotionEnabled:isEnabled]; -#endif +void Accelerometer::setAccelerometerInterval(float interval) { } -void Device::setAccelerometerInterval(float interval) { -#if !defined(CC_TARGET_OS_TVOS) - [[CCMotionDispatcher sharedMotionDispatcher] setMotionInterval:interval]; -#endif -} - -const Device::MotionValue &Device::getDeviceMotionValue() { +const Accelerometer::MotionValue &Accelerometer::getDeviceMotionValue() { #if !defined(CC_TARGET_OS_TVOS) return [[CCMotionDispatcher sharedMotionDispatcher] getMotionValue]; #else @@ -197,90 +159,4 @@ const Device::MotionValue &Device::getDeviceMotionValue() { #endif } -Device::Orientation Device::getDeviceOrientation() { - Orientation orientation = Device::Orientation::LANDSCAPE_RIGHT; - switch ([[UIApplication sharedApplication] statusBarOrientation]) { - case UIInterfaceOrientationLandscapeRight: - orientation = Device::Orientation::LANDSCAPE_RIGHT; - break; - - case UIInterfaceOrientationLandscapeLeft: - orientation = Device::Orientation::LANDSCAPE_LEFT; - break; - - case UIInterfaceOrientationPortraitUpsideDown: - orientation = Device::Orientation::PORTRAIT_UPSIDE_DOWN; - break; - - case UIInterfaceOrientationPortrait: - orientation = Device::Orientation::PORTRAIT; - break; - default: - assert(false); - break; - } - - return orientation; -} - -std::string Device::getDeviceModel() { - struct utsname systemInfo; - uname(&systemInfo); - return systemInfo.machine; -} - -void Device::setKeepScreenOn(bool value) { - [[UIApplication sharedApplication] setIdleTimerDisabled:(BOOL)value]; -} - -/*! - @brief Only works on iOS devices that support vibration (such as iPhone). Should only be used for important alerts. Use risks rejection in iTunes Store. - @param duration ignored for iOS - */ -void Device::vibrate(float duration) { - // See https://developer.apple.com/library/ios/documentation/AudioToolbox/Reference/SystemSoundServicesReference/index.html#//apple_ref/c/econst/kSystemSoundID_Vibrate - CC_UNUSED_PARAM(duration); - - // automatically vibrates for approximately 0.4 seconds - AudioServicesPlayAlertSound(kSystemSoundID_Vibrate); -} - -float Device::getBatteryLevel() { - return [UIDevice currentDevice].batteryLevel; -} - -Device::NetworkType Device::getNetworkType() { - static Reachability *__reachability = nullptr; - if (__reachability == nullptr) { - __reachability = Reachability::createForInternetConnection(); - __reachability->retain(); - } - - NetworkType ret = NetworkType::NONE; - Reachability::NetworkStatus status = __reachability->getCurrentReachabilityStatus(); - switch (status) { - case Reachability::NetworkStatus::REACHABLE_VIA_WIFI: - ret = NetworkType::LAN; - break; - case Reachability::NetworkStatus::REACHABLE_VIA_WWAN: - ret = NetworkType::WWAN; - break; - default: - ret = NetworkType::NONE; - break; - } - - return ret; -} - -cc::Vec4 Device::getSafeAreaEdge() { - UIView *screenView = UIApplication.sharedApplication.delegate.window.rootViewController.view; - - if (@available(iOS 11.0, *)) { - UIEdgeInsets safeAreaEdge = screenView.safeAreaInsets; - return cc::Vec4(safeAreaEdge.top, safeAreaEdge.left, safeAreaEdge.bottom, safeAreaEdge.right); - } - // If running on iOS devices lower than 11.0, return ZERO Vec4. - return cc::Vec4(); -} } // namespace cc diff --git a/native/cocos/platform/android/View.h b/native/cocos/platform/ios/modules/Battery.h similarity index 82% rename from native/cocos/platform/android/View.h rename to native/cocos/platform/ios/modules/Battery.h index 8952804b18..46e802fe00 100644 --- a/native/cocos/platform/android/View.h +++ b/native/cocos/platform/ios/modules/Battery.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -25,20 +25,14 @@ #pragma once -#include "base/Macros.h" -#include - -struct android_app; -struct AInputEvent; +#include "platform/interfaces/modules/IBattery.h" namespace cc { -class TouchEvent; - -class View { +class Battery : public IBattery { public: - static void engineHandleCmd(int cmd); - static int32_t engineHandleInput(struct android_app *app, AInputEvent *event); + Battery() = default; + float getBatteryLevel() const override; }; } // namespace cc diff --git a/native/cocos/platform/ios/modules/Battery.mm b/native/cocos/platform/ios/modules/Battery.mm new file mode 100644 index 0000000000..fbc74f2637 --- /dev/null +++ b/native/cocos/platform/ios/modules/Battery.mm @@ -0,0 +1,34 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/ios/modules/Battery.h" +#import + +namespace cc { + +float Battery::getBatteryLevel() const { + return [UIDevice currentDevice].batteryLevel; +} + +} // namespace cc diff --git a/native/cocos/platform/ios/modules/Network.h b/native/cocos/platform/ios/modules/Network.h new file mode 100644 index 0000000000..cd5f2d6d5a --- /dev/null +++ b/native/cocos/platform/ios/modules/Network.h @@ -0,0 +1,37 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/INetwork.h" + +namespace cc { + +class Network : public INetwork { +public: + NetworkType getNetworkType() const override; +}; + +} // namespace cc diff --git a/native/cocos/platform/ios/modules/Network.mm b/native/cocos/platform/ios/modules/Network.mm new file mode 100644 index 0000000000..2c3433bf05 --- /dev/null +++ b/native/cocos/platform/ios/modules/Network.mm @@ -0,0 +1,56 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/ios/modules/Network.h" +#include +#import +#include "platform/apple/Reachability.h" + +namespace cc { + +INetwork::NetworkType Network::getNetworkType() const { + static Reachability *__reachability = nullptr; + if (__reachability == nullptr) { + __reachability = Reachability::createForInternetConnection(); + __reachability->retain(); + } + + NetworkType ret = NetworkType::NONE; + Reachability::NetworkStatus status = __reachability->getCurrentReachabilityStatus(); + switch (status) { + case Reachability::NetworkStatus::REACHABLE_VIA_WIFI: + ret = NetworkType::LAN; + break; + case Reachability::NetworkStatus::REACHABLE_VIA_WWAN: + ret = NetworkType::WWAN; + break; + default: + ret = NetworkType::NONE; + break; + } + + return ret; +} + +} // namespace cc diff --git a/native/cocos/platform/ios/modules/Screen.h b/native/cocos/platform/ios/modules/Screen.h new file mode 100644 index 0000000000..6b62649702 --- /dev/null +++ b/native/cocos/platform/ios/modules/Screen.h @@ -0,0 +1,51 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IScreen.h" + +namespace cc { + +class Screen : public IScreen { +public: + int getDPI() const override; + float getDevicePixelRatio() const override; + void setKeepScreenOn(bool value) override; + Orientation getDeviceOrientation() const override; + Vec4 getSafeAreaEdge() const override; + /** + * @brief Get current display stats. + * @return bool, is displaying stats or not. + */ + bool isDisplayStats() override; + + /** + * @brief set display stats information. + */ + void setDisplayStats(bool isShow) override; +}; + +} // namespace cc diff --git a/native/cocos/platform/ios/modules/Screen.mm b/native/cocos/platform/ios/modules/Screen.mm new file mode 100644 index 0000000000..c9b526b66c --- /dev/null +++ b/native/cocos/platform/ios/modules/Screen.mm @@ -0,0 +1,120 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/ios/modules/Screen.h" + +#include +#import +#include +#import + +#include "base/Macros.h" +#include "cocos/bindings/jswrapper/SeApi.h" + +namespace cc { + +int Screen::getDPI() const { + static int dpi = -1; + + if (dpi == -1) { + float scale = 1.0f; + + if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { + scale = [[UIScreen mainScreen] scale]; + } + + if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { + dpi = 132 * scale; + } else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) { + dpi = 163 * scale; + } else { + dpi = 160 * scale; + } + } + return dpi; +} + +float Screen::getDevicePixelRatio() const { + return [[UIScreen mainScreen] nativeScale]; +} + +void Screen::setKeepScreenOn(bool value) { + [[UIApplication sharedApplication] setIdleTimerDisabled:(BOOL)value]; +} + +Screen::Orientation Screen::getDeviceOrientation() const { + Orientation orientation = Orientation::PORTRAIT; + switch ([[UIApplication sharedApplication] statusBarOrientation]) { + case UIInterfaceOrientationLandscapeRight: + orientation = Orientation::LANDSCAPE_RIGHT; + break; + + case UIInterfaceOrientationLandscapeLeft: + orientation = Orientation::LANDSCAPE_LEFT; + break; + + case UIInterfaceOrientationPortraitUpsideDown: + orientation = Orientation::PORTRAIT_UPSIDE_DOWN; + break; + + case UIInterfaceOrientationPortrait: + orientation = Orientation::PORTRAIT; + break; + default: + assert(false); + break; + } + + return orientation; +} + +Vec4 Screen::getSafeAreaEdge() const { + UIView *screenView = UIApplication.sharedApplication.delegate.window.rootViewController.view; + + if (@available(iOS 11.0, *)) { + UIEdgeInsets safeAreaEdge = screenView.safeAreaInsets; + return cc::Vec4(safeAreaEdge.top, safeAreaEdge.left, safeAreaEdge.bottom, safeAreaEdge.right); + } + // If running on iOS devices lower than 11.0, return ZERO Vec4. + return cc::Vec4(); +} + +bool Screen::isDisplayStats() { + se::AutoHandleScope hs; + se::Value ret; + char commandBuf[100] = "cc.debug.isDisplayStats();"; + se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret); + return ret.toBoolean(); +} + +void Screen::setDisplayStats(bool isShow) { + se::AutoHandleScope hs; + char commandBuf[100] = {0}; + sprintf(commandBuf, "cc.debug.setDisplayStats(%s);", isShow ? "true" : "false"); + se::ScriptEngine::getInstance()->evalString(commandBuf); +} + + +} // namespace cc diff --git a/native/cocos/platform/ios/modules/System.h b/native/cocos/platform/ios/modules/System.h new file mode 100644 index 0000000000..d27091baec --- /dev/null +++ b/native/cocos/platform/ios/modules/System.h @@ -0,0 +1,65 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/ISystem.h" + +namespace cc { + +class System : public ISystem { +public: + /** + * @brief Get target system type. + */ + OSType getOSType() const override; + /** + * @brief Get target device model. + */ + std::string getDeviceModel() const override; + /** + * @brief Get current language config. + * @return Current language config. + */ + LanguageType getCurrentLanguage() const override; + /** + * @brief Get current language iso 639-1 code. + * @return Current language iso 639-1 code. + */ + std::string getCurrentLanguageCode() const override; + /** + * @brief Get system version. + * @return system version. + */ + std::string getSystemVersion() const override; + /** + * @brief Open url in default browser. + * @param String with url to open. + * @return True if the resource located by the URL was successfully opened; otherwise false. + */ + bool openURL(const std::string& url) override; +}; + +} // namespace cc diff --git a/native/cocos/platform/ios/modules/System.mm b/native/cocos/platform/ios/modules/System.mm new file mode 100644 index 0000000000..7627ae4435 --- /dev/null +++ b/native/cocos/platform/ios/modules/System.mm @@ -0,0 +1,103 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/ios/modules/System.h" +#import + + +#include +#include +#include +#include + + +namespace cc { +using OSType = System::OSType; + +OSType System::getOSType() const { + return OSType::IPHONE; +} + +std::string System::getDeviceModel() const { + struct utsname systemInfo; + uname(&systemInfo); + return systemInfo.machine; +} + +System::LanguageType System::getCurrentLanguage() const { + // get the current language and country config + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; + NSArray * languages = [defaults objectForKey:@"AppleLanguages"]; + NSString * currentLanguage = [languages objectAtIndex:0]; + + // get the current language code.(such as English is "en", Chinese is "zh" and so on) + NSDictionary *temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; + NSString * languageCode = [temp objectForKey:NSLocaleLanguageCode]; + + if ([languageCode isEqualToString:@"zh"]) return LanguageType::CHINESE; + if ([languageCode isEqualToString:@"en"]) return LanguageType::ENGLISH; + if ([languageCode isEqualToString:@"fr"]) return LanguageType::FRENCH; + if ([languageCode isEqualToString:@"it"]) return LanguageType::ITALIAN; + if ([languageCode isEqualToString:@"de"]) return LanguageType::GERMAN; + if ([languageCode isEqualToString:@"es"]) return LanguageType::SPANISH; + if ([languageCode isEqualToString:@"nl"]) return LanguageType::DUTCH; + if ([languageCode isEqualToString:@"ru"]) return LanguageType::RUSSIAN; + if ([languageCode isEqualToString:@"ko"]) return LanguageType::KOREAN; + if ([languageCode isEqualToString:@"ja"]) return LanguageType::JAPANESE; + if ([languageCode isEqualToString:@"hu"]) return LanguageType::HUNGARIAN; + if ([languageCode isEqualToString:@"pt"]) return LanguageType::PORTUGUESE; + if ([languageCode isEqualToString:@"ar"]) return LanguageType::ARABIC; + if ([languageCode isEqualToString:@"nb"]) return LanguageType::NORWEGIAN; + if ([languageCode isEqualToString:@"pl"]) return LanguageType::POLISH; + if ([languageCode isEqualToString:@"tr"]) return LanguageType::TURKISH; + if ([languageCode isEqualToString:@"uk"]) return LanguageType::UKRAINIAN; + if ([languageCode isEqualToString:@"ro"]) return LanguageType::ROMANIAN; + if ([languageCode isEqualToString:@"bg"]) return LanguageType::BULGARIAN; + return LanguageType::ENGLISH; +} + +std::string System::getCurrentLanguageCode() const { + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; + NSArray * languages = [defaults objectForKey:@"AppleLanguages"]; + NSString * currentLanguage = [languages objectAtIndex:0]; + return [currentLanguage UTF8String]; +} + +std::string System::getSystemVersion() const { + NSString *systemVersion = [UIDevice currentDevice].systemVersion; + return [systemVersion UTF8String]; +} + +bool System::openURL(const std::string &url) { + NSString * msg = [NSString stringWithCString:url.c_str() encoding:NSUTF8StringEncoding]; + NSURL * nsUrl = [NSURL URLWithString:msg]; + __block BOOL flag = false; + [[UIApplication sharedApplication] openURL:nsUrl + options:@{} + completionHandler:^(BOOL success) { + flag = success; + }]; + return flag; +} +} // namespace cc diff --git a/native/cocos/platform/win32/View-win32.h b/native/cocos/platform/ios/modules/SystemWindow.h similarity index 60% rename from native/cocos/platform/win32/View-win32.h rename to native/cocos/platform/ios/modules/SystemWindow.h index b227a82e35..ecc0bec72d 100644 --- a/native/cocos/platform/win32/View-win32.h +++ b/native/cocos/platform/ios/modules/SystemWindow.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -25,47 +25,31 @@ #pragma once -#include -#include -#include -#include -#include "base/Macros.h" -#include "platform/StdC.h" +#include -// SDL headers -#include "sdl2/SDL.h" -#include "sdl2/SDL_main.h" -#include "sdl2/SDL_syswm.h" - -#include "cocos/bindings/event/EventDispatcher.h" +#include "platform/interfaces/modules/ISystemWindow.h" namespace cc { -class View { +class SystemWindow : public ISystemWindow { public: - View(const std::string &title, int width, int height); - virtual ~View(); + SystemWindow() = default; + ~SystemWindow() override; - bool init(); + bool createWindow(const char* title, + int x, int y, int w, + int h, int flags) override; + uintptr_t getWindowHandler() const override; - bool pollEvent(bool *quit, bool *resume, bool *pause, bool *close); - - std::array getViewSize() const { return std::array{_width, _height}; } - - HWND getWindowHandler(); - - void swapbuffer() { SDL_GL_SwapWindow(_window); } - - void setCursorEnabeld(bool); + Size getViewSize() const override; + /* + @brief enable/disable(lock) the cursor, default is enabled + */ + void setCursorEnabled(bool value) override; + void copyTextToClipboard(const std::string& text) override; private: - std::string _title; - int _width = 0; - int _height = 0; - bool _inited = false; - - SDL_Window *_window = nullptr; - SDL_Event sdlEvent; + int32_t _width{0}; + int32_t _height{0}; }; - } // namespace cc diff --git a/native/cocos/platform/ios/modules/SystemWindow.mm b/native/cocos/platform/ios/modules/SystemWindow.mm new file mode 100644 index 0000000000..444b599060 --- /dev/null +++ b/native/cocos/platform/ios/modules/SystemWindow.mm @@ -0,0 +1,62 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/ios/modules/SystemWindow.h" +#import +#include "platform/ios/AppDelegate.h" + +namespace { + +} + +namespace cc { + +SystemWindow::~SystemWindow() = default; + +bool SystemWindow::createWindow(const char* title, + int x, int y, int w, + int h, int flags) { + _width = w; + _height = h; +} + +void SystemWindow::setCursorEnabled(bool value) { +} + +void SystemWindow::copyTextToClipboard(const std::string& text) { + UIPasteboard* pasteboard = [UIPasteboard generalPasteboard]; + pasteboard.string = [NSString stringWithCString:text.c_str() encoding:NSUTF8StringEncoding]; +} + +uintptr_t SystemWindow::getWindowHandler() const { + return reinterpret_cast(UIApplication.sharedApplication.delegate.window.rootViewController.view); +} + +SystemWindow::Size SystemWindow::getViewSize() const { + CGRect bounds = [[UIScreen mainScreen] bounds]; + return Size{static_cast(bounds.size.width), static_cast(bounds.size.height)}; +} + + +} diff --git a/native/cocos/platform/ios/modules/Vibrator.h b/native/cocos/platform/ios/modules/Vibrator.h new file mode 100644 index 0000000000..8a91c91420 --- /dev/null +++ b/native/cocos/platform/ios/modules/Vibrator.h @@ -0,0 +1,44 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IVibrator.h" + +namespace cc { + +class Vibrator : public IVibrator { +public: + /** + * Vibrate for the specified amount of time. + * If vibrate is not supported, then invoking this method has no effect. + * Some platforms limit to a maximum duration of 5 seconds. + * Duration is ignored on iOS due to API limitations. + * @param duration The duration in seconds. + */ + void vibrate(float duration) override; +}; + +} // namespace cc diff --git a/native/cocos/platform/ios/modules/Vibrator.mm b/native/cocos/platform/ios/modules/Vibrator.mm new file mode 100644 index 0000000000..052f69c913 --- /dev/null +++ b/native/cocos/platform/ios/modules/Vibrator.mm @@ -0,0 +1,36 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/ios/modules/Vibrator.h" + +#include "base/Macros.h" + +namespace cc { + +void Vibrator::vibrate(float duration) { + CC_UNUSED_PARAM(duration); +} + +} \ No newline at end of file diff --git a/native/templates/ios/service/SDKWrapper.h b/native/cocos/platform/ios/service/SDKWrapper.h similarity index 100% rename from native/templates/ios/service/SDKWrapper.h rename to native/cocos/platform/ios/service/SDKWrapper.h diff --git a/native/templates/ios/service/SDKWrapper.m b/native/cocos/platform/ios/service/SDKWrapper.m similarity index 100% rename from native/templates/ios/service/SDKWrapper.m rename to native/cocos/platform/ios/service/SDKWrapper.m diff --git a/native/cocos/platform/java/CanvasRenderingContext2D-java.cpp b/native/cocos/platform/java/CanvasRenderingContext2D-java.cpp deleted file mode 100644 index 651be8bc77..0000000000 --- a/native/cocos/platform/java/CanvasRenderingContext2D-java.cpp +++ /dev/null @@ -1,583 +0,0 @@ -/**************************************************************************** - Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - 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 "base/csscolorparser.h" -#include "bindings/jswrapper/config.h" -#include "math/Math.h" -#include "platform/CanvasRenderingContext2D.h" - -#include "cocos/bindings/jswrapper/SeApi.h" -#include "platform/java/jni/JniHelper.h" -#include "platform/java/jni/JniImp.h" - -#if __OHOS__ - #include -#endif - -#include - -#ifndef JCLS_CANVASIMPL - #define JCLS_CANVASIMPL "com/cocos/lib/CanvasRenderingContext2DImpl" -#endif - -//NOLINTNEXTLINE -using namespace cc; - -enum class CanvasTextAlign { - LEFT, - CENTER, - RIGHT -}; - -enum class CanvasTextBaseline { - TOP, - MIDDLE, - BOTTOM, - ALPHABETIC -}; - -class CanvasRenderingContext2DImpl { -public: - CanvasRenderingContext2DImpl() { - jobject obj = JniHelper::newObject(JCLS_CANVASIMPL); - _obj = JniHelper::getEnv()->NewGlobalRef(obj); - ccDeleteLocalRef(JniHelper::getEnv(), obj); - } - - ~CanvasRenderingContext2DImpl() { - JniHelper::getEnv()->DeleteGlobalRef(_obj); - } - - void recreateBuffer(float w, float h) { - _bufferWidth = w; - _bufferHeight = h; - if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { - return; - } - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "recreateBuffer", w, h); - fillData(); - } - - void beginPath() { - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "beginPath"); - } - - void closePath() { - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "closePath"); - } - - void moveTo(float x, float y) { - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "moveTo", x, y); - } - - void lineTo(float x, float y) { - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "lineTo", x, y); - } - - void stroke() { - if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { - return; - } - - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "stroke"); - fillData(); - } - - void fill() { - if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { - return; - } - - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "fill"); - fillData(); - } - - void saveContext() { - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "saveContext"); - } - - void restoreContext() { - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "restoreContext"); - } - - void rect(float x, float y, float w, float h) { - if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { - return; - } - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "rect", x, y, w, h); - fillData(); - } - - void clearRect(float x, float y, float w, float h) { - if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { - return; - } - if (x >= _bufferWidth || y >= _bufferHeight) { - return; - } - if (x + w > _bufferWidth) { - w = _bufferWidth - x; - } - if (y + h > _bufferHeight) { - h = _bufferHeight - y; - } - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "clearRect", x, y, w, h); - fillData(); - } - - void fillRect(float x, float y, float w, float h) { - if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { - return; - } - if (x >= _bufferWidth || y >= _bufferHeight) { - return; - } - if (x + w > _bufferWidth) { - w = _bufferWidth - x; - } - if (y + h > _bufferHeight) { - h = _bufferHeight - y; - } - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "fillRect", x, y, w, h); - fillData(); - } - - void fillText(const std::string &text, float x, float y, float maxWidth) { - if (text.empty() || _bufferWidth < 1.0F || _bufferHeight < 1.0F) { - return; - } - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "fillText", text, x, y, maxWidth); - fillData(); - } - - void strokeText(const std::string &text, float x, float y, float maxWidth) { - if (text.empty() || _bufferWidth < 1.0F || _bufferHeight < 1.0F) { - return; - } - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "strokeText", text, x, y, maxWidth); - fillData(); - } - - float measureText(const std::string &text) { - if (text.empty()) { - return 0.0F; - } - return JniHelper::callObjectFloatMethod(_obj, JCLS_CANVASIMPL, "measureText", text); - } - - void updateFont(const std::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) { - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "updateFont", fontName, fontSize, bold, italic, oblique, smallCaps); - } - - void setLineCap(const std::string &lineCap) { - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setLineCap", lineCap); - } - - void setLineJoin(const std::string &lineJoin) { - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setLineJoin", lineJoin); - } - - void setTextAlign(CanvasTextAlign align) { - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setTextAlign", static_cast(align)); - } - - void setTextBaseline(CanvasTextBaseline baseline) { - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setTextBaseline", static_cast(baseline)); - } - - void setFillStyle(float r, float g, float b, float a) { - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setFillStyle", r, g, b, a); - } - - void setStrokeStyle(float r, float g, float b, float a) { - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setStrokeStyle", r, g, b, a); - } - - void setLineWidth(float lineWidth) { - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setLineWidth", lineWidth); - } - - void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) { - if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { - return; - } - - auto *arr = JniHelper::getEnv()->NewIntArray(imageData.getSize() / 4); - JniHelper::getEnv()->SetIntArrayRegion(arr, 0, imageData.getSize() / 4, - reinterpret_cast(imageData.getBytes())); - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "_fillImageData", arr, imageWidth, - imageHeight, offsetX, offsetY); - ccDeleteLocalRef(JniHelper::getEnv(), arr); - - fillData(); - } - - const Data &getDataRef() const { - return _data; - } - -#define CLAMP(V, HI) std::min((V), (HI)) - - //NOLINTNEXTLINE(readability-convert-member-functions-to-static) - void unMultiplyAlpha(unsigned char *ptr, ssize_t size) { - // Android source data is not premultiplied alpha when API >= 19 - // please refer CanvasRenderingContext2DImpl::recreateBuffer(float w, float h) - // in CanvasRenderingContext2DImpl.java - // if (getAndroidSDKInt() >= 19) - // return; - - float alpha; - for (int i = 0; i < size; i += 4) { - alpha = static_cast(ptr[i + 3]); - if (alpha > 0) { - ptr[i] = CLAMP((int)((float)ptr[i] / alpha * 255), 255); - ptr[i + 1] = CLAMP((int)((float)ptr[i + 1] / alpha * 255), 255); - ptr[i + 2] = CLAMP((int)((float)ptr[i + 2] / alpha * 255), 255); - } - } - } - - void fillData() { - jbyteArray arr = JniHelper::callObjectByteArrayMethod(_obj, JCLS_CANVASIMPL, "getDataRef"); - if (arr == nullptr) { - SE_LOGE("getDataRef return null in fillData, size: %d, %d", (int)_bufferWidth, (int)_bufferHeight); - return; - } - jsize len = JniHelper::getEnv()->GetArrayLength(arr); - auto *jbarray = static_cast(malloc(len * sizeof(jbyte))); - JniHelper::getEnv()->GetByteArrayRegion(arr, 0, len, jbarray); -#if CC_PLATFORM != CC_PLATFORM_OHOS - unMultiplyAlpha(reinterpret_cast(jbarray), len); -#endif - _data.fastSet(reinterpret_cast(jbarray), len); //IDEA: DON'T create new jbarray every time. - ccDeleteLocalRef(JniHelper::getEnv(), arr); - } - -private: - jobject _obj = nullptr; - Data _data; - float _bufferWidth = 0.0F; - float _bufferHeight = 0.0F; -}; - -namespace { -void fillRectWithColor(uint8_t *buf, uint32_t totalWidth, uint32_t totalHeight, uint32_t x, uint32_t y, uint32_t width, uint32_t height, uint8_t r, uint8_t g, uint8_t b) { - assert(x + width <= totalWidth); - assert(y + height <= totalHeight); - - uint32_t y0 = totalHeight - (y + height); - uint32_t y1 = totalHeight - y; - uint8_t *p; - for (uint32_t offsetY = y0; offsetY < y1; ++offsetY) { - for (uint32_t offsetX = x; offsetX < (x + width); ++offsetX) { - p = buf + (totalWidth * offsetY + offsetX) * 3; - *p++ = r; - *p++ = g; - *p++ = b; - } - } -} -} // namespace - -namespace cc { - -CanvasGradient::CanvasGradient() = default; -CanvasGradient::~CanvasGradient() = default; - - -void CanvasGradient::addColorStop(float offset, const std::string &color) { - // SE_LOGD("CanvasGradient::addColorStop: %p\n", this); -} - -// CanvasRenderingContext2D - -CanvasRenderingContext2D::CanvasRenderingContext2D(float width, float height) -: _width(width), - _height(height) { - // SE_LOGD("CanvasRenderingContext2D constructor: %p, width: %f, height: %f\n", this, width, height); - _impl = new CanvasRenderingContext2DImpl(); -} - -CanvasRenderingContext2D::~CanvasRenderingContext2D() { - // SE_LOGD("CanvasRenderingContext2D destructor: %p\n", this); - delete _impl; -} - -void CanvasRenderingContext2D::recreateBufferIfNeeded() { - if (_isBufferSizeDirty) { - _isBufferSizeDirty = false; - // SE_LOGD("Recreate buffer %p, w: %f, h:%f\n", this, _width, _height); - _impl->recreateBuffer(_width, _height); - if (_canvasBufferUpdatedCB != nullptr) { - _canvasBufferUpdatedCB(_impl->getDataRef()); - } - } -} - -void CanvasRenderingContext2D::rect(float x, float y, float width, float height) { - // SE_LOGD("CanvasRenderingContext2D::rect: %p, %f, %f, %f, %f\n", this, x, y, width, height); - recreateBufferIfNeeded(); - _impl->rect(x, y, width, height); -} - -void CanvasRenderingContext2D::clearRect(float x, float y, float width, float height) { - // SE_LOGD("CanvasRenderingContext2D::clearRect: %p, %f, %f, %f, %f\n", this, x, y, width, height); - recreateBufferIfNeeded(); - _impl->clearRect(x, y, width, height); -} - -void CanvasRenderingContext2D::fillRect(float x, float y, float width, float height) { - recreateBufferIfNeeded(); - _impl->fillRect(x, y, width, height); - - if (_canvasBufferUpdatedCB != nullptr) { - _canvasBufferUpdatedCB(_impl->getDataRef()); - } -} - -void CanvasRenderingContext2D::fillText(const std::string &text, float x, float y, float maxWidth) { - // SE_LOGD("CanvasRenderingContext2D::fillText: %s, %f, %f, %f\n", text.c_str(), x, y, maxWidth); - if (text.empty()) { - return; - } - recreateBufferIfNeeded(); - - _impl->fillText(text, x, y, maxWidth); - if (_canvasBufferUpdatedCB != nullptr) { - _canvasBufferUpdatedCB(_impl->getDataRef()); - } -} - -void CanvasRenderingContext2D::strokeText(const std::string &text, float x, float y, float maxWidth) { - // SE_LOGD("CanvasRenderingContext2D::strokeText: %s, %f, %f, %f\n", text.c_str(), x, y, maxWidth); - if (text.empty()) { - return; - } - recreateBufferIfNeeded(); - - _impl->strokeText(text, x, y, maxWidth); - - if (_canvasBufferUpdatedCB != nullptr) { - _canvasBufferUpdatedCB(_impl->getDataRef()); - } -} - -cc::Size CanvasRenderingContext2D::measureText(const std::string &text) { - // SE_LOGD("CanvasRenderingContext2D::measureText: %s\n", text.c_str()); - return cc::Size(_impl->measureText(text), 0); -} - -CanvasGradient *CanvasRenderingContext2D::createLinearGradient(float /*x0*/, float /*y0*/, float /*x1*/, float /*y1*/) { //NOLINT(readability-convert-member-functions-to-static) - - return nullptr; -} - -void CanvasRenderingContext2D::save() { - _impl->saveContext(); -} - -void CanvasRenderingContext2D::beginPath() { - _impl->beginPath(); -} - -void CanvasRenderingContext2D::closePath() { - _impl->closePath(); -} - -void CanvasRenderingContext2D::moveTo(float x, float y) { - _impl->moveTo(x, y); -} - -void CanvasRenderingContext2D::lineTo(float x, float y) { - _impl->lineTo(x, y); -} - -void CanvasRenderingContext2D::stroke() { - _impl->stroke(); - - if (_canvasBufferUpdatedCB != nullptr) { - _canvasBufferUpdatedCB(_impl->getDataRef()); - } -} - -void CanvasRenderingContext2D::fill() { - _impl->fill(); - - if (_canvasBufferUpdatedCB != nullptr) { - _canvasBufferUpdatedCB(_impl->getDataRef()); - } -} - -void CanvasRenderingContext2D::restore() { - _impl->restoreContext(); -} - -void CanvasRenderingContext2D::setCanvasBufferUpdatedCallback(const CanvasBufferUpdatedCallback &cb) { - _canvasBufferUpdatedCB = cb; - recreateBufferIfNeeded(); -} - -void CanvasRenderingContext2D::setWidth(float width) { //NOLINT(readability-identifier-naming) - // SE_LOGD("CanvasRenderingContext2D::set__width: %f\n", width); - if (math::IsEqualF(width, _width)) return; - _width = width; - _isBufferSizeDirty = true; - recreateBufferIfNeeded(); -} - -void CanvasRenderingContext2D::setHeight(float height) { //NOLINT(readability-identifier-naming) - // SE_LOGD("CanvasRenderingContext2D::set__height: %f\n", height); - if (math::IsEqualF(height, _height)) return; - _height = height; - _isBufferSizeDirty = true; - recreateBufferIfNeeded(); -} - -void CanvasRenderingContext2D::setLineWidth(float lineWidth) { //NOLINT(readability-identifier-naming) - _lineWidth = lineWidth; - _impl->setLineWidth(lineWidth); -} - -void CanvasRenderingContext2D::setLineJoin(const std::string &lineJoin) { //NOLINT(readability-identifier-naming) - if (lineJoin.empty()) return; - _impl->setLineJoin(lineJoin); -} - -void CanvasRenderingContext2D::setLineCap(const std::string &lineCap) { //NOLINT(readability-identifier-naming) - if (lineCap.empty()) return; - _impl->setLineCap(lineCap); -} - -/* - * support format e.g.: "oblique bold small-caps 18px Arial" - * "italic bold small-caps 25px Arial" - * "italic 25px Arial" - * */ -void CanvasRenderingContext2D::setFont(const std::string &font) { //NOLINT(readability-identifier-naming) - if (_font != font) { - _font = font; - std::string fontName = "sans-serif"; - std::string fontSizeStr = "30"; - std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))"); - std::match_results results; - if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) { - fontSizeStr = results[2].str(); - // support get font name from `60px American` or `60px "American abc-abc_abc"` - // support get font name contain space,example `times new roman` - // if regex rule that does not conform to the rules,such as Chinese,it defaults to sans-serif - std::match_results fontResults; - std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))"); - std::string tmp(results[4].str()); - if (std::regex_match(tmp, fontResults, fontRe)) { - fontName = results[4].str(); - } - } - - double fontSize = atof(fontSizeStr.c_str()); - bool isBold = font.find("bold", 0) != std::string::npos; - bool isItalic = font.find("italic", 0) != std::string::npos; - bool isSmallCaps = font.find("small-caps", 0) != std::string::npos; - bool isOblique = font.find("oblique", 0) != std::string::npos; - //font-style: italic, oblique, normal - //font-weight: normal, bold - //font-variant: normal, small-caps - _impl->updateFont(fontName, static_cast(fontSize), isBold, isItalic, isOblique, isSmallCaps); - } -} - -void CanvasRenderingContext2D::setTextAlign(const std::string &textAlign) { //NOLINT(readability-identifier-naming) - // SE_LOGD("CanvasRenderingContext2D::set_textAlign: %s\n", textAlign.c_str()); - if (textAlign == "left") { - _impl->setTextAlign(CanvasTextAlign::LEFT); - } else if (textAlign == "center" || textAlign == "middle") { - _impl->setTextAlign(CanvasTextAlign::CENTER); - } else if (textAlign == "right") { - _impl->setTextAlign(CanvasTextAlign::RIGHT); - } else { - assert(false); - } -} - -void CanvasRenderingContext2D::setTextBaseline(const std::string &textBaseline) { //NOLINT(readability-identifier-naming) - // SE_LOGD("CanvasRenderingContext2D::set_textBaseline: %s\n", textBaseline.c_str()); - if (textBaseline == "top") { - _impl->setTextBaseline(CanvasTextBaseline::TOP); - } else if (textBaseline == "middle") { - _impl->setTextBaseline(CanvasTextBaseline::MIDDLE); - } else if (textBaseline == "bottom") //REFINE:, how to deal with alphabetic, currently we handle it as bottom mode. - { - _impl->setTextBaseline(CanvasTextBaseline::BOTTOM); - } else if (textBaseline == "alphabetic") { - _impl->setTextBaseline(CanvasTextBaseline::ALPHABETIC); - } else { - assert(false); - } -} - -void CanvasRenderingContext2D::setFillStyle(const std::string &fillStyle) { //NOLINT(readability-identifier-naming) - CSSColorParser::Color color = CSSColorParser::parse(fillStyle); - _impl->setFillStyle(static_cast(color.r) / 255.0F, static_cast(color.g) / 255.0F, static_cast(color.b) / 255.0F, color.a); - // SE_LOGD("CanvasRenderingContext2D::set_fillStyle: %s, (%d, %d, %d, %f)\n", fillStyle.c_str(), color.r, color.g, color.b, color.a); -} - -void CanvasRenderingContext2D::setStrokeStyle(const std::string &strokeStyle) { //NOLINT(readability-identifier-naming) - CSSColorParser::Color color = CSSColorParser::parse(strokeStyle); - _impl->setStrokeStyle(static_cast(color.r) / 255.0F, static_cast(color.g) / 255.0F, static_cast(color.b) / 255.0F, color.a); -} - -void CanvasRenderingContext2D::setGlobalCompositeOperation(const std::string &globalCompositeOperation) { //NOLINT(readability-identifier-naming) - // SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) { //NOLINT(readability-identifier-naming) - _impl->fillImageData(imageData, imageWidth, imageHeight, offsetX, offsetY); - if (_canvasBufferUpdatedCB != nullptr) { - _canvasBufferUpdatedCB(_impl->getDataRef()); - } -} -// transform -//REFINE: - -void CanvasRenderingContext2D::translate(float x, float y) { - // SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::scale(float x, float y) { - // SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::rotate(float angle) { - // SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::transform(float a, float b, float c, float d, float e, float f) { - // SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::setTransform(float a, float b, float c, float d, float e, float f) { - // SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -} // namespace cc diff --git a/native/cocos/platform/java/jni/JniCocosKeyCodeHandler.cpp b/native/cocos/platform/java/jni/JniCocosKeyCodeHandler.cpp index fc9474badd..38ddaa368c 100644 --- a/native/cocos/platform/java/jni/JniCocosKeyCodeHandler.cpp +++ b/native/cocos/platform/java/jni/JniCocosKeyCodeHandler.cpp @@ -22,7 +22,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "platform/Application.h" #include "platform/java/jni/JniHelper.h" #if CC_PLATFORM == CC_PLATFORM_ANDROID #include @@ -30,7 +29,10 @@ #elif CC_PLATFORM == CC_PLATFORM_OHOS #include #endif + #include +#include "cocos/bindings/event/EventDispatcher.h" +#include "platform/java/jni/glue/JniNativeGlue.h" namespace { struct cc::KeyboardEvent keyboardEvent; @@ -57,15 +59,17 @@ void dispatchKeyCodeEvent(int keyCode, cc::KeyboardEvent &event) { keyCode = 0; } event.key = keyCode; - cc::EventDispatcher::dispatchKeyboardEvent(event); + JNI_NATIVE_GLUE()->dispatchEvent(event); } } // namespace + extern "C" { //NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosKeyCodeHandler_handleKeyDown(JNIEnv *env, jobject obj, jint keyCode) { keyboardEvent.action = cc::KeyboardEvent::Action::PRESS; dispatchKeyCodeEvent(keyCode, keyboardEvent); } + //NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosKeyCodeHandler_handleKeyUp(JNIEnv *env, jobject obj, jint keyCode) { keyboardEvent.action = cc::KeyboardEvent::Action::RELEASE; diff --git a/native/cocos/platform/java/jni/JniCocosOrientationHelper.cpp b/native/cocos/platform/java/jni/JniCocosOrientationHelper.cpp index 5436ab264e..02a06002e2 100644 --- a/native/cocos/platform/java/jni/JniCocosOrientationHelper.cpp +++ b/native/cocos/platform/java/jni/JniCocosOrientationHelper.cpp @@ -23,14 +23,18 @@ THE SOFTWARE. ****************************************************************************/ #include -#include "platform/Application.h" -#include "platform/Device.h" +#include "cocos/bindings/event/EventDispatcher.h" #include "platform/java/jni/JniHelper.h" +#include "platform/java/jni/glue/JniNativeGlue.h" +#include "platform/interfaces/modules/Device.h" extern "C" { + //NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosOrientationHelper_nativeOnOrientationChanged(JNIEnv *env, jobject thiz, jint rotation) { - auto orientation = cc::Device::getDeviceOrientation(); - cc::EventDispatcher::dispatchOrientationChangeEvent((int)orientation); + cc::DeviceEvent ev; + ev.type = cc::DeviceEvent::Type::DEVICE_ORIENTATION; + ev.args[0].intVal = static_cast(cc::Device::getDeviceOrientation()); + JNI_NATIVE_GLUE()->dispatchEvent(ev); } } diff --git a/native/cocos/platform/java/jni/JniCocosTouchHandler.cpp b/native/cocos/platform/java/jni/JniCocosTouchHandler.cpp index 766a7de98d..038b8744f8 100644 --- a/native/cocos/platform/java/jni/JniCocosTouchHandler.cpp +++ b/native/cocos/platform/java/jni/JniCocosTouchHandler.cpp @@ -23,8 +23,9 @@ THE SOFTWARE. ****************************************************************************/ #include -#include "platform/Application.h" +#include "cocos/bindings/event/EventDispatcher.h" #include "platform/java/jni/JniHelper.h" +#include "platform/java/jni/glue/JniNativeGlue.h" namespace { struct cc::TouchEvent touchEvent; @@ -35,7 +36,7 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionDown(JNI jfloat x, jfloat y) { touchEvent.type = cc::TouchEvent::Type::BEGAN; touchEvent.touches.emplace_back(x, y, id); - cc::EventDispatcher::dispatchTouchEvent(touchEvent); + JNI_NATIVE_GLUE()->dispatchEvent(touchEvent); touchEvent.touches.clear(); } //NOLINTNEXTLINE @@ -43,7 +44,7 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionUp(JNIEn jfloat y) { touchEvent.type = cc::TouchEvent::Type::ENDED; touchEvent.touches.emplace_back(x, y, id); - cc::EventDispatcher::dispatchTouchEvent(touchEvent); + JNI_NATIVE_GLUE()->dispatchEvent(touchEvent); touchEvent.touches.clear(); } //NOLINTNEXTLINE @@ -64,7 +65,7 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionMove(JNI touchEvent.touches.emplace_back(x[i], y[i], id[i]); } - cc::EventDispatcher::dispatchTouchEvent(touchEvent); + JNI_NATIVE_GLUE()->dispatchEvent(touchEvent); touchEvent.touches.clear(); } @@ -85,7 +86,7 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionCancel(J for (int i = 0; i < size; i++) { touchEvent.touches.emplace_back(x[i], y[i], id[i]); } - cc::EventDispatcher::dispatchTouchEvent(touchEvent); + JNI_NATIVE_GLUE()->dispatchEvent(touchEvent); touchEvent.touches.clear(); } } diff --git a/native/cocos/platform/java/jni/JniHelper.cpp b/native/cocos/platform/java/jni/JniHelper.cpp index 511fb08457..2721523c8f 100644 --- a/native/cocos/platform/java/jni/JniHelper.cpp +++ b/native/cocos/platform/java/jni/JniHelper.cpp @@ -89,8 +89,8 @@ jclass _getClassID(const char *className) { // NOLINT jstring jstrClassName = env->NewStringUTF(className); auto *klassObj = static_cast(env->CallObjectMethod(cc::JniHelper::classloader, - cc::JniHelper::loadclassMethodMethodId, - jstrClassName)); + cc::JniHelper::loadclassMethodMethodId, + jstrClassName)); if (nullptr == klassObj || env->ExceptionCheck()) { LOGE("Classloader failed to find class of %s", className); diff --git a/native/cocos/platform/java/jni/JniHelper.h b/native/cocos/platform/java/jni/JniHelper.h index 565f3ca305..ed4c1a5a6a 100644 --- a/native/cocos/platform/java/jni/JniHelper.h +++ b/native/cocos/platform/java/jni/JniHelper.h @@ -57,6 +57,7 @@ } \ } while (false) + struct android_app; namespace cc { @@ -268,7 +269,7 @@ public: std::string signature = "(" + std::string(getJNISignature(xs...)) + ")[F"; if (cc::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; - auto *array = static_cast(t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...)); + auto * array = static_cast(t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...)); CLEAR_EXCEPTON(t.env); jsize len = t.env->GetArrayLength(array); if (len <= 32) { @@ -298,7 +299,7 @@ public: std::string signature = "(" + std::string(getJNISignature(xs...)) + ")[F"; if (cc::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; - auto *array = static_cast(t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...)); + auto * array = static_cast(t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...)); CLEAR_EXCEPTON(t.env); jsize len = t.env->GetArrayLength(array); if (len == 3) { @@ -350,7 +351,7 @@ public: std::string signature = "(" + std::string(getJNISignature(xs...)) + ")Ljava/lang/String;"; if (cc::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; - auto *jret = static_cast(t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...)); + auto * jret = static_cast(t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...)); CLEAR_EXCEPTON(t.env); ret = cc::JniHelper::jstring2string(jret); ccDeleteLocalRef(t.env, jret); diff --git a/native/cocos/platform/java/jni/JniImp.cpp b/native/cocos/platform/java/jni/JniImp.cpp index 905a0c54ce..3faba86c50 100644 --- a/native/cocos/platform/java/jni/JniImp.cpp +++ b/native/cocos/platform/java/jni/JniImp.cpp @@ -24,21 +24,18 @@ ****************************************************************************/ #include "JniImp.h" -#if ANDROID - #include -#else - #include -#endif + #include #include "JniHelper.h" -#define JNI_IMP_LOG_TAG "JniImp" -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, JNI_IMP_LOG_TAG, __VA_ARGS__) - #ifndef JCLS_HELPER #define JCLS_HELPER "com/cocos/lib/CocosHelper" #endif +#ifndef JCLS_SENSOR + #define JCLS_SENSOR "com/cocos/lib/CocosSensorHandler" +#endif + using namespace cc; //NOLINT /*********************************************************** @@ -55,7 +52,7 @@ int getObbAssetFileDescriptorJNI(const std::string &path, int64_t *startOffset, if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_HELPER, "getObbAssetFileDescriptor", "(Ljava/lang/String;)[J")) { jstring stringArg = methodInfo.env->NewStringUTF(path.c_str()); - auto newArray = static_cast(methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID, stringArg)); + auto * newArray = static_cast(methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID, stringArg)); jsize theArrayLen = methodInfo.env->GetArrayLength(newArray); if (3 == theArrayLen) { @@ -93,3 +90,48 @@ bool openURLJNI(const std::string &url) { void copyTextToClipboardJNI(const std::string &text) { JniHelper::callStaticVoidMethod(JCLS_HELPER, "copyTextToClipboard", text); } + +std::string getDeviceModelJNI() { + return JniHelper::callStaticStringMethod(JCLS_HELPER, "getDeviceModel"); +} + +int getDPIJNI() { + return JniHelper::callStaticIntMethod(JCLS_HELPER, "getDPI"); +} + +void setVibrateJNI(float duration) { + JniHelper::callStaticVoidMethod(JCLS_HELPER, "vibrate", duration); +} + +int getNetworkTypeJNI() { + return JniHelper::callStaticIntMethod(JCLS_HELPER, "getNetworkType"); +} + +float *getSafeAreaEdgeJNI() { + return JniHelper::callStaticFloatArrayMethod(JCLS_HELPER, "getSafeArea"); +} + +int getDeviceRotationJNI() { + return JniHelper::callStaticIntMethod(JCLS_HELPER, "getDeviceRotation"); +} + +float getBatteryLevelJNI() { + return JniHelper::callStaticFloatMethod(JCLS_HELPER, "getBatteryLevel"); +} + +void flushTasksOnGameThreadJNI() { + cc::JniHelper::callStaticVoidMethod(JCLS_HELPER, + "flushTasksOnGameThread"); +} + +void setAccelerometerEnabledJNI(bool isEnabled) { + JniHelper::callStaticVoidMethod(JCLS_SENSOR, "setAccelerometerEnabled", isEnabled); +} + +void setAccelerometerIntervalJNI(float interval) { + JniHelper::callStaticVoidMethod(JCLS_SENSOR, "setAccelerometerInterval", interval); +} + +float *getDeviceMotionValueJNI() { + return JniHelper::callStaticFloatArrayMethod(JCLS_SENSOR, "getDeviceMotionValue"); +} \ No newline at end of file diff --git a/native/cocos/platform/java/jni/JniImp.h b/native/cocos/platform/java/jni/JniImp.h index 47daf6ec87..31881f7f56 100644 --- a/native/cocos/platform/java/jni/JniImp.h +++ b/native/cocos/platform/java/jni/JniImp.h @@ -33,4 +33,15 @@ extern std::string getCurrentLanguageJNI(); extern std::string getCurrentLanguageCodeJNI(); extern std::string getSystemVersionJNI(); extern bool openURLJNI(const std::string &url); -extern void copyTextToClipboardJNI(const std::string &text); \ No newline at end of file +extern void copyTextToClipboardJNI(const std::string &text); +extern std::string getDeviceModelJNI(); +extern int getDPIJNI(); +extern void setVibrateJNI(float duration); +extern int getNetworkTypeJNI(); +extern float * getSafeAreaEdgeJNI(); +extern int getDeviceRotationJNI(); +extern float getBatteryLevelJNI(); +extern void flushTasksOnGameThreadJNI(); +extern void setAccelerometerEnabledJNI(bool isEnabled); +extern void setAccelerometerIntervalJNI(float interval); +extern float * getDeviceMotionValueJNI(); \ No newline at end of file diff --git a/native/cocos/platform/java/jni/glue/JniNativeGlue.cpp b/native/cocos/platform/java/jni/glue/JniNativeGlue.cpp new file mode 100644 index 0000000000..a235b63426 --- /dev/null +++ b/native/cocos/platform/java/jni/glue/JniNativeGlue.cpp @@ -0,0 +1,287 @@ +/**************************************************************************** + Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/java/jni/glue/JniNativeGlue.h" +#include +#include +#include "cocos/bindings/event/CustomEventTypes.h" +#include "cocos/bindings/event/EventDispatcher.h" +#include "platform/BasePlatform.h" +#include "platform/IEventDispatch.h" +#include "platform/java/jni/JniImp.h" +#include "platform/java/jni/glue/MessagePipe.h" +#include "platform/java/jni/log.h" + +namespace cc { +JniNativeGlue::~JniNativeGlue() = default; + +JniNativeGlue* JniNativeGlue::getInstance() { + static JniNativeGlue jniNativeGlue; + return &jniNativeGlue; +} + +void JniNativeGlue::start(int argc, const char** argv) { + _messagePipe = std::make_unique(); + + BasePlatform* platform = cc::BasePlatform::getPlatform(); + if (platform->init()) { + LOGV("Platform initialization failed"); + } + platform->run(argc, argv); +} + +void JniNativeGlue::setWindowHandler(NativeWindowType* window) { + if (_pendingWindow) { + writeCommandSync(JniCommand::JNI_CMD_TERM_WINDOW); + } + _pendingWindow = window; + if (window) { + writeCommandSync(JniCommand::JNI_CMD_INIT_WINDOW); + } +} + +void JniNativeGlue::setResourceManager(ResourceManagerType* resourceManager) { + _resourceManager = resourceManager; +} + +ResourceManagerType* JniNativeGlue::getResourceManager() { + return _resourceManager; +} + +NativeWindowType* JniNativeGlue::getWindowHandler() { + return _window; +} + +void JniNativeGlue::setSdkVersion(int sdkVersion) { + _sdkVersion = sdkVersion; +} + +int JniNativeGlue::getSdkVersion() const { + return _sdkVersion; +} + +void JniNativeGlue::setObbPath(const std::string& path) { + _obbPath = path; +} + +std::string JniNativeGlue::getObbPath() const { + return _obbPath; +} + +void JniNativeGlue::setRunning(bool isRunning) { + _threadPromise.set_value(); + _running = isRunning; +} + +void JniNativeGlue::waitRunning() { + _threadPromise.get_future().get(); +} + +bool JniNativeGlue::isRunning() const { + return _running; +} + +void JniNativeGlue::flushTasksOnGameThread() const { + if (_animating) { + // Handle java events send by UI thread. Input events are handled here too. + flushTasksOnGameThreadJNI(); + } +} + +void JniNativeGlue::writeCommandAsync(JniCommand cmd) { + CommandMsg msg{.cmd = cmd, .callback = nullptr}; + _messagePipe->writeCommand(&msg, sizeof(msg)); +} + +void JniNativeGlue::writeCommandSync(JniCommand cmd) { + std::promise fu; + CommandMsg msg{.cmd = cmd, .callback = [&fu]() { + fu.set_value(); + }}; + _messagePipe->writeCommand(&msg, sizeof(msg)); + fu.get_future().get(); +} + +int JniNativeGlue::readCommand(CommandMsg* msg) { + return _messagePipe->readCommand(msg, sizeof(CommandMsg)); +} + +void JniNativeGlue::setEventDispatch(IEventDispatch* eventDispatcher) { + _eventDispatcher = eventDispatcher; +} + +void JniNativeGlue::dispatchEvent(const OSEvent& ev) { + if (_eventDispatcher) { + _eventDispatcher->dispatchEvent(ev); + } +} + +void JniNativeGlue::dispatchTouchEvent(const OSEvent& ev) { + if (_eventDispatcher) { + _eventDispatcher->dispatchTouchEvent(ev); + } +} + +bool JniNativeGlue::isPause() const { + if (!_animating) { + return true; + } + if (_appState == JniCommand::JNI_CMD_PAUSE) { + return true; + } + return false; +} + +void JniNativeGlue::onPause() { + writeCommandAsync(JniCommand::JNI_CMD_PAUSE); +} + +void JniNativeGlue::onResume() { + writeCommandAsync(JniCommand::JNI_CMD_RESUME); +} + +void JniNativeGlue::onLowMemory() { + writeCommandAsync(JniCommand::JNI_CMD_LOW_MEMORY); +} + +void JniNativeGlue::execCommand() { + static CommandMsg msg; + if (readCommand(&msg) > 0) { + preExecCmd(msg.cmd); + engineHandleCmd(msg.cmd); + postExecCmd(msg.cmd); + if (msg.callback) { + msg.callback(); + } + } +} + +void JniNativeGlue::preExecCmd(JniCommand cmd) { + switch (cmd) { + case JniCommand::JNI_CMD_INIT_WINDOW: { + LOGV("JNI_CMD_INIT_WINDOW"); + _animating = true; + _window = _pendingWindow; + } break; + case JniCommand::JNI_CMD_TERM_WINDOW: + LOGV("JNI_CMD_TERM_WINDOW"); + _animating = false; + break; + case JniCommand::JNI_CMD_RESUME: + LOGV("JNI_CMD_RESUME"); + _appState = cmd; + break; + case JniCommand::JNI_CMD_PAUSE: + LOGV("JNI_CMD_PAUSE"); + _appState = cmd; + break; + default: + break; + } +} + +void JniNativeGlue::engineHandleCmd(JniCommand cmd) { + static bool isWindowInitialized = false; + // Handle CMD here if needed. + switch (cmd) { + case JniCommand::JNI_CMD_INIT_WINDOW: { + if (!isWindowInitialized) { + isWindowInitialized = true; + return; + } + cc::CustomEvent event; + event.name = EVENT_RECREATE_WINDOW; + event.args->ptrVal = reinterpret_cast(getWindowHandler()); + dispatchEvent(event); + } break; + case JniCommand::JNI_CMD_TERM_WINDOW: { + cc::CustomEvent event; + event.name = EVENT_DESTROY_WINDOW; + event.args->ptrVal = reinterpret_cast(getWindowHandler()); + dispatchEvent(event); + } break; + case JniCommand::JNI_CMD_RESUME: { + WindowEvent ev; + ev.type = WindowEvent::Type::SHOW; + dispatchEvent(ev); + } break; + case JniCommand::JNI_CMD_PAUSE: { + WindowEvent ev; + ev.type = WindowEvent::Type::HIDDEN; + dispatchEvent(ev); + } break; + case JniCommand::JNI_CMD_DESTROY: { + LOGV("APP_CMD_DESTROY"); + WindowEvent ev; + ev.type = WindowEvent::Type::CLOSE; + dispatchEvent(ev); + setRunning(false); + } break; + case JniCommand::JNI_CMD_LOW_MEMORY: { + DeviceEvent ev; + ev.type = DeviceEvent::Type::DEVICE_MEMORY; + dispatchEvent(ev); + break; + } + default: + break; + } +} + +void JniNativeGlue::postExecCmd(JniCommand cmd) { + switch (cmd) { + case JniCommand::JNI_CMD_TERM_WINDOW: { + _window = nullptr; + } break; + default: + break; + } +} + +int32_t JniNativeGlue::getWidth() const { + int32_t width = 0; + if (_window) { +#if (CC_PLATFORM == CC_PLATFORM_ANDROID) + width = ANativeWindow_getWidth(_window); +#elif (CC_PLATFORM == CC_PLATFORM_OHOS) + width = NativeLayerHandle(_window, NativeLayerOps::GET_WIDTH); +#endif + } + return width; +} + +int32_t JniNativeGlue::getHeight() const { + int32_t height = 0; + if (_window) { +#if (CC_PLATFORM == CC_PLATFORM_ANDROID) + height = ANativeWindow_getHeight(_window); +#elif (CC_PLATFORM == CC_PLATFORM_OHOS) + height = NativeLayerHandle(_window, NativeLayerOps::GET_HEIGHT); +#endif + } + return height; +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/java/jni/glue/JniNativeGlue.h b/native/cocos/platform/java/jni/glue/JniNativeGlue.h new file mode 100644 index 0000000000..6e4b326f29 --- /dev/null +++ b/native/cocos/platform/java/jni/glue/JniNativeGlue.h @@ -0,0 +1,129 @@ +/**************************************************************************** +Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ +#pragma once + +#include +#include +#include "platform/java/jni/glue/MessagePipe.h" + +#if (CC_PLATFORM == CC_PLATFORM_ANDROID) + #include + #include + +using ResourceManagerType = AAssetManager; +using NativeWindowType = ANativeWindow; + +#elif (CC_PLATFORM == CC_PLATFORM_OHOS) + #include + #include + +using ResourceManagerType = ResourceManager; +using NativeWindowType = NativeLayer; +#endif + +namespace cc { + +class IEventDispatch; +class OSEvent; + +class JniNativeGlue { +public: + enum class JniCommand { + JNI_CMD_TERM_WINDOW = 0, + JNI_CMD_INIT_WINDOW, + JNI_CMD_RESUME, + JNI_CMD_PAUSE, + JNI_CMD_DESTROY, + JNI_CMD_LOW_MEMORY, + JNI_CMD_UNKNOW, + }; + virtual ~JniNativeGlue(); + static JniNativeGlue* getInstance(); + + virtual void start(int argc, const char** argv); + + void setWindowHandler(NativeWindowType* window); + NativeWindowType* getWindowHandler(); + + void setResourceManager(ResourceManagerType* resourceManager); + ResourceManagerType* getResourceManager(); + + void setSdkVersion(int sdkVersion); + int getSdkVersion() const; + + void setObbPath(const std::string& path); + std::string getObbPath() const; + + bool isRunning() const; + void setRunning(bool isRunning); + void waitRunning(); + + void flushTasksOnGameThread() const; + + struct CommandMsg { + JniCommand cmd; + std::function callback; + }; + void writeCommandAsync(JniCommand cmd); + void writeCommandSync(JniCommand cmd); + int readCommand(CommandMsg* msg); + + void setEventDispatch(IEventDispatch* eventDispatcher); + void dispatchEvent(const OSEvent& ev); + void dispatchTouchEvent(const OSEvent& ev); + + void onPause(); + void onResume(); + void onLowMemory(); + + bool isPause() const; + + void execCommand(); + + int32_t getWidth() const; + int32_t getHeight() const; + +private: + void preExecCmd(JniCommand cmd); + void engineHandleCmd(JniCommand cmd); + void postExecCmd(JniCommand cmd); + + bool _running{false}; + int _sdkVersion{0}; + bool _animating{false}; + + std::promise _threadPromise; + std::string _obbPath; + ResourceManagerType* _resourceManager{nullptr}; + NativeWindowType* _window{nullptr}; + NativeWindowType* _pendingWindow{nullptr}; + JniCommand _appState{JniCommand::JNI_CMD_UNKNOW}; + IEventDispatch* _eventDispatcher{nullptr}; + std::unique_ptr _messagePipe{nullptr}; +}; + +} // namespace cc + +#define JNI_NATIVE_GLUE() cc::JniNativeGlue::getInstance() \ No newline at end of file diff --git a/native/cocos/platform/java/jni/glue/MessagePipe.cpp b/native/cocos/platform/java/jni/glue/MessagePipe.cpp new file mode 100644 index 0000000000..38d1f75d62 --- /dev/null +++ b/native/cocos/platform/java/jni/glue/MessagePipe.cpp @@ -0,0 +1,67 @@ +/**************************************************************************** + Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/java/jni/glue/MessagePipe.h" +#include +#include +#include "platform/java/jni/log.h" +//#include +//#include "platform/android/jni/JniCocosActivity.h" + +namespace cc { +MessagePipe::MessagePipe() { + int messagePipe[2] = {0}; + if (pipe(messagePipe)) { + LOGV("Can not create pipe: %s", strerror(errno)); + } + + _pipeRead = messagePipe[0]; + _pipeWrite = messagePipe[1]; + + if (fcntl(_pipeRead, F_SETFL, O_NONBLOCK) < 0) { + LOGV("Can not make pipe read to non blocking mode."); + } +} + +MessagePipe::~MessagePipe() { + close(_pipeRead); + close(_pipeWrite); +} + +void MessagePipe::writeCommand(int8_t cmd) const { + write(_pipeWrite, &cmd, sizeof(cmd)); +} + +int MessagePipe::readCommand(int8_t& cmd) const { + return read(_pipeRead, &cmd, sizeof(cmd)); +} + +void MessagePipe::writeCommand(void* msg, int32_t size) const { + write(_pipeWrite, msg, size); +} + +int MessagePipe::readCommand(void* msg, int32_t size) const { + return read(_pipeRead, msg, size); +} +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/java/jni/glue/MessagePipe.h b/native/cocos/platform/java/jni/glue/MessagePipe.h new file mode 100644 index 0000000000..7674c3fe38 --- /dev/null +++ b/native/cocos/platform/java/jni/glue/MessagePipe.h @@ -0,0 +1,47 @@ +/**************************************************************************** + Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include + +namespace cc { + +class MessagePipe { +public: + MessagePipe(); + ~MessagePipe(); + + void writeCommand(int8_t cmd) const; + int readCommand(int8_t& cmd) const; + void writeCommand(void* msg, int32_t size) const; + int readCommand(void* msg, int32_t size) const; + +private: + int _pipeRead = 0; + int _pipeWrite = 0; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/java/jni/log.h b/native/cocos/platform/java/jni/log.h new file mode 100644 index 0000000000..1ba285ff90 --- /dev/null +++ b/native/cocos/platform/java/jni/log.h @@ -0,0 +1,38 @@ +/**************************************************************************** + Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#define JNI_IMP_LOG_TAG "JniImp" + +#if (CC_PLATFORM == CC_PLATFORM_ANDROID) + #include + #define LOGV(...) __android_log_print(ANDROID_LOG_INFO, "CocosActivity JNI", __VA_ARGS__) + #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, JNI_IMP_LOG_TAG, __VA_ARGS__) +#elif (CC_PLATFORM == CC_PLATFORM_OHOS) + #include + #define LOGV(...) HILOG_INFO(LOG_APP, __VA_ARGS__) + #define LOGD(...) +#endif \ No newline at end of file diff --git a/native/cocos/platform/java/modules/Accelerometer.cpp b/native/cocos/platform/java/modules/Accelerometer.cpp new file mode 100644 index 0000000000..c9ff3955c1 --- /dev/null +++ b/native/cocos/platform/java/modules/Accelerometer.cpp @@ -0,0 +1,61 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/java/modules/Accelerometer.h" +#include "platform/java/jni/JniImp.h" + +namespace cc { + +void Accelerometer::setAccelerometerEnabled(bool isEnabled) { + setAccelerometerEnabledJNI(isEnabled); +} + +void Accelerometer::setAccelerometerInterval(float interval) { + setAccelerometerIntervalJNI(interval); +} + +const Accelerometer::MotionValue& Accelerometer::getDeviceMotionValue() { + static MotionValue motionValue; + float* v = getDeviceMotionValueJNI(); + + if (v) { + motionValue.accelerationIncludingGravityX = v[0]; + motionValue.accelerationIncludingGravityY = v[1]; + motionValue.accelerationIncludingGravityZ = v[2]; + + motionValue.accelerationX = v[3]; + motionValue.accelerationY = v[4]; + motionValue.accelerationZ = v[5]; + + motionValue.rotationRateAlpha = v[6]; + motionValue.rotationRateBeta = v[7]; + motionValue.rotationRateGamma = v[8]; + } else { + memset(&motionValue, 0, sizeof(motionValue)); + } + return motionValue; +} + +} // namespace cc diff --git a/native/cocos/platform/java/modules/Accelerometer.h b/native/cocos/platform/java/modules/Accelerometer.h new file mode 100644 index 0000000000..50a3c56992 --- /dev/null +++ b/native/cocos/platform/java/modules/Accelerometer.h @@ -0,0 +1,50 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IAccelerometer.h" + +namespace cc { + +class Accelerometer : public IAccelerometer { +public: + /** + * To enable or disable accelerometer. + */ + void setAccelerometerEnabled(bool isEnabled) override; + + /** + * Sets the interval of accelerometer. + */ + void setAccelerometerInterval(float interval) override; + + /** + * Gets the motion value of current device. + */ + const MotionValue &getDeviceMotionValue() override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/java/modules/Battery.cpp b/native/cocos/platform/java/modules/Battery.cpp new file mode 100644 index 0000000000..4c0653256d --- /dev/null +++ b/native/cocos/platform/java/modules/Battery.cpp @@ -0,0 +1,34 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/java/modules/Battery.h" +#include "platform/java/jni/JniImp.h" + +namespace cc { + +float Battery::getBatteryLevel() const { + return getBatteryLevelJNI(); +} + +} // namespace cc diff --git a/native/cocos/platform/java/modules/Battery.h b/native/cocos/platform/java/modules/Battery.h new file mode 100644 index 0000000000..aa2fb2f5b0 --- /dev/null +++ b/native/cocos/platform/java/modules/Battery.h @@ -0,0 +1,37 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IBattery.h" + +namespace cc { + +class Battery : public IBattery { +public: + float getBatteryLevel() const override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/java/modules/CanvasRenderingContext2DDelegate.cpp b/native/cocos/platform/java/modules/CanvasRenderingContext2DDelegate.cpp new file mode 100644 index 0000000000..95553ad691 --- /dev/null +++ b/native/cocos/platform/java/modules/CanvasRenderingContext2DDelegate.cpp @@ -0,0 +1,248 @@ +/**************************************************************************** + Copyright (c) 2018-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/java/modules/CanvasRenderingContext2DDelegate.h" + +namespace { + +} // namespace + +#define CLAMP(V, HI) std::min((V), (HI)) + +namespace cc { +CanvasRenderingContext2DDelegate::CanvasRenderingContext2DDelegate() { + jobject obj = JniHelper::newObject(JCLS_CANVASIMPL); + _obj = JniHelper::getEnv()->NewGlobalRef(obj); + ccDeleteLocalRef(JniHelper::getEnv(), obj); +} + +CanvasRenderingContext2DDelegate::~CanvasRenderingContext2DDelegate() { + JniHelper::getEnv()->DeleteGlobalRef(_obj); +} + +void CanvasRenderingContext2DDelegate::recreateBuffer(float w, float h) { + _bufferWidth = w; + _bufferHeight = h; + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "recreateBuffer", w, h); + fillData(); +} + +void CanvasRenderingContext2DDelegate::beginPath() { + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "beginPath"); +} + +void CanvasRenderingContext2DDelegate::closePath() { + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "closePath"); +} + +void CanvasRenderingContext2DDelegate::moveTo(float x, float y) { + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "moveTo", x, y); +} + +void CanvasRenderingContext2DDelegate::lineTo(float x, float y) { + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "lineTo", x, y); +} + +void CanvasRenderingContext2DDelegate::stroke() { + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "stroke"); + fillData(); +} + +void CanvasRenderingContext2DDelegate::fill() { + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "fill"); + fillData(); +} + +void CanvasRenderingContext2DDelegate::rect(float x, float y, float w, float h) { + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "rect", x, y, w, h); + fillData(); +} + +void CanvasRenderingContext2DDelegate::saveContext() { + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "saveContext"); +} + +void CanvasRenderingContext2DDelegate::restoreContext() { + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "restoreContext"); +} + +void CanvasRenderingContext2DDelegate::clearRect(float x, float y, float w, float h) { + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + if (x >= _bufferWidth || y >= _bufferHeight) { + return; + } + if (x + w > _bufferWidth) { + w = _bufferWidth - x; + } + if (y + h > _bufferHeight) { + h = _bufferHeight - y; + } + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "clearRect", x, y, w, h); + fillData(); +} + +void CanvasRenderingContext2DDelegate::fillRect(float x, float y, float w, float h) { + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + if (x >= _bufferWidth || y >= _bufferHeight) { + return; + } + if (x + w > _bufferWidth) { + w = _bufferWidth - x; + } + if (y + h > _bufferHeight) { + h = _bufferHeight - y; + } + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "fillRect", x, y, w, h); + fillData(); +} + +void CanvasRenderingContext2DDelegate::fillText(const std::string &text, float x, float y, float maxWidth) { + if (text.empty() || _bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "fillText", text, x, y, maxWidth); + fillData(); +} + +void CanvasRenderingContext2DDelegate::strokeText(const std::string &text, float x, float y, float maxWidth) { + if (text.empty() || _bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "strokeText", text, x, y, maxWidth); + fillData(); +} + +CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::measureText(const std::string &text) { + if (text.empty()) { + return std::array{0.0F, 0.0F}; + } + float measureText1 = JniHelper::callObjectFloatMethod(_obj, JCLS_CANVASIMPL, "measureText", text); + Size size{measureText1, 0.0F}; + return size; +} + +void CanvasRenderingContext2DDelegate::updateFont(const std::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) { + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "updateFont", fontName, fontSize, bold, italic, oblique, smallCaps); +} + +void CanvasRenderingContext2DDelegate::setLineCap(const std::string &lineCap) { + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setLineCap", lineCap); +} + +void CanvasRenderingContext2DDelegate::setLineJoin(const std::string &lineJoin) { + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setLineJoin", lineJoin); +} + +void CanvasRenderingContext2DDelegate::setTextAlign(CanvasTextAlign align) { + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setTextAlign", static_cast(align)); +} + +void CanvasRenderingContext2DDelegate::setTextBaseline(CanvasTextBaseline baseline) { + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setTextBaseline", static_cast(baseline)); +} + +void CanvasRenderingContext2DDelegate::setFillStyle(float r, float g, float b, float a) { + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setFillStyle", r, g, b, a); +} + +void CanvasRenderingContext2DDelegate::setStrokeStyle(float r, float g, float b, float a) { + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setStrokeStyle", r, g, b, a); +} + +void CanvasRenderingContext2DDelegate::setLineWidth(float lineWidth) { + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setLineWidth", lineWidth); +} + +const cc::Data &CanvasRenderingContext2DDelegate::getDataRef() const { + return _data; +} + +void CanvasRenderingContext2DDelegate::fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) { + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + + auto *arr = JniHelper::getEnv()->NewIntArray(imageData.getSize() / 4); + JniHelper::getEnv()->SetIntArrayRegion(arr, 0, imageData.getSize() / 4, + reinterpret_cast(imageData.getBytes())); + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "_fillImageData", arr, imageWidth, + imageHeight, offsetX, offsetY); + ccDeleteLocalRef(JniHelper::getEnv(), arr); + + fillData(); +} + +void CanvasRenderingContext2DDelegate::fillData() { + jbyteArray arr = JniHelper::callObjectByteArrayMethod(_obj, JCLS_CANVASIMPL, "getDataRef"); + if (arr == nullptr) { + SE_LOGE("getDataRef return null in fillData, size: %d, %d", (int)_bufferWidth, (int)_bufferHeight); + return; + } + jsize len = JniHelper::getEnv()->GetArrayLength(arr); + auto *jbarray = static_cast(malloc(len * sizeof(jbyte))); + JniHelper::getEnv()->GetByteArrayRegion(arr, 0, len, jbarray); +#if CC_PLATFORM != CC_PLATFORM_OHOS + unMultiplyAlpha(reinterpret_cast(jbarray), len); +#endif + _data.fastSet(reinterpret_cast(jbarray), len); //IDEA: DON'T create new jbarray every time. + ccDeleteLocalRef(JniHelper::getEnv(), arr); +} + +void CanvasRenderingContext2DDelegate::unMultiplyAlpha(unsigned char *ptr, ssize_t size) { // NOLINT(readability-convert-member-functions-to-static) + // Android source data is not premultiplied alpha when API >= 19 + // please refer CanvasRenderingContext2DImpl::recreateBuffer(float w, float h) + // in CanvasRenderingContext2DImpl.java + // if (getAndroidSDKInt() >= 19) + // return; + + float alpha; + for (int i = 0; i < size; i += 4) { + alpha = static_cast(ptr[i + 3]); + if (alpha > 0) { + ptr[i] = CLAMP((int)((float)ptr[i] / alpha * 255), 255); + ptr[i + 1] = CLAMP((int)((float)ptr[i + 1] / alpha * 255), 255); + ptr[i + 2] = CLAMP((int)((float)ptr[i + 2] / alpha * 255), 255); + } + } +} +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/java/modules/CanvasRenderingContext2DDelegate.h b/native/cocos/platform/java/modules/CanvasRenderingContext2DDelegate.h new file mode 100644 index 0000000000..c38af6b1ef --- /dev/null +++ b/native/cocos/platform/java/modules/CanvasRenderingContext2DDelegate.h @@ -0,0 +1,95 @@ +/**************************************************************************** + Copyright (c) 2018-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h" + +#include "base/csscolorparser.h" +#include "bindings/jswrapper/config.h" +#include "math/Math.h" + +#include "cocos/bindings/jswrapper/SeApi.h" +#include "platform/java/jni/JniHelper.h" +#include "platform/java/jni/JniImp.h" + +#if __OHOS__ + #include +#endif + +#include + +#ifndef JCLS_CANVASIMPL + #define JCLS_CANVASIMPL "com/cocos/lib/CanvasRenderingContext2DImpl" +#endif +#include + +namespace cc { + +class CanvasRenderingContext2DDelegate : public ICanvasRenderingContext2D::Delegate { +public: + using Size = std::array; + CanvasRenderingContext2DDelegate(); + ~CanvasRenderingContext2DDelegate() override; + + void recreateBuffer(float w, float h) override; + void beginPath() override; + void closePath() override; + void moveTo(float x, float y) override; + void lineTo(float x, float y) override; + void stroke() override; + void saveContext() override; + void restoreContext() override; + void clearRect(float /*x*/, float /*y*/, float w, float h) override; + void fill() override; + void setLineCap(const std::string &lineCap) override; + void setLineJoin(const std::string &lineJoin) override; + void rect(float x, float y, float w, float h) override; + void fillRect(float x, float y, float w, float h) override; + void fillText(const std::string &text, float x, float y, float /*maxWidth*/) override; + void strokeText(const std::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; + Size measureText(const std::string &text) override; + void updateFont(const std::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; + void setTextAlign(CanvasTextAlign align) override; + void setTextBaseline(CanvasTextBaseline baseline) override; + void setFillStyle(float r, float g, float b, float a) override; + void setStrokeStyle(float r, float g, float b, float a) override; + void setLineWidth(float lineWidth) override; + const cc::Data &getDataRef() const override; + void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; + +private: + void fillData(); + void unMultiplyAlpha(unsigned char *ptr, ssize_t size); + +public: +private: + jobject _obj = nullptr; + Data _data; + float _bufferWidth = 0.0F; + float _bufferHeight = 0.0F; +}; + +} // namespace cc diff --git a/native/cocos/platform/java/modules/CommonScreen.cpp b/native/cocos/platform/java/modules/CommonScreen.cpp new file mode 100644 index 0000000000..971bab94e4 --- /dev/null +++ b/native/cocos/platform/java/modules/CommonScreen.cpp @@ -0,0 +1,103 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/java/modules/CommonScreen.h" +#include "cocos/bindings/jswrapper/SeApi.h" +#include "platform/java/jni/JniImp.h" + +namespace { +// constant from Android API: +// reference: https://developer.android.com/reference/android/view/Surface#ROTATION_0 +enum Rotation { + ROTATION_0 = 0, + ROTATION_90, + ROTATION_180, + ROTATION_270 +}; +} // namespace + +namespace cc { + +// int Screen::getDPI() { +// static int dpi = -1; +// if (dpi == -1) { +// AConfiguration *config = AConfiguration_new(); +// //AConfiguration_fromAssetManager(config, cocosApp.assetManager); +// int32_t density = AConfiguration_getDensity(config); +// AConfiguration_delete(config); +// const int stdDpi = 160; +// dpi = density * stdDpi; +// } +// return dpi; +// } + +float CommonScreen::getDevicePixelRatio() const { + return 1; +} + +void CommonScreen::setKeepScreenOn(bool keepScreenOn) { + // JniHelper::callStaticVoidMethod(JCLS_HELPER, "setKeepScreenOn", value); + // ANativeActivity_setWindowFlags(JniHelper::getAndroidApp()->activity, AWINDOW_FLAG_KEEP_SCREEN_ON, 0); + CC_UNUSED_PARAM(keepScreenOn); +} + +IScreen::Orientation CommonScreen::getDeviceOrientation() const { + int rotation = getDeviceRotationJNI(); + switch (rotation) { + case ROTATION_0: + return Orientation::PORTRAIT; + case ROTATION_90: + return Orientation::LANDSCAPE_RIGHT; + case ROTATION_180: + return Orientation::PORTRAIT_UPSIDE_DOWN; + case ROTATION_270: + return Orientation::LANDSCAPE_LEFT; + default: + break; + } + return Orientation::PORTRAIT; +} + +Vec4 CommonScreen::getSafeAreaEdge() const { + float *data = getSafeAreaEdgeJNI(); + return cc::Vec4(data[0], data[1], data[2], data[3]); +} + +bool CommonScreen::isDisplayStats() { //NOLINT + se::AutoHandleScope hs; + se::Value ret; + char commandBuf[100] = "cc.debug.isDisplayStats();"; + se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret); + return ret.toBoolean(); +} + +void CommonScreen::setDisplayStats(bool isShow) { //NOLINT + se::AutoHandleScope hs; + char commandBuf[100] = {0}; + sprintf(commandBuf, "cc.debug.setDisplayStats(%s);", isShow ? "true" : "false"); + se::ScriptEngine::getInstance()->evalString(commandBuf); +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/java/modules/CommonScreen.h b/native/cocos/platform/java/modules/CommonScreen.h new file mode 100644 index 0000000000..e5a55952e1 --- /dev/null +++ b/native/cocos/platform/java/modules/CommonScreen.h @@ -0,0 +1,50 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IScreen.h" + +namespace cc { + +class CommonScreen : public IScreen { +public: + float getDevicePixelRatio() const override; + void setKeepScreenOn(bool keepScreenOn) override; + Orientation getDeviceOrientation() const override; + Vec4 getSafeAreaEdge() const override; + /** + @brief Get current display stats. + @return bool, is displaying stats or not. + */ + bool isDisplayStats() override; + + /** + @brief set display stats information. + */ + void setDisplayStats(bool isShow) override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/java/modules/CommonSystem.cpp b/native/cocos/platform/java/modules/CommonSystem.cpp new file mode 100644 index 0000000000..7c4f41cff8 --- /dev/null +++ b/native/cocos/platform/java/modules/CommonSystem.cpp @@ -0,0 +1,97 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/java/modules/CommonSystem.h" +#include "platform/java/jni/JniHelper.h" +#include "platform/java/jni/JniImp.h" + +namespace cc { +CommonSystem::CommonSystem() = default; +CommonSystem::~CommonSystem() = default; + +std::string CommonSystem::getDeviceModel() const { + return getDeviceModelJNI(); +} + +CommonSystem::LanguageType CommonSystem::getCurrentLanguage() const { + std::string languageName = getCurrentLanguageJNI(); + const char* pLanguageName = languageName.c_str(); + LanguageType ret = LanguageType::ENGLISH; + + if (0 == strcmp("zh", pLanguageName)) { + ret = LanguageType::CHINESE; + } else if (0 == strcmp("en", pLanguageName)) { + ret = LanguageType::ENGLISH; + } else if (0 == strcmp("fr", pLanguageName)) { + ret = LanguageType::FRENCH; + } else if (0 == strcmp("it", pLanguageName)) { + ret = LanguageType::ITALIAN; + } else if (0 == strcmp("de", pLanguageName)) { + ret = LanguageType::GERMAN; + } else if (0 == strcmp("es", pLanguageName)) { + ret = LanguageType::SPANISH; + } else if (0 == strcmp("ru", pLanguageName)) { + ret = LanguageType::RUSSIAN; + } else if (0 == strcmp("nl", pLanguageName)) { + ret = LanguageType::DUTCH; + } else if (0 == strcmp("ko", pLanguageName)) { + ret = LanguageType::KOREAN; + } else if (0 == strcmp("ja", pLanguageName)) { + ret = LanguageType::JAPANESE; + } else if (0 == strcmp("hu", pLanguageName)) { + ret = LanguageType::HUNGARIAN; + } else if (0 == strcmp("pt", pLanguageName)) { + ret = LanguageType::PORTUGUESE; + } else if (0 == strcmp("ar", pLanguageName)) { + ret = LanguageType::ARABIC; + } else if (0 == strcmp("nb", pLanguageName)) { + ret = LanguageType::NORWEGIAN; + } else if (0 == strcmp("pl", pLanguageName)) { + ret = LanguageType::POLISH; + } else if (0 == strcmp("tr", pLanguageName)) { + ret = LanguageType::TURKISH; + } else if (0 == strcmp("uk", pLanguageName)) { + ret = LanguageType::UKRAINIAN; + } else if (0 == strcmp("ro", pLanguageName)) { + ret = LanguageType::ROMANIAN; + } else if (0 == strcmp("bg", pLanguageName)) { + ret = LanguageType::BULGARIAN; + } + return ret; +} + +std::string CommonSystem::getCurrentLanguageCode() const { + return getCurrentLanguageCodeJNI(); +} + +std::string CommonSystem::getSystemVersion() const { + return getSystemVersionJNI(); +} + +bool CommonSystem::openURL(const std::string& url) { + return openURLJNI(url); +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/java/modules/CommonSystem.h b/native/cocos/platform/java/modules/CommonSystem.h new file mode 100644 index 0000000000..cf8d82fddb --- /dev/null +++ b/native/cocos/platform/java/modules/CommonSystem.h @@ -0,0 +1,63 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/ISystem.h" + +namespace cc { + +class CommonSystem : public ISystem { +public: + CommonSystem(); + ~CommonSystem() override; + /** + @brief Get target device model. + */ + std::string getDeviceModel() const override; + /** + @brief Get current language config. + @return Current language config. + */ + LanguageType getCurrentLanguage() const override; + /** + @brief Get current language iso 639-1 code. + @return Current language iso 639-1 code. + */ + std::string getCurrentLanguageCode() const override; + /** + @brief Get system version. + @return system version. + */ + std::string getSystemVersion() const override; + /** + @brief Open url in default browser. + @param String with url to open. + @return True if the resource located by the URL was successfully opened; otherwise false. + */ + bool openURL(const std::string& url) override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/java/modules/Network.cpp b/native/cocos/platform/java/modules/Network.cpp new file mode 100644 index 0000000000..3bfd6a2e88 --- /dev/null +++ b/native/cocos/platform/java/modules/Network.cpp @@ -0,0 +1,34 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/java/modules/Network.h" +#include "platform/java/jni/JniImp.h" + +namespace cc { + +INetwork::NetworkType Network::getNetworkType() const { + return static_cast(getNetworkTypeJNI()); +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/java/modules/Network.h b/native/cocos/platform/java/modules/Network.h new file mode 100644 index 0000000000..9b1ea1b21b --- /dev/null +++ b/native/cocos/platform/java/modules/Network.h @@ -0,0 +1,37 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/INetwork.h" + +namespace cc { + +class Network : public INetwork { +public: + NetworkType getNetworkType() const override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/java/modules/SystemWindow.cpp b/native/cocos/platform/java/modules/SystemWindow.cpp new file mode 100644 index 0000000000..a07cc8f88e --- /dev/null +++ b/native/cocos/platform/java/modules/SystemWindow.cpp @@ -0,0 +1,74 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/java/modules/SystemWindow.h" +#include +#include +#include +#include +#include +#include +#include "base/Log.h" +#include "base/Macros.h" +#include "platform/java/jni/JniImp.h" +#include "platform/java/jni/glue/JniNativeGlue.h" + + +namespace { + +} // namespace + +namespace cc { + +bool SystemWindow::createWindow(const char *title, + int x, int y, int w, + int h, int flags) { + CC_UNUSED_PARAM(title); + CC_UNUSED_PARAM(x); + CC_UNUSED_PARAM(y); + CC_UNUSED_PARAM(w); + CC_UNUSED_PARAM(h); + CC_UNUSED_PARAM(flags); + return true; +} + +void SystemWindow::setCursorEnabled(bool value) { +} + +void SystemWindow::copyTextToClipboard(const std::string &text) { + copyTextToClipboardJNI(text); +} + +uintptr_t SystemWindow::getWindowHandler() const { + return reinterpret_cast( + JNI_NATIVE_GLUE()->getWindowHandler()); +} + +SystemWindow::Size SystemWindow::getViewSize() const { + return Size{static_cast(JNI_NATIVE_GLUE()->getWidth()), + static_cast(JNI_NATIVE_GLUE()->getHeight())}; +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/java/modules/SystemWindow.h b/native/cocos/platform/java/modules/SystemWindow.h new file mode 100644 index 0000000000..58d60e3d9b --- /dev/null +++ b/native/cocos/platform/java/modules/SystemWindow.h @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include + +#include "platform/interfaces/modules/ISystemWindow.h" + +namespace cc { + +class SystemWindow : public ISystemWindow { +public: + bool createWindow(const char* title, + int x, int y, int w, + int h, int flags) override; + /** + @brief enable/disable(lock) the cursor, default is enabled + */ + void setCursorEnabled(bool value) override; + void copyTextToClipboard(const std::string& text) override; + uintptr_t getWindowHandler() const override; + Size getViewSize() const override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/java/modules/Vibrator.cpp b/native/cocos/platform/java/modules/Vibrator.cpp new file mode 100644 index 0000000000..f6864085a1 --- /dev/null +++ b/native/cocos/platform/java/modules/Vibrator.cpp @@ -0,0 +1,35 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/java/modules/Vibrator.h" +#include "platform/java/jni/JniImp.h" + +namespace cc { + +void Vibrator::vibrate(float duration) { + setVibrateJNI(duration); +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/java/modules/Vibrator.h b/native/cocos/platform/java/modules/Vibrator.h new file mode 100644 index 0000000000..9a8ea1657d --- /dev/null +++ b/native/cocos/platform/java/modules/Vibrator.h @@ -0,0 +1,44 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IVibrator.h" + +namespace cc { + +class Vibrator : public IVibrator { +public: + /** + * Vibrate for the specified amount of time. + * If vibrate is not supported, then invoking this method has no effect. + * Some platforms limit to a maximum duration of 5 seconds. + * Duration is ignored on iOS due to API limitations. + * @param duration The duration in seconds. + */ + void vibrate(float duration) override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/linux/FileUtils-linux.cpp b/native/cocos/platform/linux/FileUtils-linux.cpp new file mode 100644 index 0000000000..e811987bd0 --- /dev/null +++ b/native/cocos/platform/linux/FileUtils-linux.cpp @@ -0,0 +1,105 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "FileUtils-linux.h" +#include +#include +#include +#include +#include "base/Log.h" + +#define DECLARE_GUARD std::lock_guard mutexGuard(_mutex) +#ifndef CC_RESOURCE_FOLDER_LINUX + #define CC_RESOURCE_FOLDER_LINUX ("/Resources/") +#endif + +namespace cc { + +FileUtils *FileUtils::getInstance() { + if (FileUtils::sharedFileUtils == nullptr) { + FileUtils::sharedFileUtils = new FileUtilsLinux(); + if (!FileUtils::sharedFileUtils->init()) { + delete FileUtils::sharedFileUtils; + FileUtils::sharedFileUtils = nullptr; + CC_LOG_DEBUG("ERROR: Could not init CCFileUtilsLinux"); + } + } + return FileUtils::sharedFileUtils; +} + +bool FileUtilsLinux::init() { + // get application path + char fullpath[256] = {0}; + ssize_t length = readlink("/proc/self/exe", fullpath, sizeof(fullpath) - 1); + + if (length <= 0) { + return false; + } + + fullpath[length] = '\0'; + std::string appPath = fullpath; + _defaultResRootPath = appPath.substr(0, appPath.find_last_of('/')); + _defaultResRootPath.append(CC_RESOURCE_FOLDER_LINUX); + + // Set writable path to $XDG_CONFIG_HOME or ~/.config// if $XDG_CONFIG_HOME not exists. + const char *xdg_config_path = getenv("XDG_CONFIG_HOME"); + std::string xdgConfigPath; + if (xdg_config_path == nullptr) { + xdgConfigPath = getenv("HOME"); + xdgConfigPath.append("/.config"); + } else { + xdgConfigPath = xdg_config_path; + } + _writablePath = xdgConfigPath; + _writablePath.append(appPath.substr(appPath.find_last_of('/'))); + _writablePath.append("/"); + + return FileUtils::init(); +} + +bool FileUtilsLinux::isFileExistInternal(const std::string &filename) const { + if (filename.empty()) { + return false; + } + + std::string strPath = filename; + if (!isAbsolutePath(strPath)) { // Not absolute path, add the default root path at the beginning. + strPath.insert(0, _defaultResRootPath); + } + + struct stat sts; + return (stat(strPath.c_str(), &sts) == 0) && S_ISREG(sts.st_mode); +} + +std::string FileUtilsLinux::getWritablePath() const { + struct stat st; + stat(_writablePath.c_str(), &st); + if (!S_ISDIR(st.st_mode)) { + mkdir(_writablePath.c_str(), 0744); + } + + return _writablePath; +} + +} // namespace cc diff --git a/native/cocos/platform/linux/FileUtils-linux.h b/native/cocos/platform/linux/FileUtils-linux.h new file mode 100644 index 0000000000..b578971ebd --- /dev/null +++ b/native/cocos/platform/linux/FileUtils-linux.h @@ -0,0 +1,40 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/FileUtils.h" +namespace cc { +class FileUtilsLinux : public FileUtils { +public: + friend class FileUtils; + bool isFileExistInternal(const std::string &filename) const override; + std::string getWritablePath() const override; + bool init() override; + +private: + std::string _writablePath; +}; +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/linux/LinuxPlatform.cpp b/native/cocos/platform/linux/LinuxPlatform.cpp new file mode 100644 index 0000000000..b3d2bd7185 --- /dev/null +++ b/native/cocos/platform/linux/LinuxPlatform.cpp @@ -0,0 +1,394 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/linux/LinuxPlatform.h" + +#include +#include + +#include "SDL2/SDL.h" +#include "SDL2/SDL_main.h" +#include "SDL2/SDL_syswm.h" + +#include "platform/interfaces/OSInterface.h" +#include "platform/interfaces/modules/ISystemWindow.h" + +namespace { + +std::unordered_map gKeyMap = { + {SDLK_APPLICATION, cc::KeyCode::CONTEXT_MENU}, + {SDLK_SCROLLLOCK, cc::KeyCode::SCROLLLOCK}, + {SDLK_PAUSE, cc::KeyCode::PAUSE}, + {SDLK_PRINTSCREEN, cc::KeyCode::PRINT_SCREEN}, + {SDLK_INSERT, cc::KeyCode::INSERT}, + {SDLK_ESCAPE, cc::KeyCode::ESCAPE}, + {SDLK_MINUS, cc::KeyCode::MINUS}, + {SDLK_LSHIFT, cc::KeyCode::SHIFT_LEFT}, + {SDLK_RSHIFT, cc::KeyCode::SHIFT_RIGHT}, + {SDLK_EQUALS, cc::KeyCode::EQUAL}, + {SDLK_BACKSLASH, cc::KeyCode::BACKSLASH}, + {SDLK_BACKQUOTE, cc::KeyCode::BACKQUOTE}, + {SDLK_BACKSPACE, cc::KeyCode::BACKSPACE}, + {SDLK_RETURN, cc::KeyCode::ENTER}, + {SDLK_RETURN2, cc::KeyCode::ENTER}, + {SDLK_LEFTBRACKET, cc::KeyCode::BRACKET_LEFT}, + {SDLK_RIGHTBRACKET, cc::KeyCode::BRACKET_RIGHT}, + {SDLK_SEMICOLON, cc::KeyCode::SEMICOLON}, + {SDLK_QUOTE, cc::KeyCode::QUOTE}, + {SDLK_TAB, cc::KeyCode::TAB}, + {SDLK_LCTRL, cc::KeyCode::CONTROL_LEFT}, + {SDLK_RCTRL, cc::KeyCode::CONTROL_RIGHT}, + {SDLK_LALT, cc::KeyCode::ALT_LEFT}, + {SDLK_RALT, cc::KeyCode::ALT_RIGHT}, + {SDLK_LEFT, cc::KeyCode::ARROW_LEFT}, + {SDLK_RIGHT, cc::KeyCode::ARROW_RIGHT}, + {SDLK_UP, cc::KeyCode::ARROW_UP}, + {SDLK_DOWN, cc::KeyCode::ARROW_DOWN}, + {SDLK_KP_ENTER, cc::KeyCode::NUMPAD_ENTER}, + {SDLK_KP_PLUS, cc::KeyCode::NUMPAD_PLUS}, + {SDLK_KP_MULTIPLY, cc::KeyCode::NUMPAD_MULTIPLY}, + {SDLK_KP_DIVIDE, cc::KeyCode::NUMPAD_DIVIDE}, + {SDLK_KP_MINUS, cc::KeyCode::NUMPAD_MINUS}, + {SDLK_KP_PERIOD, cc::KeyCode::NUMPAD_DECIMAL}, + {SDLK_KP_BACKSPACE, cc::KeyCode::BACKSPACE}, + {SDLK_NUMLOCKCLEAR, cc::KeyCode::NUM_LOCK}, + {SDLK_HOME, cc::KeyCode::HOME}, + {SDLK_PAGEUP, cc::KeyCode::PAGE_UP}, + {SDLK_PAGEDOWN, cc::KeyCode::PAGE_DOWN}, + {SDLK_END, cc::KeyCode::END}, + {SDLK_COMMA, cc::KeyCode::COMMA}, + {SDLK_PERIOD, cc::KeyCode::PERIOD}, + {SDLK_SLASH, cc::KeyCode::SLASH}, + {SDLK_SPACE, cc::KeyCode::SPACE}, + {SDLK_DELETE, cc::KeyCode::DELETE_KEY}, + {SDLK_CAPSLOCK, cc::KeyCode::CAPS_LOCK}, + {SDLK_KP_0, cc::KeyCode::NUMPAD_0}, + {SDLK_KP_1, cc::KeyCode::NUMPAD_1}, + {SDLK_KP_2, cc::KeyCode::NUMPAD_2}, + {SDLK_KP_3, cc::KeyCode::NUMPAD_3}, + {SDLK_KP_4, cc::KeyCode::NUMPAD_4}, + {SDLK_KP_5, cc::KeyCode::NUMPAD_5}, + {SDLK_KP_6, cc::KeyCode::NUMPAD_6}, + {SDLK_KP_7, cc::KeyCode::NUMPAD_7}, + {SDLK_KP_8, cc::KeyCode::NUMPAD_8}, + {SDLK_KP_9, cc::KeyCode::NUMPAD_9}}; + +int sdlKeycodeToCocosCode(int sdlCode, int mode) { + auto it = gKeyMap.find(sdlCode); + if (it != gKeyMap.end()) { + return static_cast(it->second); + } + + if (sdlCode >= SDLK_F1 && sdlCode <= SDLK_F12) { + // F1 ~ F12 + return 112 + (sdlCode - SDLK_F1); + } else { + int code = sdlCode & (~(1 << 30)); + if (code >= SDLK_a && code <= SDLK_z) { + return 'A' + (code - SDLK_a); + } else { + return code; + } + } +} + +std::unordered_map gWindowFlagMap = { + {cc::ISystemWindow::CC_WINDOW_FULLSCREEN, SDL_WINDOW_FULLSCREEN}, + {cc::ISystemWindow::CC_WINDOW_OPENGL, SDL_WINDOW_OPENGL}, + {cc::ISystemWindow::CC_WINDOW_SHOWN, SDL_WINDOW_SHOWN}, + {cc::ISystemWindow::CC_WINDOW_HIDDEN, SDL_WINDOW_HIDDEN}, + {cc::ISystemWindow::CC_WINDOW_BORDERLESS, SDL_WINDOW_BORDERLESS}, + {cc::ISystemWindow::CC_WINDOW_RESIZABLE, SDL_WINDOW_RESIZABLE}, + {cc::ISystemWindow::CC_WINDOW_MINIMIZED, SDL_WINDOW_MINIMIZED}, + {cc::ISystemWindow::CC_WINDOW_MAXIMIZED, SDL_WINDOW_MAXIMIZED}, + {cc::ISystemWindow::CC_WINDOW_INPUT_GRABBED, SDL_WINDOW_INPUT_GRABBED}, + {cc::ISystemWindow::CC_WINDOW_INPUT_FOCUS, SDL_WINDOW_INPUT_FOCUS}, + {cc::ISystemWindow::CC_WINDOW_MOUSE_FOCUS, SDL_WINDOW_MOUSE_FOCUS}, + {cc::ISystemWindow::CC_WINDOW_FULLSCREEN_DESKTOP, SDL_WINDOW_FULLSCREEN_DESKTOP}, + {cc::ISystemWindow::CC_WINDOW_FOREIGN, SDL_WINDOW_FOREIGN}, + {cc::ISystemWindow::CC_WINDOW_ALLOW_HIGHDPI, SDL_WINDOW_ALLOW_HIGHDPI}, + {cc::ISystemWindow::CC_WINDOW_MOUSE_CAPTURE, SDL_WINDOW_MOUSE_CAPTURE}, + {cc::ISystemWindow::CC_WINDOW_ALWAYS_ON_TOP, SDL_WINDOW_ALWAYS_ON_TOP}, + {cc::ISystemWindow::CC_WINDOW_SKIP_TASKBAR, SDL_WINDOW_SKIP_TASKBAR}, + {cc::ISystemWindow::CC_WINDOW_UTILITY, SDL_WINDOW_UTILITY}, + {cc::ISystemWindow::CC_WINDOW_TOOLTIP, SDL_WINDOW_TOOLTIP}, + {cc::ISystemWindow::CC_WINDOW_POPUP_MENU, SDL_WINDOW_POPUP_MENU}, + {cc::ISystemWindow::CC_WINDOW_VULKAN, SDL_WINDOW_VULKAN}}; + +int windowFlagsToSDLWindowFlag(int flags) { + int sdlFlags = 0; + for (auto it : gWindowFlagMap) { + if ((it.first & flags) == it.first) { + sdlFlags |= it.second; + } + } + return sdlFlags; +} + +} // namespace + +namespace cc { +LinuxPlatform::LinuxPlatform() = default; +LinuxPlatform::~LinuxPlatform() { + if (_handle) { + SDL_DestroyWindow(_handle); + _handle = nullptr; + } + if (_inited) { + SDL_Quit(); + } +} + +int32_t LinuxPlatform::init() { + UniversalPlatform::init(); + + if (SDL_Init(SDL_INIT_VIDEO) < 0) { + // Display error message + CC_LOG_ERROR("SDL could not initialize! SDL_Error: %s\n", SDL_GetError()); + return false; + } + return 0; +} + +static long getCurrentMillSecond() { + long lLastTime; + struct timeval stCurrentTime; + + gettimeofday(&stCurrentTime, NULL); + lLastTime = stCurrentTime.tv_sec * 1000 + stCurrentTime.tv_usec * 0.001; // milliseconds + return lLastTime; +} + +int32_t LinuxPlatform::loop() { + long lastTime = 0L; + long curTime = 0L; + long desiredInterval = 0L; + long actualInterval = 0L; + onResume(); + while (!_quit) { + curTime = getCurrentMillSecond(); + desiredInterval = (long)(1.0 / getFps()); + pollEvent(); + actualInterval = curTime - lastTime; + if (actualInterval >= desiredInterval) { + lastTime = getCurrentMillSecond(); + runTask(); + SDL_GL_SwapWindow(_handle); + } else { + usleep((desiredInterval - curTime + lastTime) * 1000); + } + } + + onDestory(); + return 0; +} + +void LinuxPlatform::handleWindowEvent(SDL_WindowEvent &wevent) { + WindowEvent ev; + switch (wevent.event) { + case SDL_WINDOWEVENT_SHOWN: { + ev.type = WindowEvent::Type::SHOW; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT_RESTORED: { + ev.type = WindowEvent::Type::RESTORED; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT_SIZE_CHANGED: { + ev.type = WindowEvent::Type::SIZE_CHANGED; + ev.width = wevent.data1; + ev.height = wevent.data2; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT_RESIZED: { + ev.type = WindowEvent::Type::RESIZED; + ev.width = wevent.data1; + ev.height = wevent.data2; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT_HIDDEN: { + ev.type = WindowEvent::Type::HIDDEN; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT_MINIMIZED: { + ev.type = WindowEvent::Type::MINIMIZED; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT_ENTER: { + SDL_CaptureMouse(SDL_TRUE); + break; + } + case SDL_WINDOWEVENT_CLOSE: { + ev.type = WindowEvent::Type::CLOSE; + dispatchEvent(ev); + break; + } + } +} + +void LinuxPlatform::pollEvent() { + SDL_Event sdlEvent; + int cnt = SDL_PollEvent(&sdlEvent); + if (cnt == 0) { + return; + } + cc::TouchEvent touch; + cc::MouseEvent mouse; + cc::KeyboardEvent keyboard; + switch (sdlEvent.type) { + case SDL_QUIT: { + _quit = true; + WindowEvent ev; + ev.type = WindowEvent::Type::QUIT; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT: { + handleWindowEvent(sdlEvent.window); + break; + } + case SDL_MOUSEBUTTONDOWN: { + SDL_MouseButtonEvent &event = sdlEvent.button; + mouse.type = MouseEvent::Type::DOWN; + mouse.x = static_cast(event.x); + mouse.y = static_cast(event.y); + /*if (0 > mouse.x || mouse.x > this->_width || 0 > mouse.y || mouse.y > this->_height) { + break; + }*/ + mouse.button = event.button - 1; + dispatchEvent(mouse); + break; + } + case SDL_MOUSEBUTTONUP: { + SDL_MouseButtonEvent &event = sdlEvent.button; + mouse.type = MouseEvent::Type::UP; + mouse.x = static_cast(event.x); + mouse.y = static_cast(event.y); + mouse.button = event.button - 1; + dispatchEvent(mouse); + break; + } + case SDL_MOUSEMOTION: { + SDL_MouseMotionEvent &event = sdlEvent.motion; + mouse.type = MouseEvent::Type::MOVE; + mouse.x = static_cast(event.x); + mouse.y = static_cast(event.y); + mouse.button = 0; + dispatchEvent(mouse); + break; + } + case SDL_MOUSEWHEEL: { + SDL_MouseWheelEvent &event = sdlEvent.wheel; + mouse.type = MouseEvent::Type::WHEEL; + mouse.x = static_cast(event.x); + mouse.y = static_cast(event.y); + mouse.button = 0; //TODO: direction + dispatchEvent(mouse); + break; + } + case SDL_FINGERUP: { + SDL_TouchFingerEvent &event = sdlEvent.tfinger; + touch.type = TouchEvent::Type::ENDED; + touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; + dispatchEvent(touch); + break; + } + case SDL_FINGERDOWN: { + SDL_TouchFingerEvent &event = sdlEvent.tfinger; + touch.type = TouchEvent::Type::BEGAN; + touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; + dispatchEvent(touch); + break; + } + case SDL_FINGERMOTION: { + SDL_TouchFingerEvent &event = sdlEvent.tfinger; + touch.type = TouchEvent::Type::MOVED; + touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; + dispatchEvent(touch); + break; + } + case SDL_KEYDOWN: { + SDL_KeyboardEvent &event = sdlEvent.key; + auto mode = event.keysym.mod; + keyboard.action = KeyboardEvent::Action::PRESS; + keyboard.key = sdlKeycodeToCocosCode(event.keysym.sym, mode); + keyboard.altKeyActive = mode & KMOD_ALT; + keyboard.ctrlKeyActive = mode & KMOD_CTRL; + keyboard.shiftKeyActive = mode & KMOD_SHIFT; + //CC_LOG_DEBUG("==> key %d -> code %d", event.keysym.sym, keyboard.key); + //cc::EventDispatcher::dispatchKeyboardEvent(keyboard); + dispatchEvent(keyboard); + break; + } + case SDL_KEYUP: { + SDL_KeyboardEvent &event = sdlEvent.key; + auto mode = event.keysym.mod; + keyboard.action = KeyboardEvent::Action::RELEASE; + keyboard.key = sdlKeycodeToCocosCode(event.keysym.sym, mode); + keyboard.altKeyActive = mode & KMOD_ALT; + keyboard.ctrlKeyActive = mode & KMOD_CTRL; + keyboard.shiftKeyActive = mode & KMOD_SHIFT; + dispatchEvent(keyboard); + //cc::EventDispatcher::dispatchKeyboardEvent(keyboard); + break; + } + default: + + break; + } +} + +bool LinuxPlatform::createWindow(const char *title, + int x, int y, int w, + int h, int flags) { + if (_inited) { + return true; + } + // Create window + int sdlFlags = windowFlagsToSDLWindowFlag(flags); + _handle = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, w, h, sdlFlags); + if (_handle == nullptr) { + // Display error message + CC_LOG_ERROR("Window could not be created! SDL_Error: %s\n", SDL_GetError()); + return false; + } + _inited = true; + return true; +} + +uintptr_t LinuxPlatform::getWindowHandler() const { + SDL_SysWMinfo wmInfo; + SDL_VERSION(&wmInfo.version); + SDL_GetWindowWMInfo(_handle, &wmInfo); + return reinterpret_cast(wmInfo.info.x11.window); +} + +} // namespace cc diff --git a/native/cocos/platform/linux/LinuxPlatform.h b/native/cocos/platform/linux/LinuxPlatform.h new file mode 100644 index 0000000000..231adf8170 --- /dev/null +++ b/native/cocos/platform/linux/LinuxPlatform.h @@ -0,0 +1,68 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/UniversalPlatform.h" +#include "platform/linux/modules/SystemWindow.h" + +struct SDL_WindowEvent; +struct SDL_Window; + +namespace cc { + +class LinuxPlatform : public UniversalPlatform, + public SystemWindow::Delegate { +public: + LinuxPlatform(); + /** + * Destructor of WindowPlatform. + */ + ~LinuxPlatform() override; + /** + * Implementation of Windows platform initialization. + */ + int32_t init() override; + + int32_t loop() override; + + // override from SystemWindow::Delegate + bool createWindow(const char* title, + int x, int y, int w, + int h, int flags) override; + uintptr_t getWindowHandler() const override; + struct SDL_Window* getWindow() { + return _handle; + } + +private: + void pollEvent() override; + void handleWindowEvent(SDL_WindowEvent& wevent); + bool _inited{false}; + bool _quit{false}; + struct SDL_Window* _handle{nullptr}; +}; + +} // namespace cc diff --git a/native/cocos/platform/linux/modules/Accelerometer.cpp b/native/cocos/platform/linux/modules/Accelerometer.cpp new file mode 100644 index 0000000000..e7ff316690 --- /dev/null +++ b/native/cocos/platform/linux/modules/Accelerometer.cpp @@ -0,0 +1,40 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/linux/modules/Accelerometer.h" + +namespace cc { +void Accelerometer::setAccelerometerEnabled(bool isEnabled) { +} + +void Accelerometer::setAccelerometerInterval(float interval) { +} + +const Accelerometer::MotionValue& Accelerometer::getDeviceMotionValue() { + static MotionValue motionValue; + return motionValue; +} + +} // namespace cc diff --git a/native/cocos/platform/linux/modules/Accelerometer.h b/native/cocos/platform/linux/modules/Accelerometer.h new file mode 100644 index 0000000000..50a3c56992 --- /dev/null +++ b/native/cocos/platform/linux/modules/Accelerometer.h @@ -0,0 +1,50 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IAccelerometer.h" + +namespace cc { + +class Accelerometer : public IAccelerometer { +public: + /** + * To enable or disable accelerometer. + */ + void setAccelerometerEnabled(bool isEnabled) override; + + /** + * Sets the interval of accelerometer. + */ + void setAccelerometerInterval(float interval) override; + + /** + * Gets the motion value of current device. + */ + const MotionValue &getDeviceMotionValue() override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/linux/modules/Battery.cpp b/native/cocos/platform/linux/modules/Battery.cpp new file mode 100644 index 0000000000..659bec9e50 --- /dev/null +++ b/native/cocos/platform/linux/modules/Battery.cpp @@ -0,0 +1,33 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/linux/modules/Battery.h" + +namespace cc { + +float Battery::getBatteryLevel() const { + return 1.0F; +} + +} // namespace cc diff --git a/native/cocos/platform/linux/modules/Battery.h b/native/cocos/platform/linux/modules/Battery.h new file mode 100644 index 0000000000..928cbb038e --- /dev/null +++ b/native/cocos/platform/linux/modules/Battery.h @@ -0,0 +1,37 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IBattery.h" + +namespace cc { + +class Battery : public IBattery { +public: + float getBatteryLevel() const override; +}; + +} // namespace cc diff --git a/native/cocos/platform/linux/modules/CanvasRenderingContext2DDelegate.cpp b/native/cocos/platform/linux/modules/CanvasRenderingContext2DDelegate.cpp new file mode 100644 index 0000000000..c8a36595f6 --- /dev/null +++ b/native/cocos/platform/linux/modules/CanvasRenderingContext2DDelegate.cpp @@ -0,0 +1,358 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/linux/modules/CanvasRenderingContext2DDelegate.h" +#include "SDL2/SDL.h" +#include "SDL2/SDL_syswm.h" +#include "platform/linux/LinuxPlatform.h" + +namespace { +#define RGB(r, g, b) (int)((int)r | (((int)g) << 8) | (((int)b) << 16)) +#define RGBA(r, g, b, a) (int)((int)r | (((int)g) << 8) | (((int)b) << 16) | (((int)a) << 24)) +} // namespace + +namespace { +void fillRectWithColor(uint8_t *buf, uint32_t totalWidth, uint32_t totalHeight, uint32_t x, uint32_t y, uint32_t width, uint32_t height, uint8_t r, uint8_t g, uint8_t b, uint8_t a) { + assert(x + width <= totalWidth); + assert(y + height <= totalHeight); + + uint32_t y0 = y; + uint32_t y1 = y + height; + uint8_t *p; + for (uint32_t offsetY = y0; offsetY < y1; ++offsetY) { + for (uint32_t offsetX = x; offsetX < (x + width); ++offsetX) { + p = buf + (totalWidth * offsetY + offsetX) * 4; + *p++ = r; + *p++ = g; + *p++ = b; + *p++ = a; + } + } +} +} // namespace + +namespace cc { +//static const char gdefaultFontName[] = "-*-helvetica-medium-o-*-*-24-*-*-*-*-*-iso8859-*"; +//static const char gdefaultFontName[] = "lucidasanstypewriter-bold-24"; +static const char gdefaultFontName[] = "lucidasans-24"; +static const char gdefaultFontName1[] = "lucidasans"; + +CanvasRenderingContext2DDelegate::CanvasRenderingContext2DDelegate() { + SDL_SysWMinfo wmInfo; + SDL_VERSION(&wmInfo.version); + LinuxPlatform *platform = nullptr; + CCASSERT(platform != nullptr, "Platform pointer can't be null"); + SDL_GetWindowWMInfo(reinterpret_cast(platform->getWindow()), &wmInfo); + _dis = wmInfo.info.x11.display; + _win = wmInfo.info.x11.window; +} + +CanvasRenderingContext2DDelegate::~CanvasRenderingContext2DDelegate() { + XFreePixmap(_dis, _pixmap); + XFreeGC(_dis, _gc); +} + +void CanvasRenderingContext2DDelegate::recreateBuffer(float w, float h) { + _bufferWidth = w; + _bufferHeight = h; + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + auto textureSize = static_cast(_bufferWidth * _bufferHeight * 4); + auto *data = static_cast(malloc(sizeof(int8_t) * textureSize)); + memset(data, 0x00, textureSize); + _imageData.fastSet((uint8_t *)data, textureSize); + + if (_pixmap) { + XFreePixmap(_dis, _pixmap); + _pixmap = 0; + } + if (!_win) { + return; + } + //Screen *scr = DefaultScreenOfDisplay(_dis); + _pixmap = XCreatePixmap(_dis, _win, w, h, 32); + _gc = XCreateGC(_dis, _pixmap, 0, 0); +} + +void CanvasRenderingContext2DDelegate::beginPath() { + // called: set_lineWidth() -> beginPath() -> moveTo() -> lineTo() -> stroke(), when draw line + XSetLineAttributes(_dis, _gc, static_cast(_lineWidth), LineSolid, _lineCap, _lineJoin); + XSetForeground(_dis, _gc, RGB(255, 255, 255)); +} + +void CanvasRenderingContext2DDelegate::closePath() { +} + +void CanvasRenderingContext2DDelegate::moveTo(float x, float y) { + //MoveToEx(_DC, static_cast(x), static_cast(-(y - _bufferHeight - _fontSize)), nullptr); + _x = x; + _y = y; +} + +void CanvasRenderingContext2DDelegate::lineTo(float x, float y) { + //LineTo(_DC, static_cast(x), static_cast(-(y - _bufferHeight - _fontSize))); + XDrawLine(_dis, _pixmap, _gc, _x, _y, x, y); +} + +void CanvasRenderingContext2DDelegate::stroke() { +} + +void CanvasRenderingContext2DDelegate::saveContext() { +} + +void CanvasRenderingContext2DDelegate::restoreContext() { +} + +void CanvasRenderingContext2DDelegate::clearRect(float x, float y, float w, float h) { + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + + if (_imageData.isNull()) { + return; + } + + recreateBuffer(w, h); +} + +void CanvasRenderingContext2DDelegate::fillRect(float x, float y, float w, float h) { + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + + XSetForeground(_dis, _gc, _fillStyle); + XFillRectangle(_dis, _pixmap, _gc, x, y, w, h); +} + +void CanvasRenderingContext2DDelegate::fillText(const std::string &text, float x, float y, float /*maxWidth*/) { + if (text.empty() || _bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + + Point offsetPoint = convertDrawPoint(Point{x, y}, text); + XSetForeground(_dis, _gc, 0xff000000 | _fillStyle); + XSetFont(_dis, _gc, _font->fid); + XDrawString(_dis, _pixmap, _gc, offsetPoint[0], offsetPoint[1], text.c_str(), (int)(text.length())); + XImage * image = XGetImage(_dis, _pixmap, 0, 0, _bufferWidth, _bufferHeight, AllPlanes, ZPixmap); + int width = image->width; + int height = image->height; + unsigned char *data = _imageData.getBytes(); + for (int y = 0; y < height; ++y) { + for (int x = 0; x < width; x++) { + *(((int *)data + (y * width) + x)) = static_cast(XGetPixel(image, x, y)); + } + } +} + +void CanvasRenderingContext2DDelegate::strokeText(const std::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const { + if (text.empty() || _bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } +} + +CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::measureText(const std::string &text) { + if (text.empty()) + return std::array{0.0f, 0.0f}; + int font_ascent = 0; + int font_descent = 0; + int direction = 0; + XCharStruct overall; + XQueryTextExtents(_dis, _font->fid, text.c_str(), text.length(), &direction, &font_ascent, &font_descent, &overall); + return std::array{static_cast(overall.width), + static_cast(overall.ascent + overall.descent)}; +} + +void CanvasRenderingContext2DDelegate::updateFont(const std::string &fontName, + float fontSize, + bool bold, + bool italic, + bool oblique, + bool /* smallCaps */) { + do { + _fontName = fontName; + _fontSize = static_cast(fontSize); + /// TODO(bug):Remove default settings + std::string fontName = "helvetica"; // default + char serv[1024] = {0}; + std::string slant = ""; + if (italic) { + slant = "*I"; + } else if (oblique) { + slant = "*o"; + } + // *name-bold*Italic(Oblique)*size + snprintf(serv, sizeof(serv) - 1, "*%s%s%s*--%d*", fontName.c_str(), + bold ? "*Bold" : "", + slant.c_str(), + _fontSize); + if (_font) { + XFreeFont(_dis, _font); + _font = 0; + } + + _font = XLoadQueryFont(_dis, serv); + if (!_font) { + static int fontSizes[] = {8, 10, 12, 14, 18, 24}; + int i = 0; + int size = sizeof(fontSizes) / sizeof(fontSizes[0]); + for (i = 0; i < size; ++i) { + if (_fontSize < fontSizes[i]) { + break; + } + } + if (i == 0) { + _fontSize = fontSizes[0]; + } else if (i > 1 && i < size) { + _fontSize = fontSizes[i - 1]; + } else { + _fontSize = fontSizes[size - 1]; + } + snprintf(serv, sizeof(serv) - 1, "*%s*%d*", "lucidasans", _fontSize); + _font = XLoadQueryFont(_dis, serv); + if (!_font) { + _font = XLoadQueryFont(_dis, serv); + } + } + } while (false); +} + +void CanvasRenderingContext2DDelegate::setTextAlign(CanvasTextAlign align) { + _textAlign = align; +} + +void CanvasRenderingContext2DDelegate::setTextBaseline(CanvasTextBaseline baseline) { + _textBaseLine = baseline; +} + +void CanvasRenderingContext2DDelegate::setFillStyle(float r, float g, float b, float a) { + _fillStyle = RGBA(r * 255, g * 255, b * 255, a * 255); +} + +void CanvasRenderingContext2DDelegate::setStrokeStyle(float r, float g, float b, float a) { + _strokeStyle = RGBA(r * 255, g * 255, b * 255, a * 255); +} + +void CanvasRenderingContext2DDelegate::setLineWidth(float lineWidth) { + _lineWidth = lineWidth; +} + +const cc::Data &CanvasRenderingContext2DDelegate::getDataRef() const { + return _imageData; +} + +void CanvasRenderingContext2DDelegate::removeCustomFont() { + XFreeFont(_dis, None); +} + +// x, y offset value +int CanvasRenderingContext2DDelegate::drawText(const std::string &text, int x, int y) { + XTextItem item{const_cast(text.c_str()), static_cast(text.length()), 0, None}; + return XDrawText(_dis, _pixmap, _gc, x, y, &item, 1); +} + +CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::sizeWithText(const wchar_t *pszText, int nLen) { + // if (text.empty()) + // return std::array{0.0f, 0.0f}; + // XFontStruct *fs = XLoadQueryFont(dpy, "cursor"); + // assert(fs); + // int font_ascent = 0; + // int font_descent = 0; + // XCharStruct overall; + // XQueryTextExtents(_dis, fs -> fid, text.c_str(), text.length(), nullptr, &font_ascent, &font_descent, &overall); + // return std::array{static_cast(overall.lbearing), + // static_cast(overall.rbearing)}; + return std::array{0.0F, 0.0F}; +} + +void CanvasRenderingContext2DDelegate::prepareBitmap(int nWidth, int nHeight) { +} + +void CanvasRenderingContext2DDelegate::deleteBitmap() { +} + +void CanvasRenderingContext2DDelegate::fillTextureData() { +} + +std::array CanvasRenderingContext2DDelegate::convertDrawPoint(Point point, const std::string &text) { + int font_ascent = 0; + int font_descent = 0; + int direction = 0; + XCharStruct overall; + XQueryTextExtents(_dis, _font->fid, text.c_str(), text.length(), &direction, &font_ascent, &font_descent, &overall); + int width = overall.width; + if (_textAlign == CanvasTextAlign::CENTER) { + point[0] -= width / 2.0f; + } else if (_textAlign == CanvasTextAlign::RIGHT) { + point[0] -= width; + } + + if (_textBaseLine == CanvasTextBaseline::TOP) { + point[1] += overall.ascent; + } else if (_textBaseLine == CanvasTextBaseline::MIDDLE) { + point[1] += (overall.descent - overall.ascent) / 2 - overall.descent; + } else if (_textBaseLine == CanvasTextBaseline::BOTTOM) { + point[1] += -overall.descent; + } else if (_textBaseLine == CanvasTextBaseline::ALPHABETIC) { + //point[1] -= overall.ascent; + // X11 The default way of drawing text + } + + return point; +} + +void CanvasRenderingContext2DDelegate::fill() { +} + +void CanvasRenderingContext2DDelegate::setLineCap(const std::string &lineCap) { + _lineCap = LineSolid; +} + +void CanvasRenderingContext2DDelegate::setLineJoin(const std::string &lineJoin) { + _lineJoin = JoinRound; +} + +void CanvasRenderingContext2DDelegate::fillImageData(const Data & /* imageData */, + float /* imageWidth */, + float /* imageHeight */, + float /* offsetX */, + float /* offsetY */) { + //XCreateImage(display, visual, DefaultDepth(display,DefaultScreen(display)), ZPixmap, 0, image32, width, height, 32, 0); + //XPutImage(dpy, w, gc, image, 0, 0, 50, 60, 40, 30); +} + +void CanvasRenderingContext2DDelegate::strokeText(const std::string & /* text */, + float /* x */, + float /* y */, + float /* maxWidth */) { +} + +void CanvasRenderingContext2DDelegate::rect(float /* x */, + float /* y */, + float /* w */, + float /* h */) { +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/linux/modules/CanvasRenderingContext2DDelegate.h b/native/cocos/platform/linux/modules/CanvasRenderingContext2DDelegate.h new file mode 100644 index 0000000000..6f14fbf339 --- /dev/null +++ b/native/cocos/platform/linux/modules/CanvasRenderingContext2DDelegate.h @@ -0,0 +1,122 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h" + +#include +#include +#include +#include "base/csscolorparser.h" +#include "cocos/bindings/manual/jsb_platform.h" +#include "math/Math.h" +#include "platform/FileUtils.h" + +#include +#include +#include + +namespace cc { + +class CanvasRenderingContext2DDelegate : public ICanvasRenderingContext2D::Delegate { +public: + using Point = std::array; + using Vec2 = std::array; + using Size = std::array; + using Color4F = std::array; + + CanvasRenderingContext2DDelegate(); + ~CanvasRenderingContext2DDelegate() override; + + void recreateBuffer(float w, float h) override; + void beginPath() override; + void closePath() override; + void moveTo(float x, float y) override; + void lineTo(float x, float y) override; + void stroke() override; + void saveContext() override; + void restoreContext() override; + void clearRect(float /*x*/, float /*y*/, float w, float h) override; + void fillRect(float x, float y, float w, float h) override; + void fillText(const std::string &text, float x, float y, float /*maxWidth*/) override; + void strokeText(const std::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const; + Size measureText(const std::string &text) override; + void updateFont(const std::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; + void setTextAlign(CanvasTextAlign align) override; + void setTextBaseline(CanvasTextBaseline baseline) override; + void setFillStyle(float r, float g, float b, float a) override; + void setStrokeStyle(float r, float g, float b, float a) override; + void setLineWidth(float lineWidth) override; + const cc::Data &getDataRef() const override; + void fill() override; + void setLineCap(const std::string &lineCap) override; + void setLineJoin(const std::string &lineCap) override; + void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; + void strokeText(const std::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; + void rect(float x, float y, float w, float h) override; + +private: + static wchar_t * utf8ToUtf16(const std::string &str, int *pRetLen = nullptr); + void removeCustomFont(); + int drawText(const std::string &text, int x, int y); + Size sizeWithText(const wchar_t *pszText, int nLen); + void prepareBitmap(int nWidth, int nHeight); + void deleteBitmap(); + void fillTextureData(); + std::array convertDrawPoint(Point point, const std::string &text); + +public: + Display * _dis{nullptr}; + int _screen{0}; + Drawable _win{0}; + Drawable _pixmap{0}; + XFontStruct *_font{0}; + GC _gc; + +private: + int32_t _x{0}; + int32_t _y{0}; + int32_t _lineCap{0}; + int32_t _lineJoin{0}; + +private: + cc::Data _imageData; + std::string _curFontPath; + int _savedDC{0}; + float _lineWidth{0.0F}; + float _bufferWidth{0.0F}; + float _bufferHeight{0.0F}; + + std::string _fontName; + int _fontSize{0}; + Size _textSize; + CanvasTextAlign _textAlign{CanvasTextAlign::CENTER}; + CanvasTextBaseline _textBaseLine{CanvasTextBaseline::TOP}; + unsigned long _fillStyle{0}; + unsigned long _strokeStyle{0}; +}; + +} // namespace cc diff --git a/native/cocos/platform/linux/modules/Network.cpp b/native/cocos/platform/linux/modules/Network.cpp new file mode 100644 index 0000000000..13aa70c2de --- /dev/null +++ b/native/cocos/platform/linux/modules/Network.cpp @@ -0,0 +1,33 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/linux/modules/Network.h" + +namespace cc { + +INetwork::NetworkType Network::getNetworkType() const { + return INetwork::NetworkType::LAN; +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/linux/modules/Network.h b/native/cocos/platform/linux/modules/Network.h new file mode 100644 index 0000000000..cd5f2d6d5a --- /dev/null +++ b/native/cocos/platform/linux/modules/Network.h @@ -0,0 +1,37 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/INetwork.h" + +namespace cc { + +class Network : public INetwork { +public: + NetworkType getNetworkType() const override; +}; + +} // namespace cc diff --git a/native/cocos/platform/linux/modules/Screen.cpp b/native/cocos/platform/linux/modules/Screen.cpp new file mode 100644 index 0000000000..e7b86595e3 --- /dev/null +++ b/native/cocos/platform/linux/modules/Screen.cpp @@ -0,0 +1,87 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/linux/modules/Screen.h" +#include "base/Macros.h" +#include "cocos/bindings/jswrapper/SeApi.h" +#include + +namespace cc { + +int Screen::getDPI() const { + static int dpi = -1; + if (dpi == -1) { + Display *dpy; + char * displayname = NULL; + int scr = 0; /* Screen number */ + dpy = XOpenDisplay(displayname); + /* + * there are 2.54 centimeters to an inch; so there are 25.4 millimeters. + * + * dpi = N pixels / (M millimeters / (25.4 millimeters / 1 inch)) + * = N pixels / (M inch / 25.4) + * = N * 25.4 pixels / M inch + */ + double xres = ((((double)DisplayWidth(dpy, scr)) * 25.4) / + ((double)DisplayWidthMM(dpy, scr))); + dpi = (int)(xres + 0.5); + //printf("dpi = %d\n", dpi); + XCloseDisplay(dpy); + } + return dpi; +} + +float Screen::getDevicePixelRatio() const { + return 1; +} + +void Screen::setKeepScreenOn(bool value) { + CC_UNUSED_PARAM(value); +} + +Screen::Orientation Screen::getDeviceOrientation() const { + return Orientation::PORTRAIT; +} + +Vec4 Screen::getSafeAreaEdge() const { + return cc::Vec4(); +} + +bool Screen::isDisplayStats() { + se::AutoHandleScope hs; + se::Value ret; + char commandBuf[100] = "cc.profiler.isShowingStats();"; + se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret); + return ret.toBoolean(); +} + +void Screen::setDisplayStats(bool isShow) { + se::AutoHandleScope hs; + char commandBuf[100] = {0}; + sprintf(commandBuf, isShow ? "cc.profiler.showStats();" : "cc.profiler.hideStats();"); + se::ScriptEngine::getInstance()->evalString(commandBuf); +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/linux/modules/Screen.h b/native/cocos/platform/linux/modules/Screen.h new file mode 100644 index 0000000000..06eb7a8c15 --- /dev/null +++ b/native/cocos/platform/linux/modules/Screen.h @@ -0,0 +1,51 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IScreen.h" + +namespace cc { + +class Screen : public IScreen { +public: + int getDPI() const override; + float getDevicePixelRatio() const override; + void setKeepScreenOn(bool value) override; + Orientation getDeviceOrientation() const override; + Vec4 getSafeAreaEdge() const override; + /** + @brief Get current display stats. + @return bool, is displaying stats or not. + */ + bool isDisplayStats() override; + + /** + @brief set display stats information. + */ + void setDisplayStats(bool isShow) override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/linux/modules/System.cpp b/native/cocos/platform/linux/modules/System.cpp new file mode 100644 index 0000000000..e6480d8247 --- /dev/null +++ b/native/cocos/platform/linux/modules/System.cpp @@ -0,0 +1,125 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/linux/modules/System.h" +#include +#include + +namespace cc { + +using OSType = System::OSType; + +OSType System::getOSType() const { + return OSType::LINUX; +} + +std::string System::getDeviceModel() const { + return "Linux"; +} + +System::LanguageType System::getCurrentLanguage() const { + char* pLanguageName = getenv("LANG"); + if (!pLanguageName) { + return LanguageType::ENGLISH; + } + strtok(pLanguageName, "_"); + if (!pLanguageName) { + return LanguageType::ENGLISH; + } + + return getLanguageTypeByISO2(pLanguageName); +} + +std::string System::getCurrentLanguageCode() const { + static char code[3] = {0}; + char* pLanguageName = getenv("LANG"); + if (!pLanguageName) { + return "en"; + } + strtok(pLanguageName, "_"); + if (!pLanguageName) { + return "en"; + } + strncpy(code, pLanguageName, 2); + code[2] = '\0'; + return code; +} + +std::string System::getSystemVersion() const { + struct utsname u; + uname(&u); + return u.version; +} + +bool System::openURL(const std::string& url) { + std::string op = std::string("xdg-open '").append(url).append("'"); + return system(op.c_str()) == 0; +} + +System::LanguageType System::getLanguageTypeByISO2(const char* code) const { + // this function is used by all platforms to get system language + // except windows: cocos/platform/win32/CCApplication-win32.cpp + LanguageType ret = LanguageType::ENGLISH; + + if (strncmp(code, "zh", 2) == 0) { + ret = LanguageType::CHINESE; + } else if (strncmp(code, "ja", 2) == 0) { + ret = LanguageType::JAPANESE; + } else if (strncmp(code, "fr", 2) == 0) { + ret = LanguageType::FRENCH; + } else if (strncmp(code, "it", 2) == 0) { + ret = LanguageType::ITALIAN; + } else if (strncmp(code, "de", 2) == 0) { + ret = LanguageType::GERMAN; + } else if (strncmp(code, "es", 2) == 0) { + ret = LanguageType::SPANISH; + } else if (strncmp(code, "nl", 2) == 0) { + ret = LanguageType::DUTCH; + } else if (strncmp(code, "ru", 2) == 0) { + ret = LanguageType::RUSSIAN; + } else if (strncmp(code, "hu", 2) == 0) { + ret = LanguageType::HUNGARIAN; + } else if (strncmp(code, "pt", 2) == 0) { + ret = LanguageType::PORTUGUESE; + } else if (strncmp(code, "ko", 2) == 0) { + ret = LanguageType::KOREAN; + } else if (strncmp(code, "ar", 2) == 0) { + ret = LanguageType::ARABIC; + } else if (strncmp(code, "nb", 2) == 0) { + ret = LanguageType::NORWEGIAN; + } else if (strncmp(code, "pl", 2) == 0) { + ret = LanguageType::POLISH; + } else if (strncmp(code, "tr", 2) == 0) { + ret = LanguageType::TURKISH; + } else if (strncmp(code, "uk", 2) == 0) { + ret = LanguageType::UKRAINIAN; + } else if (strncmp(code, "ro", 2) == 0) { + ret = LanguageType::ROMANIAN; + } else if (strncmp(code, "bg", 2) == 0) { + ret = LanguageType::BULGARIAN; + } + return ret; +} +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/linux/modules/System.h b/native/cocos/platform/linux/modules/System.h new file mode 100644 index 0000000000..617b45499c --- /dev/null +++ b/native/cocos/platform/linux/modules/System.h @@ -0,0 +1,68 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/ISystem.h" + +namespace cc { + +class System : public ISystem { +public: + /** + @brief Get target system type. + */ + OSType getOSType() const override; + /** + @brief Get target device model. + */ + std::string getDeviceModel() const override; + /** + @brief Get current language config. + @return Current language config. + */ + LanguageType getCurrentLanguage() const override; + /** + @brief Get current language iso 639-1 code. + @return Current language iso 639-1 code. + */ + std::string getCurrentLanguageCode() const override; + /** + @brief Get system version. + @return system version. + */ + std::string getSystemVersion() const override; + /** + @brief Open url in default browser. + @param String with url to open. + @return True if the resource located by the URL was successfully opened; otherwise false. + */ + bool openURL(const std::string& url) override; + +private: + LanguageType getLanguageTypeByISO2(const char* code) const; +}; + +} // namespace cc diff --git a/native/cocos/platform/linux/modules/SystemWindow.cpp b/native/cocos/platform/linux/modules/SystemWindow.cpp new file mode 100644 index 0000000000..ce5cbf846e --- /dev/null +++ b/native/cocos/platform/linux/modules/SystemWindow.cpp @@ -0,0 +1,83 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/linux/modules/SystemWindow.h" + +#include "base/Log.h" +#include "base/Macros.h" + +// SDL headers +#include +#include "SDL2/SDL.h" +#include "SDL2/SDL_main.h" +#include "SDL2/SDL_syswm.h" +#include "bindings/event/EventDispatcher.h" +#include "platform/IEventDispatch.h" +#include "platform/linux/LinuxPlatform.h" + +namespace { + +} // namespace + +namespace cc { +SystemWindow::SystemWindow() { +} + +SystemWindow::~SystemWindow() { +} + +bool SystemWindow::createWindow(const char *title, + int x, int y, int w, + int h, int flags) { + // Create window + + LinuxPlatform *platform = dynamic_cast(BasePlatform::getPlatform()); + CCASSERT(platform != nullptr, "Platform pointer can't be null"); + platform->createWindow(title, x, y, w, h, flags); + _width = w; + _height = h; + return true; +} + +uintptr_t SystemWindow::getWindowHandler() const { + //return _handle; + LinuxPlatform *platform = dynamic_cast(BasePlatform::getPlatform()); + CCASSERT(platform != nullptr, "Platform pointer can't be null"); + return platform->getWindowHandler(); +} + +void SystemWindow::setCursorEnabled(bool value) { + SDL_SetRelativeMouseMode(value ? SDL_FALSE : SDL_TRUE); +} + +void SystemWindow::copyTextToClipboard(const std::string &text) { + //TODO +} + +SystemWindow::Size SystemWindow::getViewSize() const { + return Size{static_cast(_width), static_cast(_height)}; +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/linux/modules/SystemWindow.h b/native/cocos/platform/linux/modules/SystemWindow.h new file mode 100644 index 0000000000..44b447075d --- /dev/null +++ b/native/cocos/platform/linux/modules/SystemWindow.h @@ -0,0 +1,68 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include + +#include "platform/interfaces/modules/ISystemWindow.h" + +struct SDL_Window; +struct SDL_WindowEvent; + +namespace cc { + +class SystemWindow : public ISystemWindow { +public: + explicit SystemWindow(); + ~SystemWindow() override; + + class Delegate { + public: + virtual ~Delegate() = default; + virtual bool createWindow(const char* title, + int x, int y, int w, + int h, int flags) = 0; + virtual uintptr_t getWindowHandler() const = 0; + }; + + bool createWindow(const char* title, + int x, int y, int w, + int h, int flags) override; + uintptr_t getWindowHandler() const override; + + Size getViewSize() const override; + /* + @brief enable/disable(lock) the cursor, default is enabled + */ + void setCursorEnabled(bool value) override; + void copyTextToClipboard(const std::string& text) override; + +private: + int _width{0}; + int _height{0}; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/linux/modules/Vibrate.cpp b/native/cocos/platform/linux/modules/Vibrate.cpp new file mode 100644 index 0000000000..c8345f6c13 --- /dev/null +++ b/native/cocos/platform/linux/modules/Vibrate.cpp @@ -0,0 +1,36 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/linux/modules/Vibrate.h" + +#include "base/Macros.h" + +namespace cc { + +void Vibrator::vibrate(float duration) { + CC_UNUSED_PARAM(duration); +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/linux/modules/Vibrate.h b/native/cocos/platform/linux/modules/Vibrate.h new file mode 100644 index 0000000000..f0afad6cbf --- /dev/null +++ b/native/cocos/platform/linux/modules/Vibrate.h @@ -0,0 +1,44 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IVibrator.h" + +namespace cc { + +class Vibrator : public IVibrator { +public: + /** + * Vibrator for the specified amount of time. + * If Vibrator is not supported, then invoking this method has no effect. + * Some platforms limit to a maximum duration of 5 seconds. + * Duration is ignored on iOS due to API limitations. + * @param duration The duration in seconds. + */ + void vibrate(float duration) override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/templates/mac/AppDelegate.h b/native/cocos/platform/mac/AppDelegate.h similarity index 100% rename from native/templates/mac/AppDelegate.h rename to native/cocos/platform/mac/AppDelegate.h diff --git a/native/templates/mac/AppDelegate.mm b/native/cocos/platform/mac/AppDelegate.mm similarity index 74% rename from native/templates/mac/AppDelegate.mm rename to native/cocos/platform/mac/AppDelegate.mm index b3184cfa26..546ba23a47 100644 --- a/native/templates/mac/AppDelegate.mm +++ b/native/cocos/platform/mac/AppDelegate.mm @@ -1,19 +1,24 @@ #import "AppDelegate.h" #include -#import "Game.h" +//#import "Game.h" #import "ViewController.h" +#include "cocos/bindings/event/EventDispatcher.h" +#include "platform/mac/MacPlatform.h" + @interface AppDelegate () { NSWindow* _window; - Game* _game; + // Game* _game; + cc::MacPlatform* _platform; } @end @implementation AppDelegate -- (void)applicationDidFinishLaunching:(NSNotification*)aNotification { - NSRect rect = NSMakeRect(200, 200, 960, 640); - _window = [[NSWindow alloc] initWithContentRect:rect +- (void)createWindow:(NSString*)title xPos:(int)x yPos:(int)y width:(int)w height:(int)h { + _window.title = title; + NSRect rect = NSMakeRect(x, y, w, h); + _window = [[NSWindow alloc] initWithContentRect:rect styleMask:NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]; @@ -21,18 +26,11 @@ NSLog(@"Failed to allocated the window."); return; } - - _window.title = @"Cocos creator 3D Game"; - ViewController* viewController = [[ViewController alloc] initWithSize:rect]; _window.contentViewController = viewController; _window.contentView = viewController.view; [_window.contentView setWantsBestResolutionOpenGLSurface:YES]; [_window makeKeyAndOrderFront:nil]; - - _game = new Game(rect.size.width, rect.size.height); - _game->init(); - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillMiniaturizeNotification) name:NSWindowWillMiniaturizeNotification @@ -47,16 +45,22 @@ object:_window]; } +- (void)applicationDidFinishLaunching:(NSNotification*)aNotification { + _platform = dynamic_cast(cc::BasePlatform::getPlatform()); + CCASSERT(_platform != nullptr, "Platform pointer can't be null"); + _platform->loop(); +} + - (void)windowWillMiniaturizeNotification { - _game->onPause(); + _platform->onPause(); } - (void)windowDidDeminiaturizeNotification { - _game->onResume(); + _platform->onResume(); } - (void)windowWillCloseNotification { - _game->onClose(); + _platform->onClose(); } - (NSWindow*)getWindow { @@ -64,13 +68,18 @@ } - (void)applicationWillTerminate:(NSNotification*)aNotification { - delete _game; + // delete _game; //FIXME: will crash if relase it here. // [_window release]; + _platform->onDestory(); } - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)theApplication { return YES; } +- (void)dispatchEvent:(const cc::OSEvent&)ev { + _platform->dispatchEvent(ev); +} + @end diff --git a/native/cocos/platform/mac/Device-mac.mm b/native/cocos/platform/mac/Device-mac.mm deleted file mode 100644 index 27413ec666..0000000000 --- a/native/cocos/platform/mac/Device-mac.mm +++ /dev/null @@ -1,114 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - 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. -****************************************************************************/ - -#if CC_PLATFORM == CC_PLATFORM_MAC_OSX - - #include "platform/Device.h" - #include "platform/apple/Device-apple.h" - #include "Reachability.h" - - #include - #include - #include - #include - -namespace cc { - -int Device::getDPI() { - NSScreen *screen = [NSScreen mainScreen]; - NSDictionary *description = [screen deviceDescription]; - NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue]; - CGSize displayPhysicalSize = CGDisplayScreenSize([[description objectForKey:@"NSScreenNumber"] unsignedIntValue]); - - return ((displayPixelSize.width / displayPhysicalSize.width) * 25.4f); -} - -void Device::setAccelerometerEnabled(bool isEnabled) { -} - -void Device::setAccelerometerInterval(float interval) { -} - -const Device::MotionValue &Device::getDeviceMotionValue() { - static MotionValue __motionValue; - return __motionValue; -} - -Device::Orientation Device::getDeviceOrientation() { - return Device::Orientation::LANDSCAPE_RIGHT; -} - -std::string Device::getDeviceModel() { - struct utsname systemInfo; - uname(&systemInfo); - return systemInfo.machine; -} - -void Device::setKeepScreenOn(bool value) { - CC_UNUSED_PARAM(value); -} - -void Device::vibrate(float duration) { - CC_UNUSED_PARAM(duration); -} - -float Device::getBatteryLevel() { - return 1.0f; -} - -Device::NetworkType Device::getNetworkType() { - static Reachability *__reachability = nullptr; - if (__reachability == nullptr) { - __reachability = Reachability::createForInternetConnection(); - __reachability->retain(); - } - - NetworkType ret = NetworkType::NONE; - Reachability::NetworkStatus status = __reachability->getCurrentReachabilityStatus(); - switch (status) { - case Reachability::NetworkStatus::REACHABLE_VIA_WIFI: - ret = NetworkType::LAN; - break; - case Reachability::NetworkStatus::REACHABLE_VIA_WWAN: - ret = NetworkType::WWAN; - break; - default: - ret = NetworkType::NONE; - break; - } - - return ret; -} - -Vec4 Device::getSafeAreaEdge() { - // no SafeArea concept on mac, return ZERO Vec4. - return Vec4(); -} - -} // namespace cc - -#endif // CC_PLATFORM == CC_PLATFORM_MAC_OSX diff --git a/native/cocos/platform/mac/MacPlatform.h b/native/cocos/platform/mac/MacPlatform.h new file mode 100644 index 0000000000..5f6c863175 --- /dev/null +++ b/native/cocos/platform/mac/MacPlatform.h @@ -0,0 +1,60 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/UniversalPlatform.h" + +namespace cc { + +class MacPlatform : public UniversalPlatform { +public: + MacPlatform() = default; + /** + * Destructor of WindowPlatform. + */ + ~MacPlatform() override; + /** + * Implementation of Windows platform initialization. + */ + int32_t init() override; + + /** + * @brief Start base platform initialization. + */ + int32_t run(int argc, const char** argv) override; + /** + * @brief Implement the main logic of the base platform. + */ + int32_t loop() override; + void setFps(int32_t fps) override; + int32_t getFps() const override; + + void onPause() override; + void onResume() override; + void onClose() override; +}; + +} // namespace cc diff --git a/native/cocos/platform/mac/MacPlatform.mm b/native/cocos/platform/mac/MacPlatform.mm new file mode 100644 index 0000000000..859c47b210 --- /dev/null +++ b/native/cocos/platform/mac/MacPlatform.mm @@ -0,0 +1,146 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/mac/MacPlatform.h" +#include "platform/interfaces/OSInterface.h" +#include "platform/interfaces/modules/ISystemWindow.h" +#include "platform/mac/AppDelegate.h" + +#import +extern int cocos_main(int argc, const char** argv); + +@interface MyTimer : NSObject { + cc::MacPlatform *_platform; + NSTimer * _timer; + int _fps; +} +- (instancetype)initWithApp:(cc::MacPlatform *)platform fps:(int)fps; +- (void)start; +- (void)changeFPS:(int)fps; +- (void)pause; +- (void)resume; +@end + +@implementation MyTimer + +- (instancetype)initWithApp:(cc::MacPlatform *)platform fps:(int)fps { + if (self = [super init]) { + _fps = fps; + _platform = platform; + } + return self; +} + +- (void)start { + _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f / _fps + target:self + selector:@selector(renderScene) + userInfo:nil + repeats:YES]; +} + +- (void)pause { + [_timer invalidate]; +} + +- (void)resume { + [self start]; +} + +- (void)changeFPS:(int)fps { + if (fps == _fps) + return; + + [self pause]; + [self resume]; +} + +- (int)getFps { + return _fps; +} + +- (void)renderScene { + _platform->runTask(); +} + +@end + +namespace { +MyTimer *_timer; +} + +namespace cc { + +MacPlatform::~MacPlatform() { + [_timer release]; +} + +int32_t MacPlatform::init() { + _timer = [[MyTimer alloc] initWithApp:this fps:60]; + return UniversalPlatform::init(); +} + +int32_t MacPlatform::loop(void) { + [_timer start]; + return cocos_main(0, nullptr); +} + +int32_t MacPlatform::run(int argc, const char** argv) { + id delegate = [[AppDelegate alloc] init]; + NSApplication.sharedApplication.delegate = delegate; + return NSApplicationMain(argc, argv); +} + +void MacPlatform::setFps(int32_t fps) { + [_timer changeFPS:fps]; +} + +int32_t MacPlatform::getFps() const { + return [_timer getFps]; +} + +void MacPlatform::onPause() { + [_timer pause]; + + cc::WindowEvent ev; + ev.type = cc::WindowEvent::Type::HIDDEN; + dispatchEvent(ev); +} + +void MacPlatform::onResume() { + [_timer resume]; + + cc::WindowEvent ev; + ev.type = cc::WindowEvent::Type::SHOW; + dispatchEvent(ev); +} + +void MacPlatform::onClose() { + cc::WindowEvent ev; + ev.type = cc::WindowEvent::Type::CLOSE; + dispatchEvent(ev); +} + +} // namespace cc diff --git a/native/templates/mac/ViewController.h b/native/cocos/platform/mac/ViewController.h similarity index 100% rename from native/templates/mac/ViewController.h rename to native/cocos/platform/mac/ViewController.h diff --git a/native/templates/mac/ViewController.mm b/native/cocos/platform/mac/ViewController.mm similarity index 100% rename from native/templates/mac/ViewController.mm rename to native/cocos/platform/mac/ViewController.mm diff --git a/native/cocos/platform/mac/modules/Accelerometer.h b/native/cocos/platform/mac/modules/Accelerometer.h new file mode 100644 index 0000000000..50a3c56992 --- /dev/null +++ b/native/cocos/platform/mac/modules/Accelerometer.h @@ -0,0 +1,50 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IAccelerometer.h" + +namespace cc { + +class Accelerometer : public IAccelerometer { +public: + /** + * To enable or disable accelerometer. + */ + void setAccelerometerEnabled(bool isEnabled) override; + + /** + * Sets the interval of accelerometer. + */ + void setAccelerometerInterval(float interval) override; + + /** + * Gets the motion value of current device. + */ + const MotionValue &getDeviceMotionValue() override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/mac/modules/Accelerometer.mm b/native/cocos/platform/mac/modules/Accelerometer.mm new file mode 100644 index 0000000000..2866f6d9d4 --- /dev/null +++ b/native/cocos/platform/mac/modules/Accelerometer.mm @@ -0,0 +1,40 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/mac/modules/Accelerometer.h" + +namespace cc { +void Accelerometer::setAccelerometerEnabled(bool isEnabled) { +} + +void Accelerometer::setAccelerometerInterval(float interval) { +} + +const Accelerometer::MotionValue& Accelerometer::getDeviceMotionValue() { + static MotionValue motionValue; + return motionValue; +} + +} // namespace cc diff --git a/native/cocos/platform/mac/modules/Battery.h b/native/cocos/platform/mac/modules/Battery.h new file mode 100644 index 0000000000..46e802fe00 --- /dev/null +++ b/native/cocos/platform/mac/modules/Battery.h @@ -0,0 +1,38 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IBattery.h" + +namespace cc { + +class Battery : public IBattery { +public: + Battery() = default; + float getBatteryLevel() const override; +}; + +} // namespace cc diff --git a/native/templates/android/template/jni/main.cpp b/native/cocos/platform/mac/modules/Battery.mm similarity index 82% rename from native/templates/android/template/jni/main.cpp rename to native/cocos/platform/mac/modules/Battery.mm index df0090badf..10f08cbfa2 100644 --- a/native/templates/android/template/jni/main.cpp +++ b/native/cocos/platform/mac/modules/Battery.mm @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -21,9 +21,13 @@ 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 "Game.h" +****************************************************************************/ +#include "platform/mac/modules/Battery.h" -cc::Application *cocos_main(int width, int height) { - return new Game(width, height); +namespace cc { + +float Battery::getBatteryLevel() const { + return 1.0F; } + +} // namespace cc diff --git a/native/cocos/platform/mac/modules/Network.h b/native/cocos/platform/mac/modules/Network.h new file mode 100644 index 0000000000..cd5f2d6d5a --- /dev/null +++ b/native/cocos/platform/mac/modules/Network.h @@ -0,0 +1,37 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/INetwork.h" + +namespace cc { + +class Network : public INetwork { +public: + NetworkType getNetworkType() const override; +}; + +} // namespace cc diff --git a/native/cocos/platform/mac/modules/Network.mm b/native/cocos/platform/mac/modules/Network.mm new file mode 100644 index 0000000000..dccb1fd46e --- /dev/null +++ b/native/cocos/platform/mac/modules/Network.mm @@ -0,0 +1,58 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/mac/modules/Network.h" +#import +#include +#include +#include "platform/apple/Reachability.h" + + +namespace cc { + +INetwork::NetworkType Network::getNetworkType() const { + static Reachability *__reachability = nullptr; + if (__reachability == nullptr) { + __reachability = Reachability::createForInternetConnection(); + __reachability->retain(); + } + + NetworkType ret = NetworkType::NONE; + Reachability::NetworkStatus status = __reachability->getCurrentReachabilityStatus(); + switch (status) { + case Reachability::NetworkStatus::REACHABLE_VIA_WIFI: + ret = NetworkType::LAN; + break; + case Reachability::NetworkStatus::REACHABLE_VIA_WWAN: + ret = NetworkType::WWAN; + break; + default: + ret = NetworkType::NONE; + break; + } + + return ret; +} + +} // namespace cc diff --git a/native/cocos/platform/mac/modules/Screen.h b/native/cocos/platform/mac/modules/Screen.h new file mode 100644 index 0000000000..e0a45f827f --- /dev/null +++ b/native/cocos/platform/mac/modules/Screen.h @@ -0,0 +1,51 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IScreen.h" + +namespace cc { + +class Screen : public IScreen { +public: + int getDPI() const override; + float getDevicePixelRatio() const override; + void setKeepScreenOn(bool value) override; + Orientation getDeviceOrientation() const override; + Vec4 getSafeAreaEdge() const override; + /** + @brief Get current display stats. + @return bool, is displaying stats or not. + */ + bool isDisplayStats() override; + + /** + @brief set display stats information. + */ + void setDisplayStats(bool isShow) override; +}; + +} // namespace cc diff --git a/native/cocos/platform/mac/modules/Screen.mm b/native/cocos/platform/mac/modules/Screen.mm new file mode 100644 index 0000000000..a44de71846 --- /dev/null +++ b/native/cocos/platform/mac/modules/Screen.mm @@ -0,0 +1,78 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/mac/modules/Screen.h" + +#import +#include +#include + +#include "base/Macros.h" +#include "cocos/bindings/jswrapper/SeApi.h" + +namespace cc { + +int Screen::getDPI() const { + NSScreen * screen = [NSScreen mainScreen]; + NSDictionary *description = [screen deviceDescription]; + NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue]; + CGSize displayPhysicalSize = CGDisplayScreenSize([[description objectForKey:@"NSScreenNumber"] unsignedIntValue]); + + return ((displayPixelSize.width / displayPhysicalSize.width) * 25.4f); +} + +float Screen::getDevicePixelRatio() const { + return [[[[NSApplication sharedApplication] delegate] getWindow] backingScaleFactor]; + ; +} + +void Screen::setKeepScreenOn(bool value) { + CC_UNUSED_PARAM(value); +} + +Screen::Orientation Screen::getDeviceOrientation() const { + return Orientation::PORTRAIT; +} + +Vec4 Screen::getSafeAreaEdge() const { + return cc::Vec4(); +} + +bool Screen::isDisplayStats() { + se::AutoHandleScope hs; + se::Value ret; + char commandBuf[100] = "cc.debug.isDisplayStats();"; + se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret); + return ret.toBoolean(); +} + +void Screen::setDisplayStats(bool isShow) { + se::AutoHandleScope hs; + char commandBuf[100] = {0}; + sprintf(commandBuf, "cc.debug.setDisplayStats(%s);", isShow ? "true" : "false"); + se::ScriptEngine::getInstance()->evalString(commandBuf); +} + +} // namespace cc diff --git a/native/cocos/platform/mac/modules/System.h b/native/cocos/platform/mac/modules/System.h new file mode 100644 index 0000000000..e6287b9965 --- /dev/null +++ b/native/cocos/platform/mac/modules/System.h @@ -0,0 +1,65 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/ISystem.h" + +namespace cc { + +class System : public ISystem { +public: + /** + @brief Get target system type. + */ + OSType getOSType() const override; + /** + @brief Get target device model. + */ + std::string getDeviceModel() const override; + /** + @brief Get current language config. + @return Current language config. + */ + LanguageType getCurrentLanguage() const override; + /** + @brief Get current language iso 639-1 code. + @return Current language iso 639-1 code. + */ + std::string getCurrentLanguageCode() const override; + /** + @brief Get system version. + @return system version. + */ + std::string getSystemVersion() const override; + /** + @brief Open url in default browser. + @param String with url to open. + @return True if the resource located by the URL was successfully opened; otherwise false. + */ + bool openURL(const std::string& url) override; +}; + +} // namespace cc diff --git a/native/cocos/platform/mac/modules/System.mm b/native/cocos/platform/mac/modules/System.mm new file mode 100644 index 0000000000..5cdb199dbe --- /dev/null +++ b/native/cocos/platform/mac/modules/System.mm @@ -0,0 +1,99 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/mac/modules/System.h" +#import + + +#include +#include +#include +#include + + +namespace cc { +using OSType = System::OSType; + +OSType System::getOSType() const { + return OSType::MAC; +} + +std::string System::getDeviceModel() const { + struct utsname systemInfo; + uname(&systemInfo); + return systemInfo.machine; +} + +System::LanguageType System::getCurrentLanguage() const { + // get the current language and country config + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; + NSArray * languages = [defaults objectForKey:@"AppleLanguages"]; + NSString * currentLanguage = [languages objectAtIndex:0]; + + // get the current language code.(such as English is "en", Chinese is "zh" and so on) + NSDictionary *temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; + NSString * languageCode = [temp objectForKey:NSLocaleLanguageCode]; + + if ([languageCode isEqualToString:@"zh"]) return LanguageType::CHINESE; + if ([languageCode isEqualToString:@"en"]) return LanguageType::ENGLISH; + if ([languageCode isEqualToString:@"fr"]) return LanguageType::FRENCH; + if ([languageCode isEqualToString:@"it"]) return LanguageType::ITALIAN; + if ([languageCode isEqualToString:@"de"]) return LanguageType::GERMAN; + if ([languageCode isEqualToString:@"es"]) return LanguageType::SPANISH; + if ([languageCode isEqualToString:@"nl"]) return LanguageType::DUTCH; + if ([languageCode isEqualToString:@"ru"]) return LanguageType::RUSSIAN; + if ([languageCode isEqualToString:@"ko"]) return LanguageType::KOREAN; + if ([languageCode isEqualToString:@"ja"]) return LanguageType::JAPANESE; + if ([languageCode isEqualToString:@"hu"]) return LanguageType::HUNGARIAN; + if ([languageCode isEqualToString:@"pt"]) return LanguageType::PORTUGUESE; + if ([languageCode isEqualToString:@"ar"]) return LanguageType::ARABIC; + if ([languageCode isEqualToString:@"nb"]) return LanguageType::NORWEGIAN; + if ([languageCode isEqualToString:@"pl"]) return LanguageType::POLISH; + if ([languageCode isEqualToString:@"tr"]) return LanguageType::TURKISH; + if ([languageCode isEqualToString:@"uk"]) return LanguageType::UKRAINIAN; + if ([languageCode isEqualToString:@"ro"]) return LanguageType::ROMANIAN; + if ([languageCode isEqualToString:@"bg"]) return LanguageType::BULGARIAN; + return LanguageType::ENGLISH; +} + +std::string System::getCurrentLanguageCode() const { + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; + NSArray * languages = [defaults objectForKey:@"AppleLanguages"]; + NSString * currentLanguage = [languages objectAtIndex:0]; + return [currentLanguage UTF8String]; +} + +std::string System::getSystemVersion() const { + NSOperatingSystemVersion v = NSProcessInfo.processInfo.operatingSystemVersion; + char version[50] = {0}; + snprintf(version, sizeof(version), "%d.%d.%d", (int)v.majorVersion, (int)v.minorVersion, (int)v.patchVersion); + return version; +} + +bool System::openURL(const std::string &url) { + NSString *msg = [NSString stringWithCString:url.c_str() encoding:NSUTF8StringEncoding]; + NSURL * nsUrl = [NSURL URLWithString:msg]; + return [[NSWorkspace sharedWorkspace] openURL:nsUrl]; +} +} // namespace cc diff --git a/native/cocos/platform/mac/modules/SystemWindow.h b/native/cocos/platform/mac/modules/SystemWindow.h new file mode 100644 index 0000000000..c82e30c314 --- /dev/null +++ b/native/cocos/platform/mac/modules/SystemWindow.h @@ -0,0 +1,56 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include + +#include "platform/interfaces/modules/ISystemWindow.h" + +namespace cc { + +class SystemWindow : public ISystemWindow { +public: + SystemWindow(); + ~SystemWindow() override; + + bool createWindow(const char* title, + int x, int y, int w, + int h, int flags) override; + uintptr_t getWindowHandler() const override; + + Size getViewSize() const override; + /* + @brief enable/disable(lock) the cursor, default is enabled + */ + void setCursorEnabled(bool value) override; + void copyTextToClipboard(const std::string& text) override; + +private: + int32_t _width{0}; + int32_t _height{0}; + bool isInit{false}; +}; +} // namespace cc diff --git a/native/cocos/platform/mac/modules/SystemWindow.mm b/native/cocos/platform/mac/modules/SystemWindow.mm new file mode 100644 index 0000000000..f9012398f8 --- /dev/null +++ b/native/cocos/platform/mac/modules/SystemWindow.mm @@ -0,0 +1,73 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/mac/modules/SystemWindow.h" +#import +#include "platform/mac/AppDelegate.h" + + +namespace { + +} + +namespace cc { + +SystemWindow::SystemWindow() = default; + +SystemWindow::~SystemWindow() = default; + +bool SystemWindow::createWindow(const char *title, + int x, int y, int w, + int h, int flags) { + if(isInit) { + return true; + } + isInit = true; + _width = w; + _height = h; + AppDelegate *delegate = [[NSApplication sharedApplication] delegate]; + NSString * aString = [NSString stringWithUTF8String:title]; + [delegate createWindow:aString xPos:x yPos:y width:w height:h]; +} + +void SystemWindow::setCursorEnabled(bool value) { +} + +void SystemWindow::copyTextToClipboard(const std::string &text) { + NSPasteboard *pasteboard = [NSPasteboard generalPasteboard]; + [pasteboard clearContents]; + NSString *tmp = [NSString stringWithCString:text.c_str() encoding:NSUTF8StringEncoding]; + [pasteboard setString:tmp forType:NSPasteboardTypeString]; +} + +uintptr_t SystemWindow::getWindowHandler() const { + NSView *view = [[[[NSApplication sharedApplication] delegate] getWindow] contentView]; + return reinterpret_cast(view); +} + +SystemWindow::Size SystemWindow::getViewSize() const { + return Size{static_cast(_width), static_cast(_height)}; +} + +} diff --git a/native/cocos/platform/mac/modules/Vibrator.h b/native/cocos/platform/mac/modules/Vibrator.h new file mode 100644 index 0000000000..9a8ea1657d --- /dev/null +++ b/native/cocos/platform/mac/modules/Vibrator.h @@ -0,0 +1,44 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IVibrator.h" + +namespace cc { + +class Vibrator : public IVibrator { +public: + /** + * Vibrate for the specified amount of time. + * If vibrate is not supported, then invoking this method has no effect. + * Some platforms limit to a maximum duration of 5 seconds. + * Duration is ignored on iOS due to API limitations. + * @param duration The duration in seconds. + */ + void vibrate(float duration) override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/mac/modules/Vibrator.mm b/native/cocos/platform/mac/modules/Vibrator.mm new file mode 100644 index 0000000000..b3b26cee77 --- /dev/null +++ b/native/cocos/platform/mac/modules/Vibrator.mm @@ -0,0 +1,36 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/mac/modules/Vibrator.h" + +#include "base/Macros.h" + +namespace cc { + +void Vibrator::vibrate(float duration) { + CC_UNUSED_PARAM(duration); +} + +} diff --git a/native/cocos/platform/ohos/Application-ohos.cpp b/native/cocos/platform/ohos/Application-ohos.cpp deleted file mode 100644 index 78d7bc88f4..0000000000 --- a/native/cocos/platform/ohos/Application-ohos.cpp +++ /dev/null @@ -1,211 +0,0 @@ -/**************************************************************************** -Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. - -http://www.cocos.com - -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 -#include -#include -#include - -#include "audio/include/AudioEngine.h" -#include "base/Scheduler.h" -#include "cocos/bindings/event/EventDispatcher.h" -#include "cocos/bindings/jswrapper/SeApi.h" -#include "pipeline/Define.h" -#include "pipeline/RenderPipeline.h" -#include "platform/Application.h" -#include "platform/Device.h" -#include "platform/java/jni/JniHelper.h" -#include "platform/java/jni/JniImp.h" -#include "platform/ohos/jni/JniCocosAbility.h" -#include "renderer/GFXDeviceManager.h" - -#include - -#define LOGD(...) HILOG_DEBUG(LOG_APP, __VA_ARGS__) - -namespace { -bool setCanvasCallback(se::Object *global) { //NOLINT - auto viewLogicalSize = cc::Application::getInstance()->getViewLogicalSize(); - se::AutoHandleScope scope; - se::ScriptEngine * se = se::ScriptEngine::getInstance(); - auto * view = cc::cocosApp.pendingWindow; - std::stringstream ss; - { - auto windowPtr = reinterpret_cast(view); - ss << "window.innerWidth = " << static_cast(viewLogicalSize.x) << ";" - << "window.innerHeight = " << static_cast(viewLogicalSize.y) << ";" - << "window.windowHandler = "; - if (sizeof(windowPtr) == 8) { // use bigint - ss << static_cast(windowPtr) << "n;"; - } - if (sizeof(windowPtr) == 4) { - ss << static_cast(windowPtr) << ";"; - } - } - se->evalString(ss.str().c_str()); - - return true; -} -} // namespace - -namespace cc { - -Application * Application::instance = nullptr; -std::shared_ptr Application::scheduler = nullptr; - -Application::Application(int width, int height) { - Application::instance = this; - scheduler = std::make_shared(); - _viewLogicalSize.x = static_cast(width); - _viewLogicalSize.y = static_cast(height); -} - -Application::~Application() { -#if USE_AUDIO - AudioEngine::end(); -#endif - - pipeline::RenderPipeline::getInstance()->destroy(); - - EventDispatcher::destroy(); - se::ScriptEngine::destroyInstance(); - - gfx::DeviceManager::destroy(); - - Application::instance = nullptr; -} - -bool Application::init() { - se::ScriptEngine *se = se::ScriptEngine::getInstance(); - se->addRegisterCallback(setCanvasCallback); - - EventDispatcher::init(); - - return true; -} - -void Application::onPause() { -} - -void Application::onResume() { -} - -void Application::onClose() { -} - -void Application::setPreferredFramesPerSecond(int fps) { - if (fps == 0) { - return; - } - - _fps = fps; - _prefererredNanosecondsPerFrame = static_cast(1.0 / _fps * NANOSECONDS_PER_SECOND); //NOLINT(google-runtime-int) -} - -std::string Application::getCurrentLanguageCode() const { //NOLINT - return getCurrentLanguageCodeJNI(); -} - -bool Application::isDisplayStats() { //NOLINT - se::AutoHandleScope hs; - se::Value ret; - char commandBuf[100] = "cc.debug.isDisplayStats();"; - se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret); - return ret.toBoolean(); -} - -void Application::setDisplayStats(bool isShow) { //NOLINT - se::AutoHandleScope hs; - char commandBuf[100] = {0}; - sprintf(commandBuf, "cc.debug.setDisplayStats(%s);", isShow ? "true" : "false"); - se::ScriptEngine::getInstance()->evalString(commandBuf); -} - -void Application::setCursorEnabled(bool value) { -} - -Application::LanguageType Application::getCurrentLanguage() const { //NOLINT - std::string languageName = getCurrentLanguageJNI(); - const char * pLanguageName = languageName.c_str(); - LanguageType ret = LanguageType::ENGLISH; - - if (0 == strcmp("zh", pLanguageName)) { - ret = LanguageType::CHINESE; - } else if (0 == strcmp("en", pLanguageName)) { - ret = LanguageType::ENGLISH; - } else if (0 == strcmp("fr", pLanguageName)) { - ret = LanguageType::FRENCH; - } else if (0 == strcmp("it", pLanguageName)) { - ret = LanguageType::ITALIAN; - } else if (0 == strcmp("de", pLanguageName)) { - ret = LanguageType::GERMAN; - } else if (0 == strcmp("es", pLanguageName)) { - ret = LanguageType::SPANISH; - } else if (0 == strcmp("ru", pLanguageName)) { - ret = LanguageType::RUSSIAN; - } else if (0 == strcmp("nl", pLanguageName)) { - ret = LanguageType::DUTCH; - } else if (0 == strcmp("ko", pLanguageName)) { - ret = LanguageType::KOREAN; - } else if (0 == strcmp("ja", pLanguageName)) { - ret = LanguageType::JAPANESE; - } else if (0 == strcmp("hu", pLanguageName)) { - ret = LanguageType::HUNGARIAN; - } else if (0 == strcmp("pt", pLanguageName)) { - ret = LanguageType::PORTUGUESE; - } else if (0 == strcmp("ar", pLanguageName)) { - ret = LanguageType::ARABIC; - } else if (0 == strcmp("nb", pLanguageName)) { - ret = LanguageType::NORWEGIAN; - } else if (0 == strcmp("pl", pLanguageName)) { - ret = LanguageType::POLISH; - } else if (0 == strcmp("tr", pLanguageName)) { - ret = LanguageType::TURKISH; - } else if (0 == strcmp("uk", pLanguageName)) { - ret = LanguageType::UKRAINIAN; - } else if (0 == strcmp("ro", pLanguageName)) { - ret = LanguageType::ROMANIAN; - } else if (0 == strcmp("bg", pLanguageName)) { - ret = LanguageType::BULGARIAN; - } - return ret; -} - -Application::Platform Application::getPlatform() const { //NOLINT - return Platform::OHOS; -} - -bool Application::openURL(const std::string &url) { //NOLINT - return openURLJNI(url); -} - -void Application::copyTextToClipboard(const std::string &text) { //NOLINT - copyTextToClipboardJNI(text); -} - -std::string Application::getSystemVersion() { //NOLINT - return getSystemVersionJNI(); -} - -} // namespace cc diff --git a/native/cocos/platform/ohos/Device-ohos.cpp b/native/cocos/platform/ohos/Device-ohos.cpp deleted file mode 100644 index 33ede63889..0000000000 --- a/native/cocos/platform/ohos/Device-ohos.cpp +++ /dev/null @@ -1,142 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2016 Chukong Technologies Inc. -Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -http://www.cocos2d-x.org - -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 -#include -#include -#include -#include -#include "base/UTF8.h" -#include "platform/Device.h" -#include "platform/FileUtils.h" -#include "platform/java/jni/JniHelper.h" -#include "platform/ohos/jni/JniCocosAbility.h" - -#ifndef JCLS_HELPER - #define JCLS_HELPER "com/cocos/lib/CocosHelper" -#endif - -#ifndef JCLS_SENSOR - #define JCLS_SENSOR "com/cocos/lib/CocosSensorHandler" -#endif - -namespace { -cc::Device::MotionValue motionValue; - -// constant from Android API: -// reference: https://developer.android.com/reference/android/view/Surface#ROTATION_0 -enum Rotation { - ROTATION_0 = 0, - ROTATION_90, - ROTATION_180, - ROTATION_270 -}; -} // namespace - -namespace cc { - -int Device::getDPI() { - static int dpi = -1; - if (dpi == -1) { - dpi = JniHelper::callStaticIntMethod(JCLS_HELPER, "getDPI"); - } - return dpi; -} - -void Device::setAccelerometerEnabled(bool isEnabled) { - JniHelper::callStaticVoidMethod(JCLS_SENSOR, "setAccelerometerEnabled", isEnabled); -} - -void Device::setAccelerometerInterval(float interval) { - JniHelper::callStaticVoidMethod(JCLS_SENSOR, "setAccelerometerInterval", interval); -} - -const Device::MotionValue &Device::getDeviceMotionValue() { - float *v = JniHelper::callStaticFloatArrayMethod(JCLS_SENSOR, "getDeviceMotionValue"); - - if (v) { - motionValue.accelerationIncludingGravityX = v[0]; - motionValue.accelerationIncludingGravityY = v[1]; - motionValue.accelerationIncludingGravityZ = v[2]; - - motionValue.accelerationX = v[3]; - motionValue.accelerationY = v[4]; - motionValue.accelerationZ = v[5]; - - motionValue.rotationRateAlpha = v[6]; - motionValue.rotationRateBeta = v[7]; - motionValue.rotationRateGamma = v[8]; - } else { - memset(&motionValue, 0, sizeof(motionValue)); - } - return motionValue; -} - -Device::Orientation Device::getDeviceOrientation() { - int rotation = JniHelper::callStaticIntMethod(JCLS_HELPER, "getDeviceRotation"); - switch (rotation) { - case ROTATION_0: - return Orientation::PORTRAIT; - case ROTATION_90: - return Orientation::LANDSCAPE_RIGHT; - case ROTATION_180: - return Orientation::PORTRAIT_UPSIDE_DOWN; - case ROTATION_270: - default: - return Orientation::LANDSCAPE_LEFT; - } -} - -std::string Device::getDeviceModel() { - return JniHelper::callStaticStringMethod(JCLS_HELPER, "getDeviceModel"); -} - -void Device::setKeepScreenOn(bool keepScreenOn) { - // JniHelper::callStaticVoidMethod(JCLS_HELPER, "setKeepScreenOn", value); - // ANativeActivity_setWindowFlags(JniHelper::getAndroidApp()->activity, AWINDOW_FLAG_KEEP_SCREEN_ON, 0); -} - -void Device::vibrate(float duration) { - JniHelper::callStaticVoidMethod(JCLS_HELPER, "vibrate", duration); -} - -float Device::getBatteryLevel() { - return JniHelper::callStaticFloatMethod(JCLS_HELPER, "getBatteryLevel"); -} - -Device::NetworkType Device::getNetworkType() { - return static_cast(JniHelper::callStaticIntMethod(JCLS_HELPER, "getNetworkType")); -} - -cc::Vec4 Device::getSafeAreaEdge() { - float *data = JniHelper::callStaticFloatArrayMethod(JCLS_HELPER, "getSafeArea"); - return cc::Vec4(data[0], data[1], data[2], data[3]); -} - -float Device::getDevicePixelRatio() { - return 1; -} -} // namespace cc diff --git a/native/cocos/platform/ohos/OhosPlatform.cpp b/native/cocos/platform/ohos/OhosPlatform.cpp new file mode 100644 index 0000000000..915e8e38fe --- /dev/null +++ b/native/cocos/platform/ohos/OhosPlatform.cpp @@ -0,0 +1,81 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 + +#include "platform/UniversalPlatform.h" +#include "platform/java/jni/glue/JniNativeGlue.h" +#include "platform/ohos/OhosPlatform.h" +#include "platform/java/modules/SystemWindow.h" + +namespace cc { +OhosPlatform::OhosPlatform() { + _jniNativeGlue = JNI_NATIVE_GLUE(); +} + +int OhosPlatform::getSdkVersion() const { + return _jniNativeGlue->getSdkVersion(); +} + +int32_t OhosPlatform::run(int argc, const char** argv) { + std::thread mainLogicThread([this, argc, argv]() { + waitWindowInitialized(); + UniversalPlatform::run(argc, argv); + onDestory(); + }); + mainLogicThread.detach(); + _jniNativeGlue->waitRunning(); + return 0; +} + +void OhosPlatform::waitWindowInitialized() { + _jniNativeGlue->setRunning(true); + while (_jniNativeGlue->isRunning()) { + pollEvent(); + NativeWindowType* wndHandle = _jniNativeGlue->getWindowHandler(); + if (wndHandle != nullptr) { + break; + } + } + _jniNativeGlue->setEventDispatch(this); +} + +int32_t OhosPlatform::loop() { + while (_jniNativeGlue->isRunning()) { + pollEvent(); + runTask(); + } + return 0; +} + +void OhosPlatform::pollEvent() { + _jniNativeGlue->execCommand(); + if (!_jniNativeGlue->isPause()) { + std::this_thread::yield(); + } + _jniNativeGlue->flushTasksOnGameThread(); +} + +}; // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/ohos/OhosPlatform.h b/native/cocos/platform/ohos/OhosPlatform.h new file mode 100644 index 0000000000..3bb1d403c7 --- /dev/null +++ b/native/cocos/platform/ohos/OhosPlatform.h @@ -0,0 +1,45 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/UniversalPlatform.h" + +namespace cc { +class JniNativeGlue; +class OhosPlatform : public UniversalPlatform { +public: + OhosPlatform(); + void pollEvent() override; + int32_t run(int argc, const char** argv) override; + int getSdkVersion() const override; + int32_t loop() override; + +private: + void waitWindowInitialized(); + + JniNativeGlue* _jniNativeGlue; +}; +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/ohos/jni/JniCocosAbility.cpp b/native/cocos/platform/ohos/jni/JniCocosAbility.cpp index 398b05fcc7..064a858dbb 100644 --- a/native/cocos/platform/ohos/jni/JniCocosAbility.cpp +++ b/native/cocos/platform/ohos/jni/JniCocosAbility.cpp @@ -34,202 +34,48 @@ THE SOFTWARE. #include #include #include "base/Log.h" -#include "platform/Application.h" -#include "platform/android/View.h" + #include "platform/java/jni/JniHelper.h" +#include "platform/java/jni/glue/JniNativeGlue.h" #include "platform/ohos/FileUtils-ohos.h" #include "platform/ohos/jni/AbilityConsts.h" + #define LOGV(...) HILOG_INFO(LOG_APP, __VA_ARGS__) - -extern "C" cc::Application *cocos_main(int, int) __attribute__((weak)); //NOLINT symbol name - -namespace cc { -CocosApp cocosApp; -} - //NOLINTNEXTLINE using namespace cc::ohos; -namespace { -int messagePipe[2]; -int pipeRead = 0; -int pipeWrite = 0; -cc::Application *game = nullptr; -std::string moduleName{"entry"}; - -struct CommandMsg { - int cmd; - std::function callback; -}; - -void createGame(NativeLayer *window) { - int width = NativeLayerHandle(window, NativeLayerOps::GET_WIDTH); - int height = NativeLayerHandle(window, NativeLayerOps::GET_HEIGHT); - game = cocos_main(width, height); - game->init(); -} - -void writeCommandAsync(int cmd) { - CommandMsg msg{.cmd = cmd, .callback = nullptr}; - write(pipeWrite, &msg, sizeof(msg)); -} - -void writeCommandSync(int cmd) { - std::promise fu; - CommandMsg msg{.cmd = cmd, .callback = [&fu]() { - fu.set_value(); - }}; - write(pipeWrite, &msg, sizeof(msg)); - fu.get_future().get(); -} - -int readCommand(CommandMsg *msg) { - return read(pipeRead, msg, sizeof(*msg)); -} - -void handlePauseResume(int8_t cmd) { - LOGV("activityState=%d", cmd); - cc::cocosApp.activityState = cmd; -} - -void preExecCmd(int cmd) { - switch (cmd) { - case ABILITY_CMD_INIT_WINDOW: { - LOGV("ABILITY_CMD_INIT_WINDOW"); - // cc::cocosApp.window = cc::cocosApp.pendingWindow; - cc::cocosApp.animating = true; - - if (!game) { - createGame(cc::cocosApp.pendingWindow); - } - } break; - case ABILITY_CMD_TERM_WINDOW: - LOGV("ABILITY_CMD_TERM_WINDOW"); - cc::cocosApp.animating = false; - break; - case ABILITY_CMD_RESUME: - LOGV("ABILITY_CMD_RESUME"); - handlePauseResume(cmd); - break; - case ABILITY_CMD_PAUSE: - LOGV("ABILITY_CMD_PAUSE"); - handlePauseResume(cmd); - break; - case ABILITY_CMD_DESTROY: - LOGV("ABILITY_CMD_DESTROY"); - cc::cocosApp.destroyRequested = true; - break; - default: - break; - } -} - -void postExecCmd(int cmd) { - switch (cmd) { - case ABILITY_CMD_TERM_WINDOW: - cc::cocosApp.pendingWindow = nullptr; - break; - default: - break; - } -} - -void glThreadEntry() { - cc::cocosApp.glThreadPromise.set_value(); - cc::cocosApp.running = true; - - int cmd = 0; - CommandMsg msg; - while (true) { - if (readCommand(&msg) > 0) { - cmd = msg.cmd; - preExecCmd(cmd); - cc::View::engineHandleCmd(cmd); - postExecCmd(cmd); - if (msg.callback) { - msg.callback(); - } - } - - if (!cc::cocosApp.animating || ABILITY_CMD_PAUSE == cc::cocosApp.activityState) { - std::this_thread::yield(); - } - - if (game && cc::cocosApp.animating) { - // Handle java events send by UI thread. Input events are handled here too. - cc::JniHelper::callStaticVoidMethod("com.cocos.lib.CocosHelper", - "flushTasksOnGameThread"); - game->tick(); - } - - if (cc::cocosApp.destroyRequested) break; - } - - close(pipeRead); - close(pipeWrite); - - delete game; - game = nullptr; -} - -inline void termAndSetPendingWindow(NativeLayer *window) { - if (cc::cocosApp.pendingWindow) { - writeCommandSync(ABILITY_CMD_TERM_WINDOW); - } - cc::cocosApp.pendingWindow = window; -} - -inline void initWithPendingWindow() { - if (cc::cocosApp.pendingWindow) { - writeCommandSync(ABILITY_CMD_INIT_WINDOW); - } -} - -} // namespace - extern "C" { //NOLINTNEXTLINE JNI function name JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onCreateNative(JNIEnv *env, jobject obj, jobject ability, jstring moduleNameJ, jstring assetPath, jobject resourceManager, jint sdkVersion) { - if (cc::cocosApp.running) { + if (JNI_NATIVE_GLUE()->isRunning()) { return; } - - std::string assetPathClone; - - jboolean isCopy = false; - const char *assetPathStr = env->GetStringUTFChars(assetPath, &isCopy); - const char *moduleNameStr = env->GetStringUTFChars(moduleNameJ, &isCopy); - assetPathClone = assetPathStr; - moduleName = moduleNameStr; - - cc::cocosApp.sdkVersion = sdkVersion; cc::JniHelper::init(env, ability); - cc::cocosApp.resourceManager = InitNativeResourceManager(env, resourceManager); + JNI_NATIVE_GLUE()->setSdkVersion(sdkVersion); + + ResourceManager *objResourceManager = InitNativeResourceManager(env, resourceManager); + JNI_NATIVE_GLUE()->setResourceManager(objResourceManager); + + jboolean isCopy = false; + std::string assetPathClone; + const char *assetPathStr = env->GetStringUTFChars(assetPath, &isCopy); + assetPathClone = assetPathStr; if (isCopy) { env->ReleaseStringUTFChars(assetPath, assetPathStr); assetPathStr = nullptr; } + std::string moduleName{"entry"}; + const char *moduleNameStr = env->GetStringUTFChars(moduleNameJ, &isCopy); + moduleName = moduleNameStr; if (isCopy) { env->ReleaseStringUTFChars(moduleNameJ, moduleNameStr); + moduleNameStr = nullptr; } - cc::FileUtilsOHOS::initResourceManager(cc::cocosApp.resourceManager, assetPathClone, moduleName); - - if (pipe(messagePipe)) { - LOGV("Can not create pipe: %s", strerror(errno)); - } - pipeRead = messagePipe[0]; - pipeWrite = messagePipe[1]; - if (fcntl(pipeRead, F_SETFL, O_NONBLOCK) < 0) { - LOGV("Can not make pipe read to non blocking mode."); - } - - std::thread glThread(glThreadEntry); - glThread.detach(); - - cc::cocosApp.glThreadPromise.get_future().get(); + cc::FileUtilsOHOS::initResourceManager(objResourceManager, assetPathClone, moduleName); + JNI_NATIVE_GLUE()->start(0, nullptr); } JNIEXPORT void JNICALL @@ -239,42 +85,29 @@ Java_com_cocos_lib_CocosAbilitySlice_onSurfaceCreatedNative(JNIEnv *env, jobject JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onSurfaceChangedNative(JNIEnv *env, jobject obj, jobject surface, jint width, //NOLINT JNI function name jint height) { //NOLINT JNI function name - termAndSetPendingWindow(GetNativeLayer(env, surface)); - initWithPendingWindow(); + JNI_NATIVE_GLUE()->setWindowHandler(GetNativeLayer(env, surface)); } JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onSurfaceDestroyNative(JNIEnv *env, jobject obj) { //NOLINT JNI function name - termAndSetPendingWindow(nullptr); + JNI_NATIVE_GLUE()->setWindowHandler(nullptr); } JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onStartNative(JNIEnv *env, jobject obj) { //NOLINT JNI function name } JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onPauseNative(JNIEnv *env, jobject obj) { //NOLINT JNI function name - writeCommandSync(ABILITY_CMD_PAUSE); + JNI_NATIVE_GLUE()->onPause(); } JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onResumeNative(JNIEnv *env, jobject obj) { //NOLINT JNI function name - writeCommandSync(ABILITY_CMD_RESUME); + JNI_NATIVE_GLUE()->onResume(); } JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onStopNative(JNIEnv *env, jobject obj) { //NOLINT JNI function name } JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onLowMemoryNative(JNIEnv *env, jobject obj) { //NOLINT JNI function name - writeCommandSync(ABILITY_CMD_LOW_MEMORY); -} - -JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onOrientationChangedNative(JNIEnv *env, jobject obj, jint orientation, jint width, jint height) { //NOLINT JNI function name - static jint pOrientation = 0; - static jint pWidth = 0; - static jint pHeight = 0; - if (game && (pOrientation != orientation || pWidth != width || pHeight != height)) { - cc::EventDispatcher::dispatchResizeEvent(width, height); - pOrientation = orientation; - pHeight = height; - pWidth = width; - } + JNI_NATIVE_GLUE()->onLowMemory(); } JNIEXPORT void JNICALL diff --git a/native/cocos/platform/ohos/jni/JniCocosAbility.h b/native/cocos/platform/ohos/jni/JniCocosAbility.h index 4f6f8d76eb..f40196b834 100644 --- a/native/cocos/platform/ohos/jni/JniCocosAbility.h +++ b/native/cocos/platform/ohos/jni/JniCocosAbility.h @@ -30,28 +30,27 @@ THE SOFTWARE. #include #include - #include namespace cc { -struct CocosApp { - ResourceManager *resourceManager = nullptr; - // NativeLayer *window = nullptr; - int sdkVersion = 0; +// struct CocosApp { +// ResourceManager *resourceManager = nullptr; +// // NativeLayer *window = nullptr; +// int sdkVersion = 0; - std::promise glThreadPromise; +// std::promise glThreadPromise; - NativeLayer *pendingWindow = nullptr; - bool destroyRequested = false; - bool animating = true; - bool running = false; - bool surfaceInited = false; +// NativeLayer *pendingWindow = nullptr; +// bool destroyRequested = false; +// bool animating = true; +// bool running = false; +// bool surfaceInited = false; - // Current state of the app's activity. May be either APP_CMD_RESUME, APP_CMD_PAUSE. - int activityState = 0; -}; +// // Current state of the app's activity. May be either APP_CMD_RESUME, APP_CMD_PAUSE. +// int activityState = 0; +// }; -extern CocosApp cocosApp; +// extern CocosApp cocosApp; } // namespace cc diff --git a/native/cocos/platform/ohos/jni/JniCocosSurfaceView.cpp b/native/cocos/platform/ohos/jni/JniCocosSurfaceView.cpp new file mode 100644 index 0000000000..9b576de24c --- /dev/null +++ b/native/cocos/platform/ohos/jni/JniCocosSurfaceView.cpp @@ -0,0 +1,21 @@ +#include +#include +#include +#include "platform/BasePlatform.h" +#include "platform/java/jni/glue/JniNativeGlue.h" + +JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onOrientationChangedNative(JNIEnv *env, jobject obj, jint orientation, jint width, jint height) { //NOLINT JNI function name + static jint pOrientation = 0; + static jint pWidth = 0; + static jint pHeight = 0; + if (pOrientation != orientation || pWidth != width || pHeight != height) { + cc::WindowEvent ev; + ev.type = cc::WindowEvent::Type::SIZE_CHANGED; + ev.width = width; + ev.height = height; + JNI_NATIVE_GLUE()->dispatchEvent(ev); + pOrientation = orientation; + pHeight = height; + pWidth = width; + } +} \ No newline at end of file diff --git a/native/cocos/platform/ohos/jni/JniInteraction.cpp b/native/cocos/platform/ohos/jni/JniInteraction.cpp new file mode 100644 index 0000000000..6c595ae908 --- /dev/null +++ b/native/cocos/platform/ohos/jni/JniInteraction.cpp @@ -0,0 +1,237 @@ +/**************************************************************************** + Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/ohos/jni/JniInteraction.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "JniCocosActivity.h" +#include "cocos/bindings/event/CustomEventTypes.h" + +#include "cocos/bindings/event/EventDispatcher.h" +#include "platform/android/FileUtils-android.h" +#include "platform/android/jni/JniCocosActivity.h" +#include "platform/java/jni/JniHelper.h" + +namespace cc { +JniInteraction::JniInteraction() = default; + +JniInteraction* JniInteraction::getInstance() { + static JniInteraction cocosInstaction; + return &cocosInstaction; +} + +void JniInteraction::init() { +} + +void JniInteraction::setObbPath(const std::string& path) { + _obbPath = path; +} + +void JniInteraction::setAAssetManager(AAssetManager* assetManager) { + _assetManager = assetManager; +} + +void JniInteraction::setResourceManager(ResourceManager* assetManager) { + _resourceManager = assetManager; +} + +void JniInteraction::setWindow(ANativeWindow* window) { + std::unique_lock lk(_mutex); + if (_pendingWindow) { + writeCommand(APP_CMD_TERM_WINDOW); + } + _pendingWindow = window; + if (window) { + writeCommand(APP_CMD_INIT_WINDOW); + } + while (_window != _pendingWindow) { + _cond.wait(lk); + } +} + +void JniInteraction::preExecCmd(int8_t cmd) { + switch (cmd) { + case APP_CMD_INIT_WINDOW: { + LOGV("APP_CMD_INIT_WINDOW"); + std::unique_lock lk(_mutex); + _window = _pendingWindow; + lk.unlock(); + _cond.notify_all(); + setAnimating(true); + } break; + case APP_CMD_TERM_WINDOW: + LOGV("APP_CMD_TERM_WINDOW"); + setAnimating(false); + _cond.notify_all(); + break; + case APP_CMD_RESUME: + LOGV("APP_CMD_RESUME"); + handlePauseResume(cmd); + break; + case APP_CMD_PAUSE: + LOGV("APP_CMD_PAUSE"); + handlePauseResume(cmd); + break; + default: + break; + } +} + +void JniInteraction::postExecCmd(int8_t cmd) { + switch (cmd) { + case APP_CMD_TERM_WINDOW: { + std::unique_lock lk(_mutex); + _window = nullptr; + lk.unlock(); + _cond.notify_all(); + } break; + default: + break; + } +} + +void JniInteraction::setAppState(int8_t cmd) { + std::unique_lock lk(_mutex); + writeCommand(cmd); + while (_appState != cmd) { + _cond.wait(lk); + } +} + +void JniInteraction::handlePauseResume(int8_t cmd) { + LOGV("appState=%d", cmd); + std::unique_lock lk(_mutex); + _appState = static_cast(cmd); + lk.unlock(); + _cond.notify_all(); +} + +void JniInteraction::flushTasksOnGameThread() const { + if (getAnimating()) { + // Handle java events send by UI thread. Input events are handled here too. + flushTasksOnGameThreadJNI(); + } +} + +void JniInteraction::setRunning(bool isRunning) { + std::unique_lock lk(_mutex); + _running = isRunning; + lk.unlock(); + _cond.notify_all(); + //_systemWindow = _platform->getInterfaces(); +} + +void JniInteraction::waitRunning() { + std::unique_lock lk(_mutex); + while (!_running) { + _cond.wait(lk); + } +} + +bool JniInteraction::isRunning() { + std::unique_lock lk(_mutex); + return _running; +} + +ANativeWindow* JniInteraction::getWindowHandle() { + std::unique_lock lk(_mutex); + return _window; +} + +void JniInteraction::execCommand() { + int8_t cmd = 0; + if (readCommand(cmd) > 0) { + preExecCmd(cmd); + engineHandleCmd(cmd); + postExecCmd(cmd); + } +} + +bool JniInteraction::isPause() const { + if (!getAnimating()) { + return true; + } + if (_appState == APP_CMD_PAUSE) { + return true; + } + return false; +} + +void JniInteraction::engineHandleCmd(int cmd) { + static bool isWindowInitialized = false; + // Handle CMD here if needed. + switch (cmd) { + case APP_CMD_INIT_WINDOW: { + if (!isWindowInitialized) { + isWindowInitialized = true; + return; + } + cc::CustomEvent event; + event.name = EVENT_RECREATE_WINDOW; + event.args->ptrVal = reinterpret_cast(getWindowHandle()); + dispatchEvent(event); + } break; + case APP_CMD_TERM_WINDOW: { + cc::CustomEvent event; + event.name = EVENT_DESTROY_WINDOW; + event.args->ptrVal = reinterpret_cast(getWindowHandle()); + dispatchEvent(event); + } break; + case APP_CMD_RESUME: { + WindowEvent ev; + ev.type = WindowEvent::Type::SHOW; + dispatchEvent(ev); + } break; + case APP_CMD_PAUSE: { + WindowEvent ev; + ev.type = WindowEvent::Type::HIDDEN; + dispatchEvent(ev); + } break; + case APP_CMD_DESTROY: { + LOGV("APP_CMD_DESTROY"); + WindowEvent ev; + ev.type = WindowEvent::Type::CLOSE; + dispatchEvent(ev); + } break; + case APP_CMD_LOW_MEMORY: { + DeviceEvent ev; + ev.type = DeviceEvent::Type::DEVICE_MEMORY; + dispatchEvent(ev); + break; + } + default: + break; + } +} + +} // namespace cc diff --git a/native/cocos/platform/ohos/jni/JniNativeGlue.cpp b/native/cocos/platform/ohos/jni/JniNativeGlue.cpp new file mode 100644 index 0000000000..4e82b36a08 --- /dev/null +++ b/native/cocos/platform/ohos/jni/JniNativeGlue.cpp @@ -0,0 +1,224 @@ +/**************************************************************************** + Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/android/jni/glue/JniNativeGlue.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "cocos/bindings/event/CustomEventTypes.h" +#include "platform/android/jni/JniCocosActivity.h" + + +#include "cocos/bindings/event/EventDispatcher.h" +#include "platform/android/FileUtils-android.h" +#include "platform/android/jni/JniCocosActivity.h" +#include "platform/java/jni/JniHelper.h" + +namespace cc { +JniInteraction::JniInteraction() = default; + +JniInteraction* JniInteraction::getInstance() { + static JniInteraction cocosInstaction; + return &cocosInstaction; +} + +void JniInteraction::init() { +} + +void JniInteraction::setObbPath(const std::string& path) { + _obbPath = path; +} + +void JniInteraction::setAAssetManager(AAssetManager* assetManager) { + _assetManager = assetManager; +} + +void JniInteraction::setWindow(ANativeWindow* window) { + if (_pendingWindow) { + writeCommandSync(ABILITY_CMD_TERM_WINDOW); + } + _pendingWindow = window; +} + +void JniInteraction::initWithPendingWindow() { + if (_pendingWindow) { + writeCommandSync(ABILITY_CMD_INIT_WINDOW); + } +} + +void JniInteraction::preExecCmd(int8_t cmd) { + switch (cmd) { + case ABILITY_CMD_INIT_WINDOW: { + LOGV("ABILITY_CMD_INIT_WINDOW"); + _window = _pendingWindow; + setAnimating(true); + } break; + case ABILITY_CMD_TERM_WINDOW: + LOGV("ABILITY_CMD_TERM_WINDOW"); + setAnimating(false); + break; + case ABILITY_CMD_RESUME: + LOGV("ABILITY_CMD_RESUME"); + handlePauseResume(cmd); + break; + case ABILITY_CMD_PAUSE: + LOGV("ABILITY_CMD_PAUSE"); + handlePauseResume(cmd); + break; + case ABILITY_CMD_DESTROY: + LOGV("ABILITY_CMD_DESTROY"); + cc::cocosApp.destroyRequested = true; + break; + default: + break; + } +} + +void JniInteraction::postExecCmd(int8_t cmd) { + switch (cmd) { + case ABILITY_CMD_TERM_WINDOW: { + _window = nullptr; + _pendingWindow = nullptr; + } break; + default: + break; + } +} + +void JniInteraction::setAppState(int8_t cmd) { + /* + std::unique_lock lk(_mutex); + writeCommand(cmd); + while (_appState != cmd) { + _cond.wait(lk); + } + */ + writeCommandSync(cmd); +} + +void JniInteraction::handlePauseResume(int8_t cmd) { + LOGV("appState=%d", cmd); + _appState = static_cast(cmd); +} + +void JniInteraction::flushTasksOnGameThread() const { + if (getAnimating()) { + // Handle java events send by UI thread. Input events are handled here too. + flushTasksOnGameThreadJNI(); + } +} + +void JniInteraction::setRunning(bool isRunning) { + _ThreadPromise.set_value(); + _running = isRunning; + //_systemWindow = _platform->getInterfaces(); +} + +void JniInteraction::waitRunning() { + _ThreadPromise.get_future().get(); +} + +bool JniInteraction::isRunning() { + return _running; +} + +ANativeWindow* JniInteraction::getWindowHandle() { + return _window; +} + +void JniInteraction::execCommand() { + CommandMsg msg; + if (readCommand(&msg) > 0) { + preExecCmd(msg.cmd); + engineHandleCmd(msg.cmd); + postExecCmd(msg.cmd); + } +} + +bool JniInteraction::isPause() const { + if (!getAnimating()) { + return true; + } + if (_appState == APP_CMD_PAUSE) { + return true; + } + return false; +} + +void JniInteraction::engineHandleCmd(int cmd) { + static bool isWindowInitialized = false; + // Handle CMD here if needed. + switch (cmd) { + case APP_CMD_INIT_WINDOW: { + if (!isWindowInitialized) { + isWindowInitialized = true; + return; + } + cc::CustomEvent event; + event.name = EVENT_RECREATE_WINDOW; + event.args->ptrVal = reinterpret_cast(getWindowHandle()); + dispatchEvent(event); + } break; + case APP_CMD_TERM_WINDOW: { + cc::CustomEvent event; + event.name = EVENT_DESTROY_WINDOW; + event.args->ptrVal = reinterpret_cast(getWindowHandle()); + dispatchEvent(event); + } break; + case APP_CMD_RESUME: { + WindowEvent ev; + ev.type = WindowEvent::Type::SHOW; + dispatchEvent(ev); + } break; + case APP_CMD_PAUSE: { + WindowEvent ev; + ev.type = WindowEvent::Type::HIDDEN; + dispatchEvent(ev); + } break; + case APP_CMD_DESTROY: { + LOGV("APP_CMD_DESTROY"); + WindowEvent ev; + ev.type = WindowEvent::Type::CLOSE; + dispatchEvent(ev); + } break; + case APP_CMD_LOW_MEMORY: { + DeviceEvent ev; + ev.type = DeviceEvent::Type::DEVICE_MEMORY; + dispatchEvent(ev); + break; + } + default: + break; + } +} + +} // namespace cc diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/JsbBridge.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/JsbBridge.java deleted file mode 100644 index 375ae8eaa4..0000000000 --- a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/JsbBridge.java +++ /dev/null @@ -1,61 +0,0 @@ -/**************************************************************************** - Copyright (c) 2018-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -package com.cocos.lib; - -public class JsbBridge { - public interface ICallback{ - /** - * Applies this callback to the given argument. - * - * @param arg0 as input - * @param arg1 as input - */ - void onScript(String arg0, String arg1); - } - private static ICallback callback; - - private static void callByScript(String arg0, String arg1){ - if(JsbBridge.callback != null) - callback.onScript(arg0, arg1); - } - - /**Add a callback which you would like to apply - * @param f ICallback, the method which will be actually applied. multiple calls will override - * */ - public static void setCallback(ICallback f){ - JsbBridge.callback = f; - } - /** - * Java dispatch Js event, use native c++ code - * @param arg0 input values - */ - private static native void nativeSendToScript(String arg0, String arg1); - public static void sendToScript(String arg0, String arg1){ - nativeSendToScript(arg0, arg1); - } - public static void sendToScript(String arg0){ - nativeSendToScript(arg0, null); - } -} \ No newline at end of file diff --git a/native/cocos/platform/ohos/modules/Screen.cpp b/native/cocos/platform/ohos/modules/Screen.cpp new file mode 100644 index 0000000000..beeffc21fe --- /dev/null +++ b/native/cocos/platform/ohos/modules/Screen.cpp @@ -0,0 +1,39 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/ohos/modules/Screen.h" +#include "platform/java/jni/JniImp.h" + +namespace cc { + +int Screen::getDPI() const { + static int dpi = -1; + if (dpi == -1) { + dpi = getDPIJNI(); + } + return dpi; +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/ohos/modules/Screen.h b/native/cocos/platform/ohos/modules/Screen.h new file mode 100644 index 0000000000..38bd7e620c --- /dev/null +++ b/native/cocos/platform/ohos/modules/Screen.h @@ -0,0 +1,37 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/java/modules/CommonScreen.h" + +namespace cc { + +class Screen : public CommonScreen { +public: + int getDPI() const override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/ohos/modules/System.cpp b/native/cocos/platform/ohos/modules/System.cpp new file mode 100644 index 0000000000..5a70ebd3a7 --- /dev/null +++ b/native/cocos/platform/ohos/modules/System.cpp @@ -0,0 +1,38 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/ohos/modules/System.h" + + +namespace cc { +System::System() = default; +System::~System() = default; + +System::OSType System::getOSType() const { + return OSType::OHOS; +} + + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/ohos/modules/System.h b/native/cocos/platform/ohos/modules/System.h new file mode 100644 index 0000000000..680a500217 --- /dev/null +++ b/native/cocos/platform/ohos/modules/System.h @@ -0,0 +1,42 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/java/modules/CommonSystem.h" + +class ANativeWindow; + +namespace cc { + +class System : public CommonSystem { +public: + System(); + ~System() override; + + OSType getOSType() const override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/qnx/FileUtils-qnx.cpp b/native/cocos/platform/qnx/FileUtils-qnx.cpp new file mode 100644 index 0000000000..cc1ec54644 --- /dev/null +++ b/native/cocos/platform/qnx/FileUtils-qnx.cpp @@ -0,0 +1,124 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "FileUtils-qnx.h" +#include +#include +#include +#include +#include +#include "base/Log.h" + +#define DECLARE_GUARD std::lock_guard mutexGuard(_mutex) +#ifndef CC_RESOURCE_FOLDER_LINUX + #define CC_RESOURCE_FOLDER_LINUX ("/Resources/") +#endif + +namespace cc { + +FileUtils *FileUtils::getInstance() { + if (FileUtils::sharedFileUtils == nullptr) { + FileUtils::sharedFileUtils = new FileUtilsQNX(); + if (!FileUtils::sharedFileUtils->init()) { + delete FileUtils::sharedFileUtils; + FileUtils::sharedFileUtils = nullptr; + CC_LOG_DEBUG("ERROR: Could not init CCFileUtilsQNX"); + } + } + return FileUtils::sharedFileUtils; +} + +bool FileUtilsQNX::init() { + // get application path + // In QNX /proc/self/exefile is not a symbolic link; It's a regular file. + std::ifstream file("/proc/self/exefile"); + if (!file) { + return false; + } + std::string appPath; + std::getline(file, appPath); + if (appPath.empty()) { + return false; + } + _defaultResRootPath = appPath.substr(0, appPath.find_last_of('/')); + _defaultResRootPath += CC_RESOURCE_FOLDER_LINUX; + + // Set writable path to $XDG_CONFIG_HOME or ~/.config// if $XDG_CONFIG_HOME not exists. + const char *xdg_config_path = getenv("XDG_CONFIG_HOME"); + std::string xdgConfigPath; + if (xdg_config_path == NULL) { + xdg_config_path = getenv("HOME"); + if (xdg_config_path) { + xdgConfigPath = xdg_config_path; + } +#if _DEBUG + // In qnx debugging mode, the environment variables of HOME cannot be obtained. + // To facilitate debugging. Set a default directory + if (!xdg_config_path) { + // Set up a user directory and resources in the same directory. + xdgConfigPath = "/data/home/root"; + + // You can get the current application directory through API + // char* buf = getcwd(NULL, 0); + // xdgConfigPath = buf; + // free(buf); + } +#endif + xdgConfigPath += "/.config"; + } else { + xdgConfigPath = xdg_config_path; + } + + _writablePath = xdgConfigPath; + _writablePath += appPath.substr(appPath.find_last_of('/')); + _writablePath += "/"; + + return FileUtils::init(); +} + +bool FileUtilsQNX::isFileExistInternal(const std::string &filename) const { + if (filename.empty()) { + return false; + } + + std::string strPath = filename; + if (!isAbsolutePath(strPath)) { // Not absolute path, add the default root path at the beginning. + strPath.insert(0, _defaultResRootPath); + } + + struct stat sts; + return (stat(strPath.c_str(), &sts) == 0) && S_ISREG(sts.st_mode); +} + +std::string FileUtilsQNX::getWritablePath() const { + struct stat st; + stat(_writablePath.c_str(), &st); + if (!S_ISDIR(st.st_mode)) { + mkdir(_writablePath.c_str(), 0744); + } + + return _writablePath; +} + +} // namespace cc diff --git a/native/cocos/platform/qnx/FileUtils-qnx.h b/native/cocos/platform/qnx/FileUtils-qnx.h new file mode 100644 index 0000000000..640af73ea3 --- /dev/null +++ b/native/cocos/platform/qnx/FileUtils-qnx.h @@ -0,0 +1,40 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/FileUtils.h" +namespace cc { +class FileUtilsQNX : public FileUtils { +public: + friend class FileUtils; + bool isFileExistInternal(const std::string &filename) const override; + std::string getWritablePath() const override; + bool init() override; + +private: + std::string _writablePath; +}; +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/qnx/QNXPlatform.cpp b/native/cocos/platform/qnx/QNXPlatform.cpp new file mode 100644 index 0000000000..bac44ccb5a --- /dev/null +++ b/native/cocos/platform/qnx/QNXPlatform.cpp @@ -0,0 +1,426 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/qnx/QnxPlatform.h" + +#include +#include + +#include "SDL2/SDL.h" +#include "SDL2/SDL_main.h" +#include "SDL2/SDL_sysvideo.h" +#include "SDL2/SDL_syswm.h" + + +#include "platform/interfaces/OSInterface.h" +#include "platform/interfaces/modules/ISystemWindow.h" + +namespace { + +std::unordered_map gKeyMap = { + {SDLK_APPLICATION, cc::KeyCode::CONTEXT_MENU}, + {SDLK_SCROLLLOCK, cc::KeyCode::SCROLLLOCK}, + {SDLK_PAUSE, cc::KeyCode::PAUSE}, + {SDLK_PRINTSCREEN, cc::KeyCode::PRINT_SCREEN}, + {SDLK_INSERT, cc::KeyCode::INSERT}, + {SDLK_ESCAPE, cc::KeyCode::ESCAPE}, + {SDLK_MINUS, cc::KeyCode::MINUS}, + {SDLK_LSHIFT, cc::KeyCode::SHIFT_LEFT}, + {SDLK_RSHIFT, cc::KeyCode::SHIFT_RIGHT}, + {SDLK_EQUALS, cc::KeyCode::EQUAL}, + {SDLK_BACKSLASH, cc::KeyCode::BACKSLASH}, + {SDLK_BACKQUOTE, cc::KeyCode::BACKQUOTE}, + {SDLK_BACKSPACE, cc::KeyCode::BACKSPACE}, + {SDLK_RETURN, cc::KeyCode::ENTER}, + {SDLK_RETURN2, cc::KeyCode::ENTER}, + {SDLK_LEFTBRACKET, cc::KeyCode::BRACKET_LEFT}, + {SDLK_RIGHTBRACKET, cc::KeyCode::BRACKET_RIGHT}, + {SDLK_SEMICOLON, cc::KeyCode::SEMICOLON}, + {SDLK_QUOTE, cc::KeyCode::QUOTE}, + {SDLK_TAB, cc::KeyCode::TAB}, + {SDLK_LCTRL, cc::KeyCode::CONTROL_LEFT}, + {SDLK_RCTRL, cc::KeyCode::CONTROL_RIGHT}, + {SDLK_LALT, cc::KeyCode::ALT_LEFT}, + {SDLK_RALT, cc::KeyCode::ALT_RIGHT}, + {SDLK_LEFT, cc::KeyCode::ARROW_LEFT}, + {SDLK_RIGHT, cc::KeyCode::ARROW_RIGHT}, + {SDLK_UP, cc::KeyCode::ARROW_UP}, + {SDLK_DOWN, cc::KeyCode::ARROW_DOWN}, + {SDLK_KP_ENTER, cc::KeyCode::NUMPAD_ENTER}, + {SDLK_KP_PLUS, cc::KeyCode::NUMPAD_PLUS}, + {SDLK_KP_MULTIPLY, cc::KeyCode::NUMPAD_MULTIPLY}, + {SDLK_KP_DIVIDE, cc::KeyCode::NUMPAD_DIVIDE}, + {SDLK_KP_MINUS, cc::KeyCode::NUMPAD_MINUS}, + {SDLK_KP_PERIOD, cc::KeyCode::NUMPAD_DECIMAL}, + {SDLK_KP_BACKSPACE, cc::KeyCode::BACKSPACE}, + {SDLK_NUMLOCKCLEAR, cc::KeyCode::NUM_LOCK}, + {SDLK_HOME, cc::KeyCode::HOME}, + {SDLK_PAGEUP, cc::KeyCode::PAGE_UP}, + {SDLK_PAGEDOWN, cc::KeyCode::PAGE_DOWN}, + {SDLK_END, cc::KeyCode::END}, + {SDLK_COMMA, cc::KeyCode::COMMA}, + {SDLK_PERIOD, cc::KeyCode::PERIOD}, + {SDLK_SLASH, cc::KeyCode::SLASH}, + {SDLK_SPACE, cc::KeyCode::SPACE}, + {SDLK_DELETE, cc::KeyCode::DELETE_KEY}, + {SDLK_CAPSLOCK, cc::KeyCode::CAPS_LOCK}, + {SDLK_KP_0, cc::KeyCode::NUMPAD_0}, + {SDLK_KP_1, cc::KeyCode::NUMPAD_1}, + {SDLK_KP_2, cc::KeyCode::NUMPAD_2}, + {SDLK_KP_3, cc::KeyCode::NUMPAD_3}, + {SDLK_KP_4, cc::KeyCode::NUMPAD_4}, + {SDLK_KP_5, cc::KeyCode::NUMPAD_5}, + {SDLK_KP_6, cc::KeyCode::NUMPAD_6}, + {SDLK_KP_7, cc::KeyCode::NUMPAD_7}, + {SDLK_KP_8, cc::KeyCode::NUMPAD_8}, + {SDLK_KP_9, cc::KeyCode::NUMPAD_9}}; + +int sdlKeycodeToCocosCode(int sdlCode, int mode) { + auto it = gKeyMap.find(sdlCode); + if (it != gKeyMap.end()) { + return static_cast(it->second); + } + + if (sdlCode >= SDLK_F1 && sdlCode <= SDLK_F12) { + // F1 ~ F12 + return 112 + (sdlCode - SDLK_F1); + } else { + int code = sdlCode & (~(1 << 30)); + if (code >= SDLK_a && code <= SDLK_z) { + return 'A' + (code - SDLK_a); + } else { + return code; + } + } +} + +std::unordered_map gWindowFlagMap = { + {cc::ISystemWindow::CC_WINDOW_FULLSCREEN, SDL_WINDOW_FULLSCREEN}, + {cc::ISystemWindow::CC_WINDOW_OPENGL, SDL_WINDOW_OPENGL}, + {cc::ISystemWindow::CC_WINDOW_SHOWN, SDL_WINDOW_SHOWN}, + {cc::ISystemWindow::CC_WINDOW_HIDDEN, SDL_WINDOW_HIDDEN}, + {cc::ISystemWindow::CC_WINDOW_BORDERLESS, SDL_WINDOW_BORDERLESS}, + {cc::ISystemWindow::CC_WINDOW_RESIZABLE, SDL_WINDOW_RESIZABLE}, + {cc::ISystemWindow::CC_WINDOW_MINIMIZED, SDL_WINDOW_MINIMIZED}, + {cc::ISystemWindow::CC_WINDOW_MAXIMIZED, SDL_WINDOW_MAXIMIZED}, + {cc::ISystemWindow::CC_WINDOW_INPUT_GRABBED, SDL_WINDOW_INPUT_GRABBED}, + {cc::ISystemWindow::CC_WINDOW_INPUT_FOCUS, SDL_WINDOW_INPUT_FOCUS}, + {cc::ISystemWindow::CC_WINDOW_MOUSE_FOCUS, SDL_WINDOW_MOUSE_FOCUS}, + {cc::ISystemWindow::CC_WINDOW_FULLSCREEN_DESKTOP, SDL_WINDOW_FULLSCREEN_DESKTOP}, + {cc::ISystemWindow::CC_WINDOW_FOREIGN, SDL_WINDOW_FOREIGN}, + {cc::ISystemWindow::CC_WINDOW_ALLOW_HIGHDPI, SDL_WINDOW_ALLOW_HIGHDPI}, + {cc::ISystemWindow::CC_WINDOW_MOUSE_CAPTURE, SDL_WINDOW_MOUSE_CAPTURE}, + {cc::ISystemWindow::CC_WINDOW_ALWAYS_ON_TOP, SDL_WINDOW_ALWAYS_ON_TOP}, + {cc::ISystemWindow::CC_WINDOW_SKIP_TASKBAR, SDL_WINDOW_SKIP_TASKBAR}, + {cc::ISystemWindow::CC_WINDOW_UTILITY, SDL_WINDOW_UTILITY}, + {cc::ISystemWindow::CC_WINDOW_TOOLTIP, SDL_WINDOW_TOOLTIP}, + {cc::ISystemWindow::CC_WINDOW_POPUP_MENU, SDL_WINDOW_POPUP_MENU}, + {cc::ISystemWindow::CC_WINDOW_VULKAN, SDL_WINDOW_VULKAN}}; + +int windowFlagsToSDLWindowFlag(int flags) { + int sdlFlags = 0; + for (auto it : gWindowFlagMap) { + if ((it.first & flags) == it.first) { + sdlFlags |= it.second; + } + } + return sdlFlags; +} + +} // namespace + +namespace cc { +QnxPlatform::QnxPlatform() = default; +QnxPlatform::~QnxPlatform() { + if (_screenWin) { + screen_destroy_window(_screenWin); + } + if (_screenCtx) { + screen_destroy_context(_screenCtx); + } +} + +int32_t QnxPlatform::init() { + UniversalPlatform::init(); + + if (SDL_Init(SDL_INIT_VIDEO) < 0) { + // Display error message + CC_LOG_ERROR("SDL could not initialize! SDL_Error: %s\n", SDL_GetError()); + return false; + } + return 0; +} + +static long getCurrentMillSecond() { + long lLastTime; + struct timeval stCurrentTime; + + gettimeofday(&stCurrentTime, NULL); + lLastTime = stCurrentTime.tv_sec * 1000 + stCurrentTime.tv_usec * 0.001; // milliseconds + return lLastTime; +} + +int32_t QnxPlatform::loop() { + long lastTime = 0L; + long curTime = 0L; + long desiredInterval = 0L; + long actualInterval = 0L; + onResume(); + while (!_quit) { + curTime = getCurrentMillSecond(); + desiredInterval = (long)(1.0 / getFps()); + + //pollEvent(); + actualInterval = curTime - lastTime; + if (actualInterval >= desiredInterval) { + lastTime = getCurrentMillSecond(); + runTask(); + //SDL_GL_SwapWindow(_handle); + } else { + usleep((desiredInterval - curTime + lastTime) * 1000); + } + } + + onDestory(); + return 0; +} + +void QnxPlatform::handleWindowEvent(SDL_WindowEvent &wevent) { + WindowEvent ev; + switch (wevent.event) { + case SDL_WINDOWEVENT_SHOWN: { + ev.type = WindowEvent::Type::SHOW; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT_RESTORED: { + ev.type = WindowEvent::Type::RESTORED; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT_SIZE_CHANGED: { + ev.type = WindowEvent::Type::SIZE_CHANGED; + ev.width = wevent.data1; + ev.height = wevent.data2; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT_RESIZED: { + ev.type = WindowEvent::Type::RESIZED; + ev.width = wevent.data1; + ev.height = wevent.data2; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT_HIDDEN: { + ev.type = WindowEvent::Type::HIDDEN; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT_MINIMIZED: { + ev.type = WindowEvent::Type::MINIMIZED; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT_ENTER: { + SDL_CaptureMouse(SDL_TRUE); + break; + } + case SDL_WINDOWEVENT_CLOSE: { + ev.type = WindowEvent::Type::CLOSE; + dispatchEvent(ev); + break; + } + } +} + +void QnxPlatform::pollEvent() { + SDL_Event sdlEvent; + int cnt = SDL_PollEvent(&sdlEvent); + if (cnt == 0) { + return; + } + cc::TouchEvent touch; + cc::MouseEvent mouse; + cc::KeyboardEvent keyboard; + switch (sdlEvent.type) { + case SDL_QUIT: { + _quit = true; + WindowEvent ev; + ev.type = WindowEvent::Type::QUIT; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT: { + handleWindowEvent(sdlEvent.window); + break; + } + case SDL_MOUSEBUTTONDOWN: { + SDL_MouseButtonEvent &event = sdlEvent.button; + mouse.type = MouseEvent::Type::DOWN; + mouse.x = static_cast(event.x); + mouse.y = static_cast(event.y); + /*if (0 > mouse.x || mouse.x > this->_width || 0 > mouse.y || mouse.y > this->_height) { + break; + }*/ + mouse.button = event.button - 1; + dispatchEvent(mouse); + break; + } + case SDL_MOUSEBUTTONUP: { + SDL_MouseButtonEvent &event = sdlEvent.button; + mouse.type = MouseEvent::Type::UP; + mouse.x = static_cast(event.x); + mouse.y = static_cast(event.y); + mouse.button = event.button - 1; + dispatchEvent(mouse); + break; + } + case SDL_MOUSEMOTION: { + SDL_MouseMotionEvent &event = sdlEvent.motion; + mouse.type = MouseEvent::Type::MOVE; + mouse.x = static_cast(event.x); + mouse.y = static_cast(event.y); + mouse.button = 0; + dispatchEvent(mouse); + break; + } + case SDL_MOUSEWHEEL: { + SDL_MouseWheelEvent &event = sdlEvent.wheel; + mouse.type = MouseEvent::Type::WHEEL; + mouse.x = static_cast(event.x); + mouse.y = static_cast(event.y); + mouse.button = 0; //TODO: direction + dispatchEvent(mouse); + break; + } + case SDL_FINGERUP: { + SDL_TouchFingerEvent &event = sdlEvent.tfinger; + touch.type = TouchEvent::Type::ENDED; + touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; + dispatchEvent(touch); + break; + } + case SDL_FINGERDOWN: { + SDL_TouchFingerEvent &event = sdlEvent.tfinger; + touch.type = TouchEvent::Type::BEGAN; + touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; + dispatchEvent(touch); + break; + } + case SDL_FINGERMOTION: { + SDL_TouchFingerEvent &event = sdlEvent.tfinger; + touch.type = TouchEvent::Type::MOVED; + touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; + dispatchEvent(touch); + break; + } + case SDL_KEYDOWN: { + SDL_KeyboardEvent &event = sdlEvent.key; + auto mode = event.keysym.mod; + keyboard.action = KeyboardEvent::Action::PRESS; + keyboard.key = sdlKeycodeToCocosCode(event.keysym.sym, mode); + keyboard.altKeyActive = mode & KMOD_ALT; + keyboard.ctrlKeyActive = mode & KMOD_CTRL; + keyboard.shiftKeyActive = mode & KMOD_SHIFT; + //CC_LOG_DEBUG("==> key %d -> code %d", event.keysym.sym, keyboard.key); + //cc::EventDispatcher::dispatchKeyboardEvent(keyboard); + dispatchEvent(keyboard); + break; + } + case SDL_KEYUP: { + SDL_KeyboardEvent &event = sdlEvent.key; + auto mode = event.keysym.mod; + keyboard.action = KeyboardEvent::Action::RELEASE; + keyboard.key = sdlKeycodeToCocosCode(event.keysym.sym, mode); + keyboard.altKeyActive = mode & KMOD_ALT; + keyboard.ctrlKeyActive = mode & KMOD_CTRL; + keyboard.shiftKeyActive = mode & KMOD_SHIFT; + dispatchEvent(keyboard); + //cc::EventDispatcher::dispatchKeyboardEvent(keyboard); + break; + } + default: + + break; + } +} + +bool QnxPlatform::createWindow(const char *title, + int x, int y, int w, + int h, int flags) { + if (_inited) { + return true; + } + int rc; + + //Create the screen context + rc = screen_create_context(&_screenCtx, SCREEN_APPLICATION_CONTEXT); + if (rc) { + perror("screen_create_window"); + return EXIT_FAILURE; + } + + //Create the screen window that will be render onto + rc = screen_create_window(&_screenWin, _screenCtx); + if (rc) { + perror("screen_create_window"); + return EXIT_FAILURE; + } + + screen_set_window_property_iv(_screenWin, SCREEN_PROPERTY_FORMAT, (const int[]){SCREEN_FORMAT_RGBX8888}); + screen_set_window_property_iv(_screenWin, SCREEN_PROPERTY_USAGE, (const int[]){SCREEN_USAGE_OPENGL_ES2}); + + int size[2] = {w, h}; /* size of the window on screen */ + rc = screen_set_window_property_iv(_screenWin, SCREEN_PROPERTY_SIZE, size); + + int dpi = 0; + screen_get_window_property_iv(_screenWin, SCREEN_PROPERTY_DPI, &dpi); + fprintf(stdout, "[glError] %d\n", dpi); + + rc = screen_create_window_buffers(_screenWin, 2); + if (rc) { + perror("screen_create_window_buffers"); + return EXIT_FAILURE; + } + + // // Create window + // int sdlFlags = windowFlagsToSDLWindowFlag(flags); + // _handle = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, w, h, sdlFlags); + // if (_handle == nullptr) { + // // Display error message + // CC_LOG_ERROR("Window could not be created! SDL_Error: %s\n", SDL_GetError()); + // return false; + // } + // _inited = true; + return true; +} + +uintptr_t QnxPlatform::getWindowHandler() const { + //int32_t *window = (int32_t *)(_handle->driverdata); + return reinterpret_cast(_screenWin); +} + +} // namespace cc diff --git a/native/cocos/platform/qnx/QNXPlatform.h b/native/cocos/platform/qnx/QNXPlatform.h new file mode 100644 index 0000000000..adac524c2c --- /dev/null +++ b/native/cocos/platform/qnx/QNXPlatform.h @@ -0,0 +1,71 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include +#include "platform/UniversalPlatform.h" +#include "platform/qnx/modules/SystemWindow.h" + +struct SDL_WindowEvent; +struct SDL_Window; + +namespace cc { + +class QnxPlatform : public UniversalPlatform, + public SystemWindow::Delegate { +public: + QnxPlatform(); + /** + * Destructor of WindowPlatform. + */ + ~QnxPlatform() override; + /** + * Implementation of Windows platform initialization. + */ + int32_t init() override; + + int32_t loop() override; + + // override from SystemWindow::Delegate + bool createWindow(const char* title, + int x, int y, int w, + int h, int flags) override; + uintptr_t getWindowHandler() const override; + struct SDL_Window* getWindow() { + return nullptr; //_handle; + } + +private: + SDL_Window* _handle; + void pollEvent() override; + void handleWindowEvent(SDL_WindowEvent& wevent); + bool _inited{false}; + bool _quit{false}; + screen_context_t _screenCtx; + screen_window_t _screenWin; +}; + +} // namespace cc diff --git a/native/cocos/platform/qnx/modules/Accelerometer.cpp b/native/cocos/platform/qnx/modules/Accelerometer.cpp new file mode 100644 index 0000000000..9051657131 --- /dev/null +++ b/native/cocos/platform/qnx/modules/Accelerometer.cpp @@ -0,0 +1,40 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/qnx/modules/Accelerometer.h" + +namespace cc { +void Accelerometer::setAccelerometerEnabled(bool isEnabled) { +} + +void Accelerometer::setAccelerometerInterval(float interval) { +} + +const Accelerometer::MotionValue& Accelerometer::getDeviceMotionValue() { + static MotionValue motionValue; + return motionValue; +} + +} // namespace cc diff --git a/native/cocos/platform/qnx/modules/Accelerometer.h b/native/cocos/platform/qnx/modules/Accelerometer.h new file mode 100644 index 0000000000..50a3c56992 --- /dev/null +++ b/native/cocos/platform/qnx/modules/Accelerometer.h @@ -0,0 +1,50 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IAccelerometer.h" + +namespace cc { + +class Accelerometer : public IAccelerometer { +public: + /** + * To enable or disable accelerometer. + */ + void setAccelerometerEnabled(bool isEnabled) override; + + /** + * Sets the interval of accelerometer. + */ + void setAccelerometerInterval(float interval) override; + + /** + * Gets the motion value of current device. + */ + const MotionValue &getDeviceMotionValue() override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/qnx/modules/Battery.cpp b/native/cocos/platform/qnx/modules/Battery.cpp new file mode 100644 index 0000000000..721ef8fb9e --- /dev/null +++ b/native/cocos/platform/qnx/modules/Battery.cpp @@ -0,0 +1,33 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/qnx/modules/Battery.h" + +namespace cc { + +float Battery::getBatteryLevel() const { + return 1.0F; +} + +} // namespace cc diff --git a/native/cocos/platform/qnx/modules/Battery.h b/native/cocos/platform/qnx/modules/Battery.h new file mode 100644 index 0000000000..928cbb038e --- /dev/null +++ b/native/cocos/platform/qnx/modules/Battery.h @@ -0,0 +1,37 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IBattery.h" + +namespace cc { + +class Battery : public IBattery { +public: + float getBatteryLevel() const override; +}; + +} // namespace cc diff --git a/native/cocos/platform/qnx/modules/CanvasRenderingContext2DDelegate.cpp b/native/cocos/platform/qnx/modules/CanvasRenderingContext2DDelegate.cpp new file mode 100644 index 0000000000..c8c01b63ad --- /dev/null +++ b/native/cocos/platform/qnx/modules/CanvasRenderingContext2DDelegate.cpp @@ -0,0 +1,302 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/qnx/modules/CanvasRenderingContext2DDelegate.h" +#include + +namespace { +#define RGB(r, g, b) (int)((int)r | (((int)g) << 8) | (((int)b) << 16)) +#define RGBA(r, g, b, a) (int)((int)r | (((int)g) << 8) | (((int)b) << 16) | (((int)a) << 24)) +} // namespace + +namespace { +void fillRectWithColor(uint8_t *buf, uint32_t totalWidth, uint32_t totalHeight, uint32_t x, uint32_t y, uint32_t width, uint32_t height, uint8_t r, uint8_t g, uint8_t b, uint8_t a) { + assert(x + width <= totalWidth); + assert(y + height <= totalHeight); + + uint32_t y0 = y; + uint32_t y1 = y + height; + uint8_t *p; + for (uint32_t offsetY = y0; offsetY < y1; ++offsetY) { + for (uint32_t offsetX = x; offsetX < (x + width); ++offsetX) { + p = buf + (totalWidth * offsetY + offsetX) * 4; + *p++ = r; + *p++ = g; + *p++ = b; + *p++ = a; + } + } +} +} // namespace + +namespace cc { +//static const char gdefaultFontName[] = "-*-helvetica-medium-o-*-*-24-*-*-*-*-*-iso8859-*"; +//static const char gdefaultFontName[] = "lucidasanstypewriter-bold-24"; +static const char gdefaultFontName[] = "lucidasans-24"; +static const char gdefaultFontName1[] = "lucidasans"; + +CanvasRenderingContext2DDelegate::CanvasRenderingContext2DDelegate() { + //_surface = cairo_image_surface_create_for_data(pointer , CAIRO_FORMAT_ARGB32,size[0], size[1], stride); + //_cr = cairo_create (_surface); +} + +CanvasRenderingContext2DDelegate::~CanvasRenderingContext2DDelegate() { + if (_cr != nullptr) { + cairo_destroy(_cr); + } + if (_surface) { + cairo_surface_destroy(_surface); + } +} + +void CanvasRenderingContext2DDelegate::recreateBuffer(float w, float h) { + _bufferWidth = w; + _bufferHeight = h; + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + auto textureSize = static_cast(_bufferWidth * _bufferHeight * 4); + auto *data = static_cast(malloc(sizeof(int8_t) * textureSize)); + memset(data, 0x00, textureSize); + _imageData.fastSet((unsigned char *)data, textureSize); + + if (_cr) { + cairo_destroy(_cr); + } + if (_surface) { + cairo_surface_destroy(_surface); + } + _surface = cairo_image_surface_create_for_data((unsigned char *)data, CAIRO_FORMAT_ARGB32, _bufferWidth, _bufferHeight, _bufferWidth * 4); + _cr = cairo_create(_surface); +} + +void CanvasRenderingContext2DDelegate::beginPath() { +} + +void CanvasRenderingContext2DDelegate::closePath() { +} + +void CanvasRenderingContext2DDelegate::moveTo(float x, float y) { + CCASSERT(_cr != nullptr, "Cr pointer cannot be empty"); + cairo_move_to(_cr, x, y); +} + +void CanvasRenderingContext2DDelegate::lineTo(float x, float y) { + CCASSERT(_cr != nullptr, "Cr pointer cannot be empty"); + cairo_line_to(_cr, x, y); +} + +void CanvasRenderingContext2DDelegate::stroke() { +} + +void CanvasRenderingContext2DDelegate::saveContext() { +} + +void CanvasRenderingContext2DDelegate::restoreContext() { +} + +void CanvasRenderingContext2DDelegate::clearRect(float x, float y, float w, float h) { + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + + if (_imageData.isNull()) { + return; + } + + recreateBuffer(w, h); +} + +void CanvasRenderingContext2DDelegate::fillRect(float x, float y, float w, float h) { + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + CCASSERT(_cr != nullptr, "Cr pointer cannot be empty"); + cairo_set_source_rgba(_cr, _fillStyle[0], _fillStyle[1], _fillStyle[2], _fillStyle[3]); + cairo_rectangle(_cr, x, y, w, h); + cairo_fill(_cr); +} + +void CanvasRenderingContext2DDelegate::fillText(const std::string &text, float x, float y, float /*maxWidth*/) { + if (text.empty() || _bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + // cairo_font_weight_t fontWeight = CAIRO_FONT_WEIGHT_NORMAL; // bold ? CAIRO_FONT_WEIGHT_BOLD : CAIRO_FONT_WEIGHT_NORMAL; + // cairo_font_slant_t fontSlant = CAIRO_FONT_SLANT_NORMAL; + // cairo_select_font_face (_cr, "Arial", fontSlant, fontWeight); + cairo_set_font_size(_cr, _fontSize); + Point offsetPoint = convertDrawPoint(Point{x, y}, text); + cairo_set_source_rgba(_cr, _fillStyle[0], _fillStyle[1], _fillStyle[2], _fillStyle[3]); + cairo_move_to(_cr, offsetPoint[0], offsetPoint[1]); + cairo_show_text(_cr, text.c_str()); +} + +void CanvasRenderingContext2DDelegate::strokeText(const std::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const { + if (text.empty() || _bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } +} + +CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::measureText(const std::string &text) { + if (text.empty()) + return std::array{0.0f, 0.0f}; + cairo_text_extents_t extents; + cairo_text_extents(_cr, text.c_str(), &extents); + return std::array{static_cast(extents.x_advance), + static_cast(extents.height)}; +} + +void CanvasRenderingContext2DDelegate::updateFont(const std::string &fontName, + float fontSize, + bool bold, + bool italic, + bool oblique, + bool /* smallCaps */) { + do { + _fontName = fontName; + _fontSize = static_cast(fontSize); + cairo_font_weight_t fontWeight = bold ? CAIRO_FONT_WEIGHT_BOLD : CAIRO_FONT_WEIGHT_NORMAL; + cairo_font_slant_t fontSlant = CAIRO_FONT_SLANT_NORMAL; + if (italic) { + fontSlant = CAIRO_FONT_SLANT_ITALIC; + } else if (oblique) { + fontSlant = CAIRO_FONT_SLANT_OBLIQUE; + } + std::cout << _fontName << std::endl; + cairo_select_font_face(_cr, _fontName.c_str(), fontSlant, fontWeight); + cairo_set_font_size(_cr, _fontSize); + } while (false); +} + +void CanvasRenderingContext2DDelegate::setTextAlign(CanvasTextAlign align) { + _textAlign = align; +} + +void CanvasRenderingContext2DDelegate::setTextBaseline(CanvasTextBaseline baseline) { + _textBaseLine = baseline; +} + +void CanvasRenderingContext2DDelegate::setFillStyle(float r, float g, float b, float a) { + _fillStyle = {r, g, b, a}; +} + +void CanvasRenderingContext2DDelegate::setStrokeStyle(float r, float g, float b, float a) { + _strokeStyle = {r, g, b, a}; +} + +void CanvasRenderingContext2DDelegate::setLineWidth(float lineWidth) { + _lineWidth = lineWidth; +} + +const cc::Data &CanvasRenderingContext2DDelegate::getDataRef() const { + return _imageData; +} + +void CanvasRenderingContext2DDelegate::removeCustomFont() { +} + +// x, y offset value +int CanvasRenderingContext2DDelegate::drawText(const std::string &text, int x, int y) { + cairo_move_to(_cr, x, y); + cairo_show_text(_cr, text.c_str()); + return 0; +} + +CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::sizeWithText(const wchar_t *pszText, int nLen) { + return std::array{0.0F, 0.0F}; +} + +void CanvasRenderingContext2DDelegate::prepareBitmap(int nWidth, int nHeight) { +} + +void CanvasRenderingContext2DDelegate::deleteBitmap() { +} + +void CanvasRenderingContext2DDelegate::fillTextureData() { +} + +std::array CanvasRenderingContext2DDelegate::convertDrawPoint(Point point, const std::string &text) { + int font_ascent = 0; + int font_descent = 0; + int direction = 0; + cairo_text_extents_t extents; + cairo_text_extents(_cr, text.c_str(), &extents); + + int width = extents.width; + if (_textAlign == CanvasTextAlign::CENTER) { + point[0] -= width / 2.0f; + } else if (_textAlign == CanvasTextAlign::RIGHT) { + point[0] -= width; + } + + if (_textBaseLine == CanvasTextBaseline::TOP) { + point[1] += -extents.y_bearing; + } else if (_textBaseLine == CanvasTextBaseline::MIDDLE) { + point[1] += extents.height / 2; + } else if (_textBaseLine == CanvasTextBaseline::BOTTOM) { + point[1] += extents.height; + } + if (text == ".") { + // The calculation of points is not the same as the calculation of numbers, + // which will cause the drawing of points and numbers to be different from the same horizontal line. + // Therefore, here is manually adjusted to calculate the drawing coordinates of + // the point according to the numerical calculation method + cairo_text_extents_t extentNumber; + cairo_text_extents(_cr, "1", &extentNumber); + point[1] += extents.y_bearing - extentNumber.y_bearing; + } + + return point; +} + +void CanvasRenderingContext2DDelegate::fill() { +} + +void CanvasRenderingContext2DDelegate::setLineCap(const std::string &lineCap) { +} + +void CanvasRenderingContext2DDelegate::setLineJoin(const std::string &lineJoin) { +} + +void CanvasRenderingContext2DDelegate::fillImageData(const Data & /* imageData */, + float /* imageWidth */, + float /* imageHeight */, + float /* offsetX */, + float /* offsetY */) { +} + +void CanvasRenderingContext2DDelegate::strokeText(const std::string & /* text */, + float /* x */, + float /* y */, + float /* maxWidth */) { +} + +void CanvasRenderingContext2DDelegate::rect(float /* x */, + float /* y */, + float /* w */, + float /* h */) { +} + +} // namespace cc diff --git a/native/cocos/platform/qnx/modules/CanvasRenderingContext2DDelegate.h b/native/cocos/platform/qnx/modules/CanvasRenderingContext2DDelegate.h new file mode 100644 index 0000000000..9ef38b251d --- /dev/null +++ b/native/cocos/platform/qnx/modules/CanvasRenderingContext2DDelegate.h @@ -0,0 +1,110 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h" + +#include +#include +#include +#include "base/csscolorparser.h" +#include "cocos/bindings/manual/jsb_platform.h" +#include "math/Math.h" +#include "platform/FileUtils.h" + +#include "cairo.h" + +namespace cc { + +class CanvasRenderingContext2DDelegate : public ICanvasRenderingContext2D::Delegate { +public: + using Point = std::array; + using Vec2 = std::array; + using Size = std::array; + using Color4F = std::array; + + CanvasRenderingContext2DDelegate(); + ~CanvasRenderingContext2DDelegate() override; + + void recreateBuffer(float w, float h) override; + void beginPath() override; + void closePath() override; + void moveTo(float x, float y) override; + void lineTo(float x, float y) override; + void stroke() override; + void saveContext() override; + void restoreContext() override; + void clearRect(float /*x*/, float /*y*/, float w, float h) override; + void fillRect(float x, float y, float w, float h) override; + void fillText(const std::string &text, float x, float y, float /*maxWidth*/) override; + void strokeText(const std::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const; + Size measureText(const std::string &text) override; + void updateFont(const std::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; + void setTextAlign(CanvasTextAlign align) override; + void setTextBaseline(CanvasTextBaseline baseline) override; + void setFillStyle(float r, float g, float b, float a) override; + void setStrokeStyle(float r, float g, float b, float a) override; + void setLineWidth(float lineWidth) override; + const cc::Data &getDataRef() const override; + void fill() override; + void setLineCap(const std::string &lineCap) override; + void setLineJoin(const std::string &lineCap) override; + void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; + void strokeText(const std::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; + void rect(float x, float y, float w, float h) override; + +private: + static wchar_t * utf8ToUtf16(const std::string &str, int *pRetLen = nullptr); + void removeCustomFont(); + int drawText(const std::string &text, int x, int y); + Size sizeWithText(const wchar_t *pszText, int nLen); + void prepareBitmap(int nWidth, int nHeight); + void deleteBitmap(); + void fillTextureData(); + std::array convertDrawPoint(Point point, const std::string &text); + +public: + cairo_surface_t *_surface{nullptr}; + cairo_t * _cr{nullptr}; + +private: + cc::Data _imageData; + std::string _curFontPath; + int _savedDC{0}; + float _lineWidth{0.0F}; + float _bufferWidth{0.0F}; + float _bufferHeight{0.0F}; + + std::string _fontName; + int _fontSize{0}; + Size _textSize; + CanvasTextAlign _textAlign{CanvasTextAlign::CENTER}; + CanvasTextBaseline _textBaseLine{CanvasTextBaseline::TOP}; + Color4F _fillStyle; + Color4F _strokeStyle; +}; + +} // namespace cc diff --git a/native/cocos/platform/qnx/modules/Network.cpp b/native/cocos/platform/qnx/modules/Network.cpp new file mode 100644 index 0000000000..6be5ba1a6e --- /dev/null +++ b/native/cocos/platform/qnx/modules/Network.cpp @@ -0,0 +1,33 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/qnx/modules/Network.h" + +namespace cc { + +INetwork::NetworkType Network::getNetworkType() const { + return INetwork::NetworkType::LAN; +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/qnx/modules/Network.h b/native/cocos/platform/qnx/modules/Network.h new file mode 100644 index 0000000000..cd5f2d6d5a --- /dev/null +++ b/native/cocos/platform/qnx/modules/Network.h @@ -0,0 +1,37 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/INetwork.h" + +namespace cc { + +class Network : public INetwork { +public: + NetworkType getNetworkType() const override; +}; + +} // namespace cc diff --git a/native/cocos/platform/qnx/modules/Screen.cpp b/native/cocos/platform/qnx/modules/Screen.cpp new file mode 100644 index 0000000000..dfd5fb2cc6 --- /dev/null +++ b/native/cocos/platform/qnx/modules/Screen.cpp @@ -0,0 +1,71 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/qnx/modules/Screen.h" +#include "cocos/bindings/jswrapper/SeApi.h" +#include "base/Macros.h" + +namespace cc { + +int Screen::getDPI() const { + static int dpi = -1; + if (dpi == -1) { + //screen_get_window_property_iv(screen_win, SCREEN_PROPERTY_DPI, &dpi); + } + return dpi; +} + +float Screen::getDevicePixelRatio() const { + return 1; +} + +void Screen::setKeepScreenOn(bool value) { + CC_UNUSED_PARAM(value); +} + +Screen::Orientation Screen::getDeviceOrientation() const { + return Orientation::PORTRAIT; +} + +Vec4 Screen::getSafeAreaEdge() const { + return cc::Vec4(); +} + +bool Screen::isDisplayStats() { + se::AutoHandleScope hs; + se::Value ret; + char commandBuf[100] = "cc.profiler.isShowingStats();"; + se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret); + return ret.toBoolean(); +} + +void Screen::setDisplayStats(bool isShow) { + se::AutoHandleScope hs; + char commandBuf[100] = {0}; + sprintf(commandBuf, isShow ? "cc.profiler.showStats();" : "cc.profiler.hideStats();"); + se::ScriptEngine::getInstance()->evalString(commandBuf); +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/qnx/modules/Screen.h b/native/cocos/platform/qnx/modules/Screen.h new file mode 100644 index 0000000000..06eb7a8c15 --- /dev/null +++ b/native/cocos/platform/qnx/modules/Screen.h @@ -0,0 +1,51 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IScreen.h" + +namespace cc { + +class Screen : public IScreen { +public: + int getDPI() const override; + float getDevicePixelRatio() const override; + void setKeepScreenOn(bool value) override; + Orientation getDeviceOrientation() const override; + Vec4 getSafeAreaEdge() const override; + /** + @brief Get current display stats. + @return bool, is displaying stats or not. + */ + bool isDisplayStats() override; + + /** + @brief set display stats information. + */ + void setDisplayStats(bool isShow) override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/qnx/modules/System.cpp b/native/cocos/platform/qnx/modules/System.cpp new file mode 100644 index 0000000000..5806c85508 --- /dev/null +++ b/native/cocos/platform/qnx/modules/System.cpp @@ -0,0 +1,126 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/qnx/modules/System.h" +#include +#include + +namespace cc { + +using OSType = System::OSType; + +OSType System::getOSType() const { + return OSType::QNX; +} + +std::string System::getDeviceModel() const { + return "QNX"; +} + +System::LanguageType System::getCurrentLanguage() const { + char* pLanguageName = getenv("LANG"); + if (!pLanguageName) { + return LanguageType::ENGLISH; + } + strtok(pLanguageName, "_"); + if (!pLanguageName) { + return LanguageType::ENGLISH; + } + + return getLanguageTypeByISO2(pLanguageName); +} + +std::string System::getCurrentLanguageCode() const { + static char code[3]={0}; + char *pLanguageName = getenv("LANG"); + if (!pLanguageName) { + return "en"; + } + strtok(pLanguageName, "_"); + if (!pLanguageName) { + return "en"; + } + strncpy(code,pLanguageName,2); + code[2]='\0'; + return code; +} + +std::string System::getSystemVersion() const { + struct utsname u; + uname(&u); + return u.version; +} + +bool System::openURL(const std::string& url) { + //std::string op = std::string("xdg-open '").append(url).append("'"); + //return system(op.c_str()) == 0; + return false; +} + +System::LanguageType System::getLanguageTypeByISO2(const char* code) const { + // this function is used by all platforms to get system language + // except windows: cocos/platform/win32/CCApplication-win32.cpp + LanguageType ret = LanguageType::ENGLISH; + + if (strncmp(code, "zh", 2) == 0) { + ret = LanguageType::CHINESE; + } else if (strncmp(code, "ja", 2) == 0) { + ret = LanguageType::JAPANESE; + } else if (strncmp(code, "fr", 2) == 0) { + ret = LanguageType::FRENCH; + } else if (strncmp(code, "it", 2) == 0) { + ret = LanguageType::ITALIAN; + } else if (strncmp(code, "de", 2) == 0) { + ret = LanguageType::GERMAN; + } else if (strncmp(code, "es", 2) == 0) { + ret = LanguageType::SPANISH; + } else if (strncmp(code, "nl", 2) == 0) { + ret = LanguageType::DUTCH; + } else if (strncmp(code, "ru", 2) == 0) { + ret = LanguageType::RUSSIAN; + } else if (strncmp(code, "hu", 2) == 0) { + ret = LanguageType::HUNGARIAN; + } else if (strncmp(code, "pt", 2) == 0) { + ret = LanguageType::PORTUGUESE; + } else if (strncmp(code, "ko", 2) == 0) { + ret = LanguageType::KOREAN; + } else if (strncmp(code, "ar", 2) == 0) { + ret = LanguageType::ARABIC; + } else if (strncmp(code, "nb", 2) == 0) { + ret = LanguageType::NORWEGIAN; + } else if (strncmp(code, "pl", 2) == 0) { + ret = LanguageType::POLISH; + } else if (strncmp(code, "tr", 2) == 0) { + ret = LanguageType::TURKISH; + } else if (strncmp(code, "uk", 2) == 0) { + ret = LanguageType::UKRAINIAN; + } else if (strncmp(code, "ro", 2) == 0) { + ret = LanguageType::ROMANIAN; + } else if (strncmp(code, "bg", 2) == 0) { + ret = LanguageType::BULGARIAN; + } + return ret; +} +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/qnx/modules/System.h b/native/cocos/platform/qnx/modules/System.h new file mode 100644 index 0000000000..87e05a1c49 --- /dev/null +++ b/native/cocos/platform/qnx/modules/System.h @@ -0,0 +1,67 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/ISystem.h" + +namespace cc { + +class System : public ISystem { +public: + /** + @brief Get target system type. + */ + OSType getOSType() const override; + /** + @brief Get target device model. + */ + std::string getDeviceModel() const override; + /** + @brief Get current language config. + @return Current language config. + */ + LanguageType getCurrentLanguage() const override; + /** + @brief Get current language iso 639-1 code. + @return Current language iso 639-1 code. + */ + std::string getCurrentLanguageCode() const override; + /** + @brief Get system version. + @return system version. + */ + std::string getSystemVersion() const override; + /** + @brief Open url in default browser. + @param String with url to open. + @return True if the resource located by the URL was successfully opened; otherwise false. + */ + bool openURL(const std::string& url) override; +private: + LanguageType getLanguageTypeByISO2(const char* code) const; +}; + +} // namespace cc diff --git a/native/cocos/platform/qnx/modules/SystemWindow.cpp b/native/cocos/platform/qnx/modules/SystemWindow.cpp new file mode 100644 index 0000000000..0cdbe5ee65 --- /dev/null +++ b/native/cocos/platform/qnx/modules/SystemWindow.cpp @@ -0,0 +1,83 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/qnx/modules/SystemWindow.h" + +#include "base/Log.h" +#include "base/Macros.h" + +// SDL headers +#include +#include "SDL2/SDL.h" +#include "SDL2/SDL_main.h" +#include "SDL2/SDL_syswm.h" +#include "bindings/event/EventDispatcher.h" +#include "platform/IEventDispatch.h" +#include "platform/qnx/QnxPlatform.h" + +namespace { + +} // namespace + +namespace cc { +SystemWindow::SystemWindow() { +} + +SystemWindow::~SystemWindow() { +} + +bool SystemWindow::createWindow(const char *title, + int x, int y, int w, + int h, int flags) { + // Create window + + QnxPlatform *platform = dynamic_cast(BasePlatform::getPlatform()); + CCASSERT(platform != nullptr, "Platform pointer can't be null"); + platform->createWindow(title, x, y, w, h, flags); + _width = w; + _height = h; + return true; +} + +uintptr_t SystemWindow::getWindowHandler() const { + //return _handle; + QnxPlatform *platform = dynamic_cast(BasePlatform::getPlatform()); + CCASSERT(platform != nullptr, "Platform pointer can't be null"); + return platform->getWindowHandler(); +} + +void SystemWindow::setCursorEnabled(bool value) { + SDL_SetRelativeMouseMode(value ? SDL_FALSE : SDL_TRUE); +} + +void SystemWindow::copyTextToClipboard(const std::string &text) { + //TODO +} + +SystemWindow::Size SystemWindow::getViewSize() const { + return Size{static_cast(_width), static_cast(_height)}; +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/qnx/modules/SystemWindow.h b/native/cocos/platform/qnx/modules/SystemWindow.h new file mode 100644 index 0000000000..44b447075d --- /dev/null +++ b/native/cocos/platform/qnx/modules/SystemWindow.h @@ -0,0 +1,68 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include + +#include "platform/interfaces/modules/ISystemWindow.h" + +struct SDL_Window; +struct SDL_WindowEvent; + +namespace cc { + +class SystemWindow : public ISystemWindow { +public: + explicit SystemWindow(); + ~SystemWindow() override; + + class Delegate { + public: + virtual ~Delegate() = default; + virtual bool createWindow(const char* title, + int x, int y, int w, + int h, int flags) = 0; + virtual uintptr_t getWindowHandler() const = 0; + }; + + bool createWindow(const char* title, + int x, int y, int w, + int h, int flags) override; + uintptr_t getWindowHandler() const override; + + Size getViewSize() const override; + /* + @brief enable/disable(lock) the cursor, default is enabled + */ + void setCursorEnabled(bool value) override; + void copyTextToClipboard(const std::string& text) override; + +private: + int _width{0}; + int _height{0}; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/qnx/modules/Vibrate.cpp b/native/cocos/platform/qnx/modules/Vibrate.cpp new file mode 100644 index 0000000000..47c392dddb --- /dev/null +++ b/native/cocos/platform/qnx/modules/Vibrate.cpp @@ -0,0 +1,36 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/qnx/modules/Vibrate.h" + +#include "base/Macros.h" + +namespace cc { + +void Vibrator::vibrate(float duration) { + CC_UNUSED_PARAM(duration); +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/qnx/modules/Vibrate.h b/native/cocos/platform/qnx/modules/Vibrate.h new file mode 100644 index 0000000000..f0afad6cbf --- /dev/null +++ b/native/cocos/platform/qnx/modules/Vibrate.h @@ -0,0 +1,44 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IVibrator.h" + +namespace cc { + +class Vibrator : public IVibrator { +public: + /** + * Vibrator for the specified amount of time. + * If Vibrator is not supported, then invoking this method has no effect. + * Some platforms limit to a maximum duration of 5 seconds. + * Duration is ignored on iOS due to API limitations. + * @param duration The duration in seconds. + */ + void vibrate(float duration) override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/win32/CanvasRenderingContext2D-win32.cpp b/native/cocos/platform/win32/CanvasRenderingContext2D-win32.cpp deleted file mode 100644 index 3691b97816..0000000000 --- a/native/cocos/platform/win32/CanvasRenderingContext2D-win32.cpp +++ /dev/null @@ -1,794 +0,0 @@ -/**************************************************************************** - Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - 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 "platform/CanvasRenderingContext2D.h" -#include -#include "base/csscolorparser.h" -#include "math/Math.h" -#include "cocos/bindings/jswrapper/SeApi.h" -#include "cocos/bindings/manual/jsb_platform.h" -#include "platform/FileUtils.h" -#include -#include -#include - -using Point = std::array; -using Vec2 = std::array; -using Size = std::array; -using Color4F = std::array; - -enum class CanvasTextAlign { - LEFT, - CENTER, - RIGHT -}; - -enum class CanvasTextBaseline { - TOP, - MIDDLE, - BOTTOM, - ALPHABETIC -}; - -namespace { -void fillRectWithColor(uint8_t *buf, uint32_t totalWidth, uint32_t totalHeight, uint32_t x, uint32_t y, uint32_t width, uint32_t height, uint8_t r, uint8_t g, uint8_t b, uint8_t a) { - assert(x + width <= totalWidth); - assert(y + height <= totalHeight); - - uint32_t y0 = y; - uint32_t y1 = y + height; - uint8_t *p; - for (uint32_t offsetY = y0; offsetY < y1; ++offsetY) { - for (uint32_t offsetX = x; offsetX < (x + width); ++offsetX) { - p = buf + (totalWidth * offsetY + offsetX) * 4; - *p++ = r; - *p++ = g; - *p++ = b; - *p++ = a; - } - } -} -} // namespace - -class CanvasRenderingContext2DImpl { -public: - CanvasRenderingContext2DImpl() { - HDC hdc = GetDC(_wnd); - _DC = CreateCompatibleDC(hdc); - ReleaseDC(_wnd, hdc); - } - - ~CanvasRenderingContext2DImpl() { - deleteBitmap(); - removeCustomFont(); - if (_DC) - DeleteDC(_DC); - } - - void recreateBuffer(float w, float h) { - _bufferWidth = w; - _bufferHeight = h; - if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { - deleteBitmap(); - return; - } - - auto textureSize = static_cast(_bufferWidth * _bufferHeight * 4); - auto *data = static_cast(malloc(sizeof(uint8_t) * textureSize)); - memset(data, 0x00, textureSize); - _imageData.fastSet(data, textureSize); - - prepareBitmap(_bufferWidth, _bufferHeight); - } - - void beginPath() { - // called: set_lineWidth() -> beginPath() -> moveTo() -> lineTo() -> stroke(), when draw line - _hpen = CreatePen(PS_SOLID, _lineWidth, RGB(255, 255, 255)); - // the return value of SelectObject is a handle to the object being replaced, so we should delete them to avoid memory leak - HGDIOBJ hOldPen = SelectObject(_DC, _hpen); - HGDIOBJ hOldBmp = SelectObject(_DC, _bmp); - DeleteObject(hOldPen); - DeleteObject(hOldBmp); - - SetBkMode(_DC, TRANSPARENT); - } - - void closePath() { - } - - void moveTo(float x, float y) { - MoveToEx(_DC, x, -(y - _bufferHeight - _fontSize), nullptr); - } - - void lineTo(float x, float y) { - LineTo(_DC, x, -(y - _bufferHeight - _fontSize)); - } - - void stroke() { - DeleteObject(_hpen); - if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { - return; - } - - fillTextureData(); - } - - void saveContext() { - _savedDC = SaveDC(_DC); - } - - void restoreContext() { - BOOL ret = RestoreDC(_DC, _savedDC); - if (0 == ret) { - SE_LOGD("CanvasRenderingContext2DImpl restore context failed.\n"); - } - } - - void clearRect(float /*x*/, float /*y*/, float w, float h) { - if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { - return; - } - - if (_imageData.isNull()) { - return; - } - - recreateBuffer(w, h); - } - - void fillRect(float x, float y, float w, float h) { - if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { - return; - } - - //not filled all Bits in buffer? the buffer length is _bufferWidth * _bufferHeight * 4, but it filled _bufferWidth * _bufferHeight * 3? - uint8_t *buffer = _imageData.getBytes(); - if (buffer) { - uint8_t r = _fillStyle[0] * 255.0f; - uint8_t g = _fillStyle[1] * 255.0f; - uint8_t b = _fillStyle[2] * 255.0f; - uint8_t a = _fillStyle[3] * 255.0f; - fillRectWithColor(buffer, - static_cast(_bufferWidth), - static_cast(_bufferHeight), - static_cast(x), - static_cast(y), - static_cast(w), - static_cast(h), r, g, b, a); - } - } - - void fillText(const std::string &text, float x, float y, float /*maxWidth*/) { - if (text.empty() || _bufferWidth < 1.0F || _bufferHeight < 1.0F) { - return; - } - - SIZE textSize = {0, 0}; - Point offsetPoint = convertDrawPoint(Point{x, y}, text); - - drawText(text, (int)offsetPoint[0], (int)offsetPoint[1]); - fillTextureData(); - } - - void strokeText(const std::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const { - if (text.empty() || _bufferWidth < 1.0F || _bufferHeight < 1.0F) { - return; - } - } - - Size measureText(const std::string &text) { - if (text.empty()) - return std::array{0.0f, 0.0f}; - - int bufferLen = 0; - wchar_t *pwszBuffer = CanvasRenderingContext2DImpl::utf8ToUtf16(text, &bufferLen); - Size size = sizeWithText(pwszBuffer, bufferLen); - //SE_LOGD("CanvasRenderingContext2DImpl::measureText: %s, %d, %d\n", text.c_str(), size.cx, size.cy); - CC_SAFE_DELETE_ARRAY(pwszBuffer); - return size; - } - - void updateFont(const std::string &fontName, float fontSize, bool bold = false) { - do { - _fontName = fontName; - _fontSize = static_cast(fontSize); - std::string fontPath; - LOGFONTA tFont = {0}; - if (!_fontName.empty()) { - // firstly, try to create font from ttf file - const auto &fontInfoMap = getFontFamilyNameMap(); - auto iter = fontInfoMap.find(_fontName); - if (iter != fontInfoMap.end()) { - fontPath = iter->second; - std::string tmpFontPath = fontPath; - int nFindPos = tmpFontPath.rfind("/"); - tmpFontPath = &tmpFontPath[nFindPos + 1]; - nFindPos = tmpFontPath.rfind("."); - // IDEA: draw ttf failed if font file name not equal font face name - // for example: "DejaVuSansMono-Oblique" not equal "DejaVu Sans Mono" when using DejaVuSansMono-Oblique.ttf - _fontName = tmpFontPath.substr(0, nFindPos); - } else { - auto nFindPos = fontName.rfind("/"); - if (nFindPos != fontName.npos) { - if (fontName.length() == nFindPos + 1) { - _fontName = ""; - } else { - _fontName = &_fontName[nFindPos + 1]; - } - } - } - tFont.lfCharSet = DEFAULT_CHARSET; - strcpy_s(tFont.lfFaceName, LF_FACESIZE, _fontName.c_str()); - } - - if (_fontSize) - tFont.lfHeight = -_fontSize; - - if (bold) - tFont.lfWeight = FW_BOLD; - else - tFont.lfWeight = FW_NORMAL; - - // disable Cleartype - tFont.lfQuality = ANTIALIASED_QUALITY; - - // delete old font - removeCustomFont(); - - if (!fontPath.empty()) { - _curFontPath = fontPath; - wchar_t *pwszBuffer = utf8ToUtf16(_curFontPath); - if (pwszBuffer) { - if (AddFontResource(pwszBuffer)) { - SendMessage(_wnd, WM_FONTCHANGE, 0, 0); - } - delete[] pwszBuffer; - pwszBuffer = nullptr; - } - } - - // create new font - _font = CreateFontIndirectA(&tFont); - if (!_font) { - // create failed, use default font - SE_LOGE("Failed to create custom font(font name: %s, font size: %f), use default font.\n", - _fontName.c_str(), fontSize); - } else { - SelectObject(_DC, _font); - SendMessage(_wnd, WM_FONTCHANGE, 0, 0); - } - } while (false); - } - - void setTextAlign(CanvasTextAlign align) { - _textAlign = align; - } - - void setTextBaseline(CanvasTextBaseline baseline) { - _textBaseLine = baseline; - } - - void setFillStyle(float r, float g, float b, float a) { - _fillStyle = {r, g, b, a}; - } - - void setStrokeStyle(float r, float g, float b, float a) { - _strokeStyle = {r, g, b, a}; - } - - void setLineWidth(float lineWidth) { - _lineWidth = lineWidth; - } - - const cc::Data &getDataRef() const { - return _imageData; - } - - HDC _DC{nullptr}; - HBITMAP _bmp{nullptr}; - -private: - cc::Data _imageData; - HFONT _font{static_cast(GetStockObject(DEFAULT_GUI_FONT))}; - HWND _wnd{nullptr}; - HPEN _hpen; - PAINTSTRUCT _paintStruct; - std::string _curFontPath; - int _savedDC{0}; - float _lineWidth = 0.0F; - float _bufferWidth = 0.0F; - float _bufferHeight = 0.0F; - - std::string _fontName; - int _fontSize; - Size _textSize; - CanvasTextAlign _textAlign; - CanvasTextBaseline _textBaseLine; - Color4F _fillStyle; - Color4F _strokeStyle; - - TEXTMETRIC _tm; - - // change utf-8 string to utf-16, pRetLen is the string length after changing - static wchar_t *utf8ToUtf16(const std::string &str, int *pRetLen = nullptr) { - wchar_t *pwszBuffer = nullptr; - do { - if (str.empty()) { - break; - } - int nLen = str.size(); - int nBufLen = nLen + 1; - pwszBuffer = new wchar_t[nBufLen]; - CC_BREAK_IF(!pwszBuffer); - memset(pwszBuffer, 0, sizeof(wchar_t) * nBufLen); - // str.size() not equal actuallyLen for Chinese char - int actuallyLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), nLen, pwszBuffer, nBufLen); - // SE_LOGE("_utf8ToUtf16, str:%s, strLen:%d, retLen:%d\n", str.c_str(), str.size(), actuallyLen); - if (pRetLen != nullptr) { - *pRetLen = actuallyLen; - } - } while (false); - return pwszBuffer; - } - - void removeCustomFont() { - HFONT hDefFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT); - if (hDefFont != _font) { - DeleteObject(SelectObject(_DC, hDefFont)); - } - // release temp font resource - if (!_curFontPath.empty()) { - wchar_t *pwszBuffer = utf8ToUtf16(_curFontPath); - if (pwszBuffer) { - RemoveFontResource(pwszBuffer); - SendMessage(_wnd, WM_FONTCHANGE, 0, 0); - delete[] pwszBuffer; - pwszBuffer = nullptr; - } - _curFontPath.clear(); - } - } - - // x, y offset value - int drawText(const std::string &text, int x, int y) { - int nRet = 0; - wchar_t *pwszBuffer = nullptr; - do { - CC_BREAK_IF(text.empty()); - - DWORD dwFmt = DT_SINGLELINE | DT_NOPREFIX; - - int bufferLen = 0; - pwszBuffer = utf8ToUtf16(text, &bufferLen); - - Size newSize = sizeWithText(pwszBuffer, bufferLen); - - _textSize = newSize; - - RECT rcText = {0}; - - rcText.right = newSize[0]; - rcText.bottom = newSize[1]; - - LONG offsetX = x; - LONG offsetY = y; - if (offsetX || offsetY) { - OffsetRect(&rcText, offsetX, offsetY); - } - - // SE_LOGE("_drawText text,%s size: (%d, %d) offset after convert: (%d, %d) \n", text.c_str(), newSize.cx, newSize.cy, offsetX, offsetY); - - SetBkMode(_DC, TRANSPARENT); - SetTextColor(_DC, RGB(255, 255, 255)); // white color - - // draw text - nRet = DrawTextW(_DC, pwszBuffer, bufferLen, &rcText, dwFmt); - } while (false); - CC_SAFE_DELETE_ARRAY(pwszBuffer); - - return nRet; - } - - Size sizeWithText(const wchar_t *pszText, int nLen) { - Size tRet{0, 0}; - do { - CC_BREAK_IF(!pszText || nLen <= 0); - - RECT rc = {0, 0, 0, 0}; - DWORD dwCalcFmt = DT_CALCRECT | DT_NOPREFIX; - - // measure text size - DrawTextW(_DC, pszText, nLen, &rc, dwCalcFmt); - - tRet[0] = rc.right; - tRet[1] = rc.bottom; - } while (false); - - return tRet; - } - - void prepareBitmap(int nWidth, int nHeight) { - // release bitmap - deleteBitmap(); - - if (nWidth > 0 && nHeight > 0) { - _bmp = CreateBitmap(nWidth, nHeight, 1, 32, nullptr); - SelectObject(_DC, _bmp); - } - } - - void deleteBitmap() { - if (_bmp) { - DeleteObject(_bmp); - _bmp = nullptr; - } - } - - void fillTextureData() { - do { - auto dataLen = static_cast(_bufferWidth * _bufferHeight * 4); - auto *dataBuf = static_cast(malloc(sizeof(unsigned char) * dataLen)); - CC_BREAK_IF(!dataBuf); - unsigned char *imageBuf = _imageData.getBytes(); - CC_BREAK_IF(!imageBuf); - - struct - { - BITMAPINFOHEADER bmiHeader; - int mask[4]; - } bi = {0}; - bi.bmiHeader.biSize = sizeof(bi.bmiHeader); - CC_BREAK_IF(!GetDIBits(_DC, _bmp, 0, 0, - nullptr, (LPBITMAPINFO)&bi, DIB_RGB_COLORS)); - - // copy pixel data - bi.bmiHeader.biHeight = (bi.bmiHeader.biHeight > 0) ? -bi.bmiHeader.biHeight : bi.bmiHeader.biHeight; - GetDIBits(_DC, _bmp, 0, _bufferHeight, dataBuf, - (LPBITMAPINFO)&bi, DIB_RGB_COLORS); - - uint8_t r = static_cast(round(_fillStyle[0] * 255)); - uint8_t g = static_cast(round(_fillStyle[1] * 255)); - uint8_t b = static_cast(round(_fillStyle[2] * 255)); - COLORREF textColor = (b << 16 | g << 8 | r) & 0x00ffffff; - COLORREF *pPixel = nullptr; - COLORREF *pImage = nullptr; - int bufferHeight = static_cast(_bufferHeight); - int bufferWidth = static_cast(_bufferWidth); - for (int y = 0; y < bufferHeight; ++y) { - pPixel = (COLORREF *)dataBuf + y * bufferWidth; - pImage = (COLORREF *)imageBuf + y * bufferWidth; - for (int x = 0; x < bufferWidth; ++x) { - COLORREF &clr = *pPixel; - COLORREF &val = *pImage; - // Because text is drawn in white color, and background color is black, - // so the red value is equal to alpha value. And we should keep this value - // as it includes anti-atlas information. - uint8_t alpha = GetRValue(clr) ? 255 : 0; - if (alpha > 0) { - val = (alpha << 24) | textColor; - } - ++pPixel; - ++pImage; - } - } - free(dataBuf); - } while (false); - } - - std::array convertDrawPoint(Point point, const std::string &text) { - Size textSize = measureText(text); - if (_textAlign == CanvasTextAlign::CENTER) { - point[0] -= textSize[0] / 2.0f; - } else if (_textAlign == CanvasTextAlign::RIGHT) { - point[0] -= textSize[0]; - } - - if (_textBaseLine == CanvasTextBaseline::TOP) { - // DrawText default - GetTextMetrics(_DC, &_tm); - point[1] += -_tm.tmInternalLeading; - } else if (_textBaseLine == CanvasTextBaseline::MIDDLE) { - point[1] += -textSize[1] / 2.0f; - } else if (_textBaseLine == CanvasTextBaseline::BOTTOM) { - point[1] += -textSize[1]; - } else if (_textBaseLine == CanvasTextBaseline::ALPHABETIC) { - GetTextMetrics(_DC, &_tm); - point[1] -= _tm.tmAscent; - } - - return point; - } -}; - -namespace cc { - -CanvasGradient::CanvasGradient() = default; - -CanvasGradient::~CanvasGradient() = default; - -void CanvasGradient::addColorStop(float offset, const std::string &color) { - //SE_LOGD("CanvasGradient::addColorStop: %p\n", this); -} - -// CanvasRenderingContext2D - -CanvasRenderingContext2D::CanvasRenderingContext2D(float width, float height) -: _width(width), - _height(height) { - //SE_LOGD("CanvasRenderingContext2D constructor: %p, width: %f, height: %f\n", this, width, height); - _impl = new CanvasRenderingContext2DImpl(); -} - -CanvasRenderingContext2D::~CanvasRenderingContext2D() { - //SE_LOGD("CanvasRenderingContext2D destructor: %p\n", this); - delete _impl; -} - -void CanvasRenderingContext2D::recreateBufferIfNeeded() { - if (_isBufferSizeDirty) { - _isBufferSizeDirty = false; - //SE_LOGD("Recreate buffer %p, w: %f, h:%f\n", this, __width, __height); - _impl->recreateBuffer(_width, _height); - if (_canvasBufferUpdatedCB != nullptr) { - _canvasBufferUpdatedCB(_impl->getDataRef()); - } - } -} - -void CanvasRenderingContext2D::clearRect(float x, float y, float width, float height) { - //SE_LOGD("CanvasRenderingContext2D::clearRect: %p, %f, %f, %f, %f\n", this, x, y, width, height); - recreateBufferIfNeeded(); - _impl->clearRect(x, y, width, height); -} - -void CanvasRenderingContext2D::fillRect(float x, float y, float width, float height) { - recreateBufferIfNeeded(); - _impl->fillRect(x, y, width, height); - - if (_canvasBufferUpdatedCB != nullptr) { - _canvasBufferUpdatedCB(_impl->getDataRef()); - } -} - -void CanvasRenderingContext2D::fillText(const std::string &text, float x, float y, float maxWidth) { - //SE_LOGD("CanvasRenderingContext2D::fillText: %s, offset: (%f, %f), %f\n", text.c_str(), x, y, maxWidth); - if (text.empty()) { - return; - } - - recreateBufferIfNeeded(); - - _impl->fillText(text, x, y, maxWidth); - if (_canvasBufferUpdatedCB != nullptr) { - _canvasBufferUpdatedCB(_impl->getDataRef()); - } -} - -void CanvasRenderingContext2D::strokeText(const std::string &text, float x, float y, float maxWidth) { - //SE_LOGD("CanvasRenderingContext2D::strokeText: %s, %f, %f, %f\n", text.c_str(), x, y, maxWidth); - if (text.empty()) { - return; - } - - recreateBufferIfNeeded(); - - _impl->strokeText(text, x, y, maxWidth); - - if (_canvasBufferUpdatedCB != nullptr) { - _canvasBufferUpdatedCB(_impl->getDataRef()); - } -} - -cc::Size CanvasRenderingContext2D::measureText(const std::string &text) { - //SE_LOGD("CanvasRenderingContext2D::measureText: %s\n", text.c_str()); - auto s = _impl->measureText(text); - return cc::Size(s[0], s[1]); -} - -CanvasGradient *CanvasRenderingContext2D::createLinearGradient(float /*x0*/, float /*y0*/, float /*x1*/, float /*y1*/) { - return nullptr; -} - -void CanvasRenderingContext2D::save() { - //SE_LOGD("CanvasRenderingContext2D::save\n"); - _impl->saveContext(); -} - -void CanvasRenderingContext2D::beginPath() { - //SE_LOGD("\n-----------begin------------------\nCanvasRenderingContext2D::beginPath\n"); - _impl->beginPath(); -} - -void CanvasRenderingContext2D::closePath() { - //SE_LOGD("CanvasRenderingContext2D::closePath\n"); - _impl->closePath(); -} - -void CanvasRenderingContext2D::moveTo(float x, float y) { - //SE_LOGD("CanvasRenderingContext2D::moveTo\n"); - _impl->moveTo(x, y); -} - -void CanvasRenderingContext2D::lineTo(float x, float y) { - //SE_LOGD("CanvasRenderingContext2D::lineTo\n"); - _impl->lineTo(x, y); -} - -void CanvasRenderingContext2D::stroke() { - //SE_LOGD("CanvasRenderingContext2D::stroke\n"); - _impl->stroke(); - - if (_canvasBufferUpdatedCB != nullptr) { - _canvasBufferUpdatedCB(_impl->getDataRef()); - } -} - -void CanvasRenderingContext2D::restore() { - //SE_LOGD("CanvasRenderingContext2D::restore\n"); - _impl->restoreContext(); -} - -void CanvasRenderingContext2D::setCanvasBufferUpdatedCallback(const CanvasBufferUpdatedCallback &cb) { - _canvasBufferUpdatedCB = cb; - recreateBufferIfNeeded(); -} - -void CanvasRenderingContext2D::setWidth(float width) { - //SE_LOGD("CanvasRenderingContext2D::set__width: %f\n", width); - if (math::IsEqualF(width, _width)) return; - _width = width; - _isBufferSizeDirty = true; - recreateBufferIfNeeded(); -} - -void CanvasRenderingContext2D::setHeight(float height) { - //SE_LOGD("CanvasRenderingContext2D::set__height: %f\n", height); - if (math::IsEqualF(height, _height)) return; - _height = height; - _isBufferSizeDirty = true; - recreateBufferIfNeeded(); -} - -void CanvasRenderingContext2D::setLineWidth(float lineWidth) { - //SE_LOGD("CanvasRenderingContext2D::set_lineWidth %d\n", lineWidth); - _lineWidth = lineWidth; - _impl->setLineWidth(lineWidth); -} - -void CanvasRenderingContext2D::setLineCap(const std::string &lineCap) { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::setLineJoin(const std::string &lineJoin) { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::fill() { - // SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} -void CanvasRenderingContext2D::rect(float x, float y, float w, float h) { - // SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::setFont(const std::string &font) { - if (_font != font) { - _font = font; - - std::string boldStr; - std::string fontName = "Arial"; - std::string fontSizeStr = "30"; - - // support get font name from `60px American` or `60px "American abc-abc_abc"` - std::regex re("(bold)?\\s*((\\d+)([\\.]\\d+)?)px\\s+([\\w-]+|\"[\\w -]+\"$)"); - std::match_results results; - if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) { - boldStr = results[1].str(); - fontSizeStr = results[2].str(); - fontName = results[5].str(); - } - - auto fontSize = static_cast(atof(fontSizeStr.c_str())); - //SE_LOGD("CanvasRenderingContext2D::set_font: %s, Size: %f, isBold: %b\n", fontName.c_str(), fontSize, !boldStr.empty()); - _impl->updateFont(fontName, fontSize, !boldStr.empty()); - } -} - -void CanvasRenderingContext2D::setTextAlign(const std::string &textAlign) { - //SE_LOGD("CanvasRenderingContext2D::set_textAlign: %s\n", textAlign.c_str()); - if (textAlign == "left") { - _impl->setTextAlign(CanvasTextAlign::LEFT); - } else if (textAlign == "center" || textAlign == "middle") { - _impl->setTextAlign(CanvasTextAlign::CENTER); - } else if (textAlign == "right") { - _impl->setTextAlign(CanvasTextAlign::RIGHT); - } else { - assert(false); - } -} - -void CanvasRenderingContext2D::setTextBaseline(const std::string &textBaseline) { - //SE_LOGD("CanvasRenderingContext2D::set_textBaseline: %s\n", textBaseline.c_str()); - if (textBaseline == "top") { - _impl->setTextBaseline(CanvasTextBaseline::TOP); - } else if (textBaseline == "middle") { - _impl->setTextBaseline(CanvasTextBaseline::MIDDLE); - } else if (textBaseline == "bottom") //REFINE:, how to deal with alphabetic, currently we handle it as bottom mode. - { - _impl->setTextBaseline(CanvasTextBaseline::BOTTOM); - } else if (textBaseline == "alphabetic") { - _impl->setTextBaseline(CanvasTextBaseline::ALPHABETIC); - } else { - assert(false); - } -} - -void CanvasRenderingContext2D::setFillStyle(const std::string &fillStyle) { - CSSColorParser::Color color = CSSColorParser::parse(fillStyle); - _impl->setFillStyle(static_cast(color.r) / 255.0F, - static_cast(color.g) / 255.0F, - static_cast(color.b) / 255.0F, - color.a); - //SE_LOGD("CanvasRenderingContext2D::set_fillStyle: %s, (%d, %d, %d, %f)\n", fillStyle.c_str(), color.r, color.g, color.b, color.a); -} - -void CanvasRenderingContext2D::setStrokeStyle(const std::string &strokeStyle) { - CSSColorParser::Color color = CSSColorParser::parse(strokeStyle); - _impl->setStrokeStyle(static_cast(color.r) / 255.0F, - static_cast(color.g) / 255.0F, - static_cast(color.b) / 255.0F, - color.a); -} - -void CanvasRenderingContext2D::setGlobalCompositeOperation(const std::string &globalCompositeOperation) { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} -// transform -//REFINE: - -void CanvasRenderingContext2D::translate(float x, float y) { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::scale(float x, float y) { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::rotate(float angle) { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::transform(float a, float b, float c, float d, float e, float f) { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -void CanvasRenderingContext2D::setTransform(float a, float b, float c, float d, float e, float f) { - //SE_LOGE("%s isn't implemented!\n", __FUNCTION__); -} - -} // namespace cc diff --git a/native/cocos/platform/win32/FileUtils-win32.cpp b/native/cocos/platform/win32/FileUtils-win32.cpp index 7abd53e31f..eb8f8e599f 100644 --- a/native/cocos/platform/win32/FileUtils-win32.cpp +++ b/native/cocos/platform/win32/FileUtils-win32.cpp @@ -28,12 +28,12 @@ #if CC_PLATFORM == CC_PLATFORM_WINDOWS #include "platform/win32/FileUtils-win32.h" + #include "platform/win32/Utils-win32.h" + #include "base/Log.h" #include #include #include #include - #include "base/Log.h" - #include "platform/win32/Utils-win32.h" using namespace std; @@ -48,8 +48,8 @@ static std::string s_resourcePath = ""; // D:\aaa\bbb\ccc\ddd\abc.txt --> D:/aaa/bbb/ccc/ddd/abc.txt static inline std::string convertPathFormatToUnixStyle(const std::string &path) { std::string ret = path; - size_t len = ret.length(); - for (size_t i = 0; i < len; ++i) { + int len = ret.length(); + for (int i = 0; i < len; ++i) { if (ret[i] == '\\') { ret[i] = '/'; } @@ -67,13 +67,7 @@ static void _checkPath() { WCHAR *pUtf16DirEnd = wcsrchr(pUtf16ExePath, L'\\'); char utf8ExeDir[CC_MAX_PATH] = {0}; - int nNum = WideCharToMultiByte(CP_UTF8, - 0, - static_cast(pUtf16ExePath), - static_cast(pUtf16DirEnd - pUtf16ExePath + 1), - static_cast(utf8ExeDir), - static_cast(sizeof(utf8ExeDir)), - nullptr, nullptr); + int nNum = WideCharToMultiByte(CP_UTF8, 0, pUtf16ExePath, pUtf16DirEnd - pUtf16ExePath + 1, utf8ExeDir, sizeof(utf8ExeDir), nullptr, nullptr); s_resourcePath = convertPathFormatToUnixStyle(utf8ExeDir); } @@ -120,7 +114,7 @@ long FileUtilsWin32::getFileSize(const std::string &filepath) { } LARGE_INTEGER size; size.HighPart = fad.nFileSizeHigh; - size.LowPart = fad.nFileSizeLow; + size.LowPart = fad.nFileSizeLow; return (long)size.QuadPart; } @@ -159,7 +153,7 @@ FileUtils::Status FileUtilsWin32::getContents(const std::string &filename, Resiz return FileUtils::Status::OPEN_FAILED; DWORD hi; - auto size = ::GetFileSize(fileHandle, &hi); + auto size = ::GetFileSize(fileHandle, &hi); if (hi > 0) { ::CloseHandle(fileHandle); return FileUtils::Status::TOO_LARGE; @@ -171,8 +165,8 @@ FileUtils::Status FileUtilsWin32::getContents(const std::string &filename, Resiz } buffer->resize(size); - DWORD sizeRead = 0; - BOOL successed = ::ReadFile(fileHandle, buffer->buffer(), size, &sizeRead, nullptr); + DWORD sizeRead = 0; + BOOL successed = ::ReadFile(fileHandle, buffer->buffer(), size, &sizeRead, nullptr); ::CloseHandle(fileHandle); if (!successed) { @@ -184,7 +178,7 @@ FileUtils::Status FileUtilsWin32::getContents(const std::string &filename, Resiz } std::string FileUtilsWin32::getPathForFilename(const std::string &filename, const std::string &searchPath) const { - std::string unixFileName = convertPathFormatToUnixStyle(filename); + std::string unixFileName = convertPathFormatToUnixStyle(filename); std::string unixSearchPath = convertPathFormatToUnixStyle(searchPath); return FileUtils::getPathForFilename(unixFileName, unixSearchPath); @@ -192,7 +186,7 @@ std::string FileUtilsWin32::getPathForFilename(const std::string &filename, cons std::string FileUtilsWin32::getFullPathForDirectoryAndFilename(const std::string &strDirectory, const std::string &strFilename) const { std::string unixDirectory = convertPathFormatToUnixStyle(strDirectory); - std::string unixFilename = convertPathFormatToUnixStyle(strFilename); + std::string unixFilename = convertPathFormatToUnixStyle(strFilename); return FileUtils::getFullPathForDirectoryAndFilename(unixDirectory, unixFilename); } @@ -209,7 +203,7 @@ string FileUtilsWin32::getWritablePath() const { // Debug app uses executable directory; Non-debug app uses local app data directory //#ifndef _DEBUG // Get filename of executable only, e.g. MyGame.exe - WCHAR * base_name = wcsrchr(full_path, '\\'); + WCHAR *base_name = wcsrchr(full_path, '\\'); wstring retPath; if (base_name) { WCHAR app_data_path[CC_MAX_PATH + 1]; @@ -271,7 +265,7 @@ bool FileUtilsWin32::renameFile(const std::string &path, const std::string &oldn std::string oldPath = path + oldname; std::string newPath = path + name; - std::regex pat("\\/"); + std::regex pat("\\/"); std::string _old = std::regex_replace(oldPath, pat, "\\"); std::string _new = std::regex_replace(newPath, pat, "\\"); @@ -287,9 +281,9 @@ bool FileUtilsWin32::createDirectory(const std::string &dirPath) { std::wstring path = StringUtf8ToWideChar(dirPath); // Split the path - size_t start = 0; - size_t found = path.find_first_of(L"/\\", start); - std::wstring subpath; + size_t start = 0; + size_t found = path.find_first_of(L"/\\", start); + std::wstring subpath; std::vector dirs; if (found != std::wstring::npos) { @@ -327,7 +321,7 @@ bool FileUtilsWin32::createDirectory(const std::string &dirPath) { } bool FileUtilsWin32::removeFile(const std::string &filepath) { - std::regex pat("\\/"); + std::regex pat("\\/"); std::string win32path = std::regex_replace(filepath, pat, "\\"); if (DeleteFile(StringUtf8ToWideChar(win32path).c_str())) { @@ -339,11 +333,11 @@ bool FileUtilsWin32::removeFile(const std::string &filepath) { } bool FileUtilsWin32::removeDirectory(const std::string &dirPath) { - std::wstring wpath = StringUtf8ToWideChar(dirPath); - std::wstring files = wpath + L"*.*"; + std::wstring wpath = StringUtf8ToWideChar(dirPath); + std::wstring files = wpath + L"*.*"; WIN32_FIND_DATA wfd; - HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0); - bool ret = true; + HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0); + bool ret = true; if (search != INVALID_HANDLE_VALUE) { BOOL find = true; while (find) { diff --git a/native/cocos/platform/win32/SystemGlue.cpp b/native/cocos/platform/win32/SystemGlue.cpp new file mode 100644 index 0000000000..e69de29bb2 diff --git a/native/cocos/platform/win32/SystemGlue.h b/native/cocos/platform/win32/SystemGlue.h new file mode 100644 index 0000000000..e69de29bb2 diff --git a/native/cocos/platform/win32/View-win32.cpp b/native/cocos/platform/win32/View-win32.cpp deleted file mode 100644 index 2ecfca8c66..0000000000 --- a/native/cocos/platform/win32/View-win32.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/**************************************************************************** - Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - 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 "View-win32.h" -#include -#include "base/Log.h" - -using namespace cc; - -namespace { - -std::unordered_map gKeyMap = { - {SDLK_APPLICATION, KeyCode::CONTEXT_MENU}, {SDLK_SCROLLLOCK, KeyCode::SCROLLLOCK}, {SDLK_PAUSE, KeyCode::PAUSE}, {SDLK_PRINTSCREEN, KeyCode::PRINT_SCREEN}, {SDLK_INSERT, KeyCode::INSERT}, {SDLK_ESCAPE, KeyCode::ESCAPE}, {SDLK_MINUS, KeyCode::MINUS}, {SDLK_LSHIFT, KeyCode::SHIFT_LEFT}, {SDLK_RSHIFT, KeyCode::SHIFT_RIGHT}, {SDLK_EQUALS, KeyCode::EQUAL}, {SDLK_BACKSLASH, KeyCode::BACKSLASH}, {SDLK_BACKQUOTE, KeyCode::BACKQUOTE}, {SDLK_BACKSPACE, KeyCode::BACKSPACE}, {SDLK_RETURN, KeyCode::ENTER}, {SDLK_RETURN2, KeyCode::ENTER}, {SDLK_LEFTBRACKET, KeyCode::BRACKET_LEFT}, {SDLK_RIGHTBRACKET, KeyCode::BRACKET_RIGHT}, {SDLK_SEMICOLON, KeyCode::SEMICOLON}, {SDLK_QUOTE, KeyCode::QUOTE}, {SDLK_TAB, KeyCode::TAB}, {SDLK_LCTRL, KeyCode::CONTROL_LEFT}, {SDLK_RCTRL, KeyCode::CONTROL_RIGHT}, {SDLK_LALT, KeyCode::ALT_LEFT}, {SDLK_RALT, KeyCode::ALT_RIGHT}, {SDLK_LEFT, KeyCode::ARROW_LEFT}, {SDLK_RIGHT, KeyCode::ARROW_RIGHT}, {SDLK_UP, KeyCode::ARROW_UP}, {SDLK_DOWN, KeyCode::ARROW_DOWN}, {SDLK_KP_ENTER, KeyCode::NUMPAD_ENTER}, {SDLK_KP_PLUS, KeyCode::NUMPAD_PLUS}, {SDLK_KP_MULTIPLY, KeyCode::NUMPAD_MULTIPLY}, {SDLK_KP_DIVIDE, KeyCode::NUMPAD_DIVIDE}, {SDLK_KP_MINUS, KeyCode::NUMPAD_MINUS}, {SDLK_KP_PERIOD, KeyCode::NUMPAD_DECIMAL}, {SDLK_KP_BACKSPACE, KeyCode::BACKSPACE}, {SDLK_NUMLOCKCLEAR, KeyCode::NUM_LOCK}, {SDLK_HOME, KeyCode::HOME}, {SDLK_PAGEUP, KeyCode::PAGE_UP}, {SDLK_PAGEDOWN, KeyCode::PAGE_DOWN}, {SDLK_END, KeyCode::END}, {SDLK_COMMA, KeyCode::COMMA}, {SDLK_PERIOD, KeyCode::PERIOD}, {SDLK_SLASH, KeyCode::SLASH}, {SDLK_SPACE, KeyCode::SPACE}, {SDLK_DELETE, KeyCode::DELETE_KEY}, {SDLK_CAPSLOCK, KeyCode::CAPS_LOCK}, {SDLK_KP_0, KeyCode::NUMPAD_0}, {SDLK_KP_1, KeyCode::NUMPAD_1}, {SDLK_KP_2, KeyCode::NUMPAD_2}, {SDLK_KP_3, KeyCode::NUMPAD_3}, {SDLK_KP_4, KeyCode::NUMPAD_4}, {SDLK_KP_5, KeyCode::NUMPAD_5}, {SDLK_KP_6, KeyCode::NUMPAD_6}, {SDLK_KP_7, KeyCode::NUMPAD_7}, {SDLK_KP_8, KeyCode::NUMPAD_8}, {SDLK_KP_9, KeyCode::NUMPAD_9}}; - -int sdlKeycodeToCocosCode(int code_, int mode) { - auto it = gKeyMap.find(code_); - if (it != gKeyMap.end()) { - return static_cast(it->second); - } - - if (code_ >= SDLK_F1 && code_ <= SDLK_F12) { - // F1 ~ F12 - return 112 + (code_ - SDLK_F1); - } else { - int code = code_ & (~(1 << 30)); - if (code >= SDLK_a && code <= SDLK_z) { - return 'A' + (code - SDLK_a); - } else { - return code; - } - } -} -} // namespace - -namespace cc { - -View::View(const std::string &title, int width, int height) : _title(title), - _width(width), - _height(height) { -} - -View::~View() { - if (_window) { - SDL_DestroyWindow(_window); - _window = nullptr; - } - if (_inited) { - SDL_Quit(); - } -} - -bool View::init() { - if (SDL_Init(SDL_INIT_VIDEO) < 0) { - // Display error message - CC_LOG_ERROR("SDL could not initialize! SDL_Error: %s\n", SDL_GetError()); - return false; - } - _inited = true; - // Create window - uint32_t flags = SDL_WINDOW_SHOWN | - SDL_WINDOW_RESIZABLE | - SDL_WINDOW_INPUT_FOCUS; - _window = SDL_CreateWindow(_title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, _width, _height, flags); - if (_window == NULL) { - // Display error message - CC_LOG_ERROR("Window could not be created! SDL_Error: %s\n", SDL_GetError()); - return false; - } - - return true; -} - -bool View::pollEvent(bool *quit, bool *resume, bool *pause, bool *close) { - int cnt = SDL_PollEvent(&sdlEvent); - if (cnt == 0) return false; - cc::TouchEvent touch; - cc::MouseEvent mouse; - cc::KeyboardEvent keyboard; - switch (sdlEvent.type) { - case SDL_QUIT: { - if (quit) *quit = true; - break; - } - case SDL_WINDOWEVENT: { - SDL_WindowEvent &wevent = sdlEvent.window; - switch (wevent.event) { - case SDL_WINDOWEVENT_SHOWN: - case SDL_WINDOWEVENT_RESTORED: - *resume = true; - break; - case SDL_WINDOWEVENT_SIZE_CHANGED: - case SDL_WINDOWEVENT_RESIZED: - this->_width = wevent.data1; - this->_height = wevent.data2; - cc::EventDispatcher::dispatchResizeEvent(wevent.data1, wevent.data2); - break; - case SDL_WINDOWEVENT_HIDDEN: - case SDL_WINDOWEVENT_MINIMIZED: - *pause = true; - break; - case SDL_WINDOWEVENT_ENTER: - SDL_CaptureMouse(SDL_TRUE); - break; - case SDL_WINDOWEVENT_CLOSE: - *close = true; - break; - } - break; - } - case SDL_MOUSEBUTTONDOWN: { - SDL_MouseButtonEvent &event = sdlEvent.button; - mouse.type = MouseEvent::Type::DOWN; - mouse.x = static_cast(event.x); - mouse.y = static_cast(event.y); - if (0 > mouse.x || mouse.x > this->_width || 0 > mouse.y || mouse.y > this->_height) { - break; - } - mouse.button = event.button - 1; - cc::EventDispatcher::dispatchMouseEvent(mouse); - break; - } - case SDL_MOUSEBUTTONUP: { - SDL_MouseButtonEvent &event = sdlEvent.button; - mouse.type = MouseEvent::Type::UP; - mouse.x = static_cast(event.x); - mouse.y = static_cast(event.y); - mouse.button = event.button - 1; - cc::EventDispatcher::dispatchMouseEvent(mouse); - break; - } - case SDL_MOUSEMOTION: { - SDL_MouseMotionEvent &event = sdlEvent.motion; - mouse.type = MouseEvent::Type::MOVE; - mouse.x = static_cast(event.x); - mouse.y = static_cast(event.y); - mouse.button = 0; - cc::EventDispatcher::dispatchMouseEvent(mouse); - break; - } - case SDL_MOUSEWHEEL: { - SDL_MouseWheelEvent &event = sdlEvent.wheel; - mouse.type = MouseEvent::Type::WHEEL; - mouse.x = static_cast(event.x); - mouse.y = static_cast(event.y); - mouse.button = 0; //TODO: direction - cc::EventDispatcher::dispatchMouseEvent(mouse); - break; - } - case SDL_FINGERUP: { - SDL_TouchFingerEvent &event = sdlEvent.tfinger; - touch.type = TouchEvent::Type::ENDED; - touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; - cc::EventDispatcher::dispatchTouchEvent(touch); - break; - } - case SDL_FINGERDOWN: { - SDL_TouchFingerEvent &event = sdlEvent.tfinger; - touch.type = TouchEvent::Type::BEGAN; - touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; - cc::EventDispatcher::dispatchTouchEvent(touch); - break; - } - case SDL_FINGERMOTION: { - SDL_TouchFingerEvent &event = sdlEvent.tfinger; - touch.type = TouchEvent::Type::MOVED; - touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; - cc::EventDispatcher::dispatchTouchEvent(touch); - break; - } - case SDL_KEYDOWN: { - SDL_KeyboardEvent &event = sdlEvent.key; - auto mode = event.keysym.mod; - keyboard.action = KeyboardEvent::Action::PRESS; - keyboard.key = sdlKeycodeToCocosCode(event.keysym.sym, mode); - keyboard.altKeyActive = mode & KMOD_ALT; - keyboard.ctrlKeyActive = mode & KMOD_CTRL; - keyboard.shiftKeyActive = mode & KMOD_SHIFT; - //CC_LOG_DEBUG("==> key %d -> code %d", event.keysym.sym, keyboard.key); - cc::EventDispatcher::dispatchKeyboardEvent(keyboard); - break; - } - case SDL_KEYUP: { - SDL_KeyboardEvent &event = sdlEvent.key; - auto mode = event.keysym.mod; - keyboard.action = KeyboardEvent::Action::RELEASE; - keyboard.key = sdlKeycodeToCocosCode(event.keysym.sym, mode); - keyboard.altKeyActive = mode & KMOD_ALT; - keyboard.ctrlKeyActive = mode & KMOD_CTRL; - keyboard.shiftKeyActive = mode & KMOD_SHIFT; - cc::EventDispatcher::dispatchKeyboardEvent(keyboard); - break; - } - default: - - break; - } - - return true; -} - -HWND View::getWindowHandler() { - assert(_window); - SDL_SysWMinfo wmInfo; - SDL_VERSION(&wmInfo.version); - SDL_GetWindowWMInfo(_window, &wmInfo); - return wmInfo.info.win.window; -} - -void View::setCursorEnabeld(bool enable) { - SDL_SetRelativeMouseMode(enable ? SDL_FALSE : SDL_TRUE); -} - -} // namespace cc diff --git a/native/cocos/platform/win32/WindowsPlatform.cpp b/native/cocos/platform/win32/WindowsPlatform.cpp new file mode 100644 index 0000000000..531fa54b18 --- /dev/null +++ b/native/cocos/platform/win32/WindowsPlatform.cpp @@ -0,0 +1,463 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/win32/WindowsPlatform.h" +#include "sdl2/SDL.h" +#include "sdl2/SDL_main.h" +#include "sdl2/SDL_syswm.h" + +#include +#include +#include +#include +#include "platform/interfaces/OSInterface.h" +#include "platform/interfaces/modules/ISystemWindow.h" + +namespace { +/** + @brief This function changes the PVRFrame show/hide setting in register. + @param bEnable If true show the PVRFrame window, otherwise hide. + */ +void PVRFrameEnableControlWindow(bool bEnable) { + HKEY hKey = 0; + + // Open PVRFrame control key, if not exist create it. + if (ERROR_SUCCESS != RegCreateKeyExW(HKEY_CURRENT_USER, + L"Software\\Imagination Technologies\\PVRVFRame\\STARTUP\\", + 0, + 0, + REG_OPTION_NON_VOLATILE, + KEY_ALL_ACCESS, + 0, + &hKey, + nullptr)) { + return; + } + + const WCHAR *wszValue = L"hide_gui"; + const WCHAR *wszNewData = (bEnable) ? L"NO" : L"YES"; + WCHAR wszOldData[256] = {0}; + DWORD dwSize = sizeof(wszOldData); + LSTATUS status = RegQueryValueExW(hKey, wszValue, 0, nullptr, (LPBYTE)wszOldData, &dwSize); + if (ERROR_FILE_NOT_FOUND == status // the key not exist + || (ERROR_SUCCESS == status // or the hide_gui value is exist + && 0 != wcscmp(wszNewData, wszOldData))) // but new data and old data not equal + { + dwSize = sizeof(WCHAR) * (wcslen(wszNewData) + 1); + RegSetValueEx(hKey, wszValue, 0, REG_SZ, (const BYTE *)wszNewData, dwSize); + } + + RegCloseKey(hKey); +} + +std::unordered_map gKeyMap = { + {SDLK_APPLICATION, cc::KeyCode::CONTEXT_MENU}, + {SDLK_SCROLLLOCK, cc::KeyCode::SCROLLLOCK}, + {SDLK_PAUSE, cc::KeyCode::PAUSE}, + {SDLK_PRINTSCREEN, cc::KeyCode::PRINT_SCREEN}, + {SDLK_INSERT, cc::KeyCode::INSERT}, + {SDLK_ESCAPE, cc::KeyCode::ESCAPE}, + {SDLK_MINUS, cc::KeyCode::MINUS}, + {SDLK_LSHIFT, cc::KeyCode::SHIFT_LEFT}, + {SDLK_RSHIFT, cc::KeyCode::SHIFT_RIGHT}, + {SDLK_EQUALS, cc::KeyCode::EQUAL}, + {SDLK_BACKSLASH, cc::KeyCode::BACKSLASH}, + {SDLK_BACKQUOTE, cc::KeyCode::BACKQUOTE}, + {SDLK_BACKSPACE, cc::KeyCode::BACKSPACE}, + {SDLK_RETURN, cc::KeyCode::ENTER}, + {SDLK_RETURN2, cc::KeyCode::ENTER}, + {SDLK_LEFTBRACKET, cc::KeyCode::BRACKET_LEFT}, + {SDLK_RIGHTBRACKET, cc::KeyCode::BRACKET_RIGHT}, + {SDLK_SEMICOLON, cc::KeyCode::SEMICOLON}, + {SDLK_QUOTE, cc::KeyCode::QUOTE}, + {SDLK_TAB, cc::KeyCode::TAB}, + {SDLK_LCTRL, cc::KeyCode::CONTROL_LEFT}, + {SDLK_RCTRL, cc::KeyCode::CONTROL_RIGHT}, + {SDLK_LALT, cc::KeyCode::ALT_LEFT}, + {SDLK_RALT, cc::KeyCode::ALT_RIGHT}, + {SDLK_LEFT, cc::KeyCode::ARROW_LEFT}, + {SDLK_RIGHT, cc::KeyCode::ARROW_RIGHT}, + {SDLK_UP, cc::KeyCode::ARROW_UP}, + {SDLK_DOWN, cc::KeyCode::ARROW_DOWN}, + {SDLK_KP_ENTER, cc::KeyCode::NUMPAD_ENTER}, + {SDLK_KP_PLUS, cc::KeyCode::NUMPAD_PLUS}, + {SDLK_KP_MULTIPLY, cc::KeyCode::NUMPAD_MULTIPLY}, + {SDLK_KP_DIVIDE, cc::KeyCode::NUMPAD_DIVIDE}, + {SDLK_KP_MINUS, cc::KeyCode::NUMPAD_MINUS}, + {SDLK_KP_PERIOD, cc::KeyCode::NUMPAD_DECIMAL}, + {SDLK_KP_BACKSPACE, cc::KeyCode::BACKSPACE}, + {SDLK_NUMLOCKCLEAR, cc::KeyCode::NUM_LOCK}, + {SDLK_HOME, cc::KeyCode::HOME}, + {SDLK_PAGEUP, cc::KeyCode::PAGE_UP}, + {SDLK_PAGEDOWN, cc::KeyCode::PAGE_DOWN}, + {SDLK_END, cc::KeyCode::END}, + {SDLK_COMMA, cc::KeyCode::COMMA}, + {SDLK_PERIOD, cc::KeyCode::PERIOD}, + {SDLK_SLASH, cc::KeyCode::SLASH}, + {SDLK_SPACE, cc::KeyCode::SPACE}, + {SDLK_DELETE, cc::KeyCode::DELETE_KEY}, + {SDLK_CAPSLOCK, cc::KeyCode::CAPS_LOCK}, + {SDLK_KP_0, cc::KeyCode::NUMPAD_0}, + {SDLK_KP_1, cc::KeyCode::NUMPAD_1}, + {SDLK_KP_2, cc::KeyCode::NUMPAD_2}, + {SDLK_KP_3, cc::KeyCode::NUMPAD_3}, + {SDLK_KP_4, cc::KeyCode::NUMPAD_4}, + {SDLK_KP_5, cc::KeyCode::NUMPAD_5}, + {SDLK_KP_6, cc::KeyCode::NUMPAD_6}, + {SDLK_KP_7, cc::KeyCode::NUMPAD_7}, + {SDLK_KP_8, cc::KeyCode::NUMPAD_8}, + {SDLK_KP_9, cc::KeyCode::NUMPAD_9}}; + +int sdlKeycodeToCocosCode(int sdlCode, int mode) { + auto it = gKeyMap.find(sdlCode); + if (it != gKeyMap.end()) { + return static_cast(it->second); + } + + if (sdlCode >= SDLK_F1 && sdlCode <= SDLK_F12) { + // F1 ~ F12 + return 112 + (sdlCode - SDLK_F1); + } else { + int code = sdlCode & (~(1 << 30)); + if (code >= SDLK_a && code <= SDLK_z) { + return 'A' + (code - SDLK_a); + } else { + return code; + } + } +} + +std::unordered_map gWindowFlagMap = { + {cc::ISystemWindow::CC_WINDOW_FULLSCREEN, SDL_WINDOW_FULLSCREEN}, + {cc::ISystemWindow::CC_WINDOW_OPENGL, SDL_WINDOW_OPENGL}, + {cc::ISystemWindow::CC_WINDOW_SHOWN, SDL_WINDOW_SHOWN}, + {cc::ISystemWindow::CC_WINDOW_HIDDEN, SDL_WINDOW_HIDDEN}, + {cc::ISystemWindow::CC_WINDOW_BORDERLESS, SDL_WINDOW_BORDERLESS}, + {cc::ISystemWindow::CC_WINDOW_RESIZABLE, SDL_WINDOW_RESIZABLE}, + {cc::ISystemWindow::CC_WINDOW_MINIMIZED, SDL_WINDOW_MINIMIZED}, + {cc::ISystemWindow::CC_WINDOW_MAXIMIZED, SDL_WINDOW_MAXIMIZED}, + {cc::ISystemWindow::CC_WINDOW_INPUT_GRABBED, SDL_WINDOW_INPUT_GRABBED}, + {cc::ISystemWindow::CC_WINDOW_INPUT_FOCUS, SDL_WINDOW_INPUT_FOCUS}, + {cc::ISystemWindow::CC_WINDOW_MOUSE_FOCUS, SDL_WINDOW_MOUSE_FOCUS}, + {cc::ISystemWindow::CC_WINDOW_FULLSCREEN_DESKTOP, SDL_WINDOW_FULLSCREEN_DESKTOP}, + {cc::ISystemWindow::CC_WINDOW_FOREIGN, SDL_WINDOW_FOREIGN}, + {cc::ISystemWindow::CC_WINDOW_ALLOW_HIGHDPI, SDL_WINDOW_ALLOW_HIGHDPI}, + {cc::ISystemWindow::CC_WINDOW_MOUSE_CAPTURE, SDL_WINDOW_MOUSE_CAPTURE}, + {cc::ISystemWindow::CC_WINDOW_ALWAYS_ON_TOP, SDL_WINDOW_ALWAYS_ON_TOP}, + {cc::ISystemWindow::CC_WINDOW_SKIP_TASKBAR, SDL_WINDOW_SKIP_TASKBAR}, + {cc::ISystemWindow::CC_WINDOW_UTILITY, SDL_WINDOW_UTILITY}, + {cc::ISystemWindow::CC_WINDOW_TOOLTIP, SDL_WINDOW_TOOLTIP}, + {cc::ISystemWindow::CC_WINDOW_POPUP_MENU, SDL_WINDOW_POPUP_MENU}, + {cc::ISystemWindow::CC_WINDOW_VULKAN, SDL_WINDOW_VULKAN}}; + +int windowFlagsToSDLWindowFlag(int flags) { + int sdlFlags = 0; + for (auto it : gWindowFlagMap) { + if ((it.first & flags) == it.first) { + sdlFlags |= it.second; + } + } + return sdlFlags; +} + +} // namespace + +namespace cc { +WindowsPlatform::WindowsPlatform() = default; +WindowsPlatform::~WindowsPlatform() { + if (_handle) { + SDL_DestroyWindow(_handle); + _handle = nullptr; + } + if (_inited) { + SDL_Quit(); + } +#ifdef USE_WIN32_CONSOLE + FreeConsole(); +#endif +} + +int32_t WindowsPlatform::init() { + UniversalPlatform::init(); +#ifdef USE_WIN32_CONSOLE + AllocConsole(); + freopen("CONIN$", "r", stdin); + freopen("CONOUT$", "w", stdout); + freopen("CONOUT$", "w", stderr); +#endif + + PVRFrameEnableControlWindow(false); + + if (SDL_Init(SDL_INIT_VIDEO) < 0) { + // Display error message + CC_LOG_ERROR("SDL could not initialize! SDL_Error: %s\n", SDL_GetError()); + return false; + } + return 0; +} + +int32_t WindowsPlatform::loop() { + /////////////////////////////////////////////////////////////////////////// + /////////////// changing timer resolution + /////////////////////////////////////////////////////////////////////////// + UINT TARGET_RESOLUTION = 1; // 1 millisecond target resolution + TIMECAPS tc; + UINT wTimerRes = 0; + if (TIMERR_NOERROR == timeGetDevCaps(&tc, sizeof(TIMECAPS))) { + wTimerRes = std::min(std::max(tc.wPeriodMin, TARGET_RESOLUTION), tc.wPeriodMax); + timeBeginPeriod(wTimerRes); + } + + float dt = 0.f; + const DWORD _16ms = 16; + + // Main message loop: + LARGE_INTEGER nFreq; + LARGE_INTEGER nLast; + LARGE_INTEGER nNow; + + LONGLONG actualInterval = 0LL; // actual frame internal + LONGLONG desiredInterval = 0LL; // desired frame internal, 1 / fps + LONG waitMS = 0L; + + QueryPerformanceCounter(&nLast); + QueryPerformanceFrequency(&nFreq); + + onResume(); + while (!_quit) { + desiredInterval = (LONGLONG)(1.0 / getFps() * nFreq.QuadPart); + pollEvent(); + QueryPerformanceCounter(&nNow); + actualInterval = nNow.QuadPart - nLast.QuadPart; + if (actualInterval >= desiredInterval) { + nLast.QuadPart = nNow.QuadPart; + runTask(); + SDL_GL_SwapWindow(_handle); + } else { + // The precision of timer on Windows is set to highest (1ms) by 'timeBeginPeriod' from above code, + // but it's still not precise enough. For example, if the precision of timer is 1ms, + // Sleep(3) may make a sleep of 2ms or 4ms. Therefore, we subtract 1ms here to make Sleep time shorter. + // If 'waitMS' is equal or less than 1ms, don't sleep and run into next loop to + // boost CPU to next frame accurately. + waitMS = static_cast((desiredInterval - actualInterval) * 1000LL / nFreq.QuadPart - 1L); + if (waitMS > 1L) + Sleep(waitMS); + } + } + + if (wTimerRes != 0) + timeEndPeriod(wTimerRes); + + onDestory(); + return 0; +} + +void WindowsPlatform::handleWindowEvent(SDL_WindowEvent &wevent) { + WindowEvent ev; + switch (wevent.event) { + case SDL_WINDOWEVENT_SHOWN: { + ev.type = WindowEvent::Type::SHOW; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT_RESTORED: { + ev.type = WindowEvent::Type::RESTORED; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT_SIZE_CHANGED: { + ev.type = WindowEvent::Type::SIZE_CHANGED; + ev.width = wevent.data1; + ev.height = wevent.data2; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT_RESIZED: { + ev.type = WindowEvent::Type::RESIZED; + ev.width = wevent.data1; + ev.height = wevent.data2; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT_HIDDEN: { + ev.type = WindowEvent::Type::HIDDEN; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT_MINIMIZED: { + ev.type = WindowEvent::Type::MINIMIZED; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT_ENTER: { + SDL_CaptureMouse(SDL_TRUE); + break; + } + case SDL_WINDOWEVENT_CLOSE: { + ev.type = WindowEvent::Type::CLOSE; + dispatchEvent(ev); + break; + } + } +} + +void WindowsPlatform::pollEvent() { + SDL_Event sdlEvent; + int cnt = SDL_PollEvent(&sdlEvent); + if (cnt == 0) { + return; + } + cc::TouchEvent touch; + cc::MouseEvent mouse; + cc::KeyboardEvent keyboard; + switch (sdlEvent.type) { + case SDL_QUIT: { + _quit = true; + WindowEvent ev; + ev.type = WindowEvent::Type::QUIT; + dispatchEvent(ev); + break; + } + case SDL_WINDOWEVENT: { + handleWindowEvent(sdlEvent.window); + break; + } + case SDL_MOUSEBUTTONDOWN: { + SDL_MouseButtonEvent &event = sdlEvent.button; + mouse.type = MouseEvent::Type::DOWN; + mouse.x = static_cast(event.x); + mouse.y = static_cast(event.y); + /*if (0 > mouse.x || mouse.x > this->_width || 0 > mouse.y || mouse.y > this->_height) { + break; + }*/ + mouse.button = event.button - 1; + dispatchEvent(mouse); + break; + } + case SDL_MOUSEBUTTONUP: { + SDL_MouseButtonEvent &event = sdlEvent.button; + mouse.type = MouseEvent::Type::UP; + mouse.x = static_cast(event.x); + mouse.y = static_cast(event.y); + mouse.button = event.button - 1; + dispatchEvent(mouse); + break; + } + case SDL_MOUSEMOTION: { + SDL_MouseMotionEvent &event = sdlEvent.motion; + mouse.type = MouseEvent::Type::MOVE; + mouse.x = static_cast(event.x); + mouse.y = static_cast(event.y); + mouse.button = 0; + dispatchEvent(mouse); + break; + } + case SDL_MOUSEWHEEL: { + SDL_MouseWheelEvent &event = sdlEvent.wheel; + mouse.type = MouseEvent::Type::WHEEL; + mouse.x = static_cast(event.x); + mouse.y = static_cast(event.y); + mouse.button = 0; //TODO: direction + dispatchEvent(mouse); + break; + } + case SDL_FINGERUP: { + SDL_TouchFingerEvent &event = sdlEvent.tfinger; + touch.type = TouchEvent::Type::ENDED; + touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; + dispatchEvent(touch); + break; + } + case SDL_FINGERDOWN: { + SDL_TouchFingerEvent &event = sdlEvent.tfinger; + touch.type = TouchEvent::Type::BEGAN; + touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; + dispatchEvent(touch); + break; + } + case SDL_FINGERMOTION: { + SDL_TouchFingerEvent &event = sdlEvent.tfinger; + touch.type = TouchEvent::Type::MOVED; + touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; + dispatchEvent(touch); + break; + } + case SDL_KEYDOWN: { + SDL_KeyboardEvent &event = sdlEvent.key; + auto mode = event.keysym.mod; + keyboard.action = KeyboardEvent::Action::PRESS; + keyboard.key = sdlKeycodeToCocosCode(event.keysym.sym, mode); + keyboard.altKeyActive = mode & KMOD_ALT; + keyboard.ctrlKeyActive = mode & KMOD_CTRL; + keyboard.shiftKeyActive = mode & KMOD_SHIFT; + //CC_LOG_DEBUG("==> key %d -> code %d", event.keysym.sym, keyboard.key); + //cc::EventDispatcher::dispatchKeyboardEvent(keyboard); + dispatchEvent(keyboard); + break; + } + case SDL_KEYUP: { + SDL_KeyboardEvent &event = sdlEvent.key; + auto mode = event.keysym.mod; + keyboard.action = KeyboardEvent::Action::RELEASE; + keyboard.key = sdlKeycodeToCocosCode(event.keysym.sym, mode); + keyboard.altKeyActive = mode & KMOD_ALT; + keyboard.ctrlKeyActive = mode & KMOD_CTRL; + keyboard.shiftKeyActive = mode & KMOD_SHIFT; + dispatchEvent(keyboard); + //cc::EventDispatcher::dispatchKeyboardEvent(keyboard); + break; + } + default: + + break; + } +} + +bool WindowsPlatform::createWindow(const char *title, + int x, int y, int w, + int h, int flags) { + if (_inited) { + return true; + } + // Create window + int sdlFlags = windowFlagsToSDLWindowFlag(flags); + _handle = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, w, h, sdlFlags); + if (_handle == nullptr) { + // Display error message + CC_LOG_ERROR("Window could not be created! SDL_Error: %s\n", SDL_GetError()); + return false; + } + _inited = true; + return true; +} + +uintptr_t WindowsPlatform::getWindowHandler() const { + SDL_SysWMinfo wmInfo; + SDL_VERSION(&wmInfo.version); + SDL_GetWindowWMInfo(_handle, &wmInfo); + return reinterpret_cast(wmInfo.info.win.window); +} + +} // namespace cc diff --git a/native/cocos/platform/win32/WindowsPlatform.h b/native/cocos/platform/win32/WindowsPlatform.h new file mode 100644 index 0000000000..98eb162757 --- /dev/null +++ b/native/cocos/platform/win32/WindowsPlatform.h @@ -0,0 +1,65 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/UniversalPlatform.h" +#include "platform/win32/modules/SystemWindow.h" + +struct SDL_WindowEvent; +struct SDL_Window; + +namespace cc { + +class WindowsPlatform : public UniversalPlatform , + public SystemWindow::Delegate{ +public: + WindowsPlatform(); + /** + * Destructor of WindowPlatform. + */ + ~WindowsPlatform() override; + /** + * Implementation of Windows platform initialization. + */ + int32_t init() override; + + int32_t loop() override; + + // override from SystemWindow::Delegate + bool createWindow(const char* title, + int x, int y, int w, + int h, int flags) override; + uintptr_t getWindowHandler() const override; + +private: + void pollEvent() override; + void handleWindowEvent(SDL_WindowEvent& wevent); + bool _inited{false}; + bool _quit{false}; + struct SDL_Window* _handle{nullptr}; +}; + +} // namespace cc diff --git a/native/cocos/platform/win32/modules/Accelerometer.cpp b/native/cocos/platform/win32/modules/Accelerometer.cpp new file mode 100644 index 0000000000..cc8aed6e93 --- /dev/null +++ b/native/cocos/platform/win32/modules/Accelerometer.cpp @@ -0,0 +1,40 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/win32/modules/Accelerometer.h" + +namespace cc { +void Accelerometer::setAccelerometerEnabled(bool isEnabled) { +} + +void Accelerometer::setAccelerometerInterval(float interval) { +} + +const Accelerometer::MotionValue& Accelerometer::getDeviceMotionValue() { + static MotionValue motionValue; + return motionValue; +} + +} // namespace cc diff --git a/native/cocos/platform/win32/modules/Accelerometer.h b/native/cocos/platform/win32/modules/Accelerometer.h new file mode 100644 index 0000000000..a760b03564 --- /dev/null +++ b/native/cocos/platform/win32/modules/Accelerometer.h @@ -0,0 +1,50 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IAccelerometer.h" + +namespace cc { + +class Accelerometer : public IAccelerometer { +public: + /** + * To enable or disable accelerometer. + */ + void setAccelerometerEnabled(bool isEnabled) override; + + /** + * Sets the interval of accelerometer. + */ + void setAccelerometerInterval(float interval) override; + + /** + * Gets the motion value of current device. + */ + const MotionValue &getDeviceMotionValue() override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/win32/modules/Battery.cpp b/native/cocos/platform/win32/modules/Battery.cpp new file mode 100644 index 0000000000..e1d792c265 --- /dev/null +++ b/native/cocos/platform/win32/modules/Battery.cpp @@ -0,0 +1,33 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/win32/modules/Battery.h" + +namespace cc { + +float Battery::getBatteryLevel() const { + return 1.0F; +} + +} // namespace cc diff --git a/native/cocos/platform/win32/modules/Battery.h b/native/cocos/platform/win32/modules/Battery.h new file mode 100644 index 0000000000..5dc4390c5d --- /dev/null +++ b/native/cocos/platform/win32/modules/Battery.h @@ -0,0 +1,37 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IBattery.h" + +namespace cc { + +class Battery : public IBattery { +public: + float getBatteryLevel() const override; +}; + +} // namespace cc diff --git a/native/cocos/platform/win32/modules/CanvasRenderingContext2DDelegate.cpp b/native/cocos/platform/win32/modules/CanvasRenderingContext2DDelegate.cpp new file mode 100644 index 0000000000..494eebaaee --- /dev/null +++ b/native/cocos/platform/win32/modules/CanvasRenderingContext2DDelegate.cpp @@ -0,0 +1,504 @@ +/**************************************************************************** + Copyright (c) 2018-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/win32/modules/CanvasRenderingContext2DDelegate.h" + +namespace { +void fillRectWithColor(uint8_t *buf, uint32_t totalWidth, uint32_t totalHeight, uint32_t x, uint32_t y, uint32_t width, uint32_t height, uint8_t r, uint8_t g, uint8_t b, uint8_t a) { + assert(x + width <= totalWidth); + assert(y + height <= totalHeight); + + uint32_t y0 = y; + uint32_t y1 = y + height; + uint8_t *p; + for (uint32_t offsetY = y0; offsetY < y1; ++offsetY) { + for (uint32_t offsetX = x; offsetX < (x + width); ++offsetX) { + p = buf + (totalWidth * offsetY + offsetX) * 4; + *p++ = r; + *p++ = g; + *p++ = b; + *p++ = a; + } + } +} +} // namespace + +namespace cc { +CanvasRenderingContext2DDelegate::CanvasRenderingContext2DDelegate() { + HDC hdc = GetDC(_wnd); + _DC = CreateCompatibleDC(hdc); + ReleaseDC(_wnd, hdc); +} + +CanvasRenderingContext2DDelegate::~CanvasRenderingContext2DDelegate() { + deleteBitmap(); + removeCustomFont(); + if (_DC) + DeleteDC(_DC); +} + +void CanvasRenderingContext2DDelegate::recreateBuffer(float w, float h) { + _bufferWidth = w; + _bufferHeight = h; + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + deleteBitmap(); + return; + } + + auto textureSize = static_cast(_bufferWidth * _bufferHeight * 4); + auto *data = static_cast(malloc(sizeof(uint8_t) * textureSize)); + memset(data, 0x00, textureSize); + _imageData.fastSet(data, textureSize); + + prepareBitmap(static_cast(_bufferWidth), static_cast(_bufferHeight)); +} + +void CanvasRenderingContext2DDelegate::beginPath() { + // called: set_lineWidth() -> beginPath() -> moveTo() -> lineTo() -> stroke(), when draw line + _hpen = CreatePen(PS_SOLID, static_cast(_lineWidth), RGB(255, 255, 255)); + // the return value of SelectObject is a handle to the object being replaced, so we should delete them to avoid memory leak + HGDIOBJ hOldPen = SelectObject(_DC, _hpen); + HGDIOBJ hOldBmp = SelectObject(_DC, _bmp); + DeleteObject(hOldPen); + DeleteObject(hOldBmp); + + SetBkMode(_DC, TRANSPARENT); +} + +void CanvasRenderingContext2DDelegate::closePath() { +} + +void CanvasRenderingContext2DDelegate::moveTo(float x, float y) { + MoveToEx(_DC, static_cast(x), static_cast(-(y - _bufferHeight - _fontSize)), nullptr); +} + +void CanvasRenderingContext2DDelegate::lineTo(float x, float y) { + LineTo(_DC, static_cast(x), static_cast(-(y - _bufferHeight - _fontSize))); +} + +void CanvasRenderingContext2DDelegate::stroke() { + DeleteObject(_hpen); + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + + fillTextureData(); +} + +void CanvasRenderingContext2DDelegate::saveContext() { + _savedDC = SaveDC(_DC); +} + +void CanvasRenderingContext2DDelegate::restoreContext() { + BOOL ret = RestoreDC(_DC, _savedDC); + if (0 == ret) { + SE_LOGD("CanvasRenderingContext2DImpl restore context failed.\n"); + } +} + +void CanvasRenderingContext2DDelegate::clearRect(float /*x*/, float /*y*/, float w, float h) { + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + + if (_imageData.isNull()) { + return; + } + + recreateBuffer(w, h); +} + +void CanvasRenderingContext2DDelegate::fillRect(float x, float y, float w, float h) { + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + + //not filled all Bits in buffer? the buffer length is _bufferWidth * _bufferHeight * 4, but it filled _bufferWidth * _bufferHeight * 3? + uint8_t *buffer = _imageData.getBytes(); + if (buffer) { + uint8_t r = static_cast(_fillStyle[0] * 255.0f); + uint8_t g = static_cast(_fillStyle[1] * 255.0f); + uint8_t b = static_cast(_fillStyle[2] * 255.0f); + uint8_t a = static_cast(_fillStyle[3] * 255.0f); + fillRectWithColor(buffer, + static_cast(_bufferWidth), + static_cast(_bufferHeight), + static_cast(x), + static_cast(y), + static_cast(w), + static_cast(h), r, g, b, a); + } +} + +void CanvasRenderingContext2DDelegate::fillText(const std::string &text, float x, float y, float /*maxWidth*/) { + if (text.empty() || _bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + + SIZE textSize = {0, 0}; + Point offsetPoint = convertDrawPoint(Point{x, y}, text); + + drawText(text, (int)offsetPoint[0], (int)offsetPoint[1]); + fillTextureData(); +} + +void CanvasRenderingContext2DDelegate::strokeText(const std::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const { + if (text.empty() || _bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } +} + +CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::measureText(const std::string &text) { + if (text.empty()) + return std::array{0.0f, 0.0f}; + + int bufferLen = 0; + wchar_t *pwszBuffer = CanvasRenderingContext2DDelegate::utf8ToUtf16(text, &bufferLen); + Size size = sizeWithText(pwszBuffer, bufferLen); + //SE_LOGD("CanvasRenderingContext2DImpl::measureText: %s, %d, %d\n", text.c_str(), size.cx, size.cy); + CC_SAFE_DELETE_ARRAY(pwszBuffer); + return size; +} + +void CanvasRenderingContext2DDelegate::updateFont(const std::string &fontName, + float fontSize, + bool bold, + bool /* italic */, + bool /* oblique */, + bool /* smallCaps */) { + do { + _fontName = fontName; + _fontSize = static_cast(fontSize); + std::string fontPath; + LOGFONTA tFont = {0}; + if (!_fontName.empty()) { + // firstly, try to create font from ttf file + const auto &fontInfoMap = getFontFamilyNameMap(); + auto iter = fontInfoMap.find(_fontName); + if (iter != fontInfoMap.end()) { + fontPath = iter->second; + std::string tmpFontPath = fontPath; + size_t nFindPos = tmpFontPath.rfind("/"); + tmpFontPath = &tmpFontPath[nFindPos + 1]; + nFindPos = tmpFontPath.rfind("."); + // IDEA: draw ttf failed if font file name not equal font face name + // for example: "DejaVuSansMono-Oblique" not equal "DejaVu Sans Mono" when using DejaVuSansMono-Oblique.ttf + _fontName = tmpFontPath.substr(0, nFindPos); + } else { + auto nFindPos = fontName.rfind("/"); + if (nFindPos != fontName.npos) { + if (fontName.length() == nFindPos + 1) { + _fontName = ""; + } else { + _fontName = &_fontName[nFindPos + 1]; + } + } + } + tFont.lfCharSet = DEFAULT_CHARSET; + strcpy_s(tFont.lfFaceName, LF_FACESIZE, _fontName.c_str()); + } + + if (_fontSize) + tFont.lfHeight = -_fontSize; + + if (bold) + tFont.lfWeight = FW_BOLD; + else + tFont.lfWeight = FW_NORMAL; + + // disable Cleartype + tFont.lfQuality = ANTIALIASED_QUALITY; + + // delete old font + removeCustomFont(); + + if (!fontPath.empty()) { + _curFontPath = fontPath; + wchar_t *pwszBuffer = utf8ToUtf16(_curFontPath); + if (pwszBuffer) { + if (AddFontResource(pwszBuffer)) { + SendMessage(_wnd, WM_FONTCHANGE, 0, 0); + } + delete[] pwszBuffer; + pwszBuffer = nullptr; + } + } + + // create new font + _font = CreateFontIndirectA(&tFont); + if (!_font) { + // create failed, use default font + SE_LOGE("Failed to create custom font(font name: %s, font size: %f), use default font.\n", + _fontName.c_str(), fontSize); + } else { + SelectObject(_DC, _font); + SendMessage(_wnd, WM_FONTCHANGE, 0, 0); + } + } while (false); +} + +void CanvasRenderingContext2DDelegate::setTextAlign(CanvasTextAlign align) { + _textAlign = align; +} + +void CanvasRenderingContext2DDelegate::setTextBaseline(CanvasTextBaseline baseline) { + _textBaseLine = baseline; +} + +void CanvasRenderingContext2DDelegate::setFillStyle(float r, float g, float b, float a) { + _fillStyle = {r, g, b, a}; +} + +void CanvasRenderingContext2DDelegate::setStrokeStyle(float r, float g, float b, float a) { + _strokeStyle = {r, g, b, a}; +} + +void CanvasRenderingContext2DDelegate::setLineWidth(float lineWidth) { + _lineWidth = lineWidth; +} + +const cc::Data &CanvasRenderingContext2DDelegate::getDataRef() const { + return _imageData; +} + +// change utf-8 string to utf-16, pRetLen is the string length after changing +wchar_t *CanvasRenderingContext2DDelegate::utf8ToUtf16(const std::string &str, int *pRetLen /* = nullptr*/) { + wchar_t *pwszBuffer = nullptr; + do { + if (str.empty()) { + break; + } + int nLen = static_cast(str.size()); + int nBufLen = nLen + 1; + pwszBuffer = new wchar_t[nBufLen]; + CC_BREAK_IF(!pwszBuffer); + memset(pwszBuffer, 0, sizeof(wchar_t) * nBufLen); + // str.size() not equal actuallyLen for Chinese char + int actuallyLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), nLen, pwszBuffer, nBufLen); + // SE_LOGE("_utf8ToUtf16, str:%s, strLen:%d, retLen:%d\n", str.c_str(), str.size(), actuallyLen); + if (pRetLen != nullptr) { + *pRetLen = actuallyLen; + } + } while (false); + return pwszBuffer; +} + +void CanvasRenderingContext2DDelegate::removeCustomFont() { + HFONT hDefFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT); + if (hDefFont != _font) { + DeleteObject(SelectObject(_DC, hDefFont)); + } + // release temp font resource + if (!_curFontPath.empty()) { + wchar_t *pwszBuffer = utf8ToUtf16(_curFontPath); + if (pwszBuffer) { + RemoveFontResource(pwszBuffer); + SendMessage(_wnd, WM_FONTCHANGE, 0, 0); + delete[] pwszBuffer; + pwszBuffer = nullptr; + } + _curFontPath.clear(); + } +} + +// x, y offset value +int CanvasRenderingContext2DDelegate::drawText(const std::string &text, int x, int y) { + int nRet = 0; + wchar_t *pwszBuffer = nullptr; + do { + CC_BREAK_IF(text.empty()); + + DWORD dwFmt = DT_SINGLELINE | DT_NOPREFIX; + + int bufferLen = 0; + pwszBuffer = utf8ToUtf16(text, &bufferLen); + + Size newSize = sizeWithText(pwszBuffer, bufferLen); + + _textSize = newSize; + + RECT rcText = {0}; + + rcText.right = static_cast(newSize[0]); + rcText.bottom = static_cast(newSize[1]); + + LONG offsetX = x; + LONG offsetY = y; + if (offsetX || offsetY) { + OffsetRect(&rcText, offsetX, offsetY); + } + + // SE_LOGE("_drawText text,%s size: (%d, %d) offset after convert: (%d, %d) \n", text.c_str(), newSize.cx, newSize.cy, offsetX, offsetY); + + SetBkMode(_DC, TRANSPARENT); + SetTextColor(_DC, RGB(255, 255, 255)); // white color + + // draw text + nRet = DrawTextW(_DC, pwszBuffer, bufferLen, &rcText, dwFmt); + } while (false); + CC_SAFE_DELETE_ARRAY(pwszBuffer); + + return nRet; +} + +CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::sizeWithText(const wchar_t *pszText, int nLen) { + Size tRet{0, 0}; + do { + CC_BREAK_IF(!pszText || nLen <= 0); + + RECT rc = {0, 0, 0, 0}; + DWORD dwCalcFmt = DT_CALCRECT | DT_NOPREFIX; + + // measure text size + DrawTextW(_DC, pszText, nLen, &rc, dwCalcFmt); + + tRet[0] = static_cast(rc.right); + tRet[1] = static_cast(rc.bottom); + } while (false); + + return tRet; +} + +void CanvasRenderingContext2DDelegate::prepareBitmap(int nWidth, int nHeight) { + // release bitmap + deleteBitmap(); + + if (nWidth > 0 && nHeight > 0) { + _bmp = CreateBitmap(nWidth, nHeight, 1, 32, nullptr); + SelectObject(_DC, _bmp); + } +} + +void CanvasRenderingContext2DDelegate::deleteBitmap() { + if (_bmp) { + DeleteObject(_bmp); + _bmp = nullptr; + } +} + +void CanvasRenderingContext2DDelegate::fillTextureData() { + do { + auto dataLen = static_cast(_bufferWidth * _bufferHeight * 4); + auto *dataBuf = static_cast(malloc(sizeof(unsigned char) * dataLen)); + CC_BREAK_IF(!dataBuf); + unsigned char *imageBuf = _imageData.getBytes(); + CC_BREAK_IF(!imageBuf); + + struct + { + BITMAPINFOHEADER bmiHeader; + int mask[4]; + } bi = {0}; + bi.bmiHeader.biSize = sizeof(bi.bmiHeader); + CC_BREAK_IF(!GetDIBits(_DC, _bmp, 0, 0, + nullptr, (LPBITMAPINFO)&bi, DIB_RGB_COLORS)); + + // copy pixel data + bi.bmiHeader.biHeight = (bi.bmiHeader.biHeight > 0) ? -bi.bmiHeader.biHeight : bi.bmiHeader.biHeight; + GetDIBits(_DC, _bmp, 0, static_cast(_bufferHeight), dataBuf, + (LPBITMAPINFO)&bi, DIB_RGB_COLORS); + + uint8_t r = static_cast(round(_fillStyle[0] * 255)); + uint8_t g = static_cast(round(_fillStyle[1] * 255)); + uint8_t b = static_cast(round(_fillStyle[2] * 255)); + COLORREF textColor = (b << 16 | g << 8 | r) & 0x00ffffff; + COLORREF *pPixel = nullptr; + COLORREF *pImage = nullptr; + int bufferHeight = static_cast(_bufferHeight); + int bufferWidth = static_cast(_bufferWidth); + for (int y = 0; y < bufferHeight; ++y) { + pPixel = (COLORREF *)dataBuf + y * bufferWidth; + pImage = (COLORREF *)imageBuf + y * bufferWidth; + for (int x = 0; x < bufferWidth; ++x) { + COLORREF &clr = *pPixel; + COLORREF &val = *pImage; + // Because text is drawn in white color, and background color is black, + // so the red value is equal to alpha value. And we should keep this value + // as it includes anti-atlas information. + uint8_t alpha = GetRValue(clr) ? 255 : 0; + if (alpha > 0) { + val = (alpha << 24) | textColor; + } + ++pPixel; + ++pImage; + } + } + free(dataBuf); + } while (false); +} + +std::array CanvasRenderingContext2DDelegate::convertDrawPoint(Point point, const std::string &text) { + Size textSize = measureText(text); + if (_textAlign == CanvasTextAlign::CENTER) { + point[0] -= textSize[0] / 2.0f; + } else if (_textAlign == CanvasTextAlign::RIGHT) { + point[0] -= textSize[0]; + } + + if (_textBaseLine == CanvasTextBaseline::TOP) { + // DrawText default + GetTextMetrics(_DC, &_tm); + point[1] += -_tm.tmInternalLeading; + } else if (_textBaseLine == CanvasTextBaseline::MIDDLE) { + point[1] += -textSize[1] / 2.0f; + } else if (_textBaseLine == CanvasTextBaseline::BOTTOM) { + point[1] += -textSize[1]; + } else if (_textBaseLine == CanvasTextBaseline::ALPHABETIC) { + GetTextMetrics(_DC, &_tm); + point[1] -= _tm.tmAscent; + } + + return point; +} + +void CanvasRenderingContext2DDelegate::fill() { +} + +void CanvasRenderingContext2DDelegate::setLineCap(const std::string & /* lineCap */) { +} + +void CanvasRenderingContext2DDelegate::setLineJoin(const std::string & /* lineCap */) { +} + +void CanvasRenderingContext2DDelegate::fillImageData(const Data & /* imageData */, + float /* imageWidth */, + float /* imageHeight */, + float /* offsetX */, + float /* offsetY */) { +} + +void CanvasRenderingContext2DDelegate::strokeText(const std::string & /* text */, + float /* x */, + float /* y */, + float /* maxWidth */) { +} + +void CanvasRenderingContext2DDelegate::rect(float /* x */, + float /* y */, + float /* w */, + float /* h */) { +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/win32/modules/CanvasRenderingContext2DDelegate.h b/native/cocos/platform/win32/modules/CanvasRenderingContext2DDelegate.h new file mode 100644 index 0000000000..4a4be0f599 --- /dev/null +++ b/native/cocos/platform/win32/modules/CanvasRenderingContext2DDelegate.h @@ -0,0 +1,116 @@ +/**************************************************************************** + Copyright (c) 2018-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h" + +#include +#include +#include +#include +#include "base/csscolorparser.h" +#include "cocos/bindings/jswrapper/SeApi.h" +#include "cocos/bindings/manual/jsb_platform.h" +#include "math/Math.h" +#include "platform/FileUtils.h" + +namespace cc { + +class CanvasRenderingContext2DDelegate : public ICanvasRenderingContext2D::Delegate { +public: + using Point = std::array; + using Vec2 = std::array; + using Size = std::array; + using Color4F = std::array; + + CanvasRenderingContext2DDelegate(); + ~CanvasRenderingContext2DDelegate() override; + + void recreateBuffer(float w, float h) override; + void beginPath() override; + void closePath() override; + void moveTo(float x, float y) override; + void lineTo(float x, float y) override; + void stroke() override; + void saveContext() override; + void restoreContext() override; + void clearRect(float /*x*/, float /*y*/, float w, float h) override; + void fillRect(float x, float y, float w, float h) override; + void fillText(const std::string &text, float x, float y, float /*maxWidth*/) override; + void strokeText(const std::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const; + Size measureText(const std::string &text) override; + void updateFont(const std::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; + void setTextAlign(CanvasTextAlign align) override; + void setTextBaseline(CanvasTextBaseline baseline) override; + void setFillStyle(float r, float g, float b, float a) override; + void setStrokeStyle(float r, float g, float b, float a) override; + void setLineWidth(float lineWidth) override; + const cc::Data &getDataRef() const override; + void fill() override; + void setLineCap(const std::string &lineCap) override; + void setLineJoin(const std::string &lineCap) override; + void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; + void strokeText(const std::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; + void rect(float x, float y, float w, float h) override; + +private: + static wchar_t * utf8ToUtf16(const std::string &str, int *pRetLen = nullptr); + void removeCustomFont(); + int drawText(const std::string &text, int x, int y); + Size sizeWithText(const wchar_t *pszText, int nLen); + void prepareBitmap(int nWidth, int nHeight); + void deleteBitmap(); + void fillTextureData(); + std::array convertDrawPoint(Point point, const std::string &text); + +public: + HDC _DC{nullptr}; + HBITMAP _bmp{nullptr}; + +private: + cc::Data _imageData; + HFONT _font{static_cast(GetStockObject(DEFAULT_GUI_FONT))}; + HWND _wnd{nullptr}; + HPEN _hpen; + PAINTSTRUCT _paintStruct; + std::string _curFontPath; + int _savedDC{0}; + float _lineWidth{0.0F}; + float _bufferWidth{0.0F}; + float _bufferHeight{0.0F}; + + std::string _fontName; + int _fontSize{0}; + Size _textSize; + CanvasTextAlign _textAlign{CanvasTextAlign::CENTER}; + CanvasTextBaseline _textBaseLine{CanvasTextBaseline::TOP}; + Color4F _fillStyle; + Color4F _strokeStyle; + + TEXTMETRIC _tm; +}; + +} // namespace cc diff --git a/native/cocos/platform/win32/modules/Network.cpp b/native/cocos/platform/win32/modules/Network.cpp new file mode 100644 index 0000000000..2044071954 --- /dev/null +++ b/native/cocos/platform/win32/modules/Network.cpp @@ -0,0 +1,33 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/win32/modules/Network.h" + +namespace cc { + +INetwork::NetworkType Network::getNetworkType() const { + return INetwork::NetworkType::LAN; +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/win32/modules/Network.h b/native/cocos/platform/win32/modules/Network.h new file mode 100644 index 0000000000..f4bcf5e504 --- /dev/null +++ b/native/cocos/platform/win32/modules/Network.h @@ -0,0 +1,37 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/INetwork.h" + +namespace cc { + +class Network : public INetwork { +public: + NetworkType getNetworkType() const override; +}; + +} // namespace cc diff --git a/native/cocos/platform/win32/Device-win32.cpp b/native/cocos/platform/win32/modules/Screen.cpp similarity index 55% rename from native/cocos/platform/win32/Device-win32.cpp rename to native/cocos/platform/win32/modules/Screen.cpp index 3ea6521397..2637b0e797 100644 --- a/native/cocos/platform/win32/Device-win32.cpp +++ b/native/cocos/platform/win32/modules/Screen.cpp @@ -1,7 +1,5 @@ /**************************************************************************** - Copyright (c) 2010-2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -25,69 +23,55 @@ THE SOFTWARE. ****************************************************************************/ -#if CC_PLATFORM == CC_PLATFORM_WINDOWS +#include "platform/win32/modules/Screen.h" +#include "cocos/bindings/jswrapper/SeApi.h" +#include "base/Macros.h" - #include "platform/Device.h" - #include "platform/FileUtils.h" - #include "platform/StdC.h" +#include namespace cc { -int Device::getDPI() { +int Screen::getDPI() const { static int dpi = -1; if (dpi == -1) { HDC hScreenDC = GetDC(nullptr); - int PixelsX = GetDeviceCaps(hScreenDC, HORZRES); - int MMX = GetDeviceCaps(hScreenDC, HORZSIZE); + int PixelsX = GetDeviceCaps(hScreenDC, HORZRES); + int MMX = GetDeviceCaps(hScreenDC, HORZSIZE); ReleaseDC(nullptr, hScreenDC); dpi = static_cast(254.0f * PixelsX / MMX / 10); } return dpi; } -void Device::setAccelerometerEnabled(bool isEnabled) {} - -void Device::setAccelerometerInterval(float interval) {} - -const Device::MotionValue &Device::getDeviceMotionValue() { - static MotionValue __motionValue; - return __motionValue; -} - -Device::Orientation Device::getDeviceOrientation() { - return Device::Orientation::PORTRAIT; -} - -std::string Device::getDeviceModel() { - // REFINE - return std::string("Windows"); -} - -void Device::setKeepScreenOn(bool value) { - CC_UNUSED_PARAM(value); -} - -void Device::vibrate(float duration) { - CC_UNUSED_PARAM(duration); -} - -float Device::getBatteryLevel() { - return 1.0f; -} - -Device::NetworkType Device::getNetworkType() { - return Device::NetworkType::LAN; -} - -cc::Vec4 Device::getSafeAreaEdge() { - // no SafeArea concept on win32, return ZERO Vec4. - return cc::Vec4(); -} - -float Device::getDevicePixelRatio() { +float Screen::getDevicePixelRatio() const { return 1; } -} // namespace cc +void Screen::setKeepScreenOn(bool value) { + CC_UNUSED_PARAM(value); +} -#endif // CC_PLATFORM == CC_PLATFORM_WINDOWS +Screen::Orientation Screen::getDeviceOrientation() const { + return Orientation::PORTRAIT; +} + +Vec4 Screen::getSafeAreaEdge() const { + return cc::Vec4(); +} + +bool Screen::isDisplayStats() { + se::AutoHandleScope hs; + se::Value ret; + char commandBuf[100] = "cc.profiler.isShowingStats();"; + se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret); + return ret.toBoolean(); +} + +void Screen::setDisplayStats(bool isShow) { + se::AutoHandleScope hs; + char commandBuf[100] = {0}; + sprintf(commandBuf, isShow ? "cc.profiler.showStats();" : "cc.profiler.hideStats();"); + se::ScriptEngine::getInstance()->evalString(commandBuf); +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/win32/modules/Screen.h b/native/cocos/platform/win32/modules/Screen.h new file mode 100644 index 0000000000..a7b021101f --- /dev/null +++ b/native/cocos/platform/win32/modules/Screen.h @@ -0,0 +1,51 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IScreen.h" + +namespace cc { + +class Screen : public IScreen { +public: + int getDPI() const override; + float getDevicePixelRatio() const override; + void setKeepScreenOn(bool value) override; + Orientation getDeviceOrientation() const override; + Vec4 getSafeAreaEdge() const override; + /** + @brief Get current display stats. + @return bool, is displaying stats or not. + */ + bool isDisplayStats() override; + + /** + @brief set display stats information. + */ + void setDisplayStats(bool isShow) override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/win32/Application-win32.cpp b/native/cocos/platform/win32/modules/System.cpp similarity index 50% rename from native/cocos/platform/win32/Application-win32.cpp rename to native/cocos/platform/win32/modules/System.cpp index ae0a5b4c43..a769f6c77e 100644 --- a/native/cocos/platform/win32/Application-win32.cpp +++ b/native/cocos/platform/win32/modules/System.cpp @@ -1,7 +1,5 @@ /**************************************************************************** - Copyright (c) 2010-2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -25,82 +23,21 @@ THE SOFTWARE. ****************************************************************************/ -#include "platform/Application.h" -#include "platform/StdC.h" // need it to include Windows.h - -#include -#include -#include -#include -#include -#include -#include "audio/include/AudioEngine.h" -#include "base/AutoreleasePool.h" -#include "base/Scheduler.h" -#include "cocos/bindings/event/EventDispatcher.h" -#include "cocos/bindings/jswrapper/SeApi.h" -#include "platform/FileUtils.h" -#include "platform/win32/View-win32.h" - -#include "pipeline/Define.h" -#include "pipeline/RenderPipeline.h" -#include "platform/Device.h" -#include "renderer/GFXDeviceManager.h" - -extern std::shared_ptr cc_get_application_view(); +#include "platform/win32/modules/System.h" +#include namespace cc { +using OSType = System::OSType; -Application * Application::instance = nullptr; -std::shared_ptr Application::scheduler = nullptr; - -Application::Application(int width, int height) { - Application::instance = this; - scheduler = std::make_shared(); - - FileUtils::getInstance()->addSearchPath("Resources", true); - - EventDispatcher::init(); - se::ScriptEngine::getInstance(); +OSType System::getOSType() const { + return OSType::WINDOWS; } -Application::~Application() { -#if USE_AUDIO - AudioEngine::end(); -#endif - - pipeline::RenderPipeline::getInstance()->destroy(); - - EventDispatcher::destroy(); - se::ScriptEngine::destroyInstance(); - - gfx::DeviceManager::destroy(); - - Application::instance = nullptr; +std::string System::getDeviceModel() const { + return "Windows"; } -bool Application::init() { - auto scheduler = Application::getInstance()->getScheduler(); - scheduler->removeAllFunctionsToBePerformedInCocosThread(); - scheduler->unscheduleAll(); - - se::ScriptEngine::getInstance()->cleanup(); - - auto view = cc_get_application_view(); - auto viewSize = view->getViewSize(); - - return true; -} - -void Application::setPreferredFramesPerSecond(int fps) { - if (fps == 0) - return; - - _fps = fps; - _prefererredNanosecondsPerFrame = static_cast(1.0 / _fps * NANOSECONDS_PER_SECOND); -} - -Application::LanguageType Application::getCurrentLanguage() const { +System::LanguageType System::getCurrentLanguage() const { LanguageType ret = LanguageType::ENGLISH; LCID localeID = GetUserDefaultLCID(); @@ -169,12 +106,12 @@ Application::LanguageType Application::getCurrentLanguage() const { return ret; } -std::string Application::getCurrentLanguageCode() const { +std::string System::getCurrentLanguageCode() const { LANGID lid = GetUserDefaultUILanguage(); const LCID locale_id = MAKELCID(lid, SORT_DEFAULT); int length = GetLocaleInfoA(locale_id, LOCALE_SISO639LANGNAME, nullptr, 0); - char *tempCode = new char[length]; + char* tempCode = new char[length]; GetLocaleInfoA(locale_id, LOCALE_SISO639LANGNAME, tempCode, length); std::string code = tempCode; delete tempCode; @@ -182,57 +119,35 @@ std::string Application::getCurrentLanguageCode() const { return code; } -bool Application::isDisplayStats() { - se::AutoHandleScope hs; - se::Value ret; - char commandBuf[100] = "cc.profiler.isShowingStats();"; - se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret); - return ret.toBoolean(); +std::string System::getSystemVersion() const { + char buff[256] = {0}; + HMODULE handle = GetModuleHandleW(L"ntdll.dll"); + if (handle) { + typedef NTSTATUS(WINAPI * RtlGetVersionPtr)(PRTL_OSVERSIONINFOW); + RtlGetVersionPtr getVersionPtr = (RtlGetVersionPtr)GetProcAddress(handle, "RtlGetVersion"); + if (getVersionPtr != NULL) { + RTL_OSVERSIONINFOW info; + if (getVersionPtr(&info) == 0) { /* STATUS_SUCCESS == 0 */ + snprintf(buff, sizeof(buff), "Windows version %d.%d.%d", info.dwMajorVersion, info.dwMinorVersion, info.dwBuildNumber); + return buff; + } + } + } + return buff; + //OSVERSIONINFO osvi; + //memset(&osvi, 0, sizeof(osvi)); + //osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); + //GetVersionEx(&osvi); + //char buff[256] = {0}; + //snprintf(buff, sizeof(buff), "Windows version %d.%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber); + //return buff; } -void Application::setDisplayStats(bool isShow) { - se::AutoHandleScope hs; - char commandBuf[100] = {0}; - sprintf(commandBuf, isShow ? "cc.profiler.showStats();" : "cc.profiler.hideStats();"); - se::ScriptEngine::getInstance()->evalString(commandBuf); -} - -void Application::setCursorEnabled(bool value) { - cc_get_application_view()->setCursorEnabeld(value); -} - -Application::Platform Application::getPlatform() const { - return Platform::WINDOWS; -} - -bool Application::openURL(const std::string &url) { - WCHAR * temp = new WCHAR[url.size() + 1]; - int wchars_num = MultiByteToWideChar(CP_UTF8, 0, url.c_str(), url.size() + 1, temp, url.size() + 1); +bool System::openURL(const std::string& url) { + WCHAR* temp = new WCHAR[url.size() + 1]; + MultiByteToWideChar(CP_UTF8, 0, url.c_str(), url.size() + 1, temp, url.size() + 1); HINSTANCE r = ShellExecuteW(NULL, L"open", temp, NULL, NULL, SW_SHOWNORMAL); delete[] temp; return (size_t)r > 32; } - -void Application::copyTextToClipboard(const std::string &text) { - //TODO -} - -void Application::onPause() { -} - -void Application::onResume() { -} - -void Application::onClose() { -} - -std::string Application::getSystemVersion() { - OSVERSIONINFO osvi; - memset(&osvi, 0, sizeof(osvi)); - osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); - GetVersionEx(&osvi); - char buff[256] = {0}; - snprintf(buff, sizeof(buff), "Windows version %d.%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber); - return buff; -} -} // namespace cc +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/win32/modules/System.h b/native/cocos/platform/win32/modules/System.h new file mode 100644 index 0000000000..e6287b9965 --- /dev/null +++ b/native/cocos/platform/win32/modules/System.h @@ -0,0 +1,65 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/ISystem.h" + +namespace cc { + +class System : public ISystem { +public: + /** + @brief Get target system type. + */ + OSType getOSType() const override; + /** + @brief Get target device model. + */ + std::string getDeviceModel() const override; + /** + @brief Get current language config. + @return Current language config. + */ + LanguageType getCurrentLanguage() const override; + /** + @brief Get current language iso 639-1 code. + @return Current language iso 639-1 code. + */ + std::string getCurrentLanguageCode() const override; + /** + @brief Get system version. + @return system version. + */ + std::string getSystemVersion() const override; + /** + @brief Open url in default browser. + @param String with url to open. + @return True if the resource located by the URL was successfully opened; otherwise false. + */ + bool openURL(const std::string& url) override; +}; + +} // namespace cc diff --git a/native/cocos/platform/win32/modules/SystemWindow.cpp b/native/cocos/platform/win32/modules/SystemWindow.cpp new file mode 100644 index 0000000000..16b2ee5421 --- /dev/null +++ b/native/cocos/platform/win32/modules/SystemWindow.cpp @@ -0,0 +1,82 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/win32/modules/SystemWindow.h" + +#include "base/Log.h" +// SDL headers +#include +#include "bindings/event/EventDispatcher.h" +#include "platform/IEventDispatch.h" +#include "platform/win32/WindowsPlatform.h" +#include "sdl2/SDL.h" +#include "sdl2/SDL_main.h" +#include "sdl2/SDL_syswm.h" + + +namespace { + +} // namespace + +namespace cc { +SystemWindow::SystemWindow() { +} + +SystemWindow::~SystemWindow() { +} + +bool SystemWindow::createWindow(const char *title, + int x, int y, int w, + int h, int flags) { + // Create window + + WindowsPlatform *platform = dynamic_cast(BasePlatform::getPlatform()); + CCASSERT(platform != nullptr, "Platform pointer can't be null"); + platform->createWindow(title, x, y, w, h, flags); + _width = w; + _height = h; + return true; +} + +uintptr_t SystemWindow::getWindowHandler() const { + //return _handle; + WindowsPlatform *platform = dynamic_cast(BasePlatform::getPlatform()); + CCASSERT(platform != nullptr, "Platform pointer can't be null"); + return platform->getWindowHandler(); +} + +void SystemWindow::setCursorEnabled(bool value) { + SDL_SetRelativeMouseMode(value ? SDL_FALSE : SDL_TRUE); +} + +void SystemWindow::copyTextToClipboard(const std::string &text) { + //TODO +} + +SystemWindow::Size SystemWindow::getViewSize() const { + return Size{static_cast(_width), static_cast(_height)}; +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/win32/modules/SystemWindow.h b/native/cocos/platform/win32/modules/SystemWindow.h new file mode 100644 index 0000000000..44b447075d --- /dev/null +++ b/native/cocos/platform/win32/modules/SystemWindow.h @@ -0,0 +1,68 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include + +#include "platform/interfaces/modules/ISystemWindow.h" + +struct SDL_Window; +struct SDL_WindowEvent; + +namespace cc { + +class SystemWindow : public ISystemWindow { +public: + explicit SystemWindow(); + ~SystemWindow() override; + + class Delegate { + public: + virtual ~Delegate() = default; + virtual bool createWindow(const char* title, + int x, int y, int w, + int h, int flags) = 0; + virtual uintptr_t getWindowHandler() const = 0; + }; + + bool createWindow(const char* title, + int x, int y, int w, + int h, int flags) override; + uintptr_t getWindowHandler() const override; + + Size getViewSize() const override; + /* + @brief enable/disable(lock) the cursor, default is enabled + */ + void setCursorEnabled(bool value) override; + void copyTextToClipboard(const std::string& text) override; + +private: + int _width{0}; + int _height{0}; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/win32/modules/Vibrator.cpp b/native/cocos/platform/win32/modules/Vibrator.cpp new file mode 100644 index 0000000000..ba6bfeadb3 --- /dev/null +++ b/native/cocos/platform/win32/modules/Vibrator.cpp @@ -0,0 +1,36 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "platform/win32/modules/Vibrator.h" + +#include "base/Macros.h" + +namespace cc { + +void Vibrator::vibrate(float duration) { + CC_UNUSED_PARAM(duration); +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/win32/modules/Vibrator.h b/native/cocos/platform/win32/modules/Vibrator.h new file mode 100644 index 0000000000..9a8ea1657d --- /dev/null +++ b/native/cocos/platform/win32/modules/Vibrator.h @@ -0,0 +1,44 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IVibrator.h" + +namespace cc { + +class Vibrator : public IVibrator { +public: + /** + * Vibrate for the specified amount of time. + * If vibrate is not supported, then invoking this method has no effect. + * Some platforms limit to a maximum duration of 5 seconds. + * Duration is ignored on iOS due to API limitations. + * @param duration The duration in seconds. + */ + void vibrate(float duration) override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/renderer/gfx-agent/BufferAgent.cpp b/native/cocos/renderer/gfx-agent/BufferAgent.cpp index dbb18bd522..d561c48004 100644 --- a/native/cocos/renderer/gfx-agent/BufferAgent.cpp +++ b/native/cocos/renderer/gfx-agent/BufferAgent.cpp @@ -28,6 +28,7 @@ #include "BufferAgent.h" #include "DeviceAgent.h" +#include namespace cc { namespace gfx { diff --git a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp index 8e2aed0fdc..da03d4e148 100644 --- a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp +++ b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp @@ -39,6 +39,8 @@ #include "base/job-system/JobSystem.h" #include "base/threading/MessageQueue.h" #include "base/threading/ThreadSafeLinearAllocator.h" +#include + namespace cc { namespace gfx { diff --git a/native/cocos/renderer/gfx-agent/DeviceAgent.cpp b/native/cocos/renderer/gfx-agent/DeviceAgent.cpp index f63f317071..d84bf04ac9 100644 --- a/native/cocos/renderer/gfx-agent/DeviceAgent.cpp +++ b/native/cocos/renderer/gfx-agent/DeviceAgent.cpp @@ -24,6 +24,7 @@ ****************************************************************************/ #include +#include #include "base/CoreStd.h" #include "base/threading/MessageQueue.h" @@ -130,12 +131,14 @@ void DeviceAgent::acquire(Swapchain *const *swapchains, uint32_t count) { actorSwapchains[i] = static_cast(swapchains[i])->getActor(); } - ENQUEUE_MESSAGE_3( + ENQUEUE_MESSAGE_4( _mainMessageQueue, DevicePresent, + device, this, actor, _actor, swapchains, actorSwapchains, count, count, { + if (device->_onAcquire) device->_onAcquire->execute(); actor->acquire(swapchains, count); }); } diff --git a/native/cocos/renderer/gfx-base/GFXDef.h b/native/cocos/renderer/gfx-base/GFXDef.h index b1f109ac98..cb11b8e603 100644 --- a/native/cocos/renderer/gfx-base/GFXDef.h +++ b/native/cocos/renderer/gfx-base/GFXDef.h @@ -62,6 +62,26 @@ DEFINE_CMP_OP(TextureBarrierInfo) #undef DEFINE_CMP_OP +class Executable { +public: + virtual ~Executable() = default; + virtual void execute() = 0; +}; + +template +class CallbackExecutable final : public Executable { +public: + using ExecuteMethod = std::remove_reference_t; + + explicit CallbackExecutable(ExecuteMethod& execute) : Executable(), _execute(execute) {} + explicit CallbackExecutable(ExecuteMethod&& execute) : Executable(), _execute(execute) {} + + void execute() override { _execute(); } + +private: + ExecuteMethod _execute; +}; + struct SwapchainTextureInfo final { Swapchain* swapchain{nullptr}; Format format{Format::UNKNOWN}; @@ -99,6 +119,5 @@ std::pair formatAlignment(Format format); uint32_t formatSize(Format format, uint32_t width, uint32_t height, uint32_t depth); uint32_t formatSurfaceSize(Format format, uint32_t width, uint32_t height, uint32_t depth, uint32_t mips); - } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-base/GFXDevice.cpp b/native/cocos/renderer/gfx-base/GFXDevice.cpp index dc7ec5c6e4..5d16229c8c 100644 --- a/native/cocos/renderer/gfx-base/GFXDevice.cpp +++ b/native/cocos/renderer/gfx-base/GFXDevice.cpp @@ -27,6 +27,7 @@ #include "GFXDevice.h" #include "GFXObject.h" +#include "base/memory/Memory.h" namespace cc { namespace gfx { @@ -81,6 +82,8 @@ void Device::destroy() { _bindingMappingInfo.samplerOffsets.clear(); doDestroy(); + + CC_SAFE_DELETE(_onAcquire); } void Device::destroySurface(void *windowHandle) { diff --git a/native/cocos/renderer/gfx-base/GFXDevice.h b/native/cocos/renderer/gfx-base/GFXDevice.h index 73639c4bed..06bff789c8 100644 --- a/native/cocos/renderer/gfx-base/GFXDevice.h +++ b/native/cocos/renderer/gfx-base/GFXDevice.h @@ -108,6 +108,11 @@ public: inline const BindingMappingInfo &bindingMappingInfo() const { return _bindingMappingInfo; } + // for external update operations which has to be performed on the device thread. + // AR camera texture update, etc. + template + void registerOnAcquireCallback(ExecuteMethod &&execute); + protected: static Device *instance; @@ -159,6 +164,7 @@ protected: Queue * _queue{nullptr}; QueryPool * _queryPool{nullptr}; CommandBuffer *_cmdBuff{nullptr}; + Executable * _onAcquire{nullptr}; uint32_t _numDrawCalls{0U}; uint32_t _numInstances{0U}; @@ -284,5 +290,10 @@ void Device::acquire(const vector &swapchains) { acquire(swapchains.data(), utils::toUint(swapchains.size())); } +template +void Device::registerOnAcquireCallback(ExecuteMethod &&execute) { + _onAcquire = CC_NEW(CallbackExecutable(std::forward(execute))); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-empty/EmptyDevice.cpp b/native/cocos/renderer/gfx-empty/EmptyDevice.cpp index 2ed140627f..45b392d3e7 100644 --- a/native/cocos/renderer/gfx-empty/EmptyDevice.cpp +++ b/native/cocos/renderer/gfx-empty/EmptyDevice.cpp @@ -82,7 +82,8 @@ void EmptyDevice::doDestroy() { CC_SAFE_DESTROY(_queue); } -void EmptyDevice::acquire(Swapchain *const *swapchains, uint32_t count) { +void EmptyDevice::acquire(Swapchain *const * /*swapchains*/, uint32_t /*count*/) { + if (_onAcquire) _onAcquire->execute(); } void EmptyDevice::present() { diff --git a/native/cocos/renderer/gfx-gles-common/eglw.h b/native/cocos/renderer/gfx-gles-common/eglw.h index 64a7d7f0c8..42ec4192d5 100644 --- a/native/cocos/renderer/gfx-gles-common/eglw.h +++ b/native/cocos/renderer/gfx-gles-common/eglw.h @@ -26,6 +26,9 @@ #pragma once #if (CC_PLATFORM != CC_PLATFORM_MAC_IOS) +#if (CC_PLATFORM == CC_PLATFORM_QNX) +#define EGL_NO_X11 1 +#endif #define EGL_EGL_PROTOTYPES 0 #include diff --git a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp index 6522e88fb3..481d72bbd5 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp @@ -256,6 +256,8 @@ void GLES2Device::doDestroy() { } void GLES2Device::acquire(Swapchain *const *swapchains, uint32_t count) { + if (_onAcquire) _onAcquire->execute(); + _swapchains.clear(); for (uint32_t i = 0; i < count; ++i) { _swapchains.push_back(static_cast(swapchains[i])->gpuSwapchain()); diff --git a/native/cocos/renderer/gfx-gles2/GLES2Swapchain.cpp b/native/cocos/renderer/gfx-gles2/GLES2Swapchain.cpp index db87233f83..66fc5e7d7b 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Swapchain.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Swapchain.cpp @@ -49,7 +49,7 @@ GLES2Swapchain::~GLES2Swapchain() { void GLES2Swapchain::doInit(const SwapchainInfo& info) { const auto* context = GLES2Device::getInstance()->context(); _gpuSwapchain = CC_NEW(GLES2GPUSwapchain); - auto* window = reinterpret_cast(info.windowHandle); + auto window = reinterpret_cast(info.windowHandle); //NOLINT[readability-qualified-auto] #if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS EGLint nFmt; @@ -130,7 +130,7 @@ void GLES2Swapchain::doDestroySurface() { void GLES2Swapchain::doCreateSurface(void* windowHandle) { auto* context = GLES2Device::getInstance()->context(); - auto* window = reinterpret_cast(windowHandle); + auto window = reinterpret_cast(windowHandle); //NOLINT [readability-qualified-auto] EGLint nFmt = 0; if (eglGetConfigAttrib(context->eglDisplay, context->eglConfig, EGL_NATIVE_VISUAL_ID, &nFmt) == EGL_FALSE) { diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp index 460688fad5..263324ea2a 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp @@ -254,6 +254,8 @@ void GLES3Device::doDestroy() { } void GLES3Device::acquire(Swapchain *const *swapchains, uint32_t count) { + if (_onAcquire) _onAcquire->execute(); + _swapchains.clear(); for (uint32_t i = 0; i < count; ++i) { _swapchains.push_back(static_cast(swapchains[i])->gpuSwapchain()); diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp b/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp index b1cc52cb34..d78576a84e 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp @@ -212,9 +212,10 @@ bool GLES3GPUContext::initialize(GLES3GPUStateCache *stateCache, GLES3GPUConstan eglAttributes.push_back(EGL_NONE); for (int m = 2; m >= 0; --m) { - eglAttributes[3] = m; - EGL_CHECK(eglDefaultContext = eglCreateContext(eglDisplay, eglConfig, nullptr, eglAttributes.data())); - if (eglDefaultContext) { + eglAttributes[3] = m; + eglDefaultContext = eglCreateContext(eglDisplay, eglConfig, nullptr, eglAttributes.data()); + EGLint err = eglGetError(); // QNX throws egl errors on mismatch + if (eglDefaultContext && err == EGL_SUCCESS) { _constantRegistry->glMinorVersion = m; break; } @@ -389,13 +390,13 @@ void GLES3GPUContext::resetStates() const { GL_CHECK(glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0)); GL_CHECK(glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, 0)); GL_CHECK(glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0)); + GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0)); } GL_CHECK(glBindTexture(GL_TEXTURE_2D, 0)); GL_CHECK(glBindTexture(GL_TEXTURE_3D, 0)); GL_CHECK(glBindTexture(GL_TEXTURE_2D_ARRAY, 0)); GL_CHECK(glBindTexture(GL_TEXTURE_CUBE_MAP, 0)); - GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0)); GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, 0)); GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)); diff --git a/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp b/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp index cfc86fb49f..d2fb999e85 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp @@ -49,7 +49,7 @@ GLES3Swapchain::~GLES3Swapchain() { void GLES3Swapchain::doInit(const SwapchainInfo& info) { const auto* context = GLES3Device::getInstance()->context(); _gpuSwapchain = CC_NEW(GLES3GPUSwapchain); - auto* window = reinterpret_cast(info.windowHandle); + auto window = reinterpret_cast(info.windowHandle); //NOLINT [readability-qualified-auto] #if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS EGLint nFmt; @@ -130,7 +130,7 @@ void GLES3Swapchain::doDestroySurface() { void GLES3Swapchain::doCreateSurface(void* windowHandle) { auto* context = GLES3Device::getInstance()->context(); - auto* window = reinterpret_cast(windowHandle); + auto window = reinterpret_cast(windowHandle); //NOLINT [readability-qualified-auto] EGLint nFmt = 0; if (eglGetConfigAttrib(context->eglDisplay, context->eglConfig, EGL_NATIVE_VISUAL_ID, &nFmt) == EGL_FALSE) { diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.mm b/native/cocos/renderer/gfx-metal/MTLDevice.mm index 0576528595..74dd2cdd4f 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.mm +++ b/native/cocos/renderer/gfx-metal/MTLDevice.mm @@ -195,6 +195,8 @@ void CCMTLDevice::doDestroy() { } void CCMTLDevice::acquire(Swapchain *const *swapchains, uint32_t count) { + if (_onAcquire) _onAcquire->execute(); + _inFlightSemaphore->wait(); for (CCMTLSwapchain *swapchain : _swapchains) { diff --git a/native/cocos/renderer/gfx-validator/BufferValidator.cpp b/native/cocos/renderer/gfx-validator/BufferValidator.cpp index 51faa8d2bf..ea29550b40 100644 --- a/native/cocos/renderer/gfx-validator/BufferValidator.cpp +++ b/native/cocos/renderer/gfx-validator/BufferValidator.cpp @@ -35,6 +35,8 @@ #include "ValidationUtils.h" #include "gfx-base/GFXDef-common.h" +#include + namespace cc { namespace gfx { diff --git a/native/cocos/renderer/gfx-validator/DeviceValidator.cpp b/native/cocos/renderer/gfx-validator/DeviceValidator.cpp index 925017ccec..5b221498c6 100644 --- a/native/cocos/renderer/gfx-validator/DeviceValidator.cpp +++ b/native/cocos/renderer/gfx-validator/DeviceValidator.cpp @@ -44,6 +44,8 @@ #include "base/Log.h" #include "gfx-base/GFXSwapchain.h" +#include + namespace cc { namespace gfx { @@ -137,6 +139,7 @@ void DeviceValidator::acquire(Swapchain *const *swapchains, uint32_t count) { swapchainActors[i] = swapchain->getActor(); } + if (_onAcquire) _onAcquire->execute(); _actor->acquire(swapchainActors.data(), count); } diff --git a/native/cocos/renderer/gfx-validator/TextureValidator.cpp b/native/cocos/renderer/gfx-validator/TextureValidator.cpp index 39f0e2c590..bf6da516c8 100644 --- a/native/cocos/renderer/gfx-validator/TextureValidator.cpp +++ b/native/cocos/renderer/gfx-validator/TextureValidator.cpp @@ -34,7 +34,7 @@ namespace cc { namespace gfx { namespace { -unordered_map featureCheckMap{ +unordered_map featureCheckMap{ {Format::RGB8, Feature::FORMAT_RGB8}, {Format::R11G11B10F, Feature::FORMAT_R11G11B10F}, }; diff --git a/native/cocos/renderer/gfx-validator/ValidationUtils.h b/native/cocos/renderer/gfx-validator/ValidationUtils.h index 3d6a1da438..b38ed65081 100644 --- a/native/cocos/renderer/gfx-validator/ValidationUtils.h +++ b/native/cocos/renderer/gfx-validator/ValidationUtils.h @@ -26,6 +26,7 @@ #pragma once #include +#include #include "base/Utils.h" #include "gfx-base/GFXDef.h" diff --git a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp index 710dc1ec56..4d01d5671d 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp @@ -48,7 +48,10 @@ CCVKGPUCommandBufferPool *CCVKGPUDevice::getCommandBufferPool() { } CCVKGPUDescriptorSetPool *CCVKGPUDevice::getDescriptorSetPool(uint32_t layoutID) { - return &_descriptorSetPools[layoutID]; + if (_descriptorSetPools.find(layoutID) == _descriptorSetPools.end()) { + _descriptorSetPools[layoutID] = std::make_unique(); + } + return _descriptorSetPools[layoutID].get(); } void insertVkDynamicStates(vector *out, const vector &dynamicStates) { diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp index cbad90f34f..0736d682dc 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp @@ -573,6 +573,8 @@ VkImageMemoryBarrier presentBarrier{ } // namespace void CCVKDevice::acquire(Swapchain *const *swapchains, uint32_t count) { + if (_onAcquire) _onAcquire->execute(); + auto *queue = static_cast(_queue); queue->gpuQueue()->lastSignaledSemaphores.clear(); vkSwapchainIndices.clear(); diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.h b/native/cocos/renderer/gfx-vulkan/VKDevice.h index 66132f2e57..715d9a0dbe 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.h +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.h @@ -27,6 +27,7 @@ #include "VKStd.h" #include "gfx-base/GFXDevice.h" +#include namespace cc { namespace gfx { diff --git a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h index 7fac360e07..3f2f293d3d 100644 --- a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h +++ b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h @@ -410,7 +410,7 @@ private: using CommandBufferPools = tbb::concurrent_unordered_map>; CommandBufferPools _commandBufferPools; - unordered_map _descriptorSetPools; + unordered_map> _descriptorSetPools; }; /** diff --git a/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp b/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp index b2c7016160..37f535ac3d 100644 --- a/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp @@ -417,7 +417,7 @@ void CCVKSwapchain::createVkSurface() { #elif defined(VK_USE_PLATFORM_XCB_KHR) VkXcbSurfaceCreateInfoKHR surfaceCreateInfo{VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR}; surfaceCreateInfo.connection = nullptr; // TODO - surfaceCreateInfo.window = static_cast(_windowHandle); + surfaceCreateInfo.window = reinterpret_cast(_windowHandle); VK_CHECK(vkCreateXcbSurfaceKHR(gpuContext->vkInstance, &surfaceCreateInfo, nullptr, &_gpuSwapchain->vkSurface)); #else #pragma error Platform not supported diff --git a/native/cocos/renderer/pipeline/Define.h b/native/cocos/renderer/pipeline/Define.h index ec5e180482..cdadf213db 100644 --- a/native/cocos/renderer/pipeline/Define.h +++ b/native/cocos/renderer/pipeline/Define.h @@ -26,7 +26,7 @@ #pragma once #include - +#include #include "base/Object.h" #include "base/TypeDef.h" #include "base/Value.h" @@ -48,7 +48,7 @@ class RenderFlow; constexpr int JOINT_UNIFORM_CAPACITY = 30; constexpr float SHADOW_CAMERA_MAX_FAR = 2000.0F; -const float COEFFICIENT_OF_EXPANSION = 2.0F * std::sqrtf(3.0F); +const float COEFFICIENT_OF_EXPANSION = 2.0F * sqrtf(3.0F); struct CC_DLL RenderObject { float depth = 0; diff --git a/native/cocos/renderer/pipeline/RenderQueue.cpp b/native/cocos/renderer/pipeline/RenderQueue.cpp index 530ba6e316..be0e47f976 100644 --- a/native/cocos/renderer/pipeline/RenderQueue.cpp +++ b/native/cocos/renderer/pipeline/RenderQueue.cpp @@ -64,7 +64,14 @@ bool RenderQueue::insertRenderPass(const RenderObject &renderObj, uint subModelI } void RenderQueue::sort() { +#if CC_PLATFORM != CC_PLATFORM_LINUX && CC_PLATFORM != CC_PLATFORM_QNX std::sort(_queue.begin(), _queue.end(), _passDesc.sortFunc); +#else + //cannot use std::function as comparator in algorithms https://gcc.gnu.org/bugzilla/show_bug.cgi?id=65942#c11 + std::sort(_queue.begin(), _queue.end(), [this](const RenderPass &a, const RenderPass &b) -> bool { + return _passDesc.sortFunc(a, b); + }); +#endif } void RenderQueue::recordCommandBuffer(gfx::Device * /*device*/, scene::Camera *camera, gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuff, uint32_t subpassIndex) { diff --git a/native/cocos/renderer/pipeline/SceneCulling.cpp b/native/cocos/renderer/pipeline/SceneCulling.cpp index 1a8f74fa94..62c7e279c4 100644 --- a/native/cocos/renderer/pipeline/SceneCulling.cpp +++ b/native/cocos/renderer/pipeline/SceneCulling.cpp @@ -31,7 +31,6 @@ #include "SceneCulling.h" #include "gfx-base/GFXDevice.h" #include "math/Quaternion.h" -#include "platform/Application.h" #include "scene/AABB.h" #include "scene/Frustum.h" #include "scene/Light.h" diff --git a/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp b/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp index 73af4a543e..bb982170c8 100644 --- a/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp +++ b/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp @@ -28,7 +28,6 @@ #include "../shadow/ShadowFlow.h" #include "ForwardFlow.h" #include "gfx-base/GFXDevice.h" -#include "platform/Application.h" #include "scene/RenderScene.h" #include "../helper/Utils.h" diff --git a/native/cocos/scene/Model.h b/native/cocos/scene/Model.h index 3792eb749c..e3fab19237 100644 --- a/native/cocos/scene/Model.h +++ b/native/cocos/scene/Model.h @@ -83,7 +83,7 @@ public: _modelBounds.set(_worldBounds->getCenter(), _worldBounds->getHalfExtents()); } inline void setInstancedAttrBlock(uint8_t *buffer, uint32_t size, InstancedAttributeBlock &&block, const std::vector &attributes) { - _instancedBuffer = {buffer, size}; + _instancedBuffer = std::make_tuple(buffer, size); _instanceAttributeBlock = std::move(block); _instanceAttributes = attributes; _transformUpdated = true; diff --git a/native/cocos/storage/local-storage/LocalStorage.cpp b/native/cocos/storage/local-storage/LocalStorage.cpp index 790f521843..cca1455087 100644 --- a/native/cocos/storage/local-storage/LocalStorage.cpp +++ b/native/cocos/storage/local-storage/LocalStorage.cpp @@ -125,7 +125,7 @@ void localStorageInit(const std::string &fullpath /* = "" */) { ret |= sqlite3_prepare_v2(_db, sql_count, -1, &_stmt_count, nullptr); if (ret != SQLITE_OK) { - printf("Error initializing DB\n"); + printf("Error initializing DB(%s)\n", fullpath.c_str()); // report error } _initialized = 1; diff --git a/native/cocos/ui/edit-box/EditBox-android.cpp b/native/cocos/ui/edit-box/EditBox-android.cpp index ee92e3132a..92f089295f 100644 --- a/native/cocos/ui/edit-box/EditBox-android.cpp +++ b/native/cocos/ui/edit-box/EditBox-android.cpp @@ -27,7 +27,6 @@ #include "cocos/bindings/event/EventDispatcher.h" #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_global.h" -#include "platform/Application.h" #include "platform/java/jni/JniHelper.h" #ifndef JCLS_EDITBOX @@ -47,7 +46,7 @@ void getTextInputCallback() { return; } - auto global = se::ScriptEngine::getInstance()->getGlobalObject(); + auto* global = se::ScriptEngine::getInstance()->getGlobalObject(); se::Value jsbVal; if (global->getProperty("jsb", &jsbVal) && jsbVal.isObject()) { jsbVal.toObject()->getProperty("onTextInput", &textInputCallback); diff --git a/native/cocos/ui/edit-box/EditBox-ios.mm b/native/cocos/ui/edit-box/EditBox-ios.mm index 82668d5055..10aa9deb39 100644 --- a/native/cocos/ui/edit-box/EditBox-ios.mm +++ b/native/cocos/ui/edit-box/EditBox-ios.mm @@ -24,7 +24,6 @@ ****************************************************************************/ #include "EditBox.h" -#include "platform/Application.h" #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_global.h" diff --git a/native/cocos/ui/edit-box/EditBox-linux.cpp b/native/cocos/ui/edit-box/EditBox-linux.cpp new file mode 100644 index 0000000000..183d88b234 --- /dev/null +++ b/native/cocos/ui/edit-box/EditBox-linux.cpp @@ -0,0 +1,41 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "EditBox.h" + +namespace cc { + +void EditBox::show(const ShowInfo &showInfo) { + return; +} + +void EditBox::hide() { + return; +} + +bool EditBox::complete() { + return true; +} +} diff --git a/native/cocos/ui/edit-box/EditBox-mac.mm b/native/cocos/ui/edit-box/EditBox-mac.mm index c87f463d86..4ebcaa02c3 100644 --- a/native/cocos/ui/edit-box/EditBox-mac.mm +++ b/native/cocos/ui/edit-box/EditBox-mac.mm @@ -24,7 +24,7 @@ ****************************************************************************/ #include "EditBox.h" -#include "platform/Application.h" + #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_global.h" diff --git a/native/cocos/ui/edit-box/EditBox-ohos.cpp b/native/cocos/ui/edit-box/EditBox-ohos.cpp index 16310cb010..4c6619fb36 100644 --- a/native/cocos/ui/edit-box/EditBox-ohos.cpp +++ b/native/cocos/ui/edit-box/EditBox-ohos.cpp @@ -26,7 +26,7 @@ #include "cocos/bindings/event/EventDispatcher.h" #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_global.h" -#include "platform/Application.h" +//#include "platform/Application.h" #include "platform/java/jni/JniHelper.h" #ifndef JCLS_EDITBOX diff --git a/native/cocos/ui/edit-box/EditBox-win32.cpp b/native/cocos/ui/edit-box/EditBox-win32.cpp index fe415544eb..cd5b43ec12 100644 --- a/native/cocos/ui/edit-box/EditBox-win32.cpp +++ b/native/cocos/ui/edit-box/EditBox-win32.cpp @@ -24,17 +24,17 @@ ****************************************************************************/ #include "EditBox.h" -#include "platform/Application.h" -#include "platform/win32/View-win32.h" +#include "cocos/application/ApplicationManager.h" #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_global.h" -#include -#include -#include -#include -#include +#include "cocos/platform/interfaces/modules/ISystemWindow.h" -extern std::shared_ptr cc_get_application_view(); + +#include +#include +#include +#include +#include namespace cc { @@ -43,14 +43,26 @@ namespace cc { ************************************************************************/ namespace { -bool g_isMultiline = false; -HWND g_hwndEditBox = nullptr; -WNDPROC g_prevMainWindowProc = nullptr; -WNDPROC g_prevEditWindowProc = nullptr; +bool g_isMultiline = false; +HWND g_hwndEditBox = nullptr; +WNDPROC g_prevMainWindowProc = nullptr; +WNDPROC g_prevEditWindowProc = nullptr; se::Value g_textInputCallback; +HWND getCurrentWindowHwnd() { + if (!CC_CURRENT_APPLICATION()) { + return nullptr; + } + ISystemWindow *systemWindowIntf = CC_GET_PLATFORM_INTERFACE(ISystemWindow); + if (!systemWindowIntf) { + return nullptr; + } + return reinterpret_cast(systemWindowIntf->getWindowHandler()); +} + int getCocosWindowHeight() { - HWND parent = cc_get_application_view()->getWindowHandler(); + //HWND parent = cc_get_application_view()->getWindowHandler(); + HWND parent = getCurrentWindowHwnd(); RECT rect; GetClientRect(parent, &rect); return (rect.bottom - rect.top); @@ -60,7 +72,7 @@ void getTextInputCallback() { if (!g_textInputCallback.isUndefined()) return; - auto global = se::ScriptEngine::getInstance()->getGlobalObject(); + auto global = se::ScriptEngine::getInstance()->getGlobalObject(); se::Value jsbVal; if (global->getProperty("jsb", &jsbVal) && jsbVal.isObject()) { jsbVal.toObject()->getProperty("onTextInput", &g_textInputCallback); @@ -75,19 +87,19 @@ void callJSFunc(const std::string &type, const std::string &text) { getTextInputCallback(); se::AutoHandleScope scope; - se::ValueArray args; + se::ValueArray args; args.push_back(se::Value(type)); args.push_back(se::Value(text)); g_textInputCallback.toObject()->call(args, nullptr); } std::string getText(HWND hwnd) { - int length = GetWindowTextLength(hwnd); - LPWSTR str = (LPWSTR)malloc(sizeof(WCHAR) * (length + 1)); + int length = GetWindowTextLength(hwnd); + LPWSTR str = (LPWSTR)malloc(sizeof(WCHAR) * (length + 1)); GetWindowText(hwnd, str, length + 1); std::wstring_convert> convert; - std::string ret(convert.to_bytes(str)); + std::string ret(convert.to_bytes(str)); free(str); return ret; @@ -97,7 +109,7 @@ std::wstring str2ws(const std::string &text) { if (text.empty()) return std::wstring(); - int sz = MultiByteToWideChar(CP_UTF8, 0, &text[0], (int)text.size(), 0, 0); + int sz = MultiByteToWideChar(CP_UTF8, 0, &text[0], (int)text.size(), 0, 0); std::wstring res(sz, 0); MultiByteToWideChar(CP_UTF8, 0, &text[0], (int)text.size(), &res[0], sz); return res; @@ -108,7 +120,7 @@ LRESULT mainWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { case WM_LBUTTONDOWN: EditBox::complete(); EditBox::hide(); - SetFocus(cc_get_application_view()->getWindowHandler()); + SetFocus(getCurrentWindowHwnd()); break; case WM_COMMAND: if (EN_CHANGE == HIWORD(wParam)) @@ -128,13 +140,13 @@ LRESULT editWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (wParam == VK_RETURN && !g_isMultiline) { EditBox::complete(); EditBox::hide(); - SetFocus(cc_get_application_view()->getWindowHandler()); + SetFocus(getCurrentWindowHwnd()); } break; default: break; } - + return CallWindowProc(g_prevEditWindowProc, hwnd, msg, wParam, lParam); } } // namespace @@ -145,9 +157,9 @@ Implementation of EditBox. void EditBox::show(const EditBox::ShowInfo &showInfo) { int windowHeight = getCocosWindowHeight(); if (!g_hwndEditBox) { - HWND parent = cc_get_application_view()->getWindowHandler(); + HWND parent = getCurrentWindowHwnd(); - UINT32 flags = WS_CHILD | ES_LEFT | WS_TABSTOP | ES_AUTOHSCROLL; + UINT32 flags = WS_CHILD | ES_LEFT | WS_TABSTOP | ES_AUTOHSCROLL; g_isMultiline = showInfo.isMultiline; if (g_isMultiline) { flags |= ES_MULTILINE; @@ -205,7 +217,7 @@ void EditBox::show(const EditBox::ShowInfo &showInfo) { void EditBox::hide() { DestroyWindow(g_hwndEditBox); - SetWindowLongPtr(cc_get_application_view()->getWindowHandler(), GWLP_WNDPROC, (LONG_PTR)g_prevMainWindowProc); + SetWindowLongPtr(getCurrentWindowHwnd(), GWLP_WNDPROC, (LONG_PTR)g_prevMainWindowProc); SetWindowLongPtr(g_hwndEditBox, GWLP_WNDPROC, (LONG_PTR)g_prevEditWindowProc); g_hwndEditBox = nullptr; } diff --git a/native/cocos/ui/videoplayer/VideoPlayer-ios.mm b/native/cocos/ui/videoplayer/VideoPlayer-ios.mm index e5b9e79a21..a3570b4d07 100644 --- a/native/cocos/ui/videoplayer/VideoPlayer-ios.mm +++ b/native/cocos/ui/videoplayer/VideoPlayer-ios.mm @@ -35,7 +35,6 @@ using namespace cc; #import #import - #include "platform/Application.h" #include "platform/FileUtils.h" @interface UIVideoViewWrapperIos : NSObject diff --git a/native/cocos/ui/videoplayer/VideoPlayer-java.cpp b/native/cocos/ui/videoplayer/VideoPlayer-java.cpp index bc7d4a9d09..57468f284b 100644 --- a/native/cocos/ui/videoplayer/VideoPlayer-java.cpp +++ b/native/cocos/ui/videoplayer/VideoPlayer-java.cpp @@ -31,8 +31,6 @@ #include #include #include - #include "../../platform/Application.h" - #include "platform/Application.h" #include "platform/FileUtils.h" #include "platform/java/jni/JniHelper.h" diff --git a/native/cocos/ui/webview/WebViewImpl-ios.mm b/native/cocos/ui/webview/WebViewImpl-ios.mm index 7db01bb93d..4df43f36f7 100644 --- a/native/cocos/ui/webview/WebViewImpl-ios.mm +++ b/native/cocos/ui/webview/WebViewImpl-ios.mm @@ -32,7 +32,6 @@ #import #include "WebView-inl.h" - #include "platform/Application.h" #include "platform/FileUtils.h" @interface UIWebViewWrapper : NSObject diff --git a/native/extensions/assets-manager/AsyncTaskPool.cpp b/native/extensions/assets-manager/AsyncTaskPool.cpp index 3b90f9ff01..73a71c9535 100644 --- a/native/extensions/assets-manager/AsyncTaskPool.cpp +++ b/native/extensions/assets-manager/AsyncTaskPool.cpp @@ -28,24 +28,22 @@ THE SOFTWARE. namespace cc { -AsyncTaskPool *AsyncTaskPool::s_asyncTaskPool = nullptr; +AsyncTaskPool *AsyncTaskPool::sAsyncTaskPool = nullptr; AsyncTaskPool *AsyncTaskPool::getInstance() { - if (s_asyncTaskPool == nullptr) { - s_asyncTaskPool = new (std::nothrow) AsyncTaskPool(); + if (sAsyncTaskPool == nullptr) { + sAsyncTaskPool = new (std::nothrow) AsyncTaskPool(); } - return s_asyncTaskPool; + return sAsyncTaskPool; } void AsyncTaskPool::destroyInstance() { - delete s_asyncTaskPool; - s_asyncTaskPool = nullptr; + delete sAsyncTaskPool; + sAsyncTaskPool = nullptr; } -AsyncTaskPool::AsyncTaskPool() { -} +AsyncTaskPool::AsyncTaskPool() = default; -AsyncTaskPool::~AsyncTaskPool() { -} +AsyncTaskPool::~AsyncTaskPool() = default; } // namespace cc diff --git a/native/extensions/assets-manager/AsyncTaskPool.h b/native/extensions/assets-manager/AsyncTaskPool.h index 9bb356f00d..0d9a630b0c 100644 --- a/native/extensions/assets-manager/AsyncTaskPool.h +++ b/native/extensions/assets-manager/AsyncTaskPool.h @@ -23,20 +23,20 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#ifndef __CCSYNC_TASK_POOL_H_ -#define __CCSYNC_TASK_POOL_H_ +#pragma once + +#include "application/ApplicationManager.h" -#include "platform/Application.h" -#include "base/Scheduler.h" -#include -#include -#include -#include -#include #include -#include #include +#include +#include +#include +#include #include +#include +#include + /** * @addtogroup base @@ -51,7 +51,7 @@ namespace cc { */ class CC_DLL AsyncTaskPool { public: - typedef std::function TaskCallBack; + using TaskCallBack = std::function; enum class TaskType { TASK_IO, @@ -97,31 +97,31 @@ protected: class ThreadTasks { struct AsyncTaskCallBack { TaskCallBack callback; - void *callbackParam; + void * callbackParam; }; public: - ThreadTasks() - : _stop(false) { + ThreadTasks() { _thread = std::thread( [this] { for (;;) { std::function task; - AsyncTaskCallBack callback; + AsyncTaskCallBack callback; { std::unique_lock lock(this->_queueMutex); this->_condition.wait(lock, [this] { return this->_stop || !this->_tasks.empty(); }); - if (this->_stop && this->_tasks.empty()) + if (this->_stop && this->_tasks.empty()) { return; - task = std::move(this->_tasks.front()); + } + task = std::move(this->_tasks.front()); callback = std::move(this->_taskCallBacks.front()); this->_tasks.pop(); this->_taskCallBacks.pop(); } task(); - Application::getInstance()->getScheduler()->performFunctionInCocosThread([&, callback] { callback.callback(callback.callbackParam); }); + CC_CURRENT_ENGINE()->getScheduler()->performFunctionInCocosThread([&, callback] { callback.callback(callback.callbackParam); }); } }); } @@ -130,20 +130,24 @@ protected: std::unique_lock lock(_queueMutex); _stop = true; - while (_tasks.size()) + while (!_tasks.empty()) { _tasks.pop(); - while (_taskCallBacks.size()) + } + while (!_taskCallBacks.empty()) { _taskCallBacks.pop(); + } } _condition.notify_all(); _thread.join(); } void clear() { std::unique_lock lock(_queueMutex); - while (_tasks.size()) + while (!_tasks.empty()) { _tasks.pop(); - while (_taskCallBacks.size()) + } + while (!_taskCallBacks.empty()) { _taskCallBacks.pop(); + } } template void enqueue(const TaskCallBack &callback, void *callbackParam, F &&f) { @@ -159,7 +163,7 @@ protected: } AsyncTaskCallBack taskCallBack; - taskCallBack.callback = callback; + taskCallBack.callback = callback; taskCallBack.callbackParam = callbackParam; _tasks.emplace([task]() { task(); }); _taskCallBacks.emplace(taskCallBack); @@ -172,28 +176,28 @@ protected: std::thread _thread; // the task queue std::queue> _tasks; - std::queue _taskCallBacks; + std::queue _taskCallBacks; // synchronization - std::mutex _queueMutex; + std::mutex _queueMutex; std::condition_variable _condition; - bool _stop; + bool _stop{false}; }; //tasks - ThreadTasks _threadTasks[int(TaskType::TASK_MAX_TYPE)]; + ThreadTasks _threadTasks[static_cast(TaskType::TASK_MAX_TYPE)]; - static AsyncTaskPool *s_asyncTaskPool; + static AsyncTaskPool *sAsyncTaskPool; }; inline void AsyncTaskPool::stopTasks(TaskType type) { - auto &threadTask = _threadTasks[(int)type]; + auto &threadTask = _threadTasks[static_cast(type)]; threadTask.clear(); } template inline void AsyncTaskPool::enqueue(AsyncTaskPool::TaskType type, const TaskCallBack &callback, void *callbackParam, F &&f) { - auto &threadTask = _threadTasks[(int)type]; + auto &threadTask = _threadTasks[static_cast(type)]; threadTask.enqueue(callback, callbackParam, f); } @@ -201,4 +205,3 @@ inline void AsyncTaskPool::enqueue(AsyncTaskPool::TaskType type, const TaskCallB } // namespace cc // end group /// @} -#endif //__CCSYNC_TASK_POOL_H_ diff --git a/native/extensions/assets-manager/Manifest.cpp b/native/extensions/assets-manager/Manifest.cpp index 05c0700faa..ea48352e0e 100644 --- a/native/extensions/assets-manager/Manifest.cpp +++ b/native/extensions/assets-manager/Manifest.cpp @@ -25,12 +25,13 @@ ****************************************************************************/ #include "Manifest.h" +#include "base/Log.h" #include "json/prettywriter.h" #include "json/stringbuffer.h" -#include "base/Log.h" +#include +#include #include -#include #define KEY_VERSION "version" #define KEY_PACKAGE_URL "packageUrl" @@ -55,50 +56,45 @@ NS_CC_EXT_BEGIN static int cmpVersion(const std::string &v1, const std::string &v2) { int i; - int oct_v1[4] = {0}, oct_v2[4] = {0}; - int filled1 = std::sscanf(v1.c_str(), "%d.%d.%d.%d", &oct_v1[0], &oct_v1[1], &oct_v1[2], &oct_v1[3]); - int filled2 = std::sscanf(v2.c_str(), "%d.%d.%d.%d", &oct_v2[0], &oct_v2[1], &oct_v2[2], &oct_v2[3]); + int octV1[4] = {0}; + int octV2[4] = {0}; + int filled1 = std::sscanf(v1.c_str(), "%d.%d.%d.%d", &octV1[0], &octV1[1], &octV1[2], &octV1[3]); + int filled2 = std::sscanf(v2.c_str(), "%d.%d.%d.%d", &octV2[0], &octV2[1], &octV2[2], &octV2[3]); if (filled1 == 0 || filled2 == 0) { return strcmp(v1.c_str(), v2.c_str()); } + int ret = 0; for (i = 0; i < 4; i++) { - if (oct_v1[i] > oct_v2[i]) - return 1; - else if (oct_v1[i] < oct_v2[i]) - return -1; + if (octV1[i] == octV2[i]) { + continue; + } + ret = (octV1[i] > octV2[i]) ? 1 : -1; + break; } - return 0; + return ret; } Manifest::Manifest(const std::string &manifestUrl /* = ""*/) : _versionLoaded(false), _loaded(false), - _updating(false), - _manifestRoot(""), - _remoteManifestUrl(""), - _remoteVersionUrl(""), - _version(""), - _engineVer("") { + _updating(false) { // Init variables _fileUtils = FileUtils::getInstance(); - if (manifestUrl.size() > 0) + if (!manifestUrl.empty()) { parseFile(manifestUrl); + } } Manifest::Manifest(const std::string &content, const std::string &manifestRoot) : _versionLoaded(false), _loaded(false), - _updating(false), - _manifestRoot(""), - _remoteManifestUrl(""), - _remoteVersionUrl(""), - _version(""), - _engineVer("") { + _updating(false) { // Init variables _fileUtils = FileUtils::getInstance(); - if (content.size() > 0) + if (!content.empty()) { parseJSONString(content, manifestRoot); + } } void Manifest::loadJson(const std::string &url) { @@ -108,7 +104,7 @@ void Manifest::loadJson(const std::string &url) { // Load file content content = _fileUtils->getStringFromFile(url); - if (content.size() == 0) { + if (content.empty()) { CC_LOG_DEBUG("Fail to retrieve local file content: %s\n", url.c_str()); } else { loadJsonFromString(content); @@ -117,7 +113,7 @@ void Manifest::loadJson(const std::string &url) { } void Manifest::loadJsonFromString(const std::string &content) { - if (content.size() == 0) { + if (content.empty()) { CC_LOG_DEBUG("Fail to parse empty json content."); } else { // Parse file with rapid json @@ -125,8 +121,9 @@ void Manifest::loadJsonFromString(const std::string &content) { // Print error if (_json.HasParseError()) { size_t offset = _json.GetErrorOffset(); - if (offset > 0) + if (offset > 0) { offset--; + } std::string errorSnippet = content.substr(offset, 10); CC_LOG_DEBUG("File parse error %d at <%s>\n", _json.GetParseError(), errorSnippet.c_str()); } @@ -188,22 +185,23 @@ bool Manifest::versionEquals(const Manifest *b) const { return false; } // Check group versions - else { - std::vector bGroups = b->getGroups(); - std::unordered_map bGroupVer = b->getGroupVerions(); - // Check group size - if (bGroups.size() != _groups.size()) - return false; + std::vector bGroups = b->getGroups(); + std::unordered_map bGroupVer = b->getGroupVerions(); + // Check group size + if (bGroups.size() != _groups.size()) { + return false; + } - // Check groups version - for (unsigned int i = 0; i < _groups.size(); ++i) { - std::string gid = _groups[i]; - // Check group name - if (gid != bGroups[i]) - return false; - // Check group version - if (_groupVer.at(gid) != bGroupVer.at(gid)) - return false; + // Check groups version + for (unsigned int i = 0; i < _groups.size(); ++i) { + std::string gid = _groups[i]; + // Check group name + if (gid != bGroups[i]) { + return false; + } + // Check group version + if (_groupVer.at(gid) != bGroupVer.at(gid)) { + return false; } } return true; @@ -211,8 +209,8 @@ bool Manifest::versionEquals(const Manifest *b) const { bool Manifest::versionGreaterOrEquals(const Manifest *b, const std::function &handle) const { std::string localVersion = getVersion(); - std::string bVersion = b->getVersion(); - bool greater; + const std::string& bVersion = b->getVersion(); + bool greater; if (handle) { greater = handle(localVersion, bVersion) >= 0; } else { @@ -223,8 +221,8 @@ bool Manifest::versionGreaterOrEquals(const Manifest *b, const std::function &handle) const { std::string localVersion = getVersion(); - std::string bVersion = b->getVersion(); - bool greater; + const std::string& bVersion = b->getVersion(); + bool greater; if (handle) { greater = handle(localVersion, bVersion) > 0; } else { @@ -234,16 +232,17 @@ bool Manifest::versionGreater(const Manifest *b, const std::function Manifest::genDiff(const Manifest *b) const { - std::unordered_map diff_map; + std::unordered_map diffMap; const std::unordered_map &bAssets = b->getAssets(); std::string key; - Asset valueA; - Asset valueB; + Asset valueA; + Asset valueB; - std::unordered_map::const_iterator valueIt, it; + std::unordered_map::const_iterator valueIt; + std::unordered_map::const_iterator it; for (it = _assets.begin(); it != _assets.end(); ++it) { - key = it->first; + key = it->first; valueA = it->second; // Deleted @@ -251,8 +250,8 @@ std::unordered_map Manifest::genDiff(const Man if (valueIt == bAssets.cend()) { AssetDiff diff; diff.asset = valueA; - diff.type = DiffType::DELETED; - diff_map.emplace(key, diff); + diff.type = DiffType::DELETED; + diffMap.emplace(key, diff); continue; } @@ -261,13 +260,13 @@ std::unordered_map Manifest::genDiff(const Man if (valueA.md5 != valueB.md5) { AssetDiff diff; diff.asset = valueB; - diff.type = DiffType::MODIFIED; - diff_map.emplace(key, diff); + diff.type = DiffType::MODIFIED; + diffMap.emplace(key, diff); } } for (it = bAssets.begin(); it != bAssets.end(); ++it) { - key = it->first; + key = it->first; valueB = it->second; // Added @@ -275,24 +274,24 @@ std::unordered_map Manifest::genDiff(const Man if (valueIt == _assets.cend()) { AssetDiff diff; diff.asset = valueB; - diff.type = DiffType::ADDED; - diff_map.emplace(key, diff); + diff.type = DiffType::ADDED; + diffMap.emplace(key, diff); } } - return diff_map; + return diffMap; } void Manifest::genResumeAssetsList(DownloadUnits *units) const { - for (auto it = _assets.begin(); it != _assets.end(); ++it) { - Asset asset = it->second; + for (const auto &it : _assets) { + Asset asset = it.second; if (asset.downloadState != DownloadState::SUCCESSED && asset.downloadState != DownloadState::UNMARKED) { DownloadUnit unit; - unit.customId = it->first; - unit.srcUrl = _packageUrl + asset.path; + unit.customId = it.first; + unit.srcUrl = _packageUrl + asset.path; unit.storagePath = _manifestRoot + asset.path; - unit.size = asset.size; + unit.size = asset.size; units->emplace(unit.customId, unit); } } @@ -302,30 +301,32 @@ std::vector Manifest::getSearchPaths() const { std::vector searchPaths; searchPaths.push_back(_manifestRoot); - for (int i = (int)_searchPaths.size() - 1; i >= 0; i--) { + for (int i = static_cast(_searchPaths.size()) - 1; i >= 0; i--) { std::string path = _searchPaths[i]; - if (path.size() > 0 && path[path.size() - 1] != '/') + if (!path.empty() && path[path.size() - 1] != '/') { path.append("/"); - path = _manifestRoot + path; + } + path = _manifestRoot + path; //NOLINT searchPaths.push_back(path); } return searchPaths; } void Manifest::prependSearchPaths() { - std::vector searchPaths = FileUtils::getInstance()->getSearchPaths(); - std::vector::iterator iter = searchPaths.begin(); - bool needChangeSearchPaths = false; + std::vector searchPaths = FileUtils::getInstance()->getSearchPaths(); + auto iter = searchPaths.begin(); + bool needChangeSearchPaths = false; if (std::find(searchPaths.begin(), searchPaths.end(), _manifestRoot) == searchPaths.end()) { searchPaths.insert(iter, _manifestRoot); needChangeSearchPaths = true; } - for (int i = (int)_searchPaths.size() - 1; i >= 0; i--) { + for (int i = static_cast(_searchPaths.size()) - 1; i >= 0; i--) { std::string path = _searchPaths[i]; - if (path.size() > 0 && path[path.size() - 1] != '/') + if (!path.empty() && path[path.size() - 1] != '/') { path.append("/"); - path = _manifestRoot + path; + } + path = _manifestRoot + path; //NOLINT iter = searchPaths.begin(); searchPaths.insert(iter, path); needChangeSearchPaths = true; @@ -380,9 +381,9 @@ void Manifest::setAssetDownloadState(const std::string &key, const Manifest::Dow if (assets.HasMember(key.c_str())) { rapidjson::Value &entry = assets[key.c_str()]; if (entry.HasMember(KEY_DOWNLOAD_STATE) && entry[KEY_DOWNLOAD_STATE].IsInt()) { - entry[KEY_DOWNLOAD_STATE].SetInt((int)state); + entry[KEY_DOWNLOAD_STATE].SetInt(static_cast(state)); } else { - entry.AddMember(KEY_DOWNLOAD_STATE, (int)state, _json.GetAllocator()); + entry.AddMember(KEY_DOWNLOAD_STATE, static_cast(state), _json.GetAllocator()); } } } @@ -397,9 +398,9 @@ void Manifest::clear() { _groupVer.clear(); _remoteManifestUrl = ""; - _remoteVersionUrl = ""; - _version = ""; - _engineVer = ""; + _remoteVersionUrl = ""; + _version = ""; + _engineVer = ""; _versionLoaded = false; } @@ -417,8 +418,9 @@ Manifest::Asset Manifest::parseAsset(const std::string &path, const rapidjson::V if (json.HasMember(KEY_MD5) && json[KEY_MD5].IsString()) { asset.md5 = json[KEY_MD5].GetString(); - } else + } else { asset.md5 = ""; + } if (json.HasMember(KEY_PATH) && json[KEY_PATH].IsString()) { asset.path = json[KEY_PATH].GetString(); @@ -426,18 +428,21 @@ Manifest::Asset Manifest::parseAsset(const std::string &path, const rapidjson::V if (json.HasMember(KEY_COMPRESSED) && json[KEY_COMPRESSED].IsBool()) { asset.compressed = json[KEY_COMPRESSED].GetBool(); - } else + } else { asset.compressed = false; + } if (json.HasMember(KEY_SIZE) && json[KEY_SIZE].IsInt()) { - asset.size = json[KEY_SIZE].GetInt(); - } else + asset.size = static_cast(json[KEY_SIZE].GetInt()); + } else { asset.size = 0; + } if (json.HasMember(KEY_DOWNLOAD_STATE) && json[KEY_DOWNLOAD_STATE].IsInt()) { asset.downloadState = (json[KEY_DOWNLOAD_STATE].GetInt()); - } else + } else { asset.downloadState = DownloadState::UNMARKED; + } return asset; } @@ -463,7 +468,7 @@ void Manifest::loadVersion(const rapidjson::Document &json) { const rapidjson::Value &groupVers = json[KEY_GROUP_VERSIONS]; if (groupVers.IsObject()) { for (rapidjson::Value::ConstMemberIterator itr = groupVers.MemberBegin(); itr != groupVers.MemberEnd(); ++itr) { - std::string group = itr->name.GetString(); + std::string group = itr->name.GetString(); std::string version = "0"; if (itr->value.IsString()) { version = itr->value.GetString(); @@ -494,7 +499,7 @@ void Manifest::loadManifest(const rapidjson::Document &json) { if (json.HasMember(KEY_PACKAGE_URL) && json[KEY_PACKAGE_URL].IsString()) { _packageUrl = json[KEY_PACKAGE_URL].GetString(); // Append automatically "/" - if (_packageUrl.size() > 0 && _packageUrl[_packageUrl.size() - 1] != '/') { + if (!_packageUrl.empty() && _packageUrl[_packageUrl.size() - 1] != '/') { _packageUrl.append("/"); } } @@ -504,8 +509,8 @@ void Manifest::loadManifest(const rapidjson::Document &json) { const rapidjson::Value &assets = json[KEY_ASSETS]; if (assets.IsObject()) { for (rapidjson::Value::ConstMemberIterator itr = assets.MemberBegin(); itr != assets.MemberEnd(); ++itr) { - std::string key = itr->name.GetString(); - Asset asset = parseAsset(key, itr->value); + std::string key = itr->name.GetString(); + Asset asset = parseAsset(key, itr->value); _assets.emplace(key, asset); } } @@ -517,7 +522,7 @@ void Manifest::loadManifest(const rapidjson::Document &json) { if (paths.IsArray()) { for (rapidjson::SizeType i = 0; i < paths.Size(); ++i) { if (paths[i].IsString()) { - _searchPaths.push_back(paths[i].GetString()); + _searchPaths.emplace_back(paths[i].GetString()); } } } @@ -527,14 +532,15 @@ void Manifest::loadManifest(const rapidjson::Document &json) { } void Manifest::saveToFile(const std::string &filepath) { - rapidjson::StringBuffer buffer; + rapidjson::StringBuffer buffer; rapidjson::PrettyWriter writer(buffer); _json.Accept(writer); std::ofstream output(FileUtils::getInstance()->getSuitableFOpen(filepath), std::ofstream::out); - if (!output.bad()) + if (!output.bad()) { output << buffer.GetString() << std::endl; + } } NS_CC_EXT_END diff --git a/native/extensions/assets-manager/Manifest.h b/native/extensions/assets-manager/Manifest.h index e675c2ed94..6b2851f672 100644 --- a/native/extensions/assets-manager/Manifest.h +++ b/native/extensions/assets-manager/Manifest.h @@ -24,8 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef __Manifest__ -#define __Manifest__ +#pragma once #include #include @@ -56,7 +55,7 @@ struct ManifestAsset { int downloadState; }; -typedef std::unordered_map DownloadUnits; +using DownloadUnits = std::unordered_map; class CC_EX_DLL Manifest : public Ref { public: @@ -77,7 +76,7 @@ public: }; //! Asset object - typedef ManifestAsset Asset; + using Asset = ManifestAsset; //! Object indicate the difference between two Assets struct AssetDiff { @@ -122,7 +121,7 @@ public: /** @brief Constructor for Manifest class, create manifest by parsing a json file * @param manifestUrl Url of the local manifest */ - Manifest(const std::string &manifestUrl = ""); + explicit Manifest(const std::string &manifestUrl = ""); /** @brief Constructor for Manifest class, create manifest by parsing a json string * @param content Json string content @@ -209,7 +208,7 @@ protected: void saveToFile(const std::string &filepath); - Asset parseAsset(const std::string &path, const rapidjson::Value &json); + static Asset parseAsset(const std::string &path, const rapidjson::Value &json); void clear(); @@ -289,4 +288,3 @@ private: }; NS_CC_EXT_END -#endif /* defined(__Manifest__) */ diff --git a/native/templates/android/template/CMakeLists.txt b/native/templates/android/template/CMakeLists.txt index 121d238d91..5bee38a37c 100755 --- a/native/templates/android/template/CMakeLists.txt +++ b/native/templates/android/template/CMakeLists.txt @@ -11,7 +11,6 @@ set(LIB_NAME cocos) set(PROJ_SOURCES ${CMAKE_CURRENT_LIST_DIR}/../common/Classes/Game.h ${CMAKE_CURRENT_LIST_DIR}/../common/Classes/Game.cpp - ${CMAKE_CURRENT_LIST_DIR}/jni/main.cpp ) diff --git a/native/templates/common/Classes/Game.cpp b/native/templates/common/Classes/Game.cpp index 0cb1162c1a..d46722b7b9 100644 --- a/native/templates/common/Classes/Game.cpp +++ b/native/templates/common/Classes/Game.cpp @@ -64,4 +64,4 @@ void Game::onClose() { cc::CocosApplication::onClose(); } -CC_APPLICATION_MAIN(Game); \ No newline at end of file +CC_APPLICATION_MAIN(Game); diff --git a/native/templates/common/Classes/Game.h b/native/templates/common/Classes/Game.h index e5114d0bd3..4d2a3b21e0 100644 --- a/native/templates/common/Classes/Game.h +++ b/native/templates/common/Classes/Game.h @@ -24,19 +24,18 @@ ****************************************************************************/ #pragma once -#include "platform/Application.h" +#include "cocos/application/CocosApplication.h" + /** @brief The cocos2d Application. The reason for implement as private inheritance is to hide some interface call by Director. */ -class Game : public cc::Application { +class Game : public cc::CocosApplication { public: - /** - * width and height in logical pixel unit - */ - Game(int width, int height); - bool init() override; + Game(); + int init() override; + //bool init() override; void onPause() override; void onResume() override; void onClose() override; diff --git a/native/templates/ios/main.m b/native/templates/ios/main.m deleted file mode 100644 index c0386fe9d1..0000000000 --- a/native/templates/ios/main.m +++ /dev/null @@ -1,10 +0,0 @@ - - -#import - -int main(int argc, char *argv[]) { - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - int retVal = UIApplicationMain(argc, argv, nil, @"AppDelegate"); - [pool release]; - return retVal; -} diff --git a/native/templates/mac/CMakeLists.txt b/native/templates/mac/CMakeLists.txt index 689bb03187..be8069035d 100644 --- a/native/templates/mac/CMakeLists.txt +++ b/native/templates/mac/CMakeLists.txt @@ -26,11 +26,11 @@ set(UI_RESOURCES ${CMAKE_CURRENT_LIST_DIR}/Icon.icns ) list(APPEND PROJ_SOURCES - ${CMAKE_CURRENT_LIST_DIR}/main.m - ${CMAKE_CURRENT_LIST_DIR}/ViewController.mm - ${CMAKE_CURRENT_LIST_DIR}/ViewController.h - ${CMAKE_CURRENT_LIST_DIR}/AppDelegate.mm - ${CMAKE_CURRENT_LIST_DIR}/AppDelegate.h + #${CMAKE_CURRENT_LIST_DIR}/main.m + #${CMAKE_CURRENT_LIST_DIR}/ViewController.mm + #${CMAKE_CURRENT_LIST_DIR}/ViewController.h + #${CMAKE_CURRENT_LIST_DIR}/AppDelegate.mm + #${CMAKE_CURRENT_LIST_DIR}/AppDelegate.h ${UI_RESOURCES} ) diff --git a/native/templates/mac/main.m b/native/templates/mac/main.m deleted file mode 100644 index 8ba283a699..0000000000 --- a/native/templates/mac/main.m +++ /dev/null @@ -1,8 +0,0 @@ -#import -#import "AppDelegate.h" - -int main(int argc, const char * argv[]) { - id delegate = [[AppDelegate alloc] init]; - NSApplication.sharedApplication.delegate = delegate; - return NSApplicationMain(argc, argv); -} diff --git a/native/templates/ohos/CMakeLists.txt b/native/templates/ohos/CMakeLists.txt index 70fd7e71e6..19d3e4665b 100644 --- a/native/templates/ohos/CMakeLists.txt +++ b/native/templates/ohos/CMakeLists.txt @@ -16,7 +16,6 @@ set(LIB_NAME cocos) set(PROJ_SOURCES ${COMMON_DIR}/Classes/Game.h ${COMMON_DIR}/Classes/Game.cpp - ${CMAKE_CURRENT_LIST_DIR}/entry/src/main/cpp/main.cpp ) diff --git a/native/templates/ohos/entry/src/main/cpp/main.cpp b/native/templates/ohos/entry/src/main/cpp/main.cpp deleted file mode 100644 index e960f35f72..0000000000 --- a/native/templates/ohos/entry/src/main/cpp/main.cpp +++ /dev/null @@ -1,8 +0,0 @@ -#include "Game.h" - -extern "C" { - -cc::Application *cocos_main(int width, int height) { - return new Game(width, height); -} -} \ No newline at end of file diff --git a/native/templates/windows/AppDelegate.h b/native/templates/windows/AppDelegate.h deleted file mode 100644 index 01e1bc21be..0000000000 --- a/native/templates/windows/AppDelegate.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include -#include -#include "Game.h" - -namespace cc { -class View; -}; - -class AppDelegate { -public: - AppDelegate(const std::string &name, int width, int height); - - void start(); - -private: - std::shared_ptr _view; - std::shared_ptr _game; - - bool _quit{false}; -}; diff --git a/native/templates/windows/CMakeLists.txt b/native/templates/windows/CMakeLists.txt index 2c485d76d9..549063272c 100644 --- a/native/templates/windows/CMakeLists.txt +++ b/native/templates/windows/CMakeLists.txt @@ -18,10 +18,7 @@ set(UI_RESOURCES ${CMAKE_CURRENT_LIST_DIR}/game.rc ) list(APPEND PROJ_SOURCES - ${CMAKE_CURRENT_LIST_DIR}/AppDelegate.h - ${CMAKE_CURRENT_LIST_DIR}/AppDelegate.cpp - ${CMAKE_CURRENT_LIST_DIR}/main.h - ${CMAKE_CURRENT_LIST_DIR}/main.cpp + ${CMAKE_CURRENT_LIST_DIR}/resource.h ${UI_RESOURCES} ) diff --git a/native/templates/windows/resource.h b/native/templates/windows/resource.h index 920119022a..8b63ba6857 100644 --- a/native/templates/windows/resource.h +++ b/native/templates/windows/resource.h @@ -2,16 +2,16 @@ // Microsoft Visual C++ generated include file. // Used by game.rc // -#define IDS_PROJNAME 100 -#define IDR_TESTJS 100 +#define IDS_PROJNAME 100 +#define IDR_TESTJS 100 // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 204 -#define _APS_NEXT_COMMAND_VALUE 32785 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif + #ifndef APSTUDIO_READONLY_SYMBOLS + #define _APS_NEXT_RESOURCE_VALUE 204 + #define _APS_NEXT_COMMAND_VALUE 32785 + #define _APS_NEXT_CONTROL_VALUE 1001 + #define _APS_NEXT_SYMED_VALUE 101 + #endif #endif diff --git a/native/tools/simulator/frameworks/runtime-src/CMakeLists.txt b/native/tools/simulator/frameworks/runtime-src/CMakeLists.txt index 2cf972c53b..c75fcec8a8 100644 --- a/native/tools/simulator/frameworks/runtime-src/CMakeLists.txt +++ b/native/tools/simulator/frameworks/runtime-src/CMakeLists.txt @@ -87,8 +87,8 @@ if(WINDOWS) proj.win32/main.cpp proj.win32/main.h proj.win32/resource.h - proj.win32/SimulatorWin.cpp - proj.win32/SimulatorWin.h + proj.win32/SimulatorApp.cpp + proj.win32/SimulatorApp.h # proj.win32/stdafx.cpp # proj.win32/stdafx.h # proj.win32/targetver.h @@ -105,13 +105,13 @@ elseif(MACOSX) proj.ios_mac/mac/zh-Hans.lproj/MainMenu.xib ) list(APPEND PROJ_SOURCES - proj.ios_mac/mac/main.mm + # proj.ios_mac/mac/main.mm proj.ios_mac/mac/SimulatorApp.h proj.ios_mac/mac/SimulatorApp.mm # proj.ios_mac/mac/AppDelegate.h # proj.ios_mac/mac/AppDelegate.mm - proj.ios_mac/mac/ViewController.h - proj.ios_mac/mac/ViewController.mm + # proj.ios_mac/mac/ViewController.h + # proj.ios_mac/mac/ViewController.mm proj.ios_mac/mac/ConsoleWindowController.h proj.ios_mac/mac/ConsoleWindowController.m ${UI_RESOURCES} diff --git a/native/tools/simulator/frameworks/runtime-src/Classes/Game.cpp b/native/tools/simulator/frameworks/runtime-src/Classes/Game.cpp index 67463653c7..aeb13b3e5e 100755 --- a/native/tools/simulator/frameworks/runtime-src/Classes/Game.cpp +++ b/native/tools/simulator/frameworks/runtime-src/Classes/Game.cpp @@ -22,48 +22,50 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - #include "Game.h" +#include "cocos/application/ApplicationManager.h" #include "cocos/bindings/event/CustomEventTypes.h" #include "cocos/bindings/event/EventDispatcher.h" -#include "cocos/bindings/manual/jsb_module_register.h" -#include "cocos/bindings/manual/jsb_global.h" #include "cocos/bindings/jswrapper/SeApi.h" -#include "cocos/bindings/event/EventDispatcher.h" #include "cocos/bindings/manual/jsb_classtype.h" +#include "cocos/bindings/manual/jsb_global.h" +#include "cocos/bindings/manual/jsb_module_register.h" + +#if (CC_PLATFORM == CC_PLATFORM_WINDOWS) +#include "SimulatorApp.h" +#elif (CC_PLATFORM == CC_PLATFORM_MAC_OSX) +#include "../proj.ios_mac/mac/SimulatorApp.h" +#endif #include "ide-support/CodeIDESupport.h" -#include "runtime/Runtime.h" #include "ide-support/RuntimeJsImpl.h" #include "runtime/ConfigParser.h" +#include "runtime/Runtime.h" + using namespace std; +Game::Game() { +} -Game::Game(int width, int height) : cc::Application(width, height) {} - -Game::~Game() -{ +Game::~Game() { // NOTE:Please don't remove this call if you want to debug with Cocos Code IDE RuntimeEngine::getInstance()->end(); } -bool Game::init() -{ - - cc::Application::init(); - se::ScriptEngine *se = se::ScriptEngine::getInstance(); - - // set default FPS - Application::getInstance()->setPreferredFramesPerSecond(60); - jsb_init_file_operation_delegate(); - jsb_register_all_modules(); +int Game::init() { + SimulatorApp::getInstance()->run(); + createWindow("My game", 0, 0, SimulatorApp::getInstance()->getWidth(), + SimulatorApp::getInstance()->getHegith(), + cc::ISystemWindow::CC_WINDOW_SHOWN | + cc::ISystemWindow::CC_WINDOW_RESIZABLE | + cc::ISystemWindow::CC_WINDOW_INPUT_FOCUS); auto parser = ConfigParser::getInstance(); - #if defined(CC_DEBUG) && (CC_DEBUG > 0) - // Enable debugger here - jsb_enable_debugger("0.0.0.0", 5086, parser->isWaitForConnect()); - #endif + setJsDebugIpAndPort("0.0.0.0", 5086, parser->isWaitForConnect()); - se->start(); + int ret = cc::CocosApplication::init(); + if (ret != 0) { + return ret; + } auto runtimeEngine = RuntimeEngine::getInstance(); runtimeEngine->setEventTrackingEnable(true); @@ -71,27 +73,31 @@ bool Game::init() runtimeEngine->addRuntime(jsRuntime, kRuntimeEngineJs); runtimeEngine->start(); - se::AutoHandleScope hs; - jsb_run_script("jsb-adapter/jsb-builtin.js"); - jsb_run_script("main.js"); + setXXTeaKey(""); + + runJsScript("jsb-adapter/jsb-builtin.js"); + runJsScript("main.js"); // Runtime end CC_LOG_DEBUG("iShow!"); - return true; + return 0; } // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void Game::onPause() { - cc::Application::onPause(); - cc::EventDispatcher::dispatchEnterBackgroundEvent(); + cc::CocosApplication::onPause(); } void Game::onResume() { - cc::Application::onResume(); - cc::EventDispatcher::dispatchEnterForegroundEvent(); + cc::CocosApplication::onResume(); } void Game::onClose() { - cc::Application::onClose(); - cc::EventDispatcher::dispatchCloseEvent(); + cc::CocosApplication::onClose(); } + +void Game::handleException(const char* location, const char* message, const char* stack) { + //TODO: nothing +} + +CC_APPLICATION_MAIN(Game); diff --git a/native/tools/simulator/frameworks/runtime-src/Classes/Game.h b/native/tools/simulator/frameworks/runtime-src/Classes/Game.h index 2b3ae739bc..dea8f45fe7 100755 --- a/native/tools/simulator/frameworks/runtime-src/Classes/Game.h +++ b/native/tools/simulator/frameworks/runtime-src/Classes/Game.h @@ -22,26 +22,25 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - #pragma once -#include "platform/Application.h" - +#include "cocos/application/CocosApplication.h" /** @brief The cocos2d Application. The reason for implement as private inheritance is to hide some interface call by Director. */ -class Game : public cc::Application -{ +class Game : public cc::CocosApplication { public: - /** - * width and height in logical pixel unit - */ + Game(); Game(int width, int height); - virtual ~Game(); - virtual bool init() override; - virtual void onPause() override; - virtual void onResume() override; - virtual void onClose() override; + ~Game(); + + int init() override; + //bool init() override; + void onPause() override; + void onResume() override; + void onClose() override; + + void handleException(const char* location, const char* message, const char* stack) override; }; diff --git a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/Base.lproj/MainMenu.xib b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/Base.lproj/MainMenu.xib index 95349511fa..9056c5a787 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/Base.lproj/MainMenu.xib +++ b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/Base.lproj/MainMenu.xib @@ -1,11 +1,11 @@ - - + + - + - + @@ -190,9 +190,10 @@ + - + diff --git a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.h b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.h index a05739afc7..10e4892aa4 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.h +++ b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.h @@ -25,37 +25,23 @@ ****************************************************************************/ -#import -#import "ConsoleWindowController.h" +//#import +//#import "ConsoleWindowController.h" #include #include "ProjectConfig/ProjectConfig.h" #include "ProjectConfig/SimulatorConfig.h" #include "Game.h" -@interface AppController : NSObject -{ - NSWindow *_window; - NSMenu *menu; - - Game *_app; - ProjectConfig _project; - int _debugLogFile; - std::string _entryPath; - - //log file - ConsoleWindowController *_consoleController; - NSFileHandle *_fileHandle; - - //console pipe - NSPipe *_pipe; - NSFileHandle *_pipeReadHandle; -} +class SimulatorApp { +public: + static SimulatorApp *getInstance(); + virtual ~SimulatorApp(); + int run(); + virtual int getWidth() const; + virtual int getHegith() const; +protected: + SimulatorApp(); -@property (nonatomic, assign) IBOutlet NSMenu* menu; - --(BOOL)application:(NSApplication*)app openFile:(NSString*)path; --(IBAction)onFileClose:(id)sender; --(IBAction)onWindowAlwaysOnTop:(id)sender; --(NSWindow*)getWindow; -@end + static SimulatorApp *_instance; +}; diff --git a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.mm b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.mm index 11ead6c94a..9359e6f245 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.mm +++ b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.mm @@ -23,7 +23,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - +#import +#import "ConsoleWindowController.h" #include #include #include @@ -40,11 +41,40 @@ #include "ide-support/CodeIDESupport.h" #include "cocos/platform/mac/View.h" - +#include "cocos/application/ApplicationManager.h" #include "platform/mac/PlayerMac.h" -#include "AppEvent.h" +#include "platform/interfaces/modules/IScreen.h" +#include "CustomAppEvent.h" #include "AppLang.h" + +@interface AppController : NSObject +{ + NSWindow *_window; + NSMenu *menu; + + Game *_app; + ProjectConfig _project; + int _debugLogFile; + std::string _entryPath; + + //log file + ConsoleWindowController *_consoleController; + NSFileHandle *_fileHandle; + + //console pipe + NSPipe *_pipe; + NSFileHandle *_pipeReadHandle; +} + +@property (nonatomic, assign) IBOutlet NSMenu* menu; + +//-(BOOL)application:(NSApplication*)app openFile:(NSString*)path; +-(IBAction)onFileClose:(id)sender; +-(IBAction)onWindowAlwaysOnTop:(id)sender; +@end + + using namespace cc; static id SIMULATOR = nullptr; @@ -69,12 +99,12 @@ std::string getCurAppName(void) -(void) dealloc { - delete _app; - _app = nullptr; + //delete _app; + //_app = nullptr; player::PlayerProtocol::getInstance()->purgeInstance(); [super dealloc]; } - +/* #pragma mark - #pragma delegates @@ -104,26 +134,7 @@ std::string getCurAppName(void) return YES; } - --(void)applicationDidFinishLaunching:(NSNotification *)aNotification -{ - SIMULATOR = self; - player::PlayerMac::create(); - - _debugLogFile = 0; - - [self parseCocosProjectConfig:&_project]; - [self updateProjectFromCommandLineArgs:&_project]; - - if (_entryPath.length()) - { - _project.setScriptFile(_entryPath); - } - - [self createWindowAndView]; - [self startup]; -} - +*/ #pragma mark - #pragma mark functions @@ -137,11 +148,6 @@ std::string getCurAppName(void) [[NSRunningApplication currentApplication] terminate]; } -- (BOOL) applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)theApplication -{ - return YES; -} - - (NSMutableArray*) makeCommandLineArgsFromProjectConfig { return [self makeCommandLineArgsFromProjectConfig:kProjectConfigAll]; @@ -241,6 +247,25 @@ std::string getCurAppName(void) config->setScriptFile(parser->getEntryFile()); } +-(void) run +{ + SIMULATOR = self; + player::PlayerMac::create(); + + _debugLogFile = 0; + + [self parseCocosProjectConfig:&_project]; + [self updateProjectFromCommandLineArgs:&_project]; + + if (_entryPath.length()) + { + _project.setScriptFile(_entryPath); + } + + [self createWindowAndView]; + [self startup]; +} + - (void) updateProjectFromCommandLineArgs:(ProjectConfig*)config { NSArray *nsargs = [[NSProcessInfo processInfo] arguments]; @@ -363,29 +388,13 @@ std::string getCurAppName(void) int frameHeight = (int) (_project.getFrameScale() * frameSize.height); - NSRect rect = NSMakeRect(200, 200, frameWidth, frameHeight); - _window = [[NSWindow alloc] initWithContentRect:rect - styleMask:NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskTitled | NSWindowStyleMaskClosable - backing:NSBackingStoreBuffered - defer:NO]; - if (!_window) { - NSLog(@"Failed to allocated the window."); - return; - } - - _window.title = @"Cocos creator 3D Game"; - - ViewController* viewController = [[ViewController alloc] initWithSize: rect]; - _window.contentViewController = viewController; - _window.contentView = viewController.view; - [_window.contentView setWantsBestResolutionOpenGLSurface:YES]; - [_window makeKeyAndOrderFront:nil]; + //NSRect rect = NSMakeRect(200, 200, frameWidth, frameHeight); NSApplication *thisApp = [NSApplication sharedApplication]; [thisApp activateIgnoringOtherApps:YES]; // create opengl view, and init app - _app = new Game(frameWidth, frameHeight); + //_app = new Game(frameWidth, frameHeight); if (pos.x != 0 && pos.y != 0) { @@ -438,7 +447,7 @@ std::string getCurAppName(void) RuntimeEngine::getInstance()->setProjectConfig(_project); - _app->init(); + //_app->init(); } @@ -523,7 +532,7 @@ std::string getCurAppName(void) ProjectConfig &project = _project; EventDispatcher::CustomEventListener listener = [self, &project, scaleMenuVector](const CustomEvent& event){ - auto menuEvent = dynamic_cast(event); + auto menuEvent = dynamic_cast(event); rapidjson::Document dArgParse; dArgParse.Parse<0>(menuEvent.getDataString().c_str()); @@ -590,8 +599,9 @@ std::string getCurAppName(void) } else if (data == "VIEW_SHOW_FPS") { - bool displayStats = !_app->isDisplayStats(); - _app->setDisplayStats(displayStats); + IScreen* screenIntf = CC_GET_PLATFORM_INTERFACE(IScreen); + bool displayStats = !screenIntf->isDisplayStats(); + screenIntf->setDisplayStats(displayStats); menuItem->setTitle(displayStats ? tr("Hide FPS") : tr("Show FPS")); } @@ -672,6 +682,16 @@ std::string getCurAppName(void) return NO; } +- (int) getHeight +{ + return _project.getFrameScale() * _project.getFrameSize().height; +} + +- (int) getWidth +{ + return _project.getFrameScale() * _project.getFrameSize().width; +} + #pragma mark - -(IBAction)onFileClose:(id)sender @@ -700,9 +720,38 @@ std::string getCurAppName(void) CC_SAFE_DELETE(_app); } -- (NSWindow*)getWindow -{ - return _window; +@end + +namespace { +AppController* app; } -@end +SimulatorApp::SimulatorApp() { + app = [[AppController alloc] init]; +} + +SimulatorApp::~SimulatorApp() { + +} + +int SimulatorApp::run() { + [app run]; + return 0; +} + +SimulatorApp* SimulatorApp::_instance = nullptr; + +SimulatorApp* SimulatorApp::getInstance() { + if (!_instance) { + _instance = new SimulatorApp(); + } + return _instance; +} + +int SimulatorApp::getWidth() const { + return [app getWidth];; +} + +int SimulatorApp::getHegith() const { + return [app getHeight];; +} diff --git a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/ViewController.h b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/ViewController.h index cbb08ca84f..d23e4318bd 100644 --- a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/ViewController.h +++ b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/ViewController.h @@ -1,3 +1,4 @@ +/* #import #import @@ -5,3 +6,4 @@ - (instancetype)initWithSize:(NSRect)rect; @end +*/ diff --git a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/ViewController.mm b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/ViewController.mm index 631658cad6..e743bfdf24 100644 --- a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/ViewController.mm +++ b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/ViewController.mm @@ -1,3 +1,4 @@ +/* #import "ViewController.h" #import "platform/mac/View.h" @@ -15,3 +16,4 @@ } @end +*/ diff --git a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/en.lproj/MainMenu.xib b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/en.lproj/MainMenu.xib index a803574695..1bb53cf407 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/en.lproj/MainMenu.xib +++ b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/en.lproj/MainMenu.xib @@ -1,887 +1,146 @@ - - - 1060 - 13D65 - 5056 - 1265.20 - 698.00 - - com.apple.InterfaceBuilder.CocoaPlugin - 5056 - - - NSCustomObject - NSMenu - NSMenuItem - - - com.apple.InterfaceBuilder.CocoaPlugin - - - PluginDependencyRecalculationVersion - - - - - AppController - - - FirstResponder - - - NSApplication - - - AMainMenu - - - - Cocos-player - - 1048576 - 2147483647 - - NSImage - NSMenuCheckmark - - - NSImage - NSMenuMixedState - - submenuAction: - - - Cocos-player - - - - About Cocos-player - - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Services - - 1048576 - 2147483647 - - - submenuAction: - - - Services - - _NSServicesMenu - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Hide Cocos-player - h - 1048576 - 2147483647 - - - - - - Hide Others - h - 1572864 - 2147483647 - - - - - - Show All - - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Quit Cocos-player - q - 1048576 - 2147483647 - - - - - _NSAppleMenu - - - - - File - - 1048576 - 2147483647 - - - submenuAction: - - - File - - - - Close - w - 1048576 - 2147483647 - - - - - - - - - View - - 1048576 - 2147483647 - - - submenuAction: - - - View - - - - YES - YES - - - 2147483647 - - - - - - Portait - - 2147483647 - 1 - - - - - - Landscape - - 2147483647 - - - - - - YES - YES - - - 2147483647 - - - - - - Actual (100%) - 0 - 1048576 - 2147483647 - 1 - - - 100 - - - - Zoom Out (75%) - 6 - 1048576 - 2147483647 - - - 75 - - - - Zoom Out (50%) - 5 - 1048576 - 2147483647 - - - 50 - - - - Zoom Out (25%) - 4 - 1048576 - 2147483647 - - - 25 - - - - - - - Control - - 2147483647 - - - submenuAction: - - - Control - - - - Relaunch - r - 1048576 - 2147483647 - - - - - - Keep Window Top - - 2147483647 - - - - - - - - - Help - - 2147483647 - - - submenuAction: - - - Help - - _NSHelpMenu - - - - _NSMainMenu - - - NSFontManager - - - AppController - - - - NO - - - - hide: - - - - SGN-0p-7lH - - - - hideOtherApplications: - - - - iJd-Ba-eXG - - - - unhideAllApplications: - - - - DR8-By-ymv - - - - terminate: - - - - DyL-yF-GYq - - - - delegate - - - - 537 - - - - menu - - - - 650 - - - - orderFrontStandardAboutPanel: - - - - tSA-7z-LPk - - - - onFileClose: - - - - 661 - - - - onScreenPortait: - - - - 667 - - - - onScreenLandscape: - - - - 647 - - - - onScreenZoomOut: - - - - yUj-fN-Rh7 - - - - onScreenZoomOut: - - - - yps-LZ-egB - - - - onScreenZoomOut: - - - - 654 - - - - onScreenZoomOut: - - - - DSu-if-D2T - - - - onRelaunch: - - - - XXg-eJ-YSn - - - - onSetTop: - - - - jvv-x1-KeN - - - - menu - - - - 550 - - - - - - 0 - - - - - - -2 - - - File's Owner - - - -1 - - - First Responder - - - -3 - - - Application - - - 29 - - - - - - - - - - - - GS6-Lb-ftA - - - - - - - - YN2-V8-ty0 - - - - - - - - - - - - - - - - HhF-Es-coQ - - - - - OzD-Nm-tPt - - - - - TOj-vg-cDm - - - - - - - - e98-We-UX5 - - - - - muN-Hw-eeZ - - - - - sH6-na-PTL - - - - - XG8-CE-veT - - - - - IqD-3v-zQT - - - - - GU5-eI-OTq - - - - - 7Z7-ot-jqY - - - - - 83 - - - - - - - - 81 - - - - - - - - 611 - - - - - 295 - - - - - - Menu Item - View - - - 296 - - - - - - - - - - - - - Menu - View - - - 579 - - - - - 592 - - - - - 593 - - - - - 594 - - - - - 595 - - - - - pqR-xy-5ip - - - - - 596 - - - - - QB8-6D-hAr - - - - - Heh-SD-KHE - - - - - - - - ysx-9J-ekz - - - - - - - - - hfu-OP-8X3 - - - - - 490 - - - - - - - - 491 - - - - - 420 - - - - - 536 - - - - - CXy-V7-NaY - - - - - - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - - - - - - - - - - AppController - NSObject - - id - id - id - id - id - id - id - - - - onFileClose: - id - - - onRelaunch: - id - - - onScreenLandscape: - id - - - onScreenPortait: - id - - - onScreenZoomOut: - id - - - onSetTop: - id - - - onViewChangeFrameSize: - id - - - - menu - NSMenu - - - menu - - menu - NSMenu - - - - IBProjectSource - ./Classes/AppController.h - - - - - 0 - IBCocoaFramework - YES - - com.apple.InterfaceBuilder.CocoaPlugin.macosx - - - - com.apple.InterfaceBuilder.CocoaPlugin.macosx - - - - com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3 - - - YES - 3 - - {11, 11} - {10, 3} - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/main.mm b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/main.mm index d76dc405f0..890b7f3889 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/main.mm +++ b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/main.mm @@ -1,3 +1,4 @@ +/* #import #import "SimulatorApp.h" @@ -6,3 +7,4 @@ int main(int argc, const char * argv[]) { NSApplication.sharedApplication.delegate = delegate; return NSApplicationMain(argc, argv); } +*/ diff --git a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/zh-Hans.lproj/MainMenu.xib b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/zh-Hans.lproj/MainMenu.xib index b610cf20e9..edf8cb37dd 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/zh-Hans.lproj/MainMenu.xib +++ b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/zh-Hans.lproj/MainMenu.xib @@ -1,11 +1,11 @@ - - + + - + - + @@ -186,9 +186,10 @@ + - + diff --git a/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorApp.cpp b/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorApp.cpp new file mode 100644 index 0000000000..64a8b3f0e2 --- /dev/null +++ b/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorApp.cpp @@ -0,0 +1,786 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "stdafx.h" +#pragma comment(lib, "comctl32.lib") + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "cocos/base/UTF8.h" + +#include "SimulatorApp.h" + +#include "AppLang.h" +#include "CustomAppEvent.h" +#include "runtime/ConfigParser.h" +#include "runtime/Runtime.h" + +#include "application/ApplicationManager.h" +#include "platform/FileUtils.h" +#include "platform/interfaces/modules/IScreen.h" +#include "platform/interfaces/modules/ISystemWindow.h" +#include "platform/win32/PlayerMenuServiceWin.h" +#include "platform/win32/PlayerWin.h" + +#include "cocos/bindings/jswrapper/SeApi.h" +#include "platform/StdC.h" +#include "resource.h" + +using namespace cc; + +static WNDPROC g_oldWindowProc = NULL; +INT_PTR CALLBACK AboutDialogCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { + LOGFONT lf; + HFONT hFont; + + UNREFERENCED_PARAMETER(lParam); + switch (message) { + case WM_INITDIALOG: + ZeroMemory(&lf, sizeof(LOGFONT)); + lf.lfHeight = 24; + lf.lfWeight = 200; + _tcscpy(lf.lfFaceName, _T("Arial")); + + hFont = CreateFontIndirect(&lf); + if ((HFONT)0 != hFont) { + SendMessage(GetDlgItem(hDlg, IDC_ABOUT_TITLE), WM_SETFONT, (WPARAM)hFont, (LPARAM)TRUE); + } + return (INT_PTR)TRUE; + + case WM_COMMAND: + if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { + EndDialog(hDlg, LOWORD(wParam)); + return (INT_PTR)TRUE; + } + break; + } + return (INT_PTR)FALSE; +} + +void onHelpAbout() { + ISystemWindow* systemWindowIntf = CC_GET_PLATFORM_INTERFACE(ISystemWindow); + HWND windowHandler = reinterpret_cast(systemWindowIntf->getWindowHandler()); + DialogBox(GetModuleHandle(NULL), + MAKEINTRESOURCE(IDD_DIALOG_ABOUT), + windowHandler, + AboutDialogCallback); +} + +void shutDownApp() { + ISystemWindow* systemWindowIntf = CC_GET_PLATFORM_INTERFACE(ISystemWindow); + HWND windowHandler = reinterpret_cast(systemWindowIntf->getWindowHandler()); + ::SendMessage(windowHandler, WM_CLOSE, NULL, NULL); +} + +std::string getCurAppPath(void) { + TCHAR szAppDir[MAX_PATH] = {0}; + if (!GetModuleFileName(NULL, szAppDir, MAX_PATH)) + return ""; + int nEnd = 0; + for (int i = 0; szAppDir[i]; i++) { + if (szAppDir[i] == '\\') + nEnd = i; + } + szAppDir[nEnd] = 0; + int iLen = 2 * wcslen(szAppDir); + char* chRtn = new char[iLen + 1]; + wcstombs(chRtn, szAppDir, iLen + 1); + std::string strPath = chRtn; + delete[] chRtn; + chRtn = NULL; + char fuldir[MAX_PATH] = {0}; + _fullpath(fuldir, strPath.c_str(), MAX_PATH); + return fuldir; +} + +static bool stringEndWith(const std::string str, const std::string needle) { + if (str.length() >= needle.length()) { + return (0 == str.compare(str.length() - needle.length(), needle.length(), needle)); + } + return false; +} + +SimulatorApp* SimulatorApp::_instance = nullptr; + +SimulatorApp* SimulatorApp::getInstance() { + if (!_instance) { + _instance = new SimulatorApp(); + } + return _instance; +} + +SimulatorApp::SimulatorApp() +: _hwnd(NULL), _hwndConsole(NULL), _writeDebugLogFile(nullptr) { +} + +SimulatorApp::~SimulatorApp() { + if (_writeDebugLogFile) { + fclose(_writeDebugLogFile); + } +} + +void SimulatorApp::quit() { + CC_CURRENT_ENGINE()->close(); +} + +void SimulatorApp::relaunch() { + _project.setWindowOffset(cc::Vec2(getPositionX(), getPositionY())); + openProjectWithProjectConfig(_project); +} + +void SimulatorApp::openNewPlayer() { + openNewPlayerWithProjectConfig(_project); +} + +void SimulatorApp::openNewPlayerWithProjectConfig(const ProjectConfig& config) { + static long taskid = 100; + stringstream buf; + buf << taskid++; + + string commandLine; + commandLine.append(getApplicationExePath()); + commandLine.append(" "); + commandLine.append(config.makeCommandLine()); + + CC_LOG_DEBUG("SimulatorApp::openNewPlayerWithProjectConfig(): %s", commandLine.c_str()); + + // http://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx + SECURITY_ATTRIBUTES sa = {0}; + sa.nLength = sizeof(sa); + + PROCESS_INFORMATION pi = {0}; + STARTUPINFO si = {0}; + si.cb = sizeof(STARTUPINFO); + +#define MAX_COMMAND 1024 // lenth of commandLine is always beyond MAX_PATH + + WCHAR command[MAX_COMMAND]; + memset(command, 0, sizeof(command)); + MultiByteToWideChar(CP_UTF8, 0, commandLine.c_str(), -1, command, MAX_COMMAND); + + BOOL success = CreateProcess(NULL, + command, // command line + NULL, // process security attributes + NULL, // primary thread security attributes + FALSE, // handles are inherited + 0, // creation flags + NULL, // use parent's environment + NULL, // use parent's current directory + &si, // STARTUPINFO pointer + &pi); // receives PROCESS_INFORMATION + + if (!success) { + CC_LOG_DEBUG("PlayerTaskWin::run() - create process failed, for execute %s", commandLine.c_str()); + } +} + +void SimulatorApp::openProjectWithProjectConfig(const ProjectConfig& config) { + quit(); + openNewPlayerWithProjectConfig(config); +} + +int SimulatorApp::getPositionX() { + RECT rect; + GetWindowRect(_hwnd, &rect); + return rect.left; +} + +int SimulatorApp::getPositionY() { + RECT rect; + GetWindowRect(_hwnd, &rect); + return rect.top; +} + +int SimulatorApp::run() { + INITCOMMONCONTROLSEX InitCtrls; + InitCtrls.dwSize = sizeof(InitCtrls); + InitCtrls.dwICC = ICC_WIN95_CLASSES; + InitCommonControlsEx(&InitCtrls); + + parseCocosProjectConfig(_project); + + // load project config from command line args + std::vector args; + for (int i = 0; i < __argc; ++i) { + wstring ws(__wargv[i]); + string s; + s.assign(ws.begin(), ws.end()); + args.push_back(s); + } + _project.parseCommandLine(args); + + if (_project.getProjectDir().empty()) { + if (args.size() == 2) { + // for Code IDE before RC2 + _project.setProjectDir(args.at(1)); + _project.setDebuggerType(kCCRuntimeDebuggerCodeIDE); + } + } + + // create the application instance + RuntimeEngine::getInstance()->setProjectConfig(_project); + + // create console window + if (_project.isShowConsole()) { + AllocConsole(); + _hwndConsole = GetConsoleWindow(); + if (_hwndConsole != NULL) { + ShowWindow(_hwndConsole, SW_SHOW); + BringWindowToTop(_hwndConsole); + freopen("CONOUT$", "wt", stdout); + freopen("CONOUT$", "wt", stderr); + + HMENU hmenu = GetSystemMenu(_hwndConsole, FALSE); + if (hmenu != NULL) { + DeleteMenu(hmenu, SC_CLOSE, MF_BYCOMMAND); + } + } + } + + // log file + if (_project.isWriteDebugLogToFile()) { + const string debugLogFilePath = _project.getDebugLogFilePath(); + _writeDebugLogFile = fopen(debugLogFilePath.c_str(), "w"); + if (!_writeDebugLogFile) { + CC_LOG_DEBUG("Cannot create debug log file %s", debugLogFilePath.c_str()); + } + } + + // set environments + SetCurrentDirectoryA(_project.getProjectDir().c_str()); + FileUtils::getInstance()->setDefaultResourceRootPath(_project.getProjectDir()); + FileUtils::getInstance()->setWritablePath(_project.getWritableRealPath().c_str()); + + // check screen DPI + HDC screen = GetDC(0); + int dpi = GetDeviceCaps(screen, LOGPIXELSX); + ReleaseDC(0, screen); + + // set scale with DPI + // 96 DPI = 100 % scaling + // 120 DPI = 125 % scaling + // 144 DPI = 150 % scaling + // 192 DPI = 200 % scaling + // http://msdn.microsoft.com/en-us/library/windows/desktop/dn469266%28v=vs.85%29.aspx#dpi_and_the_desktop_scaling_factor + // + // enable DPI-Aware with DeclareDPIAware.manifest + // http://msdn.microsoft.com/en-us/library/windows/desktop/dn469266%28v=vs.85%29.aspx#declaring_dpi_awareness + float screenScale = 1.0f; + if (dpi >= 120 && dpi < 144) { + screenScale = 1.25f; + } else if (dpi >= 144 && dpi < 192) { + screenScale = 1.5f; + } else if (dpi >= 192) { + screenScale = 2.0f; + } + CC_LOG_DEBUG("SCREEN DPI = %d, SCREEN SCALE = %0.2f", dpi, screenScale); + + // check scale + cc::Size frameSize = _project.getFrameSize(); + float frameScale = _project.getFrameScale(); + if (_project.isRetinaDisplay()) { + frameSize.width *= screenScale; + frameSize.height *= screenScale; + } else { + frameScale *= screenScale; + } + + // check screen workarea + RECT workareaSize; + if (SystemParametersInfo(SPI_GETWORKAREA, NULL, &workareaSize, NULL)) { + float workareaWidth = fabsf(workareaSize.right - workareaSize.left); + float workareaHeight = fabsf(workareaSize.bottom - workareaSize.top); + float frameBorderCX = GetSystemMetrics(SM_CXSIZEFRAME); + float frameBorderCY = GetSystemMetrics(SM_CYSIZEFRAME); + workareaWidth -= frameBorderCX * 2; + workareaHeight -= (frameBorderCY * 2 + GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYMENU)); + CC_LOG_DEBUG("WORKAREA WIDTH %0.2f, HEIGHT %0.2f", workareaWidth, workareaHeight); + while (true && frameScale > 0.25f) { + if (frameSize.width * frameScale > workareaWidth || frameSize.height * frameScale > workareaHeight) { + frameScale = frameScale - 0.25f; + } else { + break; + } + } + + if (frameScale < 0.25f) frameScale = 0.25f; + } + _project.setFrameScale(frameScale); + CC_LOG_DEBUG("FRAME SCALE = %0.2f", frameScale); + + // create opengl view + const Rect frameRect = Rect(0, 0, frameSize.width, frameSize.height); + ConfigParser::getInstance()->setInitViewSize(frameSize); + const bool isResize = _project.isResizeWindow(); + std::stringstream title; + title << "Cocos Simulator (" << _project.getFrameScale() * 100 << "%)"; + + //auto frameWidth = (int)(_project.getFrameScale() * frameSize.width); + //auto frameHeight = (int)(_project.getFrameScale() * frameSize.height); + + // path for looking Lang file, Studio Default images + FileUtils::getInstance()->addSearchPath(getApplicationPath().c_str()); + ISystemWindow* systemWindowIntf = CC_GET_PLATFORM_INTERFACE(ISystemWindow); + _hwnd = reinterpret_cast(systemWindowIntf->getWindowHandler()); + player::PlayerWin::createWithHwnd(_hwnd); + DragAcceptFiles(_hwnd, TRUE); + // SendMessage(_hwnd, WM_SETICON, ICON_BIG, (LPARAM)icon); + // SendMessage(_hwnd, WM_SETICON, ICON_SMALL, (LPARAM)icon); + // FreeResource(icon); + + // path for looking Lang file, Studio Default images + FileUtils::getInstance()->addSearchPath(getApplicationPath().c_str()); + + // set window position + if (_project.getProjectDir().length()) { + setZoom(_project.getFrameScale()); + } + Vec2 pos = _project.getWindowOffset(); + if (pos.x != 0 && pos.y != 0) { + RECT rect; + GetWindowRect(_hwnd, &rect); + if (pos.x < 0) + pos.x = 0; + if (pos.y < 0) + pos.y = 0; + MoveWindow(_hwnd, pos.x, pos.y, rect.right - rect.left, rect.bottom - rect.top, FALSE); + } + + // init player services + // the UI workflow is migrated into the Cocos Creator Editor + // setupUI(); + // DrawMenuBar(_hwnd); + + // prepare + _project.dump(); + + g_oldWindowProc = (WNDPROC)SetWindowLong(_hwnd, GWLP_WNDPROC, (LONG)SimulatorApp::windowProc); + + // update window title + updateWindowTitle(); + + return 0; +} + +// services + +void SimulatorApp::setupUI() { + auto menuBar = player::PlayerProtocol::getInstance()->getMenuService(); + + // FILE + menuBar->addItem("FILE_MENU", tr("File")); + menuBar->addItem("EXIT_MENU", tr("Exit"), "FILE_MENU"); + + // VIEW + menuBar->addItem("VIEW_MENU", tr("View")); + SimulatorConfig* config = SimulatorConfig::getInstance(); + int current = config->checkScreenSize(_project.getFrameSize()); + for (int i = 0; i < config->getScreenSizeCount(); i++) { + SimulatorScreenSize size = config->getScreenSize(i); + std::stringstream menuId; + menuId << "VIEWSIZE_ITEM_MENU_" << i; + auto menuItem = menuBar->addItem(menuId.str(), size.title.c_str(), "VIEW_MENU"); + + if (i == current) { + menuItem->setChecked(true); + } + } + + // show FPs + bool displayStats = true; // asume creator default show FPS + string fpsItemName = displayStats ? tr("Hide FPS") : tr("Show FPS"); + menuBar->addItem("FPS_MENU", fpsItemName); + + // About + menuBar->addItem("HELP_MENU", tr("Help")); + menuBar->addItem("ABOUT_MENUITEM", tr("About"), "HELP_MENU"); + + menuBar->addItem("DIRECTION_MENU_SEP", "-", "VIEW_MENU"); + menuBar->addItem("DIRECTION_PORTRAIT_MENU", tr("Portrait"), "VIEW_MENU") + ->setChecked(_project.isPortraitFrame()); + menuBar->addItem("DIRECTION_LANDSCAPE_MENU", tr("Landscape"), "VIEW_MENU") + ->setChecked(_project.isLandscapeFrame()); + + menuBar->addItem("VIEW_SCALE_MENU_SEP", "-", "VIEW_MENU"); + std::vector scaleMenuVector; + auto scale100Menu = menuBar->addItem("VIEW_SCALE_MENU_100", tr("Zoom Out").append(" (100%)"), "VIEW_MENU"); + auto scale75Menu = menuBar->addItem("VIEW_SCALE_MENU_75", tr("Zoom Out").append(" (75%)"), "VIEW_MENU"); + auto scale50Menu = menuBar->addItem("VIEW_SCALE_MENU_50", tr("Zoom Out").append(" (50%)"), "VIEW_MENU"); + auto scale25Menu = menuBar->addItem("VIEW_SCALE_MENU_25", tr("Zoom Out").append(" (25%)"), "VIEW_MENU"); + int frameScale = int(_project.getFrameScale() * 100); + + if (frameScale == 100) { + scale100Menu->setChecked(true); + } else if (frameScale == 75) { + scale75Menu->setChecked(true); + } else if (frameScale == 50) { + scale50Menu->setChecked(true); + } else if (frameScale == 25) { + scale25Menu->setChecked(true); + } else { + scale100Menu->setChecked(true); + } + + scaleMenuVector.push_back(scale100Menu); + scaleMenuVector.push_back(scale75Menu); + scaleMenuVector.push_back(scale50Menu); + scaleMenuVector.push_back(scale25Menu); + + menuBar->addItem("REFRESH_MENU_SEP", "-", "VIEW_MENU"); + menuBar->addItem("REFRESH_MENU", tr("Refresh"), "VIEW_MENU"); + + HWND& hwnd = _hwnd; + ProjectConfig& project = _project; + EventDispatcher::CustomEventListener listener = [this, &hwnd, &project, scaleMenuVector](const CustomEvent& event) { + auto menuEvent = dynamic_cast(event); + rapidjson::Document dArgParse; + dArgParse.Parse<0>(menuEvent.getDataString().c_str()); + if (dArgParse.HasMember("name")) { + string strcmd = dArgParse["name"].GetString(); + + if (strcmd == "menuClicked") { + player::PlayerMenuItem* menuItem = static_cast(menuEvent.args[0].ptrVal); + if (menuItem) { + if (menuItem->isChecked()) { + return; + } + + string data = dArgParse["data"].GetString(); + + if ((data == "CLOSE_MENU") || (data == "EXIT_MENU")) { + _instance->quit(); + } else if (data == "REFRESH_MENU") { + _instance->relaunch(); + } else if (data.find("VIEW_SCALE_MENU_") == 0) // begin with VIEW_SCALE_MENU_ + { + string tmp = data.erase(0, strlen("VIEW_SCALE_MENU_")); + float scale = atof(tmp.c_str()) / 100.0f; + project.setFrameScale(scale); + + _instance->openProjectWithProjectConfig(project); + } else if (data.find("VIEWSIZE_ITEM_MENU_") == 0) // begin with VIEWSIZE_ITEM_MENU_ + { + string tmp = data.erase(0, strlen("VIEWSIZE_ITEM_MENU_")); + int index = atoi(tmp.c_str()); + SimulatorScreenSize size = SimulatorConfig::getInstance()->getScreenSize(index); + + if (project.isLandscapeFrame()) { + std::swap(size.width, size.height); + } + + project.setFrameSize(cc::Size(size.width, size.height)); + project.setWindowOffset(cc::Vec2(_instance->getPositionX(), _instance->getPositionY())); + _instance->openProjectWithProjectConfig(project); + } else if (data == "DIRECTION_PORTRAIT_MENU") { + project.changeFrameOrientationToPortait(); + _instance->openProjectWithProjectConfig(project); + } else if (data == "DIRECTION_LANDSCAPE_MENU") { + project.changeFrameOrientationToLandscape(); + _instance->openProjectWithProjectConfig(project); + } else if (data == "ABOUT_MENUITEM") { + onHelpAbout(); + } else if (data == "FPS_MENU") { + IScreen* screenIntf = CC_GET_PLATFORM_INTERFACE(IScreen); + bool displayStats = !screenIntf->isDisplayStats(); + screenIntf->setDisplayStats(displayStats); + menuItem->setTitle(displayStats ? tr("Hide FPS") : tr("Show FPS")); + } + } + } + } + }; + EventDispatcher::addCustomEventListener(kAppEventName, listener); +} + +void SimulatorApp::setZoom(float frameScale) { + _project.setFrameScale(frameScale); +} + +void SimulatorApp::updateWindowTitle() { + std::stringstream title; + title << "Cocos " << tr("Simulator") << " (" << _project.getFrameScale() * 100 << "%)"; + std::u16string u16title; + cc::StringUtils::UTF8ToUTF16(title.str(), u16title); + SetWindowText(_hwnd, (LPCTSTR)u16title.c_str()); +} + +// debug log +void SimulatorApp::writeDebugLog(const char* log) { + if (!_writeDebugLogFile) return; + + fputs(log, _writeDebugLogFile); + fputc('\n', _writeDebugLogFile); + fflush(_writeDebugLogFile); +} + +void SimulatorApp::parseCocosProjectConfig(ProjectConfig& config) { + // get project directory + ProjectConfig tmpConfig; + // load project config from command line args + std::vector args; + for (int i = 0; i < __argc; ++i) { + wstring ws(__wargv[i]); + string s; + s.assign(ws.begin(), ws.end()); + args.push_back(s); + } + + if (args.size() >= 2) { + if (args.size() && args.at(1).at(0) == '/') { + // IDEA: + // for Code IDE before RC2 + tmpConfig.setProjectDir(args.at(1)); + } + + tmpConfig.parseCommandLine(args); + } + + // set project directory as search root path + string solutionDir = tmpConfig.getProjectDir(); + if (!solutionDir.empty()) { + for (int i = 0; i < solutionDir.size(); ++i) { + if (solutionDir[i] == '\\') { + solutionDir[i] = '/'; + } + } + int nPos = -1; + if (solutionDir[solutionDir.length() - 1] == '/') + nPos = solutionDir.rfind('/', solutionDir.length() - 2); + else + nPos = solutionDir.rfind('/'); + if (nPos > 0) + solutionDir = solutionDir.substr(0, nPos + 1); + FileUtils::getInstance()->setDefaultResourceRootPath(solutionDir); + FileUtils::getInstance()->addSearchPath(solutionDir); + FileUtils::getInstance()->addSearchPath(tmpConfig.getProjectDir().c_str()); + } else { + FileUtils::getInstance()->setDefaultResourceRootPath(tmpConfig.getProjectDir().c_str()); + } + + // parse config.json when firstly init ConfigParser single instance + auto parser = ConfigParser::getInstance(); + + // set information + config.setConsolePort(parser->getConsolePort()); + config.setFileUploadPort(parser->getUploadPort()); + config.setFrameSize(parser->getInitViewSize()); + if (parser->isLanscape()) { + config.changeFrameOrientationToLandscape(); + } else { + config.changeFrameOrientationToPortait(); + } + config.setScriptFile(parser->getEntryFile()); +} + +// +// D:\aaa\bbb\ccc\ddd\abc.txt --> D:/aaa/bbb/ccc/ddd/abc.txt +// +std::string SimulatorApp::convertPathFormatToUnixStyle(const std::string& path) { + std::string ret = path; + int len = ret.length(); + for (int i = 0; i < len; ++i) { + if (ret[i] == '\\') { + ret[i] = '/'; + } + } + return ret; +} + +// +// @return: C:/Users/win8/Documents/ +// +std::string SimulatorApp::getUserDocumentPath() { + TCHAR filePath[MAX_PATH]; + SHGetSpecialFolderPath(NULL, filePath, CSIDL_PERSONAL, FALSE); + int length = 2 * wcslen(filePath); + char* tempstring = new char[length + 1]; + wcstombs(tempstring, filePath, length + 1); + string userDocumentPath(tempstring); + delete[] tempstring; + + userDocumentPath = convertPathFormatToUnixStyle(userDocumentPath); + userDocumentPath.append("/"); + + return userDocumentPath; +} + +// +// convert Unicode/LocalCode TCHAR to Utf8 char +// +char* SimulatorApp::convertTCharToUtf8(const TCHAR* src) { +#ifdef UNICODE + WCHAR* tmp = (WCHAR*)src; + size_t size = wcslen(src) * 3 + 1; + char* dest = new char[size]; + memset(dest, 0, size); + WideCharToMultiByte(CP_UTF8, 0, tmp, -1, dest, size, NULL, NULL); + return dest; +#else + char* tmp = (char*)src; + uint32 size = strlen(tmp) + 1; + WCHAR* dest = new WCHAR[size]; + memset(dest, 0, sizeof(WCHAR) * size); + MultiByteToWideChar(CP_ACP, 0, src, -1, dest, (int)size); // convert local code to unicode. + + size = wcslen(dest) * 3 + 1; + char* dest2 = new char[size]; + memset(dest2, 0, size); + WideCharToMultiByte(CP_UTF8, 0, dest, -1, dest2, size, NULL, NULL); // convert unicode to utf8. + delete[] dest; + return dest2; +#endif +} + +// +std::string SimulatorApp::getApplicationExePath() { + TCHAR szFileName[MAX_PATH]; + GetModuleFileName(NULL, szFileName, MAX_PATH); + std::u16string u16ApplicationName; + char* applicationExePath = convertTCharToUtf8(szFileName); + std::string path(applicationExePath); + CC_SAFE_FREE(applicationExePath); + + return path; +} + +std::string SimulatorApp::getApplicationPath() { + std::string path = getApplicationExePath(); + size_t pos; + while ((pos = path.find_first_of("\\")) != std::string::npos) { + path.replace(pos, 1, "/"); + } + size_t p = path.find_last_of("/"); + string workdir; + if (p != path.npos) { + workdir = path.substr(0, p); + } + + return workdir; +} + +LRESULT CALLBACK SimulatorApp::windowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { + if (!_instance) return 0; + + switch (uMsg) { + case WM_SYSCOMMAND: + case WM_COMMAND: { + if (HIWORD(wParam) == 0) { + // menu + WORD menuId = LOWORD(wParam); + auto menuService = dynamic_cast(player::PlayerProtocol::getInstance()->getMenuService()); + auto menuItem = menuService->getItemByCommandId(menuId); + if (menuItem) { + CustomAppEvent event(kAppEventName, APP_EVENT_MENU); + + std::stringstream buf; + buf << "{\"data\":\"" << menuItem->getMenuId().c_str() << "\""; + buf << ",\"name\":" + << "\"menuClicked\"" + << "}"; + event.setDataString(buf.str()); + event.args[0].ptrVal = (void*)menuItem; + cc::EventDispatcher::dispatchCustomEvent(event); + } + + if (menuId == ID_HELP_ABOUT) { + onHelpAbout(); + } + } + break; + } + case WM_KEYDOWN: { + if (wParam == VK_F5) { + _instance->relaunch(); + } + break; + } + + case WM_COPYDATA: { + PCOPYDATASTRUCT pMyCDS = (PCOPYDATASTRUCT)lParam; + if (pMyCDS->dwData == 1) { + const char* szBuf = (const char*)(pMyCDS->lpData); + SimulatorApp::getInstance()->writeDebugLog(szBuf); + break; + } + } + + case WM_DESTROY: { + DragAcceptFiles(hWnd, FALSE); + break; + } + } + return g_oldWindowProc(hWnd, uMsg, wParam, lParam); +} + +void SimulatorApp::onOpenFile(const std::string& filePath) { + string entry = filePath; + if (entry.empty()) return; + + if (stringEndWith(entry, "config.json") || stringEndWith(entry, ".csb") || stringEndWith(entry, ".csd")) { + replaceAll(entry, "\\", "/"); + size_t p = entry.find_last_of("/"); + if (p != entry.npos) { + string workdir = entry.substr(0, p); + _project.setProjectDir(workdir); + } + + _project.setScriptFile(entry); + if (stringEndWith(entry, CONFIG_FILE)) { + ConfigParser::getInstance()->readConfig(entry); + _project.setScriptFile(ConfigParser::getInstance()->getEntryFile()); + } + openProjectWithProjectConfig(_project); + } else { + auto title = tr("Open File") + tr("Error"); + auto msg = tr("Only support") + " config.json;*.csb;*.csd"; + auto msgBox = player::PlayerProtocol::getInstance()->getMessageBoxService(); + msgBox->showMessageBox(title, msg); + } +} + +int SimulatorApp::getWidth() const { + cc::Size frameSize = _project.getFrameSize(); + float frameScale = _project.getFrameScale(); + return (int)(frameScale * frameSize.width); +} + +int SimulatorApp::getHegith() const { + cc::Size frameSize = _project.getFrameSize(); + float frameScale = _project.getFrameScale(); + return (int)(frameScale * frameSize.height); +} \ No newline at end of file diff --git a/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorWin.h b/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorApp.h old mode 100755 new mode 100644 similarity index 79% rename from native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorWin.h rename to native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorApp.h index 27a507e7ba..73769f08b6 --- a/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorWin.h +++ b/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorApp.h @@ -25,20 +25,18 @@ #pragma once -#include "stdafx.h" -#include "Resource.h" #include "Game.h" #include "ProjectConfig/ProjectConfig.h" #include "ProjectConfig/SimulatorConfig.h" -#include "cocos/platform/win32/View-win32.h" +#include "Resource.h" +#include "stdafx.h" #include -class SimulatorWin -{ +class SimulatorApp { public: - static SimulatorWin *getInstance(); - virtual ~SimulatorWin(); + static SimulatorApp *getInstance(); + virtual ~SimulatorApp(); int run(); virtual void quit(); @@ -49,22 +47,21 @@ public: virtual int getPositionX(); virtual int getPositionY(); -protected: - SimulatorWin(); - static SimulatorWin *_instance; - ProjectConfig _project; - HWND _hwnd; - HWND _hwndConsole; - + virtual int getWidth() const; + virtual int getHegith() const; + +protected: + SimulatorApp(); + + static SimulatorApp *_instance; + ProjectConfig _project; + HWND _hwnd; + HWND _hwndConsole; + FILE *_writeDebugLogFile; - std::shared_ptr _app; - std::shared_ptr _view; - - bool _quit = false; - - // + // void setupUI(); void setZoom(float frameScale); void updateWindowTitle(); @@ -79,12 +76,11 @@ protected: void onDrop(const std::string &path); // helper - std::string convertPathFormatToUnixStyle(const std::string& path); - std::string getUserDocumentPath(); - std::string getApplicationExePath(); - std::string getApplicationPath(); - static char* convertTCharToUtf8(const TCHAR* src); + std::string convertPathFormatToUnixStyle(const std::string &path); + std::string getUserDocumentPath(); + std::string getApplicationExePath(); + std::string getApplicationPath(); + static char *convertTCharToUtf8(const TCHAR *src); static LRESULT CALLBACK windowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); }; - diff --git a/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorWin.cpp b/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorWin.cpp deleted file mode 100755 index 312af61cb6..0000000000 --- a/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorWin.cpp +++ /dev/null @@ -1,1045 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - 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. - ****************************************************************************/ - - -#pragma comment(lib, "comctl32.lib") - -#include "cocos/base/UTF8.h" -#include "stdafx.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "SimulatorWin.h" - -#include "AppEvent.h" -#include "AppLang.h" -#include "runtime/ConfigParser.h" -#include "runtime/Runtime.h" - -#include "platform/Application.h" -#include "platform/win32/PlayerWin.h" -#include "platform/win32/PlayerMenuServiceWin.h" -#include "platform/FileUtils.h" - -#include "platform/StdC.h" -#include "cocos/bindings/jswrapper/SeApi.h" -#include "resource.h" - -namespace -{ - std::weak_ptr gView; - /** - @brief This function changes the PVRFrame show/hide setting in register. - @param bEnable If true show the PVRFrame window, otherwise hide. - */ - void PVRFrameEnableControlWindow(bool bEnable) - { - HKEY hKey = 0; - - // Open PVRFrame control key, if not exist create it. - if (ERROR_SUCCESS != RegCreateKeyExW(HKEY_CURRENT_USER, - L"Software\\Imagination Technologies\\PVRVFRame\\STARTUP\\", - 0, - 0, - REG_OPTION_NON_VOLATILE, - KEY_ALL_ACCESS, - 0, - &hKey, - nullptr)) - { - return; - } - - const WCHAR* wszValue = L"hide_gui"; - const WCHAR* wszNewData = (bEnable) ? L"NO" : L"YES"; - WCHAR wszOldData[256] = { 0 }; - DWORD dwSize = sizeof(wszOldData); - LSTATUS status = RegQueryValueExW(hKey, wszValue, 0, nullptr, (LPBYTE)wszOldData, &dwSize); - if (ERROR_FILE_NOT_FOUND == status // the key not exist - || (ERROR_SUCCESS == status // or the hide_gui value is exist - && 0 != wcscmp(wszNewData, wszOldData))) // but new data and old data not equal - { - dwSize = sizeof(WCHAR) * (wcslen(wszNewData) + 1); - RegSetValueEx(hKey, wszValue, 0, REG_SZ, (const BYTE*)wszNewData, dwSize); - } - - RegCloseKey(hKey); - } - - bool setCanvasCallback(se::Object* global) - { - std::stringstream ss; - se::ScriptEngine* se = se::ScriptEngine::getInstance(); - auto view = gView.lock(); - auto handler = view->getWindowHandler(); - auto viewSize = view->getViewSize(); - char commandBuf[200] = { 0 }; - ss << "window.innerWidth = " << viewSize[0] << "; " - << "window.innerHeight = " << viewSize[1] << "; " - << "window.windowHandler = " - << reinterpret_cast(handler) - << ";"; - - se->evalString(ss.str().c_str()); - return true; - } -} - -//exported function -std::shared_ptr cc_get_application_view() { - return gView.lock(); -} - - -using namespace cc; - -static WNDPROC g_oldWindowProc = NULL; -INT_PTR CALLBACK AboutDialogCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) -{ - LOGFONT lf; - HFONT hFont; - - UNREFERENCED_PARAMETER(lParam); - switch (message) - { - case WM_INITDIALOG: - ZeroMemory(&lf, sizeof(LOGFONT)); - lf.lfHeight = 24; - lf.lfWeight = 200; - _tcscpy(lf.lfFaceName, _T("Arial")); - - hFont = CreateFontIndirect(&lf); - if ((HFONT)0 != hFont) - { - SendMessage(GetDlgItem(hDlg, IDC_ABOUT_TITLE), WM_SETFONT, (WPARAM)hFont, (LPARAM)TRUE); - } - return (INT_PTR)TRUE; - - case WM_COMMAND: - if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) - { - EndDialog(hDlg, LOWORD(wParam)); - return (INT_PTR)TRUE; - } - break; - } - return (INT_PTR)FALSE; -} - - -void onHelpAbout() -{ - DialogBox(GetModuleHandle(NULL), - MAKEINTRESOURCE(IDD_DIALOG_ABOUT), - cc_get_application_view()->getWindowHandler(), - AboutDialogCallback); -} - - -void shutDownApp() -{ - - ::SendMessage(cc_get_application_view()->getWindowHandler(), WM_CLOSE, NULL, NULL); -} - -std::string getCurAppPath(void) -{ - TCHAR szAppDir[MAX_PATH] = {0}; - if (!GetModuleFileName(NULL, szAppDir, MAX_PATH)) - return ""; - int nEnd = 0; - for (int i = 0; szAppDir[i]; i++) - { - if (szAppDir[i] == '\\') - nEnd = i; - } - szAppDir[nEnd] = 0; - int iLen = 2 * wcslen(szAppDir); - char* chRtn = new char[iLen + 1]; - wcstombs(chRtn, szAppDir, iLen + 1); - std::string strPath = chRtn; - delete[] chRtn; - chRtn = NULL; - char fuldir[MAX_PATH] = {0}; - _fullpath(fuldir, strPath.c_str(), MAX_PATH); - return fuldir; -} - -static bool stringEndWith(const std::string str, const std::string needle) -{ - if (str.length() >= needle.length()) - { - return (0 == str.compare(str.length() - needle.length(), needle.length(), needle)); - } - return false; -} - -SimulatorWin *SimulatorWin::_instance = nullptr; - -SimulatorWin *SimulatorWin::getInstance() -{ - if (!_instance) - { - _instance = new SimulatorWin(); - } - return _instance; -} - -SimulatorWin::SimulatorWin() - : _hwnd(NULL) - , _hwndConsole(NULL) - , _writeDebugLogFile(nullptr) -{ -} - -SimulatorWin::~SimulatorWin() -{ - if (_writeDebugLogFile) - { - fclose(_writeDebugLogFile); - } -} - -void SimulatorWin::quit() -{ - _quit = true; -} - -void SimulatorWin::relaunch() -{ - _project.setWindowOffset(cc::Vec2(getPositionX(), getPositionY())); - openProjectWithProjectConfig(_project); -} - -void SimulatorWin::openNewPlayer() -{ - openNewPlayerWithProjectConfig(_project); -} - -void SimulatorWin::openNewPlayerWithProjectConfig(const ProjectConfig &config) -{ - static long taskid = 100; - stringstream buf; - buf << taskid++; - - string commandLine; - commandLine.append(getApplicationExePath()); - commandLine.append(" "); - commandLine.append(config.makeCommandLine()); - - CC_LOG_DEBUG("SimulatorWin::openNewPlayerWithProjectConfig(): %s", commandLine.c_str()); - - // http://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx - SECURITY_ATTRIBUTES sa = {0}; - sa.nLength = sizeof(sa); - - PROCESS_INFORMATION pi = {0}; - STARTUPINFO si = {0}; - si.cb = sizeof(STARTUPINFO); - -#define MAX_COMMAND 1024 // lenth of commandLine is always beyond MAX_PATH - - WCHAR command[MAX_COMMAND]; - memset(command, 0, sizeof(command)); - MultiByteToWideChar(CP_UTF8, 0, commandLine.c_str(), -1, command, MAX_COMMAND); - - BOOL success = CreateProcess(NULL, - command, // command line - NULL, // process security attributes - NULL, // primary thread security attributes - FALSE, // handles are inherited - 0, // creation flags - NULL, // use parent's environment - NULL, // use parent's current directory - &si, // STARTUPINFO pointer - &pi); // receives PROCESS_INFORMATION - - if (!success) - { - CC_LOG_DEBUG("PlayerTaskWin::run() - create process failed, for execute %s", commandLine.c_str()); - } -} - -void SimulatorWin::openProjectWithProjectConfig(const ProjectConfig &config) -{ - quit(); - openNewPlayerWithProjectConfig(config); -} - -int SimulatorWin::getPositionX() -{ - RECT rect; - GetWindowRect(_hwnd, &rect); - return rect.left; -} - -int SimulatorWin::getPositionY() -{ - RECT rect; - GetWindowRect(_hwnd, &rect); - return rect.top; -} - -int SimulatorWin::run() -{ - INITCOMMONCONTROLSEX InitCtrls; - InitCtrls.dwSize = sizeof(InitCtrls); - InitCtrls.dwICC = ICC_WIN95_CLASSES; - InitCommonControlsEx(&InitCtrls); - - parseCocosProjectConfig(_project); - - // load project config from command line args - std::vector args; - for (int i = 0; i < __argc; ++i) - { - wstring ws(__wargv[i]); - string s; - s.assign(ws.begin(), ws.end()); - args.push_back(s); - } - _project.parseCommandLine(args); - - if (_project.getProjectDir().empty()) - { - if (args.size() == 2) - { - // for Code IDE before RC2 - _project.setProjectDir(args.at(1)); - _project.setDebuggerType(kCCRuntimeDebuggerCodeIDE); - } - } - - // create the application instance - RuntimeEngine::getInstance()->setProjectConfig(_project); - - // create console window - if (_project.isShowConsole()) - { - AllocConsole(); - _hwndConsole = GetConsoleWindow(); - if (_hwndConsole != NULL) - { - ShowWindow(_hwndConsole, SW_SHOW); - BringWindowToTop(_hwndConsole); - freopen("CONOUT$", "wt", stdout); - freopen("CONOUT$", "wt", stderr); - - HMENU hmenu = GetSystemMenu(_hwndConsole, FALSE); - if (hmenu != NULL) - { - DeleteMenu(hmenu, SC_CLOSE, MF_BYCOMMAND); - } - } - } - - // log file - if (_project.isWriteDebugLogToFile()) - { - const string debugLogFilePath = _project.getDebugLogFilePath(); - _writeDebugLogFile = fopen(debugLogFilePath.c_str(), "w"); - if (!_writeDebugLogFile) - { - CC_LOG_DEBUG("Cannot create debug log file %s", debugLogFilePath.c_str()); - } - } - - // set environments - SetCurrentDirectoryA(_project.getProjectDir().c_str()); - FileUtils::getInstance()->setDefaultResourceRootPath(_project.getProjectDir()); - FileUtils::getInstance()->setWritablePath(_project.getWritableRealPath().c_str()); - - // check screen DPI - HDC screen = GetDC(0); - int dpi = GetDeviceCaps(screen, LOGPIXELSX); - ReleaseDC(0, screen); - - // set scale with DPI - // 96 DPI = 100 % scaling - // 120 DPI = 125 % scaling - // 144 DPI = 150 % scaling - // 192 DPI = 200 % scaling - // http://msdn.microsoft.com/en-us/library/windows/desktop/dn469266%28v=vs.85%29.aspx#dpi_and_the_desktop_scaling_factor - // - // enable DPI-Aware with DeclareDPIAware.manifest - // http://msdn.microsoft.com/en-us/library/windows/desktop/dn469266%28v=vs.85%29.aspx#declaring_dpi_awareness - float screenScale = 1.0f; - if (dpi >= 120 && dpi < 144) - { - screenScale = 1.25f; - } - else if (dpi >= 144 && dpi < 192) - { - screenScale = 1.5f; - } - else if (dpi >= 192) - { - screenScale = 2.0f; - } - CC_LOG_DEBUG("SCREEN DPI = %d, SCREEN SCALE = %0.2f", dpi, screenScale); - - // check scale - cc::Size frameSize = _project.getFrameSize(); - float frameScale = _project.getFrameScale(); - if (_project.isRetinaDisplay()) - { - frameSize.width *= screenScale; - frameSize.height *= screenScale; - } - else - { - frameScale *= screenScale; - } - - // check screen workarea - RECT workareaSize; - if (SystemParametersInfo(SPI_GETWORKAREA, NULL, &workareaSize, NULL)) - { - float workareaWidth = fabsf(workareaSize.right - workareaSize.left); - float workareaHeight = fabsf(workareaSize.bottom - workareaSize.top); - float frameBorderCX = GetSystemMetrics(SM_CXSIZEFRAME); - float frameBorderCY = GetSystemMetrics(SM_CYSIZEFRAME); - workareaWidth -= frameBorderCX * 2; - workareaHeight -= (frameBorderCY * 2 + GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYMENU)); - CC_LOG_DEBUG("WORKAREA WIDTH %0.2f, HEIGHT %0.2f", workareaWidth, workareaHeight); - while (true && frameScale > 0.25f) - { - if (frameSize.width * frameScale > workareaWidth || frameSize.height * frameScale > workareaHeight) - { - frameScale = frameScale - 0.25f; - } - else - { - break; - } - } - - if (frameScale < 0.25f) frameScale = 0.25f; - } - _project.setFrameScale(frameScale); - CC_LOG_DEBUG("FRAME SCALE = %0.2f", frameScale); - - // create opengl view - const Rect frameRect = Rect(0, 0, frameSize.width, frameSize.height); - ConfigParser::getInstance()->setInitViewSize(frameSize); - const bool isResize = _project.isResizeWindow(); - std::stringstream title; - title << "Cocos Simulator (" << _project.getFrameScale() * 100 << "%)"; - - auto frameWidth = (int) (_project.getFrameScale() * frameSize.width); - auto frameHeight = (int) (_project.getFrameScale() * frameSize.height); - - _view = std::make_shared(title.str(), frameWidth, frameHeight); - - // create opengl view, and init app - _app.reset(new Game(frameWidth, frameHeight)); - - // path for looking Lang file, Studio Default images - FileUtils::getInstance()->addSearchPath(getApplicationPath().c_str()); - - if (!_view->init()) return 1; - - gView = _view; - - _hwnd = _view->getWindowHandler(); - player::PlayerWin::createWithHwnd(_hwnd); - DragAcceptFiles(_hwnd, TRUE); - // SendMessage(_hwnd, WM_SETICON, ICON_BIG, (LPARAM)icon); - // SendMessage(_hwnd, WM_SETICON, ICON_SMALL, (LPARAM)icon); - // FreeResource(icon); - - // path for looking Lang file, Studio Default images - FileUtils::getInstance()->addSearchPath(getApplicationPath().c_str()); - - // set window position - if (_project.getProjectDir().length()) - { - setZoom(_project.getFrameScale()); - } - Vec2 pos = _project.getWindowOffset(); - if (pos.x != 0 && pos.y != 0) - { - RECT rect; - GetWindowRect(_hwnd, &rect); - if (pos.x < 0) - pos.x = 0; - if (pos.y < 0) - pos.y = 0; - MoveWindow(_hwnd, pos.x, pos.y, rect.right - rect.left, rect.bottom - rect.top, FALSE); - } - - // init player services - // the UI workflow is migrated into the Cocos Creator Editor - // setupUI(); - // DrawMenuBar(_hwnd); - - // prepare - _project.dump(); - - g_oldWindowProc = (WNDPROC)SetWindowLong(_hwnd, GWLP_WNDPROC, (LONG)SimulatorWin::windowProc); - - // update window title - updateWindowTitle(); - - bool resume, pause, close; - se::ScriptEngine::getInstance()->addPermanentRegisterCallback(setCanvasCallback); - - if (!_app->init()) return 1; - _quit = false; - - PVRFrameEnableControlWindow(false); - - /////////////////////////////////////////////////////////////////////////// - /////////////// changing timer resolution - /////////////////////////////////////////////////////////////////////////// - UINT TARGET_RESOLUTION = 1; // 1 millisecond target resolution - TIMECAPS tc; - UINT wTimerRes = 0; - if (TIMERR_NOERROR == timeGetDevCaps(&tc, sizeof(TIMECAPS))) - { - wTimerRes = std::min(std::max(tc.wPeriodMin, TARGET_RESOLUTION), tc.wPeriodMax); - timeBeginPeriod(wTimerRes); - } - - float dt = 0.f; - const DWORD _16ms = 16; - - // Main message loop: - LARGE_INTEGER nFreq; - LARGE_INTEGER nLast; - LARGE_INTEGER nNow; - - LONGLONG actualInterval = 0LL; // actual frame internal - LONGLONG desiredInterval = 0LL; // desired frame internal, 1 / fps - LONG waitMS = 0L; - - QueryPerformanceCounter(&nLast); - QueryPerformanceFrequency(&nFreq); - se::ScriptEngine* se = se::ScriptEngine::getInstance(); - - - _app->onResume(); - - while (!_quit) - { - desiredInterval = (LONGLONG)(1.0 / _app->getPreferredFramesPerSecond() * nFreq.QuadPart); - - resume = false; - pause = false; - close = false; - while (_view->pollEvent(&_quit, &resume, &pause, &close)) {} - - if (pause) _app->onPause(); - if (resume) _app->onResume(); - if (close) _app->onClose(); - - QueryPerformanceCounter(&nNow); - actualInterval = nNow.QuadPart - nLast.QuadPart; - if (actualInterval >= desiredInterval) - { - nLast.QuadPart = nNow.QuadPart; - _app->tick(); - _view->swapbuffer(); - } - else - { - // The precision of timer on Windows is set to highest (1ms) by 'timeBeginPeriod' from above code, - // but it's still not precise enough. For example, if the precision of timer is 1ms, - // Sleep(3) may make a sleep of 2ms or 4ms. Therefore, we subtract 1ms here to make Sleep time shorter. - // If 'waitMS' is equal or less than 1ms, don't sleep and run into next loop to - // boost CPU to next frame accurately. - waitMS = (desiredInterval - actualInterval) * 1000LL / nFreq.QuadPart - 1L; - if (waitMS > 1L) - Sleep(waitMS); - } - } - - - if (wTimerRes != 0) - timeEndPeriod(wTimerRes); - - return 0; -} - -// services - -void SimulatorWin::setupUI() -{ - auto menuBar = player::PlayerProtocol::getInstance()->getMenuService(); - - // FILE - menuBar->addItem("FILE_MENU", tr("File")); - menuBar->addItem("EXIT_MENU", tr("Exit"), "FILE_MENU"); - - // VIEW - menuBar->addItem("VIEW_MENU", tr("View")); - SimulatorConfig *config = SimulatorConfig::getInstance(); - int current = config->checkScreenSize(_project.getFrameSize()); - for (int i = 0; i < config->getScreenSizeCount(); i++) - { - SimulatorScreenSize size = config->getScreenSize(i); - std::stringstream menuId; - menuId << "VIEWSIZE_ITEM_MENU_" << i; - auto menuItem = menuBar->addItem(menuId.str(), size.title.c_str(), "VIEW_MENU"); - - if (i == current) - { - menuItem->setChecked(true); - } - } - - // show FPs - bool displayStats = true; // asume creator default show FPS - string fpsItemName = displayStats ? tr("Hide FPS") : tr("Show FPS"); - menuBar->addItem("FPS_MENU", fpsItemName); - - // About - menuBar->addItem("HELP_MENU", tr("Help")); - menuBar->addItem("ABOUT_MENUITEM", tr("About"), "HELP_MENU"); - - menuBar->addItem("DIRECTION_MENU_SEP", "-", "VIEW_MENU"); - menuBar->addItem("DIRECTION_PORTRAIT_MENU", tr("Portrait"), "VIEW_MENU") - ->setChecked(_project.isPortraitFrame()); - menuBar->addItem("DIRECTION_LANDSCAPE_MENU", tr("Landscape"), "VIEW_MENU") - ->setChecked(_project.isLandscapeFrame()); - - menuBar->addItem("VIEW_SCALE_MENU_SEP", "-", "VIEW_MENU"); - std::vector scaleMenuVector; - auto scale100Menu = menuBar->addItem("VIEW_SCALE_MENU_100", tr("Zoom Out").append(" (100%)"), "VIEW_MENU"); - auto scale75Menu = menuBar->addItem("VIEW_SCALE_MENU_75", tr("Zoom Out").append(" (75%)"), "VIEW_MENU"); - auto scale50Menu = menuBar->addItem("VIEW_SCALE_MENU_50", tr("Zoom Out").append(" (50%)"), "VIEW_MENU"); - auto scale25Menu = menuBar->addItem("VIEW_SCALE_MENU_25", tr("Zoom Out").append(" (25%)"), "VIEW_MENU"); - int frameScale = int(_project.getFrameScale() * 100); - - if (frameScale == 100) - { - scale100Menu->setChecked(true); - } - else if (frameScale == 75) - { - scale75Menu->setChecked(true); - } - else if (frameScale == 50) - { - scale50Menu->setChecked(true); - } - else if (frameScale == 25) - { - scale25Menu->setChecked(true); - } - else - { - scale100Menu->setChecked(true); - } - - scaleMenuVector.push_back(scale100Menu); - scaleMenuVector.push_back(scale75Menu); - scaleMenuVector.push_back(scale50Menu); - scaleMenuVector.push_back(scale25Menu); - - menuBar->addItem("REFRESH_MENU_SEP", "-", "VIEW_MENU"); - menuBar->addItem("REFRESH_MENU", tr("Refresh"), "VIEW_MENU"); - - HWND &hwnd = _hwnd; - ProjectConfig &project = _project; - EventDispatcher::CustomEventListener listener = [this, &hwnd, &project, scaleMenuVector](const CustomEvent& event) { - auto menuEvent = dynamic_cast(event); - rapidjson::Document dArgParse; - dArgParse.Parse<0>(menuEvent.getDataString().c_str()); - if (dArgParse.HasMember("name")) - { - string strcmd = dArgParse["name"].GetString(); - - if (strcmd == "menuClicked") - { - player::PlayerMenuItem *menuItem = static_cast(menuEvent.args[0].ptrVal); - if (menuItem) - { - if (menuItem->isChecked()) - { - return; - } - - string data = dArgParse["data"].GetString(); - - if ((data == "CLOSE_MENU") || (data == "EXIT_MENU")) - { - _instance->quit(); - } - else if (data == "REFRESH_MENU") - { - _instance->relaunch(); - } - else if (data.find("VIEW_SCALE_MENU_") == 0) // begin with VIEW_SCALE_MENU_ - { - string tmp = data.erase(0, strlen("VIEW_SCALE_MENU_")); - float scale = atof(tmp.c_str()) / 100.0f; - project.setFrameScale(scale); - - _instance->openProjectWithProjectConfig(project); - } - else if (data.find("VIEWSIZE_ITEM_MENU_") == 0) // begin with VIEWSIZE_ITEM_MENU_ - { - string tmp = data.erase(0, strlen("VIEWSIZE_ITEM_MENU_")); - int index = atoi(tmp.c_str()); - SimulatorScreenSize size = SimulatorConfig::getInstance()->getScreenSize(index); - - if (project.isLandscapeFrame()) - { - std::swap(size.width, size.height); - } - - project.setFrameSize(cc::Size(size.width, size.height)); - project.setWindowOffset(cc::Vec2(_instance->getPositionX(), _instance->getPositionY())); - _instance->openProjectWithProjectConfig(project); - } - else if (data == "DIRECTION_PORTRAIT_MENU") - { - project.changeFrameOrientationToPortait(); - _instance->openProjectWithProjectConfig(project); - } - else if (data == "DIRECTION_LANDSCAPE_MENU") - { - project.changeFrameOrientationToLandscape(); - _instance->openProjectWithProjectConfig(project); - } - else if (data == "ABOUT_MENUITEM") - { - onHelpAbout(); - } - else if (data == "FPS_MENU") - { - bool displayStats = !_app->isDisplayStats(); - _app->setDisplayStats(displayStats); - menuItem->setTitle(displayStats ? tr("Hide FPS") : tr("Show FPS")); - } - } - } - } - }; - EventDispatcher::addCustomEventListener(kAppEventName, listener); -} - -void SimulatorWin::setZoom(float frameScale) -{ - _project.setFrameScale(frameScale); -} - -void SimulatorWin::updateWindowTitle() -{ - std::stringstream title; - title << "Cocos " << tr("Simulator") << " (" << _project.getFrameScale() * 100 << "%)"; - std::u16string u16title; - cc::StringUtils::UTF8ToUTF16(title.str(), u16title); - SetWindowText(_hwnd, (LPCTSTR)u16title.c_str()); -} - -// debug log -void SimulatorWin::writeDebugLog(const char *log) -{ - if (!_writeDebugLogFile) return; - - fputs(log, _writeDebugLogFile); - fputc('\n', _writeDebugLogFile); - fflush(_writeDebugLogFile); -} - -void SimulatorWin::parseCocosProjectConfig(ProjectConfig &config) -{ - // get project directory - ProjectConfig tmpConfig; - // load project config from command line args - std::vector args; - for (int i = 0; i < __argc; ++i) - { - wstring ws(__wargv[i]); - string s; - s.assign(ws.begin(), ws.end()); - args.push_back(s); - } - - if (args.size() >= 2) - { - if (args.size() && args.at(1).at(0) == '/') - { - // IDEA: - // for Code IDE before RC2 - tmpConfig.setProjectDir(args.at(1)); - } - - tmpConfig.parseCommandLine(args); - } - - // set project directory as search root path - string solutionDir = tmpConfig.getProjectDir(); - if (!solutionDir.empty()) - { - for (int i = 0; i < solutionDir.size(); ++i) - { - if (solutionDir[i] == '\\') - { - solutionDir[i] = '/'; - } - } - int nPos = -1; - if (solutionDir[solutionDir.length() - 1] == '/') - nPos = solutionDir.rfind('/', solutionDir.length() - 2); - else - nPos = solutionDir.rfind('/'); - if (nPos > 0) - solutionDir = solutionDir.substr(0, nPos + 1); - FileUtils::getInstance()->setDefaultResourceRootPath(solutionDir); - FileUtils::getInstance()->addSearchPath(solutionDir); - FileUtils::getInstance()->addSearchPath(tmpConfig.getProjectDir().c_str()); - } - else - { - FileUtils::getInstance()->setDefaultResourceRootPath(tmpConfig.getProjectDir().c_str()); - } - - // parse config.json when firstly init ConfigParser single instance - auto parser = ConfigParser::getInstance(); - - // set information - config.setConsolePort(parser->getConsolePort()); - config.setFileUploadPort(parser->getUploadPort()); - config.setFrameSize(parser->getInitViewSize()); - if (parser->isLanscape()) - { - config.changeFrameOrientationToLandscape(); - } - else - { - config.changeFrameOrientationToPortait(); - } - config.setScriptFile(parser->getEntryFile()); -} - -// -// D:\aaa\bbb\ccc\ddd\abc.txt --> D:/aaa/bbb/ccc/ddd/abc.txt -// -std::string SimulatorWin::convertPathFormatToUnixStyle(const std::string& path) -{ - std::string ret = path; - int len = ret.length(); - for (int i = 0; i < len; ++i) - { - if (ret[i] == '\\') - { - ret[i] = '/'; - } - } - return ret; -} - -// -// @return: C:/Users/win8/Documents/ -// -std::string SimulatorWin::getUserDocumentPath() -{ - TCHAR filePath[MAX_PATH]; - SHGetSpecialFolderPath(NULL, filePath, CSIDL_PERSONAL, FALSE); - int length = 2 * wcslen(filePath); - char* tempstring = new char[length + 1]; - wcstombs(tempstring, filePath, length + 1); - string userDocumentPath(tempstring); - delete [] tempstring; - - userDocumentPath = convertPathFormatToUnixStyle(userDocumentPath); - userDocumentPath.append("/"); - - return userDocumentPath; -} - -// -// convert Unicode/LocalCode TCHAR to Utf8 char -// -char* SimulatorWin::convertTCharToUtf8(const TCHAR* src) -{ -#ifdef UNICODE - WCHAR* tmp = (WCHAR*)src; - size_t size = wcslen(src) * 3 + 1; - char* dest = new char[size]; - memset(dest, 0, size); - WideCharToMultiByte(CP_UTF8, 0, tmp, -1, dest, size, NULL, NULL); - return dest; -#else - char* tmp = (char*)src; - uint32 size = strlen(tmp) + 1; - WCHAR* dest = new WCHAR[size]; - memset(dest, 0, sizeof(WCHAR)*size); - MultiByteToWideChar(CP_ACP, 0, src, -1, dest, (int)size); // convert local code to unicode. - - size = wcslen(dest) * 3 + 1; - char* dest2 = new char[size]; - memset(dest2, 0, size); - WideCharToMultiByte(CP_UTF8, 0, dest, -1, dest2, size, NULL, NULL); // convert unicode to utf8. - delete[] dest; - return dest2; -#endif -} - -// -std::string SimulatorWin::getApplicationExePath() -{ - TCHAR szFileName[MAX_PATH]; - GetModuleFileName(NULL, szFileName, MAX_PATH); - std::u16string u16ApplicationName; - char *applicationExePath = convertTCharToUtf8(szFileName); - std::string path(applicationExePath); - CC_SAFE_FREE(applicationExePath); - - return path; -} - -std::string SimulatorWin::getApplicationPath() -{ - std::string path = getApplicationExePath(); - size_t pos; - while ((pos = path.find_first_of("\\")) != std::string::npos) - { - path.replace(pos, 1, "/"); - } - size_t p = path.find_last_of("/"); - string workdir; - if (p != path.npos) - { - workdir = path.substr(0, p); - } - - return workdir; -} - -LRESULT CALLBACK SimulatorWin::windowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - if (!_instance) return 0; - - switch (uMsg) - { - case WM_SYSCOMMAND: - case WM_COMMAND: - { - if (HIWORD(wParam) == 0) - { - // menu - WORD menuId = LOWORD(wParam); - auto menuService = dynamic_cast (player::PlayerProtocol::getInstance()->getMenuService()); - auto menuItem = menuService->getItemByCommandId(menuId); - if (menuItem) - { - AppEvent event(kAppEventName, APP_EVENT_MENU); - - std::stringstream buf; - buf << "{\"data\":\"" << menuItem->getMenuId().c_str() << "\""; - buf << ",\"name\":" << "\"menuClicked\"" << "}"; - event.setDataString(buf.str()); - event.args[0].ptrVal = (void*)menuItem; - cc::EventDispatcher::dispatchCustomEvent(event); - } - - if (menuId == ID_HELP_ABOUT) - { - onHelpAbout(); - } - } - break; - } - case WM_KEYDOWN: - { - if (wParam == VK_F5) - { - _instance->relaunch(); - } - break; - } - - case WM_COPYDATA: - { - PCOPYDATASTRUCT pMyCDS = (PCOPYDATASTRUCT)lParam; - if (pMyCDS->dwData == 1) - { - const char *szBuf = (const char*)(pMyCDS->lpData); - SimulatorWin::getInstance()->writeDebugLog(szBuf); - break; - } - } - - case WM_DESTROY: - { - DragAcceptFiles(hWnd, FALSE); - break; - } - - } - return g_oldWindowProc(hWnd, uMsg, wParam, lParam); -} - -void SimulatorWin::onOpenFile(const std::string &filePath) -{ - string entry = filePath; - if (entry.empty()) return; - - if (stringEndWith(entry, "config.json") || stringEndWith(entry, ".csb") || stringEndWith(entry, ".csd")) - { - replaceAll(entry, "\\", "/"); - size_t p = entry.find_last_of("/"); - if (p != entry.npos) - { - string workdir = entry.substr(0, p); - _project.setProjectDir(workdir); - } - - _project.setScriptFile(entry); - if (stringEndWith(entry, CONFIG_FILE)) - { - ConfigParser::getInstance()->readConfig(entry); - _project.setScriptFile(ConfigParser::getInstance()->getEntryFile()); - } - openProjectWithProjectConfig(_project); - } - else - { - auto title = tr("Open File") + tr("Error"); - auto msg = tr("Only support") + " config.json;*.csb;*.csd"; - auto msgBox = player::PlayerProtocol::getInstance()->getMessageBoxService(); - msgBox->showMessageBox(title, msg); - } -} - diff --git a/native/tools/simulator/frameworks/runtime-src/proj.win32/main.cpp b/native/tools/simulator/frameworks/runtime-src/proj.win32/main.cpp index 659e5a6dac..8e6f1fd995 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.win32/main.cpp +++ b/native/tools/simulator/frameworks/runtime-src/proj.win32/main.cpp @@ -24,18 +24,14 @@ ****************************************************************************/ #include "main.h" -#include "SimulatorWin.h" #include -#include "cocos/bindings/jswrapper/SeApi.h" +#include "cocos/platform/BasePlatform.h" int APIENTRY _tWinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) -{ - UNREFERENCED_PARAMETER(hPrevInstance); - UNREFERENCED_PARAMETER(lpCmdLine); - int mainResult = SimulatorWin::getInstance()->run(); - se::ScriptEngine::getInstance()->destroyInstance(); - return mainResult; -} + HINSTANCE hPrevInstance, + LPTSTR lpCmdLine, + int nCmdShow) { + UNREFERENCED_PARAMETER(hPrevInstance); + UNREFERENCED_PARAMETER(lpCmdLine); + START_PLATFORM(0, (const char**)nullptr); +} \ No newline at end of file diff --git a/native/tools/simulator/frameworks/runtime-src/proj.win32/main.h b/native/tools/simulator/frameworks/runtime-src/proj.win32/main.h index fd9f9320da..0e14be6b01 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.win32/main.h +++ b/native/tools/simulator/frameworks/runtime-src/proj.win32/main.h @@ -26,10 +26,10 @@ #ifndef __MAIN_H__ #define __MAIN_H__ -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: -#include #include +#include -#endif // __WINMAIN_H__ +#endif // __WINMAIN_H__ diff --git a/native/tools/simulator/libsimulator/CMakeLists.txt b/native/tools/simulator/libsimulator/CMakeLists.txt index 8146b73175..fa24289d05 100644 --- a/native/tools/simulator/libsimulator/CMakeLists.txt +++ b/native/tools/simulator/libsimulator/CMakeLists.txt @@ -93,8 +93,8 @@ libsimulator_source_files( lib/runtime/VisibleRect.h ) libsimulator_source_files( - lib/AppEvent.cpp - lib/AppEvent.h + lib/CustomAppEvent.cpp + lib/CustomAppEvent.h lib/AppLang.cpp lib/AppLang.h lib/cocos2dx_extra.h diff --git a/native/tools/simulator/libsimulator/lib/AppEvent.cpp b/native/tools/simulator/libsimulator/lib/CustomAppEvent.cpp old mode 100755 new mode 100644 similarity index 84% rename from native/tools/simulator/libsimulator/lib/AppEvent.cpp rename to native/tools/simulator/libsimulator/lib/CustomAppEvent.cpp index 4f6d57bf59..0c5c51c530 --- a/native/tools/simulator/libsimulator/lib/AppEvent.cpp +++ b/native/tools/simulator/libsimulator/lib/CustomAppEvent.cpp @@ -24,14 +24,14 @@ ****************************************************************************/ // -// AppEvent.cpp +// CustomAppEvent.cpp // Simulator // // -#include "AppEvent.h" +#include "CustomAppEvent.h" -AppEvent::AppEvent(const std::string& eventName, int type) +CustomAppEvent::CustomAppEvent(const std::string& eventName, int type) : CustomEvent() , _eventName(eventName) { @@ -39,21 +39,21 @@ AppEvent::AppEvent(const std::string& eventName, int type) setEventType(type); } -void AppEvent::setEventType(int type) +void CustomAppEvent::setEventType(int type) { _eventType = type; } -int AppEvent::getEventType() +int CustomAppEvent::getEventType() { return _eventType; } -void AppEvent::setDataString(std::string data) +void CustomAppEvent::setDataString(std::string data) { _dataString = data; } -std::string AppEvent::getDataString() +std::string CustomAppEvent::getDataString() { return _dataString; } diff --git a/native/tools/simulator/libsimulator/lib/AppEvent.h b/native/tools/simulator/libsimulator/lib/CustomAppEvent.h similarity index 94% rename from native/tools/simulator/libsimulator/lib/AppEvent.h rename to native/tools/simulator/libsimulator/lib/CustomAppEvent.h index 28d13fc335..9efd3b6532 100644 --- a/native/tools/simulator/libsimulator/lib/AppEvent.h +++ b/native/tools/simulator/libsimulator/lib/CustomAppEvent.h @@ -49,10 +49,10 @@ enum { #define kAppEventName "APP.EVENT" -class CC_LIBSIM_DLL AppEvent : public cc::CustomEvent { +class CC_LIBSIM_DLL CustomAppEvent : public cc::CustomEvent { public: /** Constructor */ - AppEvent(const std::string &eventName, int type); + CustomAppEvent(const std::string &eventName, int type); /** Gets event name */ inline const std::string &getEventName() const { return _eventName; }; diff --git a/native/tools/simulator/libsimulator/lib/platform/mac/PlayerMenuServiceMac.mm b/native/tools/simulator/libsimulator/lib/platform/mac/PlayerMenuServiceMac.mm index 630074551a..3a1dc4b5c1 100755 --- a/native/tools/simulator/libsimulator/lib/platform/mac/PlayerMenuServiceMac.mm +++ b/native/tools/simulator/libsimulator/lib/platform/mac/PlayerMenuServiceMac.mm @@ -27,7 +27,7 @@ #include "PlayerMenuServiceMac.h" #include "PlayerUtils.h" #include "cocos/bindings/event/EventDispatcher.h" -#include "AppEvent.h" +#include "CustomAppEvent.h" #include /////////////////////////////////////// menu helper ////////////////////////////////////////////// @@ -109,7 +109,7 @@ static bool __G_IS_MENUBAR_ENABLED__ = true; // WTF -(void) onClicked:(id)sender { - AppEvent event(kAppEventName, APP_EVENT_MENU); + CustomAppEvent event(kAppEventName, APP_EVENT_MENU); std::stringstream buf; buf << "{\"data\":\"" << self.macMenuItem->getMenuId().c_str() << "\""; diff --git a/native/tools/tojs/cocos.ini b/native/tools/tojs/cocos.ini index 31f913853a..207a3cc630 100644 --- a/native/tools/tojs/cocos.ini +++ b/native/tools/tojs/cocos.ini @@ -24,14 +24,14 @@ cxxgenerator_headers = extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s # what headers to parse -headers = %(cocosdir)s/cocos/platform/FileUtils.h %(cocosdir)s/cocos/platform/CanvasRenderingContext2D.h %(cocosdir)s/cocos/platform/Device.h %(cocosdir)s/cocos/platform/SAXParser.h +headers = %(cocosdir)s/cocos/platform/FileUtils.h %(cocosdir)s/cocos/bindings/event/EventDispatcher.h %(cocosdir)s/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.h %(cocosdir)s/cocos/platform/interfaces/modules/Device.h %(cocosdir)s/cocos/platform/SAXParser.h replace_headers= # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". -classes = FileUtils$ SAXParser CanvasRenderingContext2D CanvasGradient Device DownloaderHints +classes = FileUtils$ SAXParser OSInterface ICanvasRenderingContext2D CanvasRenderingContext2D ICanvasGradient CanvasGradient Device DownloaderHints classes_need_extend = @@ -49,11 +49,12 @@ skip = FileUtils::[getFileData setFilenameLookupDictionary destroyInstance getFu Device::[getDeviceMotionValue], CanvasRenderingContext2D::[setCanvasBufferUpdatedCallback set_.+ fillText strokeText fillRect measureText], Data::[takeBuffer getBytes fastSet copy], + OSInterface::[dispatchEvent dispatchTouchEvent], Value::[asValueVector asValueMap asIntKeyMap] rename_functions = FileUtils::[loadFilenameLookupDictionaryFromFile=loadFilenameLookup] -getter_setter=CanvasRenderingContext2D::[width//setWidth height//setHeight fillStyle//setFillStyle font//setFont globalCompositeOperation//setGlobalCompositeOperation lineCap//setLineCap lineJoin//setLineJoin lineWidth//setLineWidth strokeStyle//setStrokeStyle textAlign//setTextAlign textBaseline//setTextBaseline] +getter_setter=ICanvasRenderingContext2D::[width//setWidth height//setHeight fillStyle//setFillStyle font//setFont globalCompositeOperation//setGlobalCompositeOperation lineCap//setLineCap lineJoin//setLineJoin lineWidth//setLineWidth strokeStyle//setStrokeStyle textAlign//setTextAlign textBaseline//setTextBaseline] rename_classes = SAXParser::PlistParser @@ -68,7 +69,7 @@ base_classes_to_skip = Ref Clonable # classes that create no constructor # Set is special and we will use a hand-written constructor -abstract_classes = SAXParser Device +abstract_classes = SAXParser Device ICanvasRenderingContext2D ICanvasGradient OSInterface persistent_classes = FileUtils