diff options
| author | Egor Yusov <egor.yusov@gmail.com> | 2019-11-11 15:42:14 +0000 |
|---|---|---|
| committer | Egor Yusov <egor.yusov@gmail.com> | 2019-11-11 15:42:14 +0000 |
| commit | ee177d37df85b982d6c528a7b79e3cd9ca9749d6 (patch) | |
| tree | dda6c9b0c2a3f2756c08b71ebaca32644dbc9d32 /NativeApp | |
| parent | Updated HLSL2GLSL converter app (diff) | |
| download | DiligentTools-ee177d37df85b982d6c528a7b79e3cd9ca9749d6.tar.gz DiligentTools-ee177d37df85b982d6c528a7b79e3cd9ca9749d6.zip | |
Moved Native App from master repository
Diffstat (limited to 'NativeApp')
107 files changed, 12803 insertions, 0 deletions
diff --git a/NativeApp/Android/.gitignore b/NativeApp/Android/.gitignore new file mode 100644 index 0000000..8e7c6d9 --- /dev/null +++ b/NativeApp/Android/.gitignore @@ -0,0 +1,4 @@ +/build +/.externalNativeBuild +*.iml +.cxx diff --git a/NativeApp/Android/CMakeLists.txt b/NativeApp/Android/CMakeLists.txt new file mode 100644 index 0000000..87d8f3c --- /dev/null +++ b/NativeApp/Android/CMakeLists.txt @@ -0,0 +1,8 @@ +cmake_minimum_required (VERSION 3.6) + +add_library(native_app_glue ${ANDROID_NDK}/sources/android/native_app_glue/android_native_app_glue.c) +target_link_libraries(native_app_glue log) +target_include_directories(native_app_glue INTERFACE ${ANDROID_NDK}/sources/android/native_app_glue) +set_common_target_properties(native_app_glue) + +add_subdirectory(ndk_helper) diff --git a/NativeApp/Android/android_common.gradle b/NativeApp/Android/android_common.gradle new file mode 100644 index 0000000..5be7b80 --- /dev/null +++ b/NativeApp/Android/android_common.gradle @@ -0,0 +1,12 @@ +android { + compileSdkVersion=28 + + defaultConfig { + minSdkVersion 21 + targetSdkVersion 28 + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + } +} diff --git a/NativeApp/Android/build.gradle b/NativeApp/Android/build.gradle new file mode 100644 index 0000000..ac62940 --- /dev/null +++ b/NativeApp/Android/build.gradle @@ -0,0 +1,43 @@ +apply plugin: 'com.android.library' +apply from: "android_common.gradle" + +android { + defaultConfig { + + ndk { + abiFilters 'armeabi-v7a'//, 'armeabi', 'arm64-v8a','x86', 'x86_64' + } + externalNativeBuild { + cmake { + arguments '-DANDROID_TOOLCHAIN=clang', '-DANDROID_STL=c++_static', '-DENABLE_TESTS=TRUE' + } + } + } + + externalNativeBuild { + cmake { + version '3.10.2' + path '../../../CMakeLists.txt' + } + } + + sourceSets { + main { + java.srcDirs = ['src/main/java', 'ndk_helper/src/java'] + } + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +buildDir './build' + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation 'com.android.support:appcompat-v7:28.0.0' +} diff --git a/NativeApp/Android/ndk_helper/CMakeLists.txt b/NativeApp/Android/ndk_helper/CMakeLists.txt new file mode 100644 index 0000000..653847d --- /dev/null +++ b/NativeApp/Android/ndk_helper/CMakeLists.txt @@ -0,0 +1,42 @@ +cmake_minimum_required (VERSION 3.6) + +project(NDKHelper CXX) + +set(SOURCE + src/gestureDetector.cpp + src/JNIHelper.cpp + src/perfMonitor.cpp + src/sensorManager.cpp + src/tapCamera.cpp + src/vecmath.cpp +) + +set(INCLUDE + include/gestureDetector.h + include/JNIHelper.h + include/perfMonitor.h + include/sensorManager.h + include/tapCamera.h +) + +add_library(NDKHelper STATIC ${SOURCE} ${INCLUDE}) +set_common_target_properties(NDKHelper) + +target_include_directories(NDKHelper +PUBLIC + include +) + +target_link_libraries(NDKHelper +PRIVATE + Diligent-BuildSettings +PUBLIC + native_app_glue +) + +source_group("src" FILES ${SOURCE}) +source_group("include" FILES ${INCLUDE}) + +set_target_properties(NDKHelper PROPERTIES + FOLDER Core/External +) diff --git a/NativeApp/Android/ndk_helper/include/GLContext.h b/NativeApp/Android/ndk_helper/include/GLContext.h new file mode 100644 index 0000000..551794f --- /dev/null +++ b/NativeApp/Android/ndk_helper/include/GLContext.h @@ -0,0 +1,115 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//-------------------------------------------------------------------------------- +// GLContext.h +//-------------------------------------------------------------------------------- +#ifndef GLCONTEXT_H_ +#define GLCONTEXT_H_ + +#include <EGL/egl.h> +#include <GLES2/gl2.h> +#include <android/log.h> + +#include "JNIHelper.h" + +namespace ndk_helper { + +//-------------------------------------------------------------------------------- +// Constants +//-------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------- +// Class +//-------------------------------------------------------------------------------- + +/****************************************************************** + * OpenGL context handler + * The class handles OpenGL and EGL context based on Android activity life cycle + * The caller needs to call corresponding methods for each activity life cycle + *events as it's done in sample codes. + * + * Also the class initializes OpenGL ES3 when the compatible driver is installed + *in the device. + * getGLVersion() returns 3.0~ when the device supports OpenGLES3.0 + * + * Thread safety: OpenGL context is expecting used within dedicated single + *thread, + * thus GLContext class is not designed as a thread-safe + */ +class GLContext { + private: + // EGL configurations + ANativeWindow* window_; + EGLDisplay display_; + EGLSurface surface_; + EGLContext context_; + EGLConfig config_; + + // Screen parameters + int32_t screen_width_; + int32_t screen_height_; + int32_t color_size_; + int32_t depth_size_; + + // Flags + bool gles_initialized_; + bool egl_context_initialized_; + bool es3_supported_; + float gl_version_; + bool context_valid_; + + void InitGLES(); + void Terminate(); + bool InitEGLSurface(); + bool InitEGLContext(); + + GLContext(GLContext const&); + void operator=(GLContext const&); + GLContext(); + virtual ~GLContext(); + + public: + static GLContext* GetInstance() { + // Singleton + static GLContext instance; + + return &instance; + } + + bool Init(ANativeWindow* window); + EGLint Swap(); + bool Invalidate(); + + void Suspend(); + EGLint Resume(ANativeWindow* window); + + ANativeWindow* GetANativeWindow(void) const { return window_; }; + int32_t GetScreenWidth() const { return screen_width_; } + int32_t GetScreenHeight() const { return screen_height_; } + + int32_t GetBufferColorSize() const { return color_size_; } + int32_t GetBufferDepthSize() const { return depth_size_; } + float GetGLVersion() const { return gl_version_; } + bool CheckExtension(const char* extension); + + EGLDisplay GetDisplay() const { return display_; } + EGLSurface GetSurface() const { return surface_; } +}; + +} // namespace ndkHelper + +#endif /* GLCONTEXT_H_ */ diff --git a/NativeApp/Android/ndk_helper/include/JNIHelper.h b/NativeApp/Android/ndk_helper/include/JNIHelper.h new file mode 100644 index 0000000..0e69905 --- /dev/null +++ b/NativeApp/Android/ndk_helper/include/JNIHelper.h @@ -0,0 +1,330 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include <jni.h> +#include <vector> +#include <string> +#include <functional> +#include <assert.h> +#include <mutex> +#include <pthread.h> + +#include <android/log.h> +#include <android_native_app_glue.h> + +#define LOGI(...) \ + ((void)__android_log_print( \ + ANDROID_LOG_INFO, ndk_helper::JNIHelper::GetInstance()->GetAppName(), \ + __VA_ARGS__)) +#define LOGW(...) \ + ((void)__android_log_print( \ + ANDROID_LOG_WARN, ndk_helper::JNIHelper::GetInstance()->GetAppName(), \ + __VA_ARGS__)) +#define LOGE(...) \ + ((void)__android_log_print( \ + ANDROID_LOG_ERROR, ndk_helper::JNIHelper::GetInstance()->GetAppName(), \ + __VA_ARGS__)) + +namespace ndk_helper { + +class JUIView; + +/****************************************************************** + * Helper functions for JNI calls + * This class wraps JNI calls and provides handy interface calling commonly used + *features + * in Java SDK. + * Such as + * - loading graphics files (e.g. PNG, JPG) + * - character code conversion + * - retrieving system properties which only supported in Java SDK + * + * NOTE: To use this class, add NDKHelper.java as a corresponding helpers in + *Java code + */ +class JNIHelper { + private: + std::string app_name_; + + ANativeActivity* activity_; + jobject jni_helper_java_ref_; + jclass jni_helper_java_class_; + + jstring GetExternalFilesDirJString(JNIEnv* env); + jclass RetrieveClass(JNIEnv* jni, const char* class_name); + + JNIHelper(); + ~JNIHelper(); + JNIHelper(const JNIHelper& rhs); + JNIHelper& operator=(const JNIHelper& rhs); + + std::string app_label_; + + // mutex for synchronization + // This class uses singleton pattern and can be invoked from multiple threads, + // each methods locks the mutex for a thread safety + mutable std::mutex mutex_; + + /* + * Call method in JNIHelper class + */ + jobject CallObjectMethod(const char* strMethodName, const char* strSignature, + ...); + void CallVoidMethod(const char* strMethodName, const char* strSignature, ...); + + /* + * Unregister this thread from the VM + */ + static void DetachCurrentThreadDtor(void* p) { + LOGI("detached current thread"); + ANativeActivity* activity = (ANativeActivity*)p; + activity->vm->DetachCurrentThread(); + } + + public: + /* + * To load your own Java classes, JNIHelper requires to be initialized with a + *ANativeActivity handle. + * This methods need to be called before any call to the helper class. + * Static member of the class + * + * arguments: + * in: activity, pointer to ANativeActivity. Used internally to set up JNI + *environment + * in: helper_class_name, pointer to Java side helper class name. (e.g. + *"com/sample/helper/NDKHelper" in samples ) + */ + static void Init(ANativeActivity* activity, const char* helper_class_name); + + /* + * Init() that accept so name. + * When using a JUI helper class, Java side requires SO name to initialize JNI + * calls to invoke native callbacks. + * Use this version when using JUI helper. + * + * arguments: + * in: activity, pointer to ANativeActivity. Used internally to set up JNI + * environment + * in: helper_class_name, pointer to Java side helper class name. (e.g. + * "com/sample/helper/NDKHelper" in samples ) + * in: native_soname, pointer to soname of native library. (e.g. + * "NativeActivity" for "libNativeActivity.so" ) + */ + static void Init(ANativeActivity* activity, const char* helper_class_name, + const char* native_soname); + + /* + * Retrieve the singleton object of the helper. + * Static member of the class + + * Methods in the class are designed as thread safe. + */ + static JNIHelper* GetInstance(); + + /* + * Read a file from a strorage. + * First, the method tries to read the file from an external storage. + * If it fails to read, it falls back to use assset manager and try to read + * the file from APK asset. + * + * arguments: + * in: file_name, file name to read + * out: buffer_ref, pointer to a vector buffer to read a file. + * when the call succeeded, the buffer includes contents of specified + *file + * when the call failed, contents of the buffer remains same + * return: + * true when file read succeeded + * false when it failed to read the file + */ + bool ReadFile(const char* file_name, std::vector<uint8_t>* buffer_ref); + + /* + * Load and create OpenGL texture from given file name. + * The method invokes BitmapFactory in Java so it can read jpeg/png formatted + * files + * + * The methods creates mip-map and set texture parameters like this, + * glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, + * GL_LINEAR_MIPMAP_NEAREST ); + * glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); + * glGenerateMipmap( GL_TEXTURE_2D ); + * + * arguments: + * in: file_name, file name to read, PNG&JPG is supported + * outWidth(Optional) pointer to retrieve original bitmap width + * outHeight(Optional) pointer to retrieve original bitmap height + * return: + * OpenGL texture name when the call succeeded + * When it failed to load the texture, it returns -1 + */ + uint32_t LoadTexture(const char* file_name, int32_t* outWidth = nullptr, + int32_t* outHeight = nullptr, bool* hasAlpha = nullptr); + + /* + * Load and create OpenGL cubemap texture from given file name + * into specified cubemap face & miplevel + * The method invokes BitmapFactory in Java so it can read jpeg/png formatted + * files + * + * arguments: + * in: file_name, file name to read, PNG&JPG is supported + * outWidth(Optional) pointer to retrieve original bitmap width + * outHeight(Optional) pointer to retrieve original bitmap height + * return: + * OpenGL texture name when the call succeeded + * When it failed to load the texture, it returns -1 + */ + uint32_t LoadCubemapTexture(const char* file_name, const int32_t face, + const int32_t miplevel, const bool sRGB, + int32_t* outWidth = nullptr, + int32_t* outHeight = nullptr, + bool* hasAlpha = nullptr); + + /* + * Load and create image and return it as a byte array. + * The method invokes BitmapFactory in Java so it can read jpeg/png formatted + * files + * + * arguments: + * in: file_name, file name to read, PNG&JPG is supported + * outWidth(Optional) pointer to retrieve original bitmap width + * outHeight(Optional) pointer to retrieve original bitmap height + * return: + * Java ByteBuffer object containing image data converted to RGBA values. + */ + jobject LoadImage(const char* file_name, int32_t* outWidth = nullptr, + int32_t* outHeight = nullptr, bool* hasAlpha = nullptr); + + /* + * Convert string from character code other than UTF-8 + * + * arguments: + * in: str, pointer to a string which is encoded other than UTF-8 + * in: encoding, pointer to a character encoding string. + * The encoding string can be any valid java.nio.charset.Charset name + * e.g. "UTF-16", "Shift_JIS" + * return: converted input string as an UTF-8 std::string + */ + std::string ConvertString(const char* str, const char* encode); + /* + * Retrieve external file directory through JNI call + * + * return: std::string containing external file diretory + */ + std::string GetExternalFilesDir(); + + /* + * Retrieve string resource with a given name + * arguments: + * in: resourceName, name of string resource to retrieve + * return: string resource value, returns "" when there is no string resource + * with given name + */ + std::string GetStringResource(const std::string& resourceName); + + /* + * Audio helper + * Retrieves native audio buffer size which is required to achieve low latency + * audio + * + * return: Native audio buffer size which is a hint to achieve low latency + * audio + * If the API is not supported (API level < 17), it returns 0 + */ + int32_t GetNativeAudioBufferSize(); + + /* + * Audio helper + * Retrieves native audio sample rate which is required to achieve low latency + * audio + * + * return: Native audio sample rate which is a hint to achieve low latency + * audio + */ + int32_t GetNativeAudioSampleRate(); + + /* + * Retrieves application bundle name + * + * return: pointer to an app name string + * + */ + const char* GetAppName() const { return app_name_.c_str(); } + + /* + * Retrieves application label + * + * return: pointer to an app label string + * + */ + const char* GetAppLabel() const { return app_label_.c_str(); } + + /* + * Execute given function in Java UIThread. + * + * arguments: + * in: pFunction, a pointer to a function to be executed in Java UI Thread. + * Note that the helper function returns immediately without synchronizing a + * function completion. + */ + void RunOnUiThread(std::function<void()> callback); + + /* + * Attach current thread + * In Android, the thread doesn't have to be 'Detach' current thread + * as application process is only killed and VM does not shut down + */ + JNIEnv* AttachCurrentThread() { + JNIEnv* env; + if (activity_->vm->GetEnv((void**)&env, JNI_VERSION_1_4) == JNI_OK) + return env; + activity_->vm->AttachCurrentThread(&env, NULL); + pthread_key_create((int32_t*)activity_, DetachCurrentThreadDtor); + return env; + } + + void DetachCurrentThread() { + activity_->vm->DetachCurrentThread(); + return; + } + + /* + * Decrement a global reference to the object + * arguments: + * in: obj, obj to decrement a global reference + */ + void DeleteObject(jobject obj); + + /* + * Helper methods to call a method in given object + */ + jobject CreateObject(const char* class_name); + jobject CallObjectMethod(jobject object, const char* strMethodName, + const char* strSignature, ...); + void CallVoidMethod(jobject object, const char* strMethodName, + const char* strSignature, ...); + float CallFloatMethod(jobject object, const char* strMethodName, + const char* strSignature, ...); + int32_t CallIntMethod(jobject object, const char* strMethodName, + const char* strSignature, ...); + bool CallBooleanMethod(jobject object, const char* strMethodName, + const char* strSignature, ...); +}; + +} // namespace ndkHelper diff --git a/NativeApp/Android/ndk_helper/include/NDKHelper.h b/NativeApp/Android/ndk_helper/include/NDKHelper.h new file mode 100644 index 0000000..4c979e6 --- /dev/null +++ b/NativeApp/Android/ndk_helper/include/NDKHelper.h @@ -0,0 +1,43 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _NDKSUPPORT_H +#define _NDKSUPPORT_H + +#define NDK_HELPER_VERSION "0.90" + +/****************************************************************** + * NDK support helpers + * Utility module to provide misc functionalities that is used widely in native + * applications, + * such as gesture detection, jni bridge, openGL context etc. + * + * The purpose of this module is, + * - Provide best practices using NDK + * - Provide handy utility functions for NDK development + * - Make NDK samples more simpler and readable + */ +#include "gl3stub.h" // GLES3 stubs +#include "GLContext.h" // EGL & OpenGL manager +#include "shader.h" // Shader compiler support +#include "vecmath.h" // Vector math support, C++ implementation n current version +#include "tapCamera.h" // Tap/Pinch camera control +#include "JNIHelper.h" // JNI support +#include "gestureDetector.h" // Tap/Doubletap/Pinch detector +#include "perfMonitor.h" // FPS counter +#include "sensorManager.h" // SensorManager +#include "interpolator.h" // Interpolator +#endif diff --git a/NativeApp/Android/ndk_helper/include/gestureDetector.h b/NativeApp/Android/ndk_helper/include/gestureDetector.h new file mode 100644 index 0000000..87849ff --- /dev/null +++ b/NativeApp/Android/ndk_helper/include/gestureDetector.h @@ -0,0 +1,144 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//-------------------------------------------------------------------------------- +// gestureDetector.h +//-------------------------------------------------------------------------------- +#ifndef GESTUREDETECTOR_H_ +#define GESTUREDETECTOR_H_ + +#include <vector> + +#include <android/sensor.h> +#include <android/log.h> +#include <android_native_app_glue.h> +#include <android/native_window_jni.h> +#include "JNIHelper.h" +#include "vecmath.h" + +namespace ndk_helper { +//-------------------------------------------------------------------------------- +// Constants +//-------------------------------------------------------------------------------- +const int32_t DOUBLE_TAP_TIMEOUT = 300 * 1000000; +const int32_t TAP_TIMEOUT = 180 * 1000000; +const int32_t DOUBLE_TAP_SLOP = 100; +const int32_t TOUCH_SLOP = 8; + +enum { + GESTURE_STATE_NONE = 0, + GESTURE_STATE_START = 1, + GESTURE_STATE_MOVE = 2, + GESTURE_STATE_END = 4, + GESTURE_STATE_ACTION = (GESTURE_STATE_START | GESTURE_STATE_END), +}; +typedef int32_t GESTURE_STATE; + +/****************************************************************** + * Base class of Gesture Detectors + * GestureDetectors handles input events and detect gestures + * Note that different detectors may detect gestures with an event at + * same time. The caller needs to manage gesture priority accordingly + * + */ +class GestureDetector { + protected: + float dp_factor_; + + public: + GestureDetector(); + virtual ~GestureDetector() {} + virtual void SetConfiguration(AConfiguration* config); + + virtual GESTURE_STATE Detect(const AInputEvent* motion_event) = 0; +}; + +/****************************************************************** + * Tap gesture detector + * Returns GESTURE_STATE_ACTION when a tap gesture is detected + * + */ +class TapDetector : public GestureDetector { + private: + int32_t down_pointer_id_; + float down_x_; + float down_y_; + + public: + TapDetector(); + virtual ~TapDetector() {} + virtual GESTURE_STATE Detect(const AInputEvent* motion_event); +}; + +/****************************************************************** + * Pinch gesture detector + * Returns GESTURE_STATE_ACTION when a double-tap gesture is detected + * + */ +class DoubletapDetector : public GestureDetector { + private: + TapDetector tap_detector_; + int64_t last_tap_time_; + float last_tap_x_; + float last_tap_y_; + + public: + DoubletapDetector(); + virtual ~DoubletapDetector() {} + virtual GESTURE_STATE Detect(const AInputEvent* motion_event); + virtual void SetConfiguration(AConfiguration* config); +}; + +/****************************************************************** + * Double gesture detector + * Returns pinch gesture state when a pinch gesture is detected + * The class handles multiple touches more than 2 + * When the finger 1,2,3 are tapped and then finger 1 is released, + * the detector start new pinch gesture with finger 2 & 3. + */ +class PinchDetector : public GestureDetector { + private: + int32_t FindIndex(const AInputEvent* event, int32_t id); + const AInputEvent* event_; + std::vector<int32_t> vec_pointers_; + + public: + PinchDetector() {} + virtual ~PinchDetector() {} + virtual GESTURE_STATE Detect(const AInputEvent* event); + bool GetPointers(Vec2& v1, Vec2& v2); +}; + +/****************************************************************** + * Drag gesture detector + * Returns drag gesture state when a drag-tap gesture is detected + * + */ +class DragDetector : public GestureDetector { + private: + int32_t FindIndex(const AInputEvent* event, int32_t id); + const AInputEvent* event_; + std::vector<int32_t> vec_pointers_; + + public: + DragDetector() : event_(nullptr) {} + virtual ~DragDetector() {} + virtual GESTURE_STATE Detect(const AInputEvent* event); + bool GetPointer(Vec2& v); +}; + +} // namespace ndkHelper +#endif /* GESTUREDETECTOR_H_ */ diff --git a/NativeApp/Android/ndk_helper/include/gl3stub.h b/NativeApp/Android/ndk_helper/include/gl3stub.h new file mode 100644 index 0000000..4d28853 --- /dev/null +++ b/NativeApp/Android/ndk_helper/include/gl3stub.h @@ -0,0 +1,661 @@ +#ifndef __gl3_h_ +#define __gl3_h_ + +/* + * stub gl3.h for dynamic loading, based on: + * gl3.h last updated on $Date: 2013-02-12 14:37:24 -0800 (Tue, 12 Feb 2013) $ + * + * Changes: + * - Added #include <GLES2/gl2.h> + * - Removed duplicate OpenGL ES 2.0 declarations + * - Converted OpenGL ES 3.0 function prototypes to function pointer + * declarations + * - Added gl3stubInit() declaration + */ + +#include <GLES2/gl2.h> +#include <android/api-level.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/* + ** Copyright (c) 2007-2013 The Khronos Group Inc. + ** + ** Permission is hereby granted, free of charge, to any person obtaining a + ** copy of this software and/or associated documentation files (the + ** "Materials"), to deal in the Materials without restriction, including + ** without limitation the rights to use, copy, modify, merge, publish, + ** distribute, sublicense, and/or sell copies of the Materials, and to + ** permit persons to whom the Materials are 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 Materials. + ** + ** THE MATERIALS ARE 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 + ** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + */ + +/* + * This files is for apps that want to use ES3 if present, + * but continue to work on pre-API-18 devices. They can't just link to -lGLESv3 + *since + * that library doesn't exist on pre-API-18 devices. + * The function dynamically check if OpenGLES3.0 APIs are present and fill in if + *there are. + * Also the header defines some extra variables for OpenGLES3.0. + * + */ + +/* Call this function before calling any OpenGL ES 3.0 functions. It will + * return GL_TRUE if the OpenGL ES 3.0 was successfully initialized, GL_FALSE + * otherwise. */ +GLboolean gl3stubInit(); + +/*------------------------------------------------------------------------- + * Data type definitions + *-----------------------------------------------------------------------*/ + +/* OpenGL ES 3.0 */ + +typedef unsigned short GLhalf; +#if __ANDROID_API__ <= 19 +typedef khronos_int64_t GLint64; +typedef khronos_uint64_t GLuint64; +typedef struct __GLsync* GLsync; +#endif + +/*------------------------------------------------------------------------- + * Token definitions + *-----------------------------------------------------------------------*/ + +/* OpenGL ES core versions */ +#define GL_ES_VERSION_3_0 1 + +/* OpenGL ES 3.0 */ + +#define GL_READ_BUFFER 0x0C02 +#define GL_UNPACK_ROW_LENGTH 0x0CF2 +#define GL_UNPACK_SKIP_ROWS 0x0CF3 +#define GL_UNPACK_SKIP_PIXELS 0x0CF4 +#define GL_PACK_ROW_LENGTH 0x0D02 +#define GL_PACK_SKIP_ROWS 0x0D03 +#define GL_PACK_SKIP_PIXELS 0x0D04 +#define GL_COLOR 0x1800 +#define GL_DEPTH 0x1801 +#define GL_STENCIL 0x1802 +#define GL_RED 0x1903 +#define GL_RGB8 0x8051 +#define GL_RGBA8 0x8058 +#define GL_RGB10_A2 0x8059 +#define GL_TEXTURE_BINDING_3D 0x806A +#define GL_UNPACK_SKIP_IMAGES 0x806D +#define GL_UNPACK_IMAGE_HEIGHT 0x806E +#define GL_TEXTURE_3D 0x806F +#define GL_TEXTURE_WRAP_R 0x8072 +#define GL_MAX_3D_TEXTURE_SIZE 0x8073 +#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 +#define GL_MAX_ELEMENTS_VERTICES 0x80E8 +#define GL_MAX_ELEMENTS_INDICES 0x80E9 +#define GL_TEXTURE_MIN_LOD 0x813A +#define GL_TEXTURE_MAX_LOD 0x813B +#define GL_TEXTURE_BASE_LEVEL 0x813C +#define GL_TEXTURE_MAX_LEVEL 0x813D +#define GL_MIN 0x8007 +#define GL_MAX 0x8008 +#define GL_DEPTH_COMPONENT24 0x81A6 +#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD +#define GL_TEXTURE_COMPARE_MODE 0x884C +#define GL_TEXTURE_COMPARE_FUNC 0x884D +#define GL_CURRENT_QUERY 0x8865 +#define GL_QUERY_RESULT 0x8866 +#define GL_QUERY_RESULT_AVAILABLE 0x8867 +#define GL_BUFFER_MAPPED 0x88BC +#define GL_BUFFER_MAP_POINTER 0x88BD +#define GL_STREAM_READ 0x88E1 +#define GL_STREAM_COPY 0x88E2 +#define GL_STATIC_READ 0x88E5 +#define GL_STATIC_COPY 0x88E6 +#define GL_DYNAMIC_READ 0x88E9 +#define GL_DYNAMIC_COPY 0x88EA +#define GL_MAX_DRAW_BUFFERS 0x8824 +#define GL_DRAW_BUFFER0 0x8825 +#define GL_DRAW_BUFFER1 0x8826 +#define GL_DRAW_BUFFER2 0x8827 +#define GL_DRAW_BUFFER3 0x8828 +#define GL_DRAW_BUFFER4 0x8829 +#define GL_DRAW_BUFFER5 0x882A +#define GL_DRAW_BUFFER6 0x882B +#define GL_DRAW_BUFFER7 0x882C +#define GL_DRAW_BUFFER8 0x882D +#define GL_DRAW_BUFFER9 0x882E +#define GL_DRAW_BUFFER10 0x882F +#define GL_DRAW_BUFFER11 0x8830 +#define GL_DRAW_BUFFER12 0x8831 +#define GL_DRAW_BUFFER13 0x8832 +#define GL_DRAW_BUFFER14 0x8833 +#define GL_DRAW_BUFFER15 0x8834 +#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 +#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A +#define GL_SAMPLER_3D 0x8B5F +#define GL_SAMPLER_2D_SHADOW 0x8B62 +#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B +#define GL_PIXEL_PACK_BUFFER 0x88EB +#define GL_PIXEL_UNPACK_BUFFER 0x88EC +#define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED +#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF +#define GL_FLOAT_MAT2x3 0x8B65 +#define GL_FLOAT_MAT2x4 0x8B66 +#define GL_FLOAT_MAT3x2 0x8B67 +#define GL_FLOAT_MAT3x4 0x8B68 +#define GL_FLOAT_MAT4x2 0x8B69 +#define GL_FLOAT_MAT4x3 0x8B6A +#define GL_SRGB 0x8C40 +#define GL_SRGB8 0x8C41 +#define GL_SRGB8_ALPHA8 0x8C43 +#define GL_COMPARE_REF_TO_TEXTURE 0x884E +#define GL_MAJOR_VERSION 0x821B +#define GL_MINOR_VERSION 0x821C +#define GL_NUM_EXTENSIONS 0x821D +#define GL_RGBA32F 0x8814 +#define GL_RGB32F 0x8815 +#define GL_RGBA16F 0x881A +#define GL_RGB16F 0x881B +#define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD +#define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF +#define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 +#define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 +#define GL_MAX_VARYING_COMPONENTS 0x8B4B +#define GL_TEXTURE_2D_ARRAY 0x8C1A +#define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D +#define GL_R11F_G11F_B10F 0x8C3A +#define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B +#define GL_RGB9_E5 0x8C3D +#define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E +#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 +#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 +#define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 +#define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 +#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 +#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 +#define GL_RASTERIZER_DISCARD 0x8C89 +#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B +#define GL_INTERLEAVED_ATTRIBS 0x8C8C +#define GL_SEPARATE_ATTRIBS 0x8C8D +#define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E +#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F +#define GL_RGBA32UI 0x8D70 +#define GL_RGB32UI 0x8D71 +#define GL_RGBA16UI 0x8D76 +#define GL_RGB16UI 0x8D77 +#define GL_RGBA8UI 0x8D7C +#define GL_RGB8UI 0x8D7D +#define GL_RGBA32I 0x8D82 +#define GL_RGB32I 0x8D83 +#define GL_RGBA16I 0x8D88 +#define GL_RGB16I 0x8D89 +#define GL_RGBA8I 0x8D8E +#define GL_RGB8I 0x8D8F +#define GL_RED_INTEGER 0x8D94 +#define GL_RGB_INTEGER 0x8D98 +#define GL_RGBA_INTEGER 0x8D99 +#define GL_SAMPLER_2D_ARRAY 0x8DC1 +#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 +#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 +#define GL_UNSIGNED_INT_VEC2 0x8DC6 +#define GL_UNSIGNED_INT_VEC3 0x8DC7 +#define GL_UNSIGNED_INT_VEC4 0x8DC8 +#define GL_INT_SAMPLER_2D 0x8DCA +#define GL_INT_SAMPLER_3D 0x8DCB +#define GL_INT_SAMPLER_CUBE 0x8DCC +#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF +#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 +#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 +#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 +#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 +#define GL_BUFFER_ACCESS_FLAGS 0x911F +#define GL_BUFFER_MAP_LENGTH 0x9120 +#define GL_BUFFER_MAP_OFFSET 0x9121 +#define GL_DEPTH_COMPONENT32F 0x8CAC +#define GL_DEPTH32F_STENCIL8 0x8CAD +#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD +#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 +#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 +#define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 +#define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 +#define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 +#define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 +#define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 +#define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 +#define GL_FRAMEBUFFER_DEFAULT 0x8218 +#define GL_FRAMEBUFFER_UNDEFINED 0x8219 +#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A +#define GL_DEPTH_STENCIL 0x84F9 +#define GL_UNSIGNED_INT_24_8 0x84FA +#define GL_DEPTH24_STENCIL8 0x88F0 +#define GL_UNSIGNED_NORMALIZED 0x8C17 +#define GL_DRAW_FRAMEBUFFER_BINDING GL_FRAMEBUFFER_BINDING +#define GL_READ_FRAMEBUFFER 0x8CA8 +#define GL_DRAW_FRAMEBUFFER 0x8CA9 +#define GL_READ_FRAMEBUFFER_BINDING 0x8CAA +#define GL_RENDERBUFFER_SAMPLES 0x8CAB +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 +#define GL_MAX_COLOR_ATTACHMENTS 0x8CDF +#define GL_COLOR_ATTACHMENT1 0x8CE1 +#define GL_COLOR_ATTACHMENT2 0x8CE2 +#define GL_COLOR_ATTACHMENT3 0x8CE3 +#define GL_COLOR_ATTACHMENT4 0x8CE4 +#define GL_COLOR_ATTACHMENT5 0x8CE5 +#define GL_COLOR_ATTACHMENT6 0x8CE6 +#define GL_COLOR_ATTACHMENT7 0x8CE7 +#define GL_COLOR_ATTACHMENT8 0x8CE8 +#define GL_COLOR_ATTACHMENT9 0x8CE9 +#define GL_COLOR_ATTACHMENT10 0x8CEA +#define GL_COLOR_ATTACHMENT11 0x8CEB +#define GL_COLOR_ATTACHMENT12 0x8CEC +#define GL_COLOR_ATTACHMENT13 0x8CED +#define GL_COLOR_ATTACHMENT14 0x8CEE +#define GL_COLOR_ATTACHMENT15 0x8CEF +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 +#define GL_MAX_SAMPLES 0x8D57 +#define GL_HALF_FLOAT 0x140B +#define GL_MAP_READ_BIT 0x0001 +#define GL_MAP_WRITE_BIT 0x0002 +#define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 +#define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 +#define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 +#define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 +#define GL_RG 0x8227 +#define GL_RG_INTEGER 0x8228 +#define GL_R8 0x8229 +#define GL_RG8 0x822B +#define GL_R16F 0x822D +#define GL_R32F 0x822E +#define GL_RG16F 0x822F +#define GL_RG32F 0x8230 +#define GL_R8I 0x8231 +#define GL_R8UI 0x8232 +#define GL_R16I 0x8233 +#define GL_R16UI 0x8234 +#define GL_R32I 0x8235 +#define GL_R32UI 0x8236 +#define GL_RG8I 0x8237 +#define GL_RG8UI 0x8238 +#define GL_RG16I 0x8239 +#define GL_RG16UI 0x823A +#define GL_RG32I 0x823B +#define GL_RG32UI 0x823C +#define GL_VERTEX_ARRAY_BINDING 0x85B5 +#define GL_R8_SNORM 0x8F94 +#define GL_RG8_SNORM 0x8F95 +#define GL_RGB8_SNORM 0x8F96 +#define GL_RGBA8_SNORM 0x8F97 +#define GL_SIGNED_NORMALIZED 0x8F9C +#define GL_PRIMITIVE_RESTART_FIXED_INDEX 0x8D69 +#define GL_COPY_READ_BUFFER 0x8F36 +#define GL_COPY_WRITE_BUFFER 0x8F37 +#define GL_COPY_READ_BUFFER_BINDING GL_COPY_READ_BUFFER +#define GL_COPY_WRITE_BUFFER_BINDING GL_COPY_WRITE_BUFFER +#define GL_UNIFORM_BUFFER 0x8A11 +#define GL_UNIFORM_BUFFER_BINDING 0x8A28 +#define GL_UNIFORM_BUFFER_START 0x8A29 +#define GL_UNIFORM_BUFFER_SIZE 0x8A2A +#define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B +#define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D +#define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E +#define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F +#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 +#define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 +#define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 +#define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 +#define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 +#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 +#define GL_UNIFORM_TYPE 0x8A37 +#define GL_UNIFORM_SIZE 0x8A38 +#define GL_UNIFORM_NAME_LENGTH 0x8A39 +#define GL_UNIFORM_BLOCK_INDEX 0x8A3A +#define GL_UNIFORM_OFFSET 0x8A3B +#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C +#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D +#define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E +#define GL_UNIFORM_BLOCK_BINDING 0x8A3F +#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 +#define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 +#define GL_INVALID_INDEX 0xFFFFFFFFu +#define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122 +#define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125 +#define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111 +#define GL_OBJECT_TYPE 0x9112 +#define GL_SYNC_CONDITION 0x9113 +#define GL_SYNC_STATUS 0x9114 +#define GL_SYNC_FLAGS 0x9115 +#define GL_SYNC_FENCE 0x9116 +#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 +#define GL_UNSIGNALED 0x9118 +#define GL_SIGNALED 0x9119 +#define GL_ALREADY_SIGNALED 0x911A +#define GL_TIMEOUT_EXPIRED 0x911B +#define GL_CONDITION_SATISFIED 0x911C +#define GL_WAIT_FAILED 0x911D +#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 +#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull +#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE +#define GL_ANY_SAMPLES_PASSED 0x8C2F +#define GL_ANY_SAMPLES_PASSED_CONSERVATIVE 0x8D6A +#define GL_SAMPLER_BINDING 0x8919 +#define GL_RGB10_A2UI 0x906F +#define GL_TEXTURE_SWIZZLE_R 0x8E42 +#define GL_TEXTURE_SWIZZLE_G 0x8E43 +#define GL_TEXTURE_SWIZZLE_B 0x8E44 +#define GL_TEXTURE_SWIZZLE_A 0x8E45 +#define GL_GREEN 0x1904 +#define GL_BLUE 0x1905 +#define GL_INT_2_10_10_10_REV 0x8D9F +#define GL_TRANSFORM_FEEDBACK 0x8E22 +#define GL_TRANSFORM_FEEDBACK_PAUSED 0x8E23 +#define GL_TRANSFORM_FEEDBACK_ACTIVE 0x8E24 +#define GL_TRANSFORM_FEEDBACK_BINDING 0x8E25 +#define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 0x8257 +#define GL_PROGRAM_BINARY_LENGTH 0x8741 +#define GL_NUM_PROGRAM_BINARY_FORMATS 0x87FE +#define GL_PROGRAM_BINARY_FORMATS 0x87FF +#define GL_COMPRESSED_R11_EAC 0x9270 +#define GL_COMPRESSED_SIGNED_R11_EAC 0x9271 +#define GL_COMPRESSED_RG11_EAC 0x9272 +#define GL_COMPRESSED_SIGNED_RG11_EAC 0x9273 +#define GL_COMPRESSED_RGB8_ETC2 0x9274 +#define GL_COMPRESSED_SRGB8_ETC2 0x9275 +#define GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276 +#define GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9277 +#define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 +#define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279 +#define GL_TEXTURE_IMMUTABLE_FORMAT 0x912F +#define GL_MAX_ELEMENT_INDEX 0x8D6B +#define GL_NUM_SAMPLE_COUNTS 0x9380 +#define GL_TEXTURE_IMMUTABLE_LEVELS 0x82DF + +/*------------------------------------------------------------------------- + * Entrypoint definitions + *-----------------------------------------------------------------------*/ + +/* OpenGL ES 3.0 */ + +extern GL_APICALL void (*GL_APIENTRY glReadBuffer)(GLenum mode); +extern GL_APICALL void (*GL_APIENTRY glDrawRangeElements)( + GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, + const GLvoid* indices); +extern GL_APICALL void (*GL_APIENTRY glTexImage3D)( + GLenum target, GLint level, GLint internalformat, GLsizei width, + GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, + const GLvoid* pixels); +extern GL_APICALL void (*GL_APIENTRY glTexSubImage3D)( + GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, + GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, + const GLvoid* pixels); +extern GL_APICALL void (*GL_APIENTRY glCopyTexSubImage3D)( + GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, + GLint x, GLint y, GLsizei width, GLsizei height); +extern GL_APICALL void (*GL_APIENTRY glCompressedTexImage3D)( + GLenum target, GLint level, GLenum internalformat, GLsizei width, + GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, + const GLvoid* data); +extern GL_APICALL void (*GL_APIENTRY glCompressedTexSubImage3D)( + GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, + GLsizei width, GLsizei height, GLsizei depth, GLenum format, + GLsizei imageSize, const GLvoid* data); +extern GL_APICALL void (*GL_APIENTRY glGenQueries)(GLsizei n, GLuint* ids); +extern GL_APICALL void (*GL_APIENTRY glDeleteQueries)(GLsizei n, + const GLuint* ids); +extern GL_APICALL GLboolean (*GL_APIENTRY glIsQuery)(GLuint id); +extern GL_APICALL void (*GL_APIENTRY glBeginQuery)(GLenum target, GLuint id); +extern GL_APICALL void (*GL_APIENTRY glEndQuery)(GLenum target); +extern GL_APICALL void (*GL_APIENTRY glGetQueryiv)(GLenum target, GLenum pname, + GLint* params); +extern GL_APICALL void (*GL_APIENTRY glGetQueryObjectuiv)(GLuint id, + GLenum pname, + GLuint* params); +extern GL_APICALL GLboolean (*GL_APIENTRY glUnmapBuffer)(GLenum target); +extern GL_APICALL void (*GL_APIENTRY glGetBufferPointerv)(GLenum target, + GLenum pname, + GLvoid** params); +extern GL_APICALL void (*GL_APIENTRY glDrawBuffers)(GLsizei n, + const GLenum* bufs); +extern GL_APICALL void (*GL_APIENTRY glUniformMatrix2x3fv)( + GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); +extern GL_APICALL void (*GL_APIENTRY glUniformMatrix3x2fv)( + GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); +extern GL_APICALL void (*GL_APIENTRY glUniformMatrix2x4fv)( + GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); +extern GL_APICALL void (*GL_APIENTRY glUniformMatrix4x2fv)( + GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); +extern GL_APICALL void (*GL_APIENTRY glUniformMatrix3x4fv)( + GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); +extern GL_APICALL void (*GL_APIENTRY glUniformMatrix4x3fv)( + GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); +extern GL_APICALL void (*GL_APIENTRY glBlitFramebuffer)( + GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, + GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +extern GL_APICALL void (*GL_APIENTRY glRenderbufferStorageMultisample)( + GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, + GLsizei height); +extern GL_APICALL void (*GL_APIENTRY glFramebufferTextureLayer)( + GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +extern GL_APICALL GLvoid* (*GL_APIENTRY glMapBufferRange)(GLenum target, + GLintptr offset, + GLsizeiptr length, + GLbitfield access); +extern GL_APICALL void (*GL_APIENTRY glFlushMappedBufferRange)( + GLenum target, GLintptr offset, GLsizeiptr length); +extern GL_APICALL void (*GL_APIENTRY glBindVertexArray)(GLuint array); +extern GL_APICALL void (*GL_APIENTRY glDeleteVertexArrays)( + GLsizei n, const GLuint* arrays); +extern GL_APICALL void (*GL_APIENTRY glGenVertexArrays)(GLsizei n, + GLuint* arrays); +extern GL_APICALL GLboolean (*GL_APIENTRY glIsVertexArray)(GLuint array); +extern GL_APICALL void (*GL_APIENTRY glGetIntegeri_v)(GLenum target, + GLuint index, + GLint* data); +extern GL_APICALL void (*GL_APIENTRY glBeginTransformFeedback)( + GLenum primitiveMode); +extern GL_APICALL void (*GL_APIENTRY glEndTransformFeedback)(void); +extern GL_APICALL void (*GL_APIENTRY glBindBufferRange)(GLenum target, + GLuint index, + GLuint buffer, + GLintptr offset, + GLsizeiptr size); +extern GL_APICALL void (*GL_APIENTRY glBindBufferBase)(GLenum target, + GLuint index, + GLuint buffer); +extern GL_APICALL void (*GL_APIENTRY glTransformFeedbackVaryings)( + GLuint program, GLsizei count, const GLchar* const* varyings, + GLenum bufferMode); +extern GL_APICALL void (*GL_APIENTRY glGetTransformFeedbackVarying)( + GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, + GLsizei* size, GLenum* type, GLchar* name); +extern GL_APICALL void (*GL_APIENTRY glVertexAttribIPointer)( + GLuint index, GLint size, GLenum type, GLsizei stride, + const GLvoid* pointer); +extern GL_APICALL void (*GL_APIENTRY glGetVertexAttribIiv)(GLuint index, + GLenum pname, + GLint* params); +extern GL_APICALL void (*GL_APIENTRY glGetVertexAttribIuiv)(GLuint index, + GLenum pname, + GLuint* params); +extern GL_APICALL void (*GL_APIENTRY glVertexAttribI4i)(GLuint index, GLint x, + GLint y, GLint z, + GLint w); +extern GL_APICALL void (*GL_APIENTRY glVertexAttribI4ui)(GLuint index, GLuint x, + GLuint y, GLuint z, + GLuint w); +extern GL_APICALL void (*GL_APIENTRY glVertexAttribI4iv)(GLuint index, + const GLint* v); +extern GL_APICALL void (*GL_APIENTRY glVertexAttribI4uiv)(GLuint index, + const GLuint* v); +extern GL_APICALL void (*GL_APIENTRY glGetUniformuiv)(GLuint program, + GLint location, + GLuint* params); +extern GL_APICALL GLint (*GL_APIENTRY glGetFragDataLocation)( + GLuint program, const GLchar* name); +extern GL_APICALL void (*GL_APIENTRY glUniform1ui)(GLint location, GLuint v0); +extern GL_APICALL void (*GL_APIENTRY glUniform2ui)(GLint location, GLuint v0, + GLuint v1); +extern GL_APICALL void (*GL_APIENTRY glUniform3ui)(GLint location, GLuint v0, + GLuint v1, GLuint v2); +extern GL_APICALL void (*GL_APIENTRY glUniform4ui)(GLint location, GLuint v0, + GLuint v1, GLuint v2, + GLuint v3); +extern GL_APICALL void (*GL_APIENTRY glUniform1uiv)(GLint location, + GLsizei count, + const GLuint* value); +extern GL_APICALL void (*GL_APIENTRY glUniform2uiv)(GLint location, + GLsizei count, + const GLuint* value); +extern GL_APICALL void (*GL_APIENTRY glUniform3uiv)(GLint location, + GLsizei count, + const GLuint* value); +extern GL_APICALL void (*GL_APIENTRY glUniform4uiv)(GLint location, + GLsizei count, + const GLuint* value); +extern GL_APICALL void (*GL_APIENTRY glClearBufferiv)(GLenum buffer, + GLint drawbuffer, + const GLint* value); +extern GL_APICALL void (*GL_APIENTRY glClearBufferuiv)(GLenum buffer, + GLint drawbuffer, + const GLuint* value); +extern GL_APICALL void (*GL_APIENTRY glClearBufferfv)(GLenum buffer, + GLint drawbuffer, + const GLfloat* value); +extern GL_APICALL void (*GL_APIENTRY glClearBufferfi)(GLenum buffer, + GLint drawbuffer, + GLfloat depth, + GLint stencil); +extern GL_APICALL const GLubyte* (*GL_APIENTRY glGetStringi)(GLenum name, + GLuint index); +extern GL_APICALL void (*GL_APIENTRY glCopyBufferSubData)(GLenum readTarget, + GLenum writeTarget, + GLintptr readOffset, + GLintptr writeOffset, + GLsizeiptr size); +extern GL_APICALL void (*GL_APIENTRY glGetUniformIndices)( + GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, + GLuint* uniformIndices); +extern GL_APICALL void (*GL_APIENTRY glGetActiveUniformsiv)( + GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, + GLenum pname, GLint* params); +extern GL_APICALL GLuint (*GL_APIENTRY glGetUniformBlockIndex)( + GLuint program, const GLchar* uniformBlockName); +extern GL_APICALL void (*GL_APIENTRY glGetActiveUniformBlockiv)( + GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params); +extern GL_APICALL void (*GL_APIENTRY glGetActiveUniformBlockName)( + GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, + GLchar* uniformBlockName); +extern GL_APICALL void (*GL_APIENTRY glUniformBlockBinding)( + GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); +extern GL_APICALL void (*GL_APIENTRY glDrawArraysInstanced)( + GLenum mode, GLint first, GLsizei count, GLsizei instanceCount); +extern GL_APICALL void (*GL_APIENTRY glDrawElementsInstanced)( + GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, + GLsizei instanceCount); +extern GL_APICALL GLsync (*GL_APIENTRY glFenceSync)(GLenum condition, + GLbitfield flags); +extern GL_APICALL GLboolean (*GL_APIENTRY glIsSync)(GLsync sync); +extern GL_APICALL void (*GL_APIENTRY glDeleteSync)(GLsync sync); +extern GL_APICALL GLenum (*GL_APIENTRY glClientWaitSync)(GLsync sync, + GLbitfield flags, + GLuint64 timeout); +extern GL_APICALL void (*GL_APIENTRY glWaitSync)(GLsync sync, GLbitfield flags, + GLuint64 timeout); +extern GL_APICALL void (*GL_APIENTRY glGetInteger64v)(GLenum pname, + GLint64* params); +extern GL_APICALL void (*GL_APIENTRY glGetSynciv)(GLsync sync, GLenum pname, + GLsizei bufSize, + GLsizei* length, + GLint* values); +extern GL_APICALL void (*GL_APIENTRY glGetInteger64i_v)(GLenum target, + GLuint index, + GLint64* data); +extern GL_APICALL void (*GL_APIENTRY glGetBufferParameteri64v)(GLenum target, + GLenum pname, + GLint64* params); +extern GL_APICALL void (*GL_APIENTRY glGenSamplers)(GLsizei count, + GLuint* samplers); +extern GL_APICALL void (*GL_APIENTRY glDeleteSamplers)(GLsizei count, + const GLuint* samplers); +extern GL_APICALL GLboolean (*GL_APIENTRY glIsSampler)(GLuint sampler); +extern GL_APICALL void (*GL_APIENTRY glBindSampler)(GLuint unit, + GLuint sampler); +extern GL_APICALL void (*GL_APIENTRY glSamplerParameteri)(GLuint sampler, + GLenum pname, + GLint param); +extern GL_APICALL void (*GL_APIENTRY glSamplerParameteriv)(GLuint sampler, + GLenum pname, + const GLint* param); +extern GL_APICALL void (*GL_APIENTRY glSamplerParameterf)(GLuint sampler, + GLenum pname, + GLfloat param); +extern GL_APICALL void (*GL_APIENTRY glSamplerParameterfv)( + GLuint sampler, GLenum pname, const GLfloat* param); +extern GL_APICALL void (*GL_APIENTRY glGetSamplerParameteriv)(GLuint sampler, + GLenum pname, + GLint* params); +extern GL_APICALL void (*GL_APIENTRY glGetSamplerParameterfv)(GLuint sampler, + GLenum pname, + GLfloat* params); +extern GL_APICALL void (*GL_APIENTRY glVertexAttribDivisor)(GLuint index, + GLuint divisor); +extern GL_APICALL void (*GL_APIENTRY glBindTransformFeedback)(GLenum target, + GLuint id); +extern GL_APICALL void (*GL_APIENTRY glDeleteTransformFeedbacks)( + GLsizei n, const GLuint* ids); +extern GL_APICALL void (*GL_APIENTRY glGenTransformFeedbacks)(GLsizei n, + GLuint* ids); +extern GL_APICALL GLboolean (*GL_APIENTRY glIsTransformFeedback)(GLuint id); +extern GL_APICALL void (*GL_APIENTRY glPauseTransformFeedback)(void); +extern GL_APICALL void (*GL_APIENTRY glResumeTransformFeedback)(void); +extern GL_APICALL void (*GL_APIENTRY glGetProgramBinary)(GLuint program, + GLsizei bufSize, + GLsizei* length, + GLenum* binaryFormat, + GLvoid* binary); +extern GL_APICALL void (*GL_APIENTRY glProgramBinary)(GLuint program, + GLenum binaryFormat, + const GLvoid* binary, + GLsizei length); +extern GL_APICALL void (*GL_APIENTRY glProgramParameteri)(GLuint program, + GLenum pname, + GLint value); +extern GL_APICALL void (*GL_APIENTRY glInvalidateFramebuffer)( + GLenum target, GLsizei numAttachments, const GLenum* attachments); +extern GL_APICALL void (*GL_APIENTRY glInvalidateSubFramebuffer)( + GLenum target, GLsizei numAttachments, const GLenum* attachments, GLint x, + GLint y, GLsizei width, GLsizei height); +extern GL_APICALL void (*GL_APIENTRY glTexStorage2D)(GLenum target, + GLsizei levels, + GLenum internalformat, + GLsizei width, + GLsizei height); +extern GL_APICALL void (*GL_APIENTRY glTexStorage3D)( + GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, + GLsizei height, GLsizei depth); +extern GL_APICALL void (*GL_APIENTRY glGetInternalformativ)( + GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, + GLint* params); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/NativeApp/Android/ndk_helper/include/interpolator.h b/NativeApp/Android/ndk_helper/include/interpolator.h new file mode 100644 index 0000000..c198bc8 --- /dev/null +++ b/NativeApp/Android/ndk_helper/include/interpolator.h @@ -0,0 +1,80 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERPOLATOR_H_ +#define INTERPOLATOR_H_ + +#include <jni.h> +#include <errno.h> +#include <time.h> +#include "JNIHelper.h" +#include "perfMonitor.h" +#include <list> + +namespace ndk_helper { + +enum INTERPOLATOR_TYPE { + INTERPOLATOR_TYPE_LINEAR, + INTERPOLATOR_TYPE_EASEINQUAD, + INTERPOLATOR_TYPE_EASEOUTQUAD, + INTERPOLATOR_TYPE_EASEINOUTQUAD, + INTERPOLATOR_TYPE_EASEINCUBIC, + INTERPOLATOR_TYPE_EASEOUTCUBIC, + INTERPOLATOR_TYPE_EASEINOUTCUBIC, + INTERPOLATOR_TYPE_EASEINQUART, + INTERPOLATOR_TYPE_EASEINEXPO, + INTERPOLATOR_TYPE_EASEOUTEXPO, +}; + +struct InterpolatorParams { + float dest_value_; + INTERPOLATOR_TYPE type_; + double duration_; +}; + +/****************************************************************** + * Interpolates values with several interpolation methods + */ +class Interpolator { + private: + double start_time_; + double dest_time_; + INTERPOLATOR_TYPE type_; + + float start_value_; + float dest_value_; + std::list<InterpolatorParams> list_params_; + + float GetFormula(const INTERPOLATOR_TYPE type, const float t, const float b, + const float d, const float c); + + public: + Interpolator(); + ~Interpolator(); + + Interpolator& Set(const float start, const float dest, + const INTERPOLATOR_TYPE type, double duration); + + Interpolator& Add(const float dest, const INTERPOLATOR_TYPE type, + const double duration); + + bool Update(const double currentTime, float& p); + + void Clear(); +}; + +} // namespace ndkHelper +#endif /* INTERPOLATOR_H_ */ diff --git a/NativeApp/Android/ndk_helper/include/perfMonitor.h b/NativeApp/Android/ndk_helper/include/perfMonitor.h new file mode 100644 index 0000000..432569a --- /dev/null +++ b/NativeApp/Android/ndk_helper/include/perfMonitor.h @@ -0,0 +1,59 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERFMONITOR_H_ +#define PERFMONITOR_H_ + +#include <jni.h> +#include <errno.h> +#include <time.h> +#include "JNIHelper.h" + +namespace ndk_helper { + +const int32_t kNumSamples = 100; + +/****************************************************************** + * Helper class for a performance monitoring and get current tick time + */ +class PerfMonitor { + private: + float current_FPS_; + time_t tv_last_sec_; + + double last_tick_; + int32_t tickindex_; + double ticksum_; + double ticklist_[kNumSamples]; + + double UpdateTick(double current_tick); + + public: + PerfMonitor(); + virtual ~PerfMonitor(); + + bool Update(float &fFPS); + + static double GetCurrentTime() { + struct timeval time; + gettimeofday(&time, NULL); + double ret = time.tv_sec + time.tv_usec * 1.0 / 1000000.0; + return ret; + } +}; + +} // namespace ndkHelper +#endif /* PERFMONITOR_H_ */ diff --git a/NativeApp/Android/ndk_helper/include/sensorManager.h b/NativeApp/Android/ndk_helper/include/sensorManager.h new file mode 100644 index 0000000..d0b77f8 --- /dev/null +++ b/NativeApp/Android/ndk_helper/include/sensorManager.h @@ -0,0 +1,64 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//-------------------------------------------------------------------------------- +// sensorManager.h +//-------------------------------------------------------------------------------- +#ifndef SENSORMANAGER_H_ +#define SENSORMANAGER_H_ + +#include <android/sensor.h> +#include "JNIHelper.h" + +namespace ndk_helper { +//-------------------------------------------------------------------------------- +// Constants +//-------------------------------------------------------------------------------- +enum ORIENTATION { + ORIENTATION_UNKNOWN = -1, + ORIENTATION_PORTRAIT = 0, + ORIENTATION_LANDSCAPE = 1, + ORIENTATION_REVERSE_PORTRAIT = 2, + ORIENTATION_REVERSE_LANDSCAPE = 3, +}; + +/* + * Helper to handle sensor inputs such as accelerometer. + * The helper also check for screen rotation + * + */ +class SensorManager { + ASensorManager *sensorManager_; + const ASensor *accelerometerSensor_; + ASensorEventQueue *sensorEventQueue_; + + protected: + public: + SensorManager(); + ~SensorManager(); + void Init(android_app *state); + void Suspend(); + void Resume(); +}; + +/* + * AcquireASensorManagerInstance(android_app* app) + * Workaround ASensorManager_getInstance() deprecation false alarm + * for Android-N and before, when compiling with NDK-r15 + */ +ASensorManager* AcquireASensorManagerInstance(android_app* app); +} // namespace ndkHelper +#endif /* SENSORMANAGER_H_ */ diff --git a/NativeApp/Android/ndk_helper/include/shader.h b/NativeApp/Android/ndk_helper/include/shader.h new file mode 100644 index 0000000..39a2ec9 --- /dev/null +++ b/NativeApp/Android/ndk_helper/include/shader.h @@ -0,0 +1,120 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SHADER_H_ +#define SHADER_H_ + +#include <jni.h> + +#include <vector> +#include <map> +#include <string> + +#include <EGL/egl.h> +#include <GLES/gl.h> + +#include <android/log.h> + +#include "JNIHelper.h" + +namespace ndk_helper { + +namespace shader { + +/****************************************************************** + * Shader compiler helper + * namespace: ndkHelper::shader + * + */ + +/****************************************************************** + * CompileShader() with vector + * + * arguments: + * out: shader, shader variable + * in: type, shader type (i.e. GL_VERTEX_SHADER/GL_FRAGMENT_SHADER) + * in: data, source vector + * return: true if a shader compilation succeeded, false if it failed + * + */ +bool CompileShader(GLuint *shader, const GLenum type, + std::vector<uint8_t> &data); + +/****************************************************************** + * CompileShader() with buffer + * + * arguments: + * out: shader, shader variable + * in: type, shader type (i.e. GL_VERTEX_SHADER/GL_FRAGMENT_SHADER) + * in: source, source buffer + * in: iSize, buffer size + * return: true if a shader compilation succeeded, false if it failed + * + */ +bool CompileShader(GLuint *shader, const GLenum type, const GLchar *source, + const int32_t iSize); + +/****************************************************************** + * CompileShader() with filename + * + * arguments: + * out: shader, shader variable + * in: type, shader type (i.e. GL_VERTEX_SHADER/GL_FRAGMENT_SHADER) + * in: strFilename, filename + * return: true if a shader compilation succeeded, false if it failed + * + */ +bool CompileShader(GLuint *shader, const GLenum type, const char *strFileName); + +/****************************************************************** + * CompileShader() with std::map helps patching on a shader on the fly. + * + * arguments: + * out: shader, shader variable + * in: type, shader type (i.e. GL_VERTEX_SHADER/GL_FRAGMENT_SHADER) + * in: mapParameters + * For a example, + * map : %KEY% -> %VALUE% replaces all %KEY% entries in the given shader + *code to %VALUE" + * return: true if a shader compilation succeeded, false if it failed + * + */ +bool CompileShader(GLuint *shader, const GLenum type, const char *str_file_name, + const std::map<std::string, std::string> &map_parameters); + +/****************************************************************** + * LinkProgram() + * + * arguments: + * in: program, program + * return: true if a shader linkage succeeded, false if it failed + * + */ +bool LinkProgram(const GLuint prog); + +/****************************************************************** + * validateProgram() + * + * arguments: + * in: program, program + * return: true if a shader validation succeeded, false if it failed + * + */ +bool ValidateProgram(const GLuint prog); +} // namespace shader + +} // namespace ndkHelper +#endif /* SHADER_H_ */ diff --git a/NativeApp/Android/ndk_helper/include/tapCamera.h b/NativeApp/Android/ndk_helper/include/tapCamera.h new file mode 100644 index 0000000..ea6266f --- /dev/null +++ b/NativeApp/Android/ndk_helper/include/tapCamera.h @@ -0,0 +1,110 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once +#include <vector> +#include <string> +#include <GLES2/gl2.h> + +#include "JNIHelper.h" +#include "vecmath.h" +#include "interpolator.h" + +namespace ndk_helper { + +/****************************************************************** + * Camera control helper class with a tap gesture + * This class is mainly used for 3D space camera control in samples. + * + */ +class TapCamera { + private: + // Trackball + Vec2 vec_ball_center_; + float ball_radius_; + Quaternion quat_ball_now_; + Quaternion quat_ball_down_; + Vec2 vec_ball_now_; + Vec2 vec_ball_down_; + Quaternion quat_ball_rot_; + + bool dragging_; + bool pinching_; + + // Pinch related info + Vec2 vec_pinch_start_; + Vec2 vec_pinch_start_center_; + float pinch_start_distance_SQ_; + + // Camera shift + Vec3 vec_offset_; + Vec3 vec_offset_now_; + + // Camera Rotation + float camera_rotation_; + float camera_rotation_start_; + float camera_rotation_now_; + + // Momentum support + bool momentum_; + double time_stamp_; + Vec2 vec_drag_delta_; + Vec2 vec_last_input_; + Vec3 vec_offset_last_; + Vec3 vec_offset_delta_; + float momemtum_steps_; + + Vec2 vec_flip_; + float flip_z_; + + Mat4 mat_rotation_; + Mat4 mat_transform_; + + Vec3 vec_pinch_transform_factor_; + + Vec3 PointOnSphere(Vec2& point); + void BallUpdate(); + void InitParameters(); + + public: + TapCamera(); + virtual ~TapCamera(); + void BeginDrag(const Vec2& vec); + void EndDrag(); + void Drag(const Vec2& vec); + void Update(); + void Update(const double time); + + Mat4& GetRotationMatrix(); + Mat4& GetTransformMatrix(); + + void BeginPinch(const Vec2& v1, const Vec2& v2); + void EndPinch(); + void Pinch(const Vec2& v1, const Vec2& v2); + + void SetFlip(const float x, const float y, const float z) { + vec_flip_ = Vec2(x, y); + flip_z_ = z; + } + + void SetPinchTransformFactor(const float x, const float y, const float z) { + vec_pinch_transform_factor_ = Vec3(x, y, z); + } + + void Reset(const bool bAnimate); +}; + +} // namespace ndkHelper diff --git a/NativeApp/Android/ndk_helper/include/vecmath.h b/NativeApp/Android/ndk_helper/include/vecmath.h new file mode 100644 index 0000000..a4ba481 --- /dev/null +++ b/NativeApp/Android/ndk_helper/include/vecmath.h @@ -0,0 +1,965 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef VECMATH_H_ +#define VECMATH_H_ + +#include <cmath> +#include "JNIHelper.h" + +namespace ndk_helper { + +/****************************************************************** + * Helper class for vector math operations + * Currently all implementations are in pure C++. + * Each class is an opaque class so caller does not have a direct access + * to each element. This is for an ease of future optimization to use vector + *operations. + * + */ + +class Vec2; +class Vec3; +class Vec4; +class Mat4; + +/****************************************************************** + * 2 elements vector class + * + */ +class Vec2 { + private: + float x_; + float y_; + + public: + friend class Vec3; + friend class Vec4; + friend class Mat4; + friend class Quaternion; + + Vec2() { x_ = y_ = 0.f; } + + Vec2(const float fX, const float fY) { + x_ = fX; + y_ = fY; + } + + Vec2(const Vec2& vec) { + x_ = vec.x_; + y_ = vec.y_; + } + + Vec2(const float* pVec) { + x_ = (*pVec++); + y_ = (*pVec++); + } + + // Operators + Vec2 operator*(const Vec2& rhs) const { + Vec2 ret; + ret.x_ = x_ * rhs.x_; + ret.y_ = y_ * rhs.y_; + return ret; + } + + Vec2 operator/(const Vec2& rhs) const { + Vec2 ret; + ret.x_ = x_ / rhs.x_; + ret.y_ = y_ / rhs.y_; + return ret; + } + + Vec2 operator+(const Vec2& rhs) const { + Vec2 ret; + ret.x_ = x_ + rhs.x_; + ret.y_ = y_ + rhs.y_; + return ret; + } + + Vec2 operator-(const Vec2& rhs) const { + Vec2 ret; + ret.x_ = x_ - rhs.x_; + ret.y_ = y_ - rhs.y_; + return ret; + } + + Vec2& operator+=(const Vec2& rhs) { + x_ += rhs.x_; + y_ += rhs.y_; + return *this; + } + + Vec2& operator-=(const Vec2& rhs) { + x_ -= rhs.x_; + y_ -= rhs.y_; + return *this; + } + + Vec2& operator*=(const Vec2& rhs) { + x_ *= rhs.x_; + y_ *= rhs.y_; + return *this; + } + + Vec2& operator/=(const Vec2& rhs) { + x_ /= rhs.x_; + y_ /= rhs.y_; + return *this; + } + + // External operators + friend Vec2 operator-(const Vec2& rhs) { return Vec2(rhs) *= -1; } + + friend Vec2 operator*(const float lhs, const Vec2& rhs) { + Vec2 ret; + ret.x_ = lhs * rhs.x_; + ret.y_ = lhs * rhs.y_; + return ret; + } + + friend Vec2 operator/(const float lhs, const Vec2& rhs) { + Vec2 ret; + ret.x_ = lhs / rhs.x_; + ret.y_ = lhs / rhs.y_; + return ret; + } + + // Operators with float + Vec2 operator*(const float& rhs) const { + Vec2 ret; + ret.x_ = x_ * rhs; + ret.y_ = y_ * rhs; + return ret; + } + + Vec2& operator*=(const float& rhs) { + x_ = x_ * rhs; + y_ = y_ * rhs; + return *this; + } + + Vec2 operator/(const float& rhs) const { + Vec2 ret; + ret.x_ = x_ / rhs; + ret.y_ = y_ / rhs; + return ret; + } + + Vec2& operator/=(const float& rhs) { + x_ = x_ / rhs; + y_ = y_ / rhs; + return *this; + } + + // Compare + bool operator==(const Vec2& rhs) const { + if (x_ != rhs.x_ || y_ != rhs.y_) return false; + return true; + } + + bool operator!=(const Vec2& rhs) const { + if (x_ == rhs.x_) return false; + + return true; + } + + float Length() const { return sqrtf(x_ * x_ + y_ * y_); } + + Vec2 Normalize() { + float len = Length(); + x_ = x_ / len; + y_ = y_ / len; + return *this; + } + + float Dot(const Vec2& rhs) { return x_ * rhs.x_ + y_ * rhs.y_; } + + bool Validate() { + if (std::isnan(x_) || std::isnan(y_)) return false; + return true; + } + + void Value(float& fX, float& fY) { + fX = x_; + fY = y_; + } + + void Dump() { LOGI("Vec2 %f %f", x_, y_); } +}; + +/****************************************************************** + * 3 elements vector class + * + */ +class Vec3 { + private: + float x_, y_, z_; + + public: + friend class Vec4; + friend class Mat4; + friend class Quaternion; + + Vec3() { x_ = y_ = z_ = 0.f; } + + Vec3(const float fX, const float fY, const float fZ) { + x_ = fX; + y_ = fY; + z_ = fZ; + } + + Vec3(const Vec3& vec) { + x_ = vec.x_; + y_ = vec.y_; + z_ = vec.z_; + } + + Vec3(const float* pVec) { + x_ = (*pVec++); + y_ = (*pVec++); + z_ = *pVec; + } + + Vec3(const Vec2& vec, float f) { + x_ = vec.x_; + y_ = vec.y_; + z_ = f; + } + + Vec3(const Vec4& vec); + + // Operators + Vec3 operator*(const Vec3& rhs) const { + Vec3 ret; + ret.x_ = x_ * rhs.x_; + ret.y_ = y_ * rhs.y_; + ret.z_ = z_ * rhs.z_; + return ret; + } + + Vec3 operator/(const Vec3& rhs) const { + Vec3 ret; + ret.x_ = x_ / rhs.x_; + ret.y_ = y_ / rhs.y_; + ret.z_ = z_ / rhs.z_; + return ret; + } + + Vec3 operator+(const Vec3& rhs) const { + Vec3 ret; + ret.x_ = x_ + rhs.x_; + ret.y_ = y_ + rhs.y_; + ret.z_ = z_ + rhs.z_; + return ret; + } + + Vec3 operator-(const Vec3& rhs) const { + Vec3 ret; + ret.x_ = x_ - rhs.x_; + ret.y_ = y_ - rhs.y_; + ret.z_ = z_ - rhs.z_; + return ret; + } + + Vec3& operator+=(const Vec3& rhs) { + x_ += rhs.x_; + y_ += rhs.y_; + z_ += rhs.z_; + return *this; + } + + Vec3& operator-=(const Vec3& rhs) { + x_ -= rhs.x_; + y_ -= rhs.y_; + z_ -= rhs.z_; + return *this; + } + + Vec3& operator*=(const Vec3& rhs) { + x_ *= rhs.x_; + y_ *= rhs.y_; + z_ *= rhs.z_; + return *this; + } + + Vec3& operator/=(const Vec3& rhs) { + x_ /= rhs.x_; + y_ /= rhs.y_; + z_ /= rhs.z_; + return *this; + } + + // External operators + friend Vec3 operator-(const Vec3& rhs) { return Vec3(rhs) *= -1; } + + friend Vec3 operator*(const float lhs, const Vec3& rhs) { + Vec3 ret; + ret.x_ = lhs * rhs.x_; + ret.y_ = lhs * rhs.y_; + ret.z_ = lhs * rhs.z_; + return ret; + } + + friend Vec3 operator/(const float lhs, const Vec3& rhs) { + Vec3 ret; + ret.x_ = lhs / rhs.x_; + ret.y_ = lhs / rhs.y_; + ret.z_ = lhs / rhs.z_; + return ret; + } + + // Operators with float + Vec3 operator*(const float& rhs) const { + Vec3 ret; + ret.x_ = x_ * rhs; + ret.y_ = y_ * rhs; + ret.z_ = z_ * rhs; + return ret; + } + + Vec3& operator*=(const float& rhs) { + x_ = x_ * rhs; + y_ = y_ * rhs; + z_ = z_ * rhs; + return *this; + } + + Vec3 operator/(const float& rhs) const { + Vec3 ret; + ret.x_ = x_ / rhs; + ret.y_ = y_ / rhs; + ret.z_ = z_ / rhs; + return ret; + } + + Vec3& operator/=(const float& rhs) { + x_ = x_ / rhs; + y_ = y_ / rhs; + z_ = z_ / rhs; + return *this; + } + + // Compare + bool operator==(const Vec3& rhs) const { + if (x_ != rhs.x_ || y_ != rhs.y_ || z_ != rhs.z_) return false; + return true; + } + + bool operator!=(const Vec3& rhs) const { + if (x_ == rhs.x_) return false; + + return true; + } + + float Length() const { return sqrtf(x_ * x_ + y_ * y_ + z_ * z_); } + + Vec3 Normalize() { + float len = Length(); + x_ = x_ / len; + y_ = y_ / len; + z_ = z_ / len; + return *this; + } + + float Dot(const Vec3& rhs) { return x_ * rhs.x_ + y_ * rhs.y_ + z_ * rhs.z_; } + + Vec3 Cross(const Vec3& rhs) { + Vec3 ret; + ret.x_ = y_ * rhs.z_ - z_ * rhs.y_; + ret.y_ = z_ * rhs.x_ - x_ * rhs.z_; + ret.z_ = x_ * rhs.y_ - y_ * rhs.x_; + return ret; + } + + bool Validate() { + if (std::isnan(x_) || std::isnan(y_) || std::isnan(z_)) return false; + return true; + } + + void Value(float& fX, float& fY, float& fZ) { + fX = x_; + fY = y_; + fZ = z_; + } + + void Dump() { LOGI("Vec3 %f %f %f", x_, y_, z_); } +}; + +/****************************************************************** + * 4 elements vector class + * + */ +class Vec4 { + private: + float x_, y_, z_, w_; + + public: + friend class Vec3; + friend class Mat4; + friend class Quaternion; + + Vec4() { x_ = y_ = z_ = w_ = 0.f; } + + Vec4(const float fX, const float fY, const float fZ, const float fW) { + x_ = fX; + y_ = fY; + z_ = fZ; + w_ = fW; + } + + Vec4(const Vec4& vec) { + x_ = vec.x_; + y_ = vec.y_; + z_ = vec.z_; + w_ = vec.w_; + } + + Vec4(const Vec3& vec, const float fW) { + x_ = vec.x_; + y_ = vec.y_; + z_ = vec.z_; + w_ = fW; + } + + Vec4(const float* pVec) { + x_ = (*pVec++); + y_ = (*pVec++); + z_ = *pVec; + w_ = *pVec; + } + + // Operators + Vec4 operator*(const Vec4& rhs) const { + Vec4 ret; + ret.x_ = x_ * rhs.x_; + ret.y_ = y_ * rhs.y_; + ret.z_ = z_ * rhs.z_; + ret.w_ = z_ * rhs.w_; + return ret; + } + + Vec4 operator/(const Vec4& rhs) const { + Vec4 ret; + ret.x_ = x_ / rhs.x_; + ret.y_ = y_ / rhs.y_; + ret.z_ = z_ / rhs.z_; + ret.w_ = z_ / rhs.w_; + return ret; + } + + Vec4 operator+(const Vec4& rhs) const { + Vec4 ret; + ret.x_ = x_ + rhs.x_; + ret.y_ = y_ + rhs.y_; + ret.z_ = z_ + rhs.z_; + ret.w_ = z_ + rhs.w_; + return ret; + } + + Vec4 operator-(const Vec4& rhs) const { + Vec4 ret; + ret.x_ = x_ - rhs.x_; + ret.y_ = y_ - rhs.y_; + ret.z_ = z_ - rhs.z_; + ret.w_ = z_ - rhs.w_; + return ret; + } + + Vec4& operator+=(const Vec4& rhs) { + x_ += rhs.x_; + y_ += rhs.y_; + z_ += rhs.z_; + w_ += rhs.w_; + return *this; + } + + Vec4& operator-=(const Vec4& rhs) { + x_ -= rhs.x_; + y_ -= rhs.y_; + z_ -= rhs.z_; + w_ -= rhs.w_; + return *this; + } + + Vec4& operator*=(const Vec4& rhs) { + x_ *= rhs.x_; + y_ *= rhs.y_; + z_ *= rhs.z_; + w_ *= rhs.w_; + return *this; + } + + Vec4& operator/=(const Vec4& rhs) { + x_ /= rhs.x_; + y_ /= rhs.y_; + z_ /= rhs.z_; + w_ /= rhs.w_; + return *this; + } + + // External operators + friend Vec4 operator-(const Vec4& rhs) { return Vec4(rhs) *= -1; } + + friend Vec4 operator*(const float lhs, const Vec4& rhs) { + Vec4 ret; + ret.x_ = lhs * rhs.x_; + ret.y_ = lhs * rhs.y_; + ret.z_ = lhs * rhs.z_; + ret.w_ = lhs * rhs.w_; + return ret; + } + + friend Vec4 operator/(const float lhs, const Vec4& rhs) { + Vec4 ret; + ret.x_ = lhs / rhs.x_; + ret.y_ = lhs / rhs.y_; + ret.z_ = lhs / rhs.z_; + ret.w_ = lhs / rhs.w_; + return ret; + } + + // Operators with float + Vec4 operator*(const float& rhs) const { + Vec4 ret; + ret.x_ = x_ * rhs; + ret.y_ = y_ * rhs; + ret.z_ = z_ * rhs; + ret.w_ = w_ * rhs; + return ret; + } + + Vec4& operator*=(const float& rhs) { + x_ = x_ * rhs; + y_ = y_ * rhs; + z_ = z_ * rhs; + w_ = w_ * rhs; + return *this; + } + + Vec4 operator/(const float& rhs) const { + Vec4 ret; + ret.x_ = x_ / rhs; + ret.y_ = y_ / rhs; + ret.z_ = z_ / rhs; + ret.w_ = w_ / rhs; + return ret; + } + + Vec4& operator/=(const float& rhs) { + x_ = x_ / rhs; + y_ = y_ / rhs; + z_ = z_ / rhs; + w_ = w_ / rhs; + return *this; + } + + // Compare + bool operator==(const Vec4& rhs) const { + if (x_ != rhs.x_ || y_ != rhs.y_ || z_ != rhs.z_ || w_ != rhs.w_) + return false; + return true; + } + + bool operator!=(const Vec4& rhs) const { + if (x_ == rhs.x_) return false; + + return true; + } + + Vec4 operator*(const Mat4& rhs) const; + + float Length() const { return sqrtf(x_ * x_ + y_ * y_ + z_ * z_ + w_ * w_); } + + Vec4 Normalize() { + float len = Length(); + x_ = x_ / len; + y_ = y_ / len; + z_ = z_ / len; + w_ = w_ / len; + return *this; + } + + float Dot(const Vec3& rhs) { return x_ * rhs.x_ + y_ * rhs.y_ + z_ * rhs.z_; } + + Vec3 Cross(const Vec3& rhs) { + Vec3 ret; + ret.x_ = y_ * rhs.z_ - z_ * rhs.y_; + ret.y_ = z_ * rhs.x_ - x_ * rhs.z_; + ret.z_ = x_ * rhs.y_ - y_ * rhs.x_; + return ret; + } + + bool Validate() { + if (std::isnan(x_) || std::isnan(y_) || + std::isnan(z_) || std::isnan(w_)) + return false; + + return true; + } + + void Value(float& fX, float& fY, float& fZ, float& fW) { + fX = x_; + fY = y_; + fZ = z_; + fW = w_; + } +}; + +/****************************************************************** + * 4x4 matrix + * + */ +class Mat4 { + private: + float f_[16]; + + public: + friend class Vec3; + friend class Vec4; + friend class Quaternion; + + Mat4(); + Mat4(const float*); + + Mat4 operator*(const Mat4& rhs) const; + Vec4 operator*(const Vec4& rhs) const; + + Mat4 operator+(const Mat4& rhs) const { + Mat4 ret; + for (int32_t i = 0; i < 16; ++i) { + ret.f_[i] = f_[i] + rhs.f_[i]; + } + return ret; + } + + Mat4 operator-(const Mat4& rhs) const { + Mat4 ret; + for (int32_t i = 0; i < 16; ++i) { + ret.f_[i] = f_[i] - rhs.f_[i]; + } + return ret; + } + + Mat4& operator+=(const Mat4& rhs) { + for (int32_t i = 0; i < 16; ++i) { + f_[i] += rhs.f_[i]; + } + return *this; + } + + Mat4& operator-=(const Mat4& rhs) { + for (int32_t i = 0; i < 16; ++i) { + f_[i] -= rhs.f_[i]; + } + return *this; + } + + Mat4& operator*=(const Mat4& rhs) { + Mat4 ret; + ret.f_[0] = f_[0] * rhs.f_[0] + f_[4] * rhs.f_[1] + f_[8] * rhs.f_[2] + + f_[12] * rhs.f_[3]; + ret.f_[1] = f_[1] * rhs.f_[0] + f_[5] * rhs.f_[1] + f_[9] * rhs.f_[2] + + f_[13] * rhs.f_[3]; + ret.f_[2] = f_[2] * rhs.f_[0] + f_[6] * rhs.f_[1] + f_[10] * rhs.f_[2] + + f_[14] * rhs.f_[3]; + ret.f_[3] = f_[3] * rhs.f_[0] + f_[7] * rhs.f_[1] + f_[11] * rhs.f_[2] + + f_[15] * rhs.f_[3]; + + ret.f_[4] = f_[0] * rhs.f_[4] + f_[4] * rhs.f_[5] + f_[8] * rhs.f_[6] + + f_[12] * rhs.f_[7]; + ret.f_[5] = f_[1] * rhs.f_[4] + f_[5] * rhs.f_[5] + f_[9] * rhs.f_[6] + + f_[13] * rhs.f_[7]; + ret.f_[6] = f_[2] * rhs.f_[4] + f_[6] * rhs.f_[5] + f_[10] * rhs.f_[6] + + f_[14] * rhs.f_[7]; + ret.f_[7] = f_[3] * rhs.f_[4] + f_[7] * rhs.f_[5] + f_[11] * rhs.f_[6] + + f_[15] * rhs.f_[7]; + + ret.f_[8] = f_[0] * rhs.f_[8] + f_[4] * rhs.f_[9] + f_[8] * rhs.f_[10] + + f_[12] * rhs.f_[11]; + ret.f_[9] = f_[1] * rhs.f_[8] + f_[5] * rhs.f_[9] + f_[9] * rhs.f_[10] + + f_[13] * rhs.f_[11]; + ret.f_[10] = f_[2] * rhs.f_[8] + f_[6] * rhs.f_[9] + f_[10] * rhs.f_[10] + + f_[14] * rhs.f_[11]; + ret.f_[11] = f_[3] * rhs.f_[8] + f_[7] * rhs.f_[9] + f_[11] * rhs.f_[10] + + f_[15] * rhs.f_[11]; + + ret.f_[12] = f_[0] * rhs.f_[12] + f_[4] * rhs.f_[13] + f_[8] * rhs.f_[14] + + f_[12] * rhs.f_[15]; + ret.f_[13] = f_[1] * rhs.f_[12] + f_[5] * rhs.f_[13] + f_[9] * rhs.f_[14] + + f_[13] * rhs.f_[15]; + ret.f_[14] = f_[2] * rhs.f_[12] + f_[6] * rhs.f_[13] + f_[10] * rhs.f_[14] + + f_[14] * rhs.f_[15]; + ret.f_[15] = f_[3] * rhs.f_[12] + f_[7] * rhs.f_[13] + f_[11] * rhs.f_[14] + + f_[15] * rhs.f_[15]; + + *this = ret; + return *this; + } + + Mat4 operator*(const float rhs) { + Mat4 ret; + for (int32_t i = 0; i < 16; ++i) { + ret.f_[i] = f_[i] * rhs; + } + return ret; + } + + Mat4& operator*=(const float rhs) { + for (int32_t i = 0; i < 16; ++i) { + f_[i] *= rhs; + } + return *this; + } + + Mat4& operator=(const Mat4& rhs) { + for (int32_t i = 0; i < 16; ++i) { + f_[i] = rhs.f_[i]; + } + return *this; + } + + Mat4 Inverse(); + + Mat4 Transpose() { + Mat4 ret; + ret.f_[0] = f_[0]; + ret.f_[1] = f_[4]; + ret.f_[2] = f_[8]; + ret.f_[3] = f_[12]; + ret.f_[4] = f_[1]; + ret.f_[5] = f_[5]; + ret.f_[6] = f_[9]; + ret.f_[7] = f_[13]; + ret.f_[8] = f_[2]; + ret.f_[9] = f_[6]; + ret.f_[10] = f_[10]; + ret.f_[11] = f_[14]; + ret.f_[12] = f_[3]; + ret.f_[13] = f_[7]; + ret.f_[14] = f_[11]; + ret.f_[15] = f_[15]; + *this = ret; + return *this; + } + + Mat4& PostTranslate(float tx, float ty, float tz) { + f_[12] += (tx * f_[0]) + (ty * f_[4]) + (tz * f_[8]); + f_[13] += (tx * f_[1]) + (ty * f_[5]) + (tz * f_[9]); + f_[14] += (tx * f_[2]) + (ty * f_[6]) + (tz * f_[10]); + f_[15] += (tx * f_[3]) + (ty * f_[7]) + (tz * f_[11]); + return *this; + } + + float* Ptr() { return f_; } + + //-------------------------------------------------------------------------------- + // Misc + //-------------------------------------------------------------------------------- + static Mat4 Perspective(float width, float height, float nearPlane, + float farPlane); + static Mat4 Ortho2D(float left, float top, float right, float bottom); + + static Mat4 LookAt(const Vec3& vEye, const Vec3& vAt, const Vec3& vUp); + + static Mat4 Translation(const float fX, const float fY, const float fZ); + static Mat4 Translation(const Vec3 vec); + + static Mat4 RotationX(const float angle); + + static Mat4 RotationY(const float angle); + + static Mat4 RotationZ(const float angle); + + static Mat4 Scale(const float scaleX, const float scaleY, const float scaleZ); + + static Mat4 Identity() { + Mat4 ret; + ret.f_[0] = 1.f; + ret.f_[1] = 0; + ret.f_[2] = 0; + ret.f_[3] = 0; + ret.f_[4] = 0; + ret.f_[5] = 1.f; + ret.f_[6] = 0; + ret.f_[7] = 0; + ret.f_[8] = 0; + ret.f_[9] = 0; + ret.f_[10] = 1.f; + ret.f_[11] = 0; + ret.f_[12] = 0; + ret.f_[13] = 0; + ret.f_[14] = 0; + ret.f_[15] = 1.f; + return ret; + } + + void Dump() { + LOGI("%f %f %f %f", f_[0], f_[1], f_[2], f_[3]); + LOGI("%f %f %f %f", f_[4], f_[5], f_[6], f_[7]); + LOGI("%f %f %f %f", f_[8], f_[9], f_[10], f_[11]); + LOGI("%f %f %f %f", f_[12], f_[13], f_[14], f_[15]); + } +}; + +/****************************************************************** + * Quaternion class + * + */ +class Quaternion { + private: + float x_, y_, z_, w_; + + public: + friend class Vec3; + friend class Vec4; + friend class Mat4; + + Quaternion() { + x_ = 0.f; + y_ = 0.f; + z_ = 0.f; + w_ = 1.f; + } + + Quaternion(const float fX, const float fY, const float fZ, const float fW) { + x_ = fX; + y_ = fY; + z_ = fZ; + w_ = fW; + } + + Quaternion(const Vec3 vec, const float fW) { + x_ = vec.x_; + y_ = vec.y_; + z_ = vec.z_; + w_ = fW; + } + + Quaternion(const float* p) { + x_ = *p++; + y_ = *p++; + z_ = *p++; + w_ = *p++; + } + + Quaternion operator*(const Quaternion rhs) { + Quaternion ret; + ret.x_ = x_ * rhs.w_ + y_ * rhs.z_ - z_ * rhs.y_ + w_ * rhs.x_; + ret.y_ = -x_ * rhs.z_ + y_ * rhs.w_ + z_ * rhs.x_ + w_ * rhs.y_; + ret.z_ = x_ * rhs.y_ - y_ * rhs.x_ + z_ * rhs.w_ + w_ * rhs.z_; + ret.w_ = -x_ * rhs.x_ - y_ * rhs.y_ - z_ * rhs.z_ + w_ * rhs.w_; + return ret; + } + + Quaternion& operator*=(const Quaternion rhs) { + Quaternion ret; + ret.x_ = x_ * rhs.w_ + y_ * rhs.z_ - z_ * rhs.y_ + w_ * rhs.x_; + ret.y_ = -x_ * rhs.z_ + y_ * rhs.w_ + z_ * rhs.x_ + w_ * rhs.y_; + ret.z_ = x_ * rhs.y_ - y_ * rhs.x_ + z_ * rhs.w_ + w_ * rhs.z_; + ret.w_ = -x_ * rhs.x_ - y_ * rhs.y_ - z_ * rhs.z_ + w_ * rhs.w_; + *this = ret; + return *this; + } + + Quaternion Conjugate() { + x_ = -x_; + y_ = -y_; + z_ = -z_; + return *this; + } + + // Non destuctive version + Quaternion Conjugated() { + Quaternion ret; + ret.x_ = -x_; + ret.y_ = -y_; + ret.z_ = -z_; + ret.w_ = w_; + return ret; + } + + void ToMatrix(Mat4& mat) { + float x2 = x_ * x_ * 2.0f; + float y2 = y_ * y_ * 2.0f; + float z2 = z_ * z_ * 2.0f; + float xy = x_ * y_ * 2.0f; + float yz = y_ * z_ * 2.0f; + float zx = z_ * x_ * 2.0f; + float xw = x_ * w_ * 2.0f; + float yw = y_ * w_ * 2.0f; + float zw = z_ * w_ * 2.0f; + + mat.f_[0] = 1.0f - y2 - z2; + mat.f_[1] = xy + zw; + mat.f_[2] = zx - yw; + mat.f_[4] = xy - zw; + mat.f_[5] = 1.0f - z2 - x2; + mat.f_[6] = yz + xw; + mat.f_[8] = zx + yw; + mat.f_[9] = yz - xw; + mat.f_[10] = 1.0f - x2 - y2; + + mat.f_[3] = mat.f_[7] = mat.f_[11] = mat.f_[12] = mat.f_[13] = mat.f_[14] = + 0.0f; + mat.f_[15] = 1.0f; + } + + void ToMatrixPreserveTranslate(Mat4& mat) { + float x2 = x_ * x_ * 2.0f; + float y2 = y_ * y_ * 2.0f; + float z2 = z_ * z_ * 2.0f; + float xy = x_ * y_ * 2.0f; + float yz = y_ * z_ * 2.0f; + float zx = z_ * x_ * 2.0f; + float xw = x_ * w_ * 2.0f; + float yw = y_ * w_ * 2.0f; + float zw = z_ * w_ * 2.0f; + + mat.f_[0] = 1.0f - y2 - z2; + mat.f_[1] = xy + zw; + mat.f_[2] = zx - yw; + mat.f_[4] = xy - zw; + mat.f_[5] = 1.0f - z2 - x2; + mat.f_[6] = yz + xw; + mat.f_[8] = zx + yw; + mat.f_[9] = yz - xw; + mat.f_[10] = 1.0f - x2 - y2; + + mat.f_[3] = mat.f_[7] = mat.f_[11] = 0.0f; + mat.f_[15] = 1.0f; + } + + static Quaternion RotationAxis(const Vec3 axis, const float angle) { + Quaternion ret; + float s = sinf(angle / 2); + ret.x_ = s * axis.x_; + ret.y_ = s * axis.y_; + ret.z_ = s * axis.z_; + ret.w_ = cosf(angle / 2); + return ret; + } + + void Value(float& fX, float& fY, float& fZ, float& fW) { + fX = x_; + fY = y_; + fZ = z_; + fW = w_; + } +}; + +} // namespace ndk_helper +#endif /* VECMATH_H_ */ diff --git a/NativeApp/Android/ndk_helper/src/GLContext.cpp b/NativeApp/Android/ndk_helper/src/GLContext.cpp new file mode 100644 index 0000000..53f16ff --- /dev/null +++ b/NativeApp/Android/ndk_helper/src/GLContext.cpp @@ -0,0 +1,269 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//-------------------------------------------------------------------------------- +// GLContext.cpp +//-------------------------------------------------------------------------------- +//-------------------------------------------------------------------------------- +// includes +//-------------------------------------------------------------------------------- +#include "GLContext.h" + +#include <string.h> +#include <unistd.h> + +#include "gl3stub.h" + +namespace ndk_helper { + +//-------------------------------------------------------------------------------- +// eGLContext +//-------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------- +// Ctor +//-------------------------------------------------------------------------------- +GLContext::GLContext() + : window_(nullptr), + display_(EGL_NO_DISPLAY), + surface_(EGL_NO_SURFACE), + context_(EGL_NO_CONTEXT), + screen_width_(0), + screen_height_(0), + gles_initialized_(false), + egl_context_initialized_(false), + es3_supported_(false) {} + +void GLContext::InitGLES() { + if (gles_initialized_) return; + // + // Initialize OpenGL ES 3 if available + // + const char* versionStr = (const char*)glGetString(GL_VERSION); + if (strstr(versionStr, "OpenGL ES 3.") && gl3stubInit()) { + es3_supported_ = true; + gl_version_ = 3.0f; + } else { + gl_version_ = 2.0f; + } + + gles_initialized_ = true; +} + +//-------------------------------------------------------------------------------- +// Dtor +//-------------------------------------------------------------------------------- +GLContext::~GLContext() { Terminate(); } + +bool GLContext::Init(ANativeWindow* window) { + if (egl_context_initialized_) return true; + + // + // Initialize EGL + // + window_ = window; + InitEGLSurface(); + InitEGLContext(); + InitGLES(); + + egl_context_initialized_ = true; + + return true; +} + +bool GLContext::InitEGLSurface() { + display_ = eglGetDisplay(EGL_DEFAULT_DISPLAY); + eglInitialize(display_, 0, 0); + + /* + * Here specify the attributes of the desired configuration. + * Below, we select an EGLConfig with at least 8 bits per color + * component compatible with on-screen windows + */ + const EGLint attribs[] = {EGL_RENDERABLE_TYPE, + EGL_OPENGL_ES2_BIT, // Request opengl ES2.0 + EGL_SURFACE_TYPE, + EGL_WINDOW_BIT, + EGL_BLUE_SIZE, + 8, + EGL_GREEN_SIZE, + 8, + EGL_RED_SIZE, + 8, + EGL_DEPTH_SIZE, + 24, + EGL_NONE}; + color_size_ = 8; + depth_size_ = 24; + + EGLint num_configs; + eglChooseConfig(display_, attribs, &config_, 1, &num_configs); + + if (!num_configs) { + // Fall back to 16bit depth buffer + const EGLint attribs[] = {EGL_RENDERABLE_TYPE, + EGL_OPENGL_ES2_BIT, // Request opengl ES2.0 + EGL_SURFACE_TYPE, + EGL_WINDOW_BIT, + EGL_BLUE_SIZE, + 8, + EGL_GREEN_SIZE, + 8, + EGL_RED_SIZE, + 8, + EGL_DEPTH_SIZE, + 16, + EGL_NONE}; + eglChooseConfig(display_, attribs, &config_, 1, &num_configs); + depth_size_ = 16; + } + + if (!num_configs) { + LOGW("Unable to retrieve EGL config"); + return false; + } + + surface_ = eglCreateWindowSurface(display_, config_, window_, NULL); + eglQuerySurface(display_, surface_, EGL_WIDTH, &screen_width_); + eglQuerySurface(display_, surface_, EGL_HEIGHT, &screen_height_); + + return true; +} + +bool GLContext::InitEGLContext() { + const EGLint context_attribs[] = {EGL_CONTEXT_CLIENT_VERSION, + 2, // Request opengl ES2.0 + EGL_NONE}; + context_ = eglCreateContext(display_, config_, NULL, context_attribs); + + if (eglMakeCurrent(display_, surface_, surface_, context_) == EGL_FALSE) { + LOGW("Unable to eglMakeCurrent"); + return false; + } + + context_valid_ = true; + return true; +} + +EGLint GLContext::Swap() { + bool b = eglSwapBuffers(display_, surface_); + if (!b) { + EGLint err = eglGetError(); + if (err == EGL_BAD_SURFACE) { + // Recreate surface + InitEGLSurface(); + return EGL_SUCCESS; // Still consider glContext is valid + } else if (err == EGL_CONTEXT_LOST || err == EGL_BAD_CONTEXT) { + // Context has been lost!! + context_valid_ = false; + Terminate(); + InitEGLContext(); + } + return err; + } + return EGL_SUCCESS; +} + +void GLContext::Terminate() { + if (display_ != EGL_NO_DISPLAY) { + eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); + if (context_ != EGL_NO_CONTEXT) { + eglDestroyContext(display_, context_); + } + + if (surface_ != EGL_NO_SURFACE) { + eglDestroySurface(display_, surface_); + } + eglTerminate(display_); + } + + display_ = EGL_NO_DISPLAY; + context_ = EGL_NO_CONTEXT; + surface_ = EGL_NO_SURFACE; + window_ = nullptr; + context_valid_ = false; +} + +EGLint GLContext::Resume(ANativeWindow* window) { + if (egl_context_initialized_ == false) { + Init(window); + return EGL_SUCCESS; + } + + int32_t original_widhth = screen_width_; + int32_t original_height = screen_height_; + + // Create surface + window_ = window; + surface_ = eglCreateWindowSurface(display_, config_, window_, NULL); + eglQuerySurface(display_, surface_, EGL_WIDTH, &screen_width_); + eglQuerySurface(display_, surface_, EGL_HEIGHT, &screen_height_); + + if (screen_width_ != original_widhth || screen_height_ != original_height) { + // Screen resized + LOGI("Screen resized"); + } + + if (eglMakeCurrent(display_, surface_, surface_, context_) == EGL_TRUE) + return EGL_SUCCESS; + + EGLint err = eglGetError(); + LOGW("Unable to eglMakeCurrent %d", err); + + if (err == EGL_CONTEXT_LOST) { + // Recreate context + LOGI("Re-creating egl context"); + InitEGLContext(); + } else { + // Recreate surface + Terminate(); + InitEGLSurface(); + InitEGLContext(); + } + + return err; +} + +void GLContext::Suspend() { + if (surface_ != EGL_NO_SURFACE) { + eglDestroySurface(display_, surface_); + surface_ = EGL_NO_SURFACE; + } +} + +bool GLContext::Invalidate() { + Terminate(); + + egl_context_initialized_ = false; + return true; +} + +bool GLContext::CheckExtension(const char* extension) { + if (extension == NULL) return false; + + std::string extensions = std::string((char*)glGetString(GL_EXTENSIONS)); + std::string str = std::string(extension); + str.append(" "); + + size_t pos = 0; + if (extensions.find(extension, pos) != std::string::npos) { + return true; + } + + return false; +} + +} // namespace ndkHelper diff --git a/NativeApp/Android/ndk_helper/src/JNIHelper.cpp b/NativeApp/Android/ndk_helper/src/JNIHelper.cpp new file mode 100644 index 0000000..dfaa0bf --- /dev/null +++ b/NativeApp/Android/ndk_helper/src/JNIHelper.cpp @@ -0,0 +1,770 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "JNIHelper.h" + +#include <string.h> + +#include <fstream> +#include <iostream> + +#include <EGL/egl.h> +#include <GLES2/gl2.h> + +namespace ndk_helper { + +#define NATIVEACTIVITY_CLASS_NAME "android/app/NativeActivity" + +//--------------------------------------------------------------------------- +// JNI Helper functions +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +// Singleton +//--------------------------------------------------------------------------- +JNIHelper* JNIHelper::GetInstance() { + static JNIHelper helper; + return &helper; +} + +//--------------------------------------------------------------------------- +// Ctor +//--------------------------------------------------------------------------- +JNIHelper::JNIHelper() : activity_(NULL) {} + +//--------------------------------------------------------------------------- +// Dtor +//--------------------------------------------------------------------------- +JNIHelper::~JNIHelper() { + // Lock mutex + std::lock_guard<std::mutex> lock(mutex_); + + JNIEnv* env = AttachCurrentThread(); + env->DeleteGlobalRef(jni_helper_java_ref_); + env->DeleteGlobalRef(jni_helper_java_class_); + + DetachCurrentThread(); +} + +//--------------------------------------------------------------------------- +// Init +//--------------------------------------------------------------------------- +void JNIHelper::Init(ANativeActivity* activity, const char* helper_class_name) { + JNIHelper& helper = *GetInstance(); + + helper.activity_ = activity; + + // Lock mutex + std::lock_guard<std::mutex> lock(helper.mutex_); + + JNIEnv* env = helper.AttachCurrentThread(); + + // Retrieve app bundle id + jclass android_content_Context = env->GetObjectClass(helper.activity_->clazz); + jmethodID midGetPackageName = env->GetMethodID( + android_content_Context, "getPackageName", "()Ljava/lang/String;"); + + jstring packageName = (jstring)env->CallObjectMethod(helper.activity_->clazz, + midGetPackageName); + const char* appname = env->GetStringUTFChars(packageName, NULL); + helper.app_name_ = std::string(appname); + + jclass cls = helper.RetrieveClass(env, helper_class_name); + helper.jni_helper_java_class_ = (jclass)env->NewGlobalRef(cls); + + jmethodID constructor = + env->GetMethodID(helper.jni_helper_java_class_, "<init>", + "(Landroid/app/NativeActivity;)V"); + + helper.jni_helper_java_ref_ = env->NewObject(helper.jni_helper_java_class_, + constructor, activity->clazz); + helper.jni_helper_java_ref_ = env->NewGlobalRef(helper.jni_helper_java_ref_); + + // Get app label + jstring labelName = (jstring)helper.CallObjectMethod("getApplicationName", + "()Ljava/lang/String;"); + const char* label = env->GetStringUTFChars(labelName, NULL); + helper.app_label_ = std::string(label); + + env->ReleaseStringUTFChars(packageName, appname); + env->ReleaseStringUTFChars(labelName, label); + env->DeleteLocalRef(packageName); + env->DeleteLocalRef(labelName); + env->DeleteLocalRef(cls); +} + +void JNIHelper::Init(ANativeActivity* activity, const char* helper_class_name, + const char* native_soname) { + Init(activity, helper_class_name); + if (native_soname) { + JNIHelper& helper = *GetInstance(); + // Lock mutex + std::lock_guard<std::mutex> lock(helper.mutex_); + + JNIEnv* env = helper.AttachCurrentThread(); + + // Setup soname + jstring soname = env->NewStringUTF(native_soname); + + jmethodID mid = env->GetMethodID(helper.jni_helper_java_class_, + "loadLibrary", "(Ljava/lang/String;)V"); + env->CallVoidMethod(helper.jni_helper_java_ref_, mid, soname); + + env->DeleteLocalRef(soname); + } +} + +//--------------------------------------------------------------------------- +// readFile +//--------------------------------------------------------------------------- +bool JNIHelper::ReadFile(const char* fileName, + std::vector<uint8_t>* buffer_ref) { + if (activity_ == NULL) { + LOGI( + "JNIHelper has not been initialized.Call init() to initialize the " + "helper"); + return false; + } + + // Lock mutex + std::lock_guard<std::mutex> lock(mutex_); + + // First, try reading from externalFileDir; + JNIEnv* env = AttachCurrentThread(); + jstring str_path = GetExternalFilesDirJString(env); + + std::string s; + if(str_path) { + const char* path = env->GetStringUTFChars(str_path, NULL); + s = std::string(path); + if (fileName[0] != '/') { + s.append("/"); + } + s.append(fileName); + env->ReleaseStringUTFChars(str_path, path); + env->DeleteLocalRef(str_path); + } + std::ifstream f(s.c_str(), std::ios::binary); + activity_->vm->DetachCurrentThread(); + if (f) { + LOGI("reading:%s", s.c_str()); + f.seekg(0, std::ifstream::end); + int32_t fileSize = f.tellg(); + f.seekg(0, std::ifstream::beg); + buffer_ref->reserve(fileSize); + buffer_ref->assign(std::istreambuf_iterator<char>(f), + std::istreambuf_iterator<char>()); + f.close(); + return true; + } else { + // Fallback to assetManager + AAssetManager* assetManager = activity_->assetManager; + AAsset* assetFile = + AAssetManager_open(assetManager, fileName, AASSET_MODE_BUFFER); + if (!assetFile) { + return false; + } + uint8_t* data = (uint8_t*)AAsset_getBuffer(assetFile); + int32_t size = AAsset_getLength(assetFile); + if (data == NULL) { + AAsset_close(assetFile); + + LOGI("Failed to load:%s", fileName); + return false; + } + + buffer_ref->reserve(size); + buffer_ref->assign(data, data + size); + + AAsset_close(assetFile); + return true; + } +} + +std::string JNIHelper::GetExternalFilesDir() { + if (activity_ == NULL) { + LOGI( + "JNIHelper has not been initialized. Call init() to initialize the " + "helper"); + return std::string(""); + } + + // Lock mutex + std::lock_guard<std::mutex> lock(mutex_); + + // First, try reading from externalFileDir; + JNIEnv* env = AttachCurrentThread(); + + jstring strPath = GetExternalFilesDirJString(env); + const char* path = env->GetStringUTFChars(strPath, NULL); + std::string s(path); + + env->ReleaseStringUTFChars(strPath, path); + env->DeleteLocalRef(strPath); + return s; +} + +uint32_t JNIHelper::LoadTexture(const char* file_name, int32_t* outWidth, + int32_t* outHeight, bool* hasAlpha) { + if (activity_ == NULL) { + LOGI( + "JNIHelper has not been initialized. Call init() to initialize the " + "helper"); + return 0; + } + + // Lock mutex + std::lock_guard<std::mutex> lock(mutex_); + + JNIEnv* env = AttachCurrentThread(); + jstring name = env->NewStringUTF(file_name); + + GLuint tex; + glGenTextures(1, &tex); + glBindTexture(GL_TEXTURE_2D, tex); + + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, + GL_LINEAR_MIPMAP_NEAREST); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + jmethodID mid = env->GetMethodID(jni_helper_java_class_, "loadTexture", + "(Ljava/lang/String;)Ljava/lang/Object;"); + + jobject out = env->CallObjectMethod(jni_helper_java_ref_, mid, name); + + jclass javaCls = + RetrieveClass(env, "com/sample/helper/NDKHelper$TextureInformation"); + jfieldID fidRet = env->GetFieldID(javaCls, "ret", "Z"); + jfieldID fidHasAlpha = env->GetFieldID(javaCls, "alphaChannel", "Z"); + jfieldID fidWidth = env->GetFieldID(javaCls, "originalWidth", "I"); + jfieldID fidHeight = env->GetFieldID(javaCls, "originalHeight", "I"); + bool ret = env->GetBooleanField(out, fidRet); + bool alpha = env->GetBooleanField(out, fidHasAlpha); + int32_t width = env->GetIntField(out, fidWidth); + int32_t height = env->GetIntField(out, fidHeight); + if (!ret) { + glDeleteTextures(1, &tex); + tex = -1; + LOGI("Texture load failed %s", file_name); + } + LOGI("Loaded texture original size:%dx%d alpha:%d", width, height, + (int32_t)alpha); + if (outWidth != NULL) { + *outWidth = width; + } + if (outHeight != NULL) { + *outHeight = height; + } + if (hasAlpha != NULL) { + *hasAlpha = alpha; + } + + // Generate mipmap + glGenerateMipmap(GL_TEXTURE_2D); + + env->DeleteLocalRef(name); + DetachCurrentThread(); + + return tex; +} + +uint32_t JNIHelper::LoadCubemapTexture(const char* file_name, + const int32_t face, + const int32_t miplevel, const bool sRGB, + int32_t* outWidth, int32_t* outHeight, + bool* hasAlpha) { + if (activity_ == NULL) { + LOGI( + "JNIHelper has not been initialized. Call init() to initialize the " + "helper"); + return 0; + } + + // Lock mutex + std::lock_guard<std::mutex> lock(mutex_); + + JNIEnv* env = AttachCurrentThread(); + jstring name = env->NewStringUTF(file_name); + + jmethodID mid = env->GetMethodID(jni_helper_java_class_, "loadCubemapTexture", + "(Ljava/lang/String;IIZ)Ljava/lang/Object;"); + + jobject out = + env->CallObjectMethod(jni_helper_java_ref_, mid, name, face, miplevel); + + jclass javaCls = + RetrieveClass(env, "com/sample/helper/NDKHelper$TextureInformation"); + jfieldID fidRet = env->GetFieldID(javaCls, "ret", "Z"); + jfieldID fidHasAlpha = env->GetFieldID(javaCls, "alphaChannel", "Z"); + jfieldID fidWidth = env->GetFieldID(javaCls, "originalWidth", "I"); + jfieldID fidHeight = env->GetFieldID(javaCls, "originalHeight", "I"); + bool ret = env->GetBooleanField(out, fidRet); + bool alpha = env->GetBooleanField(out, fidHasAlpha); + int32_t width = env->GetIntField(out, fidWidth); + int32_t height = env->GetIntField(out, fidHeight); + if (!ret) { + LOGI("Texture load failed %s", file_name); + } + LOGI("Loaded texture original size:%dx%d alpha:%d", width, height, + (int32_t)alpha); + if (outWidth != NULL) { + *outWidth = width; + } + if (outHeight != NULL) { + *outHeight = height; + } + if (hasAlpha != NULL) { + *hasAlpha = alpha; + } + + env->DeleteLocalRef(name); + env->DeleteLocalRef(javaCls); + + return 0; +} + +jobject JNIHelper::LoadImage(const char* file_name, int32_t* outWidth, + int32_t* outHeight, bool* hasAlpha) { + if (activity_ == NULL) { + LOGI( + "JNIHelper has not been initialized. Call init() to initialize the " + "helper"); + return 0; + } + + // Lock mutex + std::lock_guard<std::mutex> lock(mutex_); + + JNIEnv* env = AttachCurrentThread(); + jstring name = env->NewStringUTF(file_name); + + jmethodID mid = env->GetMethodID(jni_helper_java_class_, "loadImage", + "(Ljava/lang/String;)Ljava/lang/Object;"); + + jobject out = env->CallObjectMethod(jni_helper_java_ref_, mid, name); + + jclass javaCls = + RetrieveClass(env, "com/sample/helper/NDKHelper$TextureInformation"); + jfieldID fidRet = env->GetFieldID(javaCls, "ret", "Z"); + jfieldID fidHasAlpha = env->GetFieldID(javaCls, "alphaChannel", "Z"); + jfieldID fidWidth = env->GetFieldID(javaCls, "originalWidth", "I"); + jfieldID fidHeight = env->GetFieldID(javaCls, "originalHeight", "I"); + bool ret = env->GetBooleanField(out, fidRet); + bool alpha = env->GetBooleanField(out, fidHasAlpha); + int32_t width = env->GetIntField(out, fidWidth); + int32_t height = env->GetIntField(out, fidHeight); + if (!ret) { + LOGI("Texture load failed %s", file_name); + } + LOGI("Loaded texture original size:%dx%d alpha:%d", width, height, + (int32_t)alpha); + if (outWidth != NULL) { + *outWidth = width; + } + if (outHeight != NULL) { + *outHeight = height; + } + if (hasAlpha != NULL) { + *hasAlpha = alpha; + } + + jfieldID fidImage = env->GetFieldID(javaCls, "image", "Ljava/lang/Object;"); + jobject array = env->GetObjectField(out, fidImage); + jobject objGlobal = env->NewGlobalRef(array); + + env->DeleteLocalRef(name); + env->DeleteLocalRef(javaCls); + + return objGlobal; +} + +std::string JNIHelper::ConvertString(const char* str, const char* encode) { + if (activity_ == NULL) { + LOGI( + "JNIHelper has not been initialized. Call init() to initialize the " + "helper"); + return std::string(""); + } + + // Lock mutex + std::lock_guard<std::mutex> lock(mutex_); + + JNIEnv* env = AttachCurrentThread(); + env->PushLocalFrame(16); + + int32_t iLength = strlen((const char*)str); + + jbyteArray array = env->NewByteArray(iLength); + env->SetByteArrayRegion(array, 0, iLength, (const signed char*)str); + + jstring strEncode = env->NewStringUTF(encode); + + jclass cls = env->FindClass("java/lang/String"); + jmethodID ctor = env->GetMethodID(cls, "<init>", "([BLjava/lang/String;)V"); + jstring object = (jstring)env->NewObject(cls, ctor, array, strEncode); + + const char* cparam = env->GetStringUTFChars(object, NULL); + + std::string s = std::string(cparam); + + env->ReleaseStringUTFChars(object, cparam); + env->DeleteLocalRef(array); + env->DeleteLocalRef(strEncode); + env->DeleteLocalRef(object); + env->DeleteLocalRef(cls); + + env->PopLocalFrame(NULL); + + return s; +} +/* + * Retrieve string resource with a given name + * arguments: + * in: resourceName, name of string resource to retrieve + * return: string resource value, returns "" when there is no string resource + * with given name + */ +std::string JNIHelper::GetStringResource(const std::string& resourceName) { + if (activity_ == NULL) { + LOGI( + "JNIHelper has not been initialized. Call init() to initialize the " + "helper"); + return std::string(""); + } + + // Lock mutex + std::lock_guard<std::mutex> lock(mutex_); + + JNIEnv* env = AttachCurrentThread(); + jstring name = env->NewStringUTF(resourceName.c_str()); + + jstring ret = (jstring)CallObjectMethod( + "getStringResource", "(Ljava/lang/String;)Ljava/lang/String;", name); + + const char* resource = env->GetStringUTFChars(ret, NULL); + std::string s = std::string(resource); + + env->ReleaseStringUTFChars(ret, resource); + env->DeleteLocalRef(ret); + env->DeleteLocalRef(name); + + return s; +} +/* + * Audio helpers + */ +int32_t JNIHelper::GetNativeAudioBufferSize() { + if (activity_ == NULL) { + LOGI( + "JNIHelper has not been initialized. Call init() to initialize the " + "helper"); + return 0; + } + + JNIEnv* env = AttachCurrentThread(); + jmethodID mid = env->GetMethodID(jni_helper_java_class_, + "getNativeAudioBufferSize", "()I"); + int32_t i = env->CallIntMethod(jni_helper_java_ref_, mid); + return i; +} + +int32_t JNIHelper::GetNativeAudioSampleRate() { + if (activity_ == NULL) { + LOGI( + "JNIHelper has not been initialized. Call init() to initialize the " + "helper"); + return 0; + } + + JNIEnv* env = AttachCurrentThread(); + jmethodID mid = env->GetMethodID(jni_helper_java_class_, + "getNativeAudioSampleRate", "()I"); + int32_t i = env->CallIntMethod(jni_helper_java_ref_, mid); + return i; +} + +//--------------------------------------------------------------------------- +// Misc implementations +//--------------------------------------------------------------------------- +jclass JNIHelper::RetrieveClass(JNIEnv* jni, const char* class_name) { + jclass activity_class = jni->FindClass(NATIVEACTIVITY_CLASS_NAME); + jmethodID get_class_loader = jni->GetMethodID( + activity_class, "getClassLoader", "()Ljava/lang/ClassLoader;"); + jobject cls = jni->CallObjectMethod(activity_->clazz, get_class_loader); + jclass class_loader = jni->FindClass("java/lang/ClassLoader"); + jmethodID find_class = jni->GetMethodID( + class_loader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;"); + + jstring str_class_name = jni->NewStringUTF(class_name); + jclass class_retrieved = + (jclass)jni->CallObjectMethod(cls, find_class, str_class_name); + jni->DeleteLocalRef(str_class_name); + jni->DeleteLocalRef(activity_class); + jni->DeleteLocalRef(class_loader); + return class_retrieved; +} + +jstring JNIHelper::GetExternalFilesDirJString(JNIEnv* env) { + if (activity_ == NULL) { + LOGI( + "JNIHelper has not been initialized. Call init() to initialize the " + "helper"); + return NULL; + } + + jstring obj_Path = nullptr; + // Invoking getExternalFilesDir() java API + jclass cls_Env = env->FindClass(NATIVEACTIVITY_CLASS_NAME); + jmethodID mid = env->GetMethodID(cls_Env, "getExternalFilesDir", + "(Ljava/lang/String;)Ljava/io/File;"); + jobject obj_File = env->CallObjectMethod(activity_->clazz, mid, NULL); + if (obj_File) { + jclass cls_File = env->FindClass("java/io/File"); + jmethodID mid_getPath = + env->GetMethodID(cls_File, "getPath", "()Ljava/lang/String;"); + obj_Path = (jstring)env->CallObjectMethod(obj_File, mid_getPath); + } + return obj_Path; +} + +void JNIHelper::DeleteObject(jobject obj) { + if (obj == NULL) { + LOGI("obj can not be NULL"); + return; + } + + JNIEnv* env = AttachCurrentThread(); + env->DeleteGlobalRef(obj); +} + +jobject JNIHelper::CallObjectMethod(const char* strMethodName, + const char* strSignature, ...) { + if (activity_ == NULL) { + LOGI( + "JNIHelper has not been initialized. Call init() to initialize the " + "helper"); + return NULL; + } + + JNIEnv* env = AttachCurrentThread(); + jmethodID mid = + env->GetMethodID(jni_helper_java_class_, strMethodName, strSignature); + if (mid == NULL) { + LOGI("method ID %s, '%s' not found", strMethodName, strSignature); + return NULL; + } + + va_list args; + va_start(args, strSignature); + jobject obj = env->CallObjectMethodV(jni_helper_java_ref_, mid, args); + va_end(args); + + return obj; +} + +void JNIHelper::CallVoidMethod(const char* strMethodName, + const char* strSignature, ...) { + if (activity_ == NULL) { + LOGI( + "JNIHelper has not been initialized. Call init() to initialize the " + "helper"); + return; + } + + JNIEnv* env = AttachCurrentThread(); + jmethodID mid = + env->GetMethodID(jni_helper_java_class_, strMethodName, strSignature); + if (mid == NULL) { + LOGI("method ID %s, '%s' not found", strMethodName, strSignature); + return; + } + va_list args; + va_start(args, strSignature); + env->CallVoidMethodV(jni_helper_java_ref_, mid, args); + va_end(args); + + return; +} + +jobject JNIHelper::CallObjectMethod(jobject object, const char* strMethodName, + const char* strSignature, ...) { + if (activity_ == NULL) { + LOGI( + "JNIHelper has not been initialized. Call init() to initialize the " + "helper"); + return NULL; + } + + JNIEnv* env = AttachCurrentThread(); + jclass cls = env->GetObjectClass(object); + jmethodID mid = env->GetMethodID(cls, strMethodName, strSignature); + if (mid == NULL) { + LOGI("method ID %s, '%s' not found", strMethodName, strSignature); + return NULL; + } + + va_list args; + va_start(args, strSignature); + jobject obj = env->CallObjectMethodV(object, mid, args); + va_end(args); + + env->DeleteLocalRef(cls); + return obj; +} + +void JNIHelper::CallVoidMethod(jobject object, const char* strMethodName, + const char* strSignature, ...) { + if (activity_ == NULL) { + LOGI( + "JNIHelper has not been initialized. Call init() to initialize the " + "helper"); + return; + } + + JNIEnv* env = AttachCurrentThread(); + jclass cls = env->GetObjectClass(object); + jmethodID mid = env->GetMethodID(cls, strMethodName, strSignature); + if (mid == NULL) { + LOGI("method ID %s, '%s' not found", strMethodName, strSignature); + return; + } + + va_list args; + va_start(args, strSignature); + env->CallVoidMethodV(object, mid, args); + va_end(args); + + env->DeleteLocalRef(cls); + return; +} + +float JNIHelper::CallFloatMethod(jobject object, const char* strMethodName, + const char* strSignature, ...) { + float f = 0.f; + if (activity_ == NULL) { + LOGI( + "JNIHelper has not been initialized. Call init() to initialize the " + "helper"); + return f; + } + + JNIEnv* env = AttachCurrentThread(); + jclass cls = env->GetObjectClass(object); + jmethodID mid = env->GetMethodID(cls, strMethodName, strSignature); + if (mid == NULL) { + LOGI("method ID %s, '%s' not found", strMethodName, strSignature); + return f; + } + va_list args; + va_start(args, strSignature); + f = env->CallFloatMethodV(object, mid, args); + va_end(args); + + env->DeleteLocalRef(cls); + return f; +} + +int32_t JNIHelper::CallIntMethod(jobject object, const char* strMethodName, + const char* strSignature, ...) { + int32_t i = 0; + if (activity_ == NULL) { + LOGI( + "JNIHelper has not been initialized. Call init() to initialize the " + "helper"); + return i; + } + + JNIEnv* env = AttachCurrentThread(); + jclass cls = env->GetObjectClass(object); + jmethodID mid = env->GetMethodID(cls, strMethodName, strSignature); + if (mid == NULL) { + LOGI("method ID %s, '%s' not found", strMethodName, strSignature); + return i; + } + va_list args; + va_start(args, strSignature); + i = env->CallIntMethodV(object, mid, args); + va_end(args); + + env->DeleteLocalRef(cls); + return i; +} + +bool JNIHelper::CallBooleanMethod(jobject object, const char* strMethodName, + const char* strSignature, ...) { + bool b; + if (activity_ == NULL) { + LOGI( + "JNIHelper has not been initialized. Call init() to initialize the " + "helper"); + return false; + } + + JNIEnv* env = AttachCurrentThread(); + jclass cls = env->GetObjectClass(object); + jmethodID mid = env->GetMethodID(cls, strMethodName, strSignature); + if (mid == NULL) { + LOGI("method ID %s, '%s' not found", strMethodName, strSignature); + return false; + } + va_list args; + va_start(args, strSignature); + b = env->CallBooleanMethodV(object, mid, args); + va_end(args); + + env->DeleteLocalRef(cls); + return b; +} + +jobject JNIHelper::CreateObject(const char* class_name) { + JNIEnv* env = AttachCurrentThread(); + + jclass cls = env->FindClass(class_name); + jmethodID constructor = env->GetMethodID(cls, "<init>", "()V"); + + jobject obj = env->NewObject(cls, constructor); + jobject objGlobal = env->NewGlobalRef(obj); + env->DeleteLocalRef(obj); + env->DeleteLocalRef(cls); + return objGlobal; +} + +void JNIHelper::RunOnUiThread(std::function<void()> callback) { + // Lock mutex + std::lock_guard<std::mutex> lock(mutex_); + + JNIEnv* env = AttachCurrentThread(); + static jmethodID mid = NULL; + if (mid == NULL) + mid = env->GetMethodID(jni_helper_java_class_, "runOnUIThread", "(J)V"); + + // Allocate temporary function object to be passed around + std::function<void()>* pCallback = new std::function<void()>(callback); + env->CallVoidMethod(jni_helper_java_ref_, mid, (int64_t)pCallback); +} + +// This JNI function is invoked from UIThread asynchronously +extern "C" { +JNIEXPORT void Java_com_sample_helper_NDKHelper_RunOnUiThreadHandler( + JNIEnv* env, jobject thiz, int64_t pointer) { + std::function<void()>* pCallback = (std::function<void()>*)pointer; + (*pCallback)(); + + // Deleting temporary object + delete pCallback; +} +} + +} // namespace ndkHelper diff --git a/NativeApp/Android/ndk_helper/src/gestureDetector.cpp b/NativeApp/Android/ndk_helper/src/gestureDetector.cpp new file mode 100644 index 0000000..74e5411 --- /dev/null +++ b/NativeApp/Android/ndk_helper/src/gestureDetector.cpp @@ -0,0 +1,301 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "gestureDetector.h" + +//-------------------------------------------------------------------------------- +// gestureDetector.cpp +//-------------------------------------------------------------------------------- +namespace ndk_helper { + +//-------------------------------------------------------------------------------- +// includes +//-------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------- +// GestureDetector +//-------------------------------------------------------------------------------- +GestureDetector::GestureDetector() { dp_factor_ = 1.f; } + +void GestureDetector::SetConfiguration(AConfiguration* config) { + dp_factor_ = 160.f / AConfiguration_getDensity(config); +} + +//-------------------------------------------------------------------------------- +// TapDetector +//-------------------------------------------------------------------------------- +TapDetector::TapDetector() : down_x_(0), down_y_(0) {} + +GESTURE_STATE TapDetector::Detect(const AInputEvent* motion_event) { + if (AMotionEvent_getPointerCount(motion_event) > 1) { + // Only support single touch + return false; + } + + int32_t action = AMotionEvent_getAction(motion_event); + unsigned int flags = action & AMOTION_EVENT_ACTION_MASK; + switch (flags) { + case AMOTION_EVENT_ACTION_DOWN: + down_pointer_id_ = AMotionEvent_getPointerId(motion_event, 0); + down_x_ = AMotionEvent_getX(motion_event, 0); + down_y_ = AMotionEvent_getY(motion_event, 0); + break; + case AMOTION_EVENT_ACTION_UP: { + int64_t eventTime = AMotionEvent_getEventTime(motion_event); + int64_t downTime = AMotionEvent_getDownTime(motion_event); + if (eventTime - downTime <= TAP_TIMEOUT) { + if (down_pointer_id_ == AMotionEvent_getPointerId(motion_event, 0)) { + float x = AMotionEvent_getX(motion_event, 0) - down_x_; + float y = AMotionEvent_getY(motion_event, 0) - down_y_; + if (x * x + y * y < TOUCH_SLOP * TOUCH_SLOP * dp_factor_) { + LOGI("TapDetector: Tap detected"); + return GESTURE_STATE_ACTION; + } + } + } + break; + } + } + return GESTURE_STATE_NONE; +} + +//-------------------------------------------------------------------------------- +// DoubletapDetector +//-------------------------------------------------------------------------------- +DoubletapDetector::DoubletapDetector() + : last_tap_time_(0), last_tap_x_(0), last_tap_y_(0) {} + +GESTURE_STATE DoubletapDetector::Detect(const AInputEvent* motion_event) { + if (AMotionEvent_getPointerCount(motion_event) > 1) { + // Only support single double tap + return false; + } + + bool tap_detected = tap_detector_.Detect(motion_event); + + int32_t action = AMotionEvent_getAction(motion_event); + unsigned int flags = action & AMOTION_EVENT_ACTION_MASK; + switch (flags) { + case AMOTION_EVENT_ACTION_DOWN: { + int64_t eventTime = AMotionEvent_getEventTime(motion_event); + if (eventTime - last_tap_time_ <= DOUBLE_TAP_TIMEOUT) { + float x = AMotionEvent_getX(motion_event, 0) - last_tap_x_; + float y = AMotionEvent_getY(motion_event, 0) - last_tap_y_; + if (x * x + y * y < DOUBLE_TAP_SLOP * DOUBLE_TAP_SLOP * dp_factor_) { + LOGI("DoubletapDetector: Doubletap detected"); + return GESTURE_STATE_ACTION; + } + } + break; + } + case AMOTION_EVENT_ACTION_UP: + if (tap_detected) { + last_tap_time_ = AMotionEvent_getEventTime(motion_event); + last_tap_x_ = AMotionEvent_getX(motion_event, 0); + last_tap_y_ = AMotionEvent_getY(motion_event, 0); + } + break; + } + return GESTURE_STATE_NONE; +} + +void DoubletapDetector::SetConfiguration(AConfiguration* config) { + dp_factor_ = 160.f / AConfiguration_getDensity(config); + tap_detector_.SetConfiguration(config); +} + +//-------------------------------------------------------------------------------- +// PinchDetector +//-------------------------------------------------------------------------------- + +int32_t PinchDetector::FindIndex(const AInputEvent* event, int32_t id) { + int32_t count = AMotionEvent_getPointerCount(event); + for (auto i = 0; i < count; ++i) { + if (id == AMotionEvent_getPointerId(event, i)) return i; + } + return -1; +} + +GESTURE_STATE PinchDetector::Detect(const AInputEvent* event) { + GESTURE_STATE ret = GESTURE_STATE_NONE; + int32_t action = AMotionEvent_getAction(event); + uint32_t flags = action & AMOTION_EVENT_ACTION_MASK; + event_ = event; + + int32_t count = AMotionEvent_getPointerCount(event); + switch (flags) { + case AMOTION_EVENT_ACTION_DOWN: + vec_pointers_.push_back(AMotionEvent_getPointerId(event, 0)); + break; + case AMOTION_EVENT_ACTION_POINTER_DOWN: { + int32_t iIndex = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> + AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; + vec_pointers_.push_back(AMotionEvent_getPointerId(event, iIndex)); + if (count == 2) { + // Start new pinch + ret = GESTURE_STATE_START; + } + } break; + case AMOTION_EVENT_ACTION_UP: + vec_pointers_.pop_back(); + break; + case AMOTION_EVENT_ACTION_POINTER_UP: { + int32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> + AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; + int32_t released_pointer_id = AMotionEvent_getPointerId(event, index); + + std::vector<int32_t>::iterator it = vec_pointers_.begin(); + std::vector<int32_t>::iterator it_end = vec_pointers_.end(); + int32_t i = 0; + for (; it != it_end; ++it, ++i) { + if (*it == released_pointer_id) { + vec_pointers_.erase(it); + break; + } + } + + if (i <= 1) { + // Reset pinch or drag + if (count != 2) { + // Start new pinch + ret = GESTURE_STATE_START | GESTURE_STATE_END; + } + } + } break; + case AMOTION_EVENT_ACTION_MOVE: + switch (count) { + case 1: + break; + default: + // Multi touch + ret = GESTURE_STATE_MOVE; + break; + } + break; + case AMOTION_EVENT_ACTION_CANCEL: + break; + } + + return ret; +} + +bool PinchDetector::GetPointers(Vec2& v1, Vec2& v2) { + if (vec_pointers_.size() < 2) return false; + + int32_t index = FindIndex(event_, vec_pointers_[0]); + if (index == -1) return false; + + float x = AMotionEvent_getX(event_, index); + float y = AMotionEvent_getY(event_, index); + + index = FindIndex(event_, vec_pointers_[1]); + if (index == -1) return false; + + float x2 = AMotionEvent_getX(event_, index); + float y2 = AMotionEvent_getY(event_, index); + + v1 = Vec2(x, y); + v2 = Vec2(x2, y2); + + return true; +} + +//-------------------------------------------------------------------------------- +// DragDetector +//-------------------------------------------------------------------------------- + +int32_t DragDetector::FindIndex(const AInputEvent* event, int32_t id) { + int32_t count = AMotionEvent_getPointerCount(event); + for (auto i = 0; i < count; ++i) { + if (id == AMotionEvent_getPointerId(event, i)) return i; + } + return -1; +} + +GESTURE_STATE DragDetector::Detect(const AInputEvent* event) { + GESTURE_STATE ret = GESTURE_STATE_NONE; + int32_t action = AMotionEvent_getAction(event); + int32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> + AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; + uint32_t flags = action & AMOTION_EVENT_ACTION_MASK; + event_ = event; + + int32_t count = AMotionEvent_getPointerCount(event); + switch (flags) { + case AMOTION_EVENT_ACTION_DOWN: + vec_pointers_.push_back(AMotionEvent_getPointerId(event, 0)); + ret = GESTURE_STATE_START; + break; + case AMOTION_EVENT_ACTION_POINTER_DOWN: + vec_pointers_.push_back(AMotionEvent_getPointerId(event, index)); + break; + case AMOTION_EVENT_ACTION_UP: + vec_pointers_.pop_back(); + ret = GESTURE_STATE_END; + break; + case AMOTION_EVENT_ACTION_POINTER_UP: { + int32_t released_pointer_id = AMotionEvent_getPointerId(event, index); + + auto it = vec_pointers_.begin(); + auto it_end = vec_pointers_.end(); + int32_t i = 0; + for (; it != it_end; ++it, ++i) { + if (*it == released_pointer_id) { + vec_pointers_.erase(it); + break; + } + } + + if (i <= 1) { + // Reset pinch or drag + if (count == 2) { + ret = GESTURE_STATE_START; + } + } + break; + } + case AMOTION_EVENT_ACTION_MOVE: + switch (count) { + case 1: + // Drag + ret = GESTURE_STATE_MOVE; + break; + default: + break; + } + break; + case AMOTION_EVENT_ACTION_CANCEL: + break; + } + + return ret; +} + +bool DragDetector::GetPointer(Vec2& v) { + if (vec_pointers_.size() < 1) return false; + + int32_t iIndex = FindIndex(event_, vec_pointers_[0]); + if (iIndex == -1) return false; + + float x = AMotionEvent_getX(event_, iIndex); + float y = AMotionEvent_getY(event_, iIndex); + + v = Vec2(x, y); + + return true; +} + +} // namespace ndkHelper diff --git a/NativeApp/Android/ndk_helper/src/gl3stub.c b/NativeApp/Android/ndk_helper/src/gl3stub.c new file mode 100644 index 0000000..d918b2c --- /dev/null +++ b/NativeApp/Android/ndk_helper/src/gl3stub.c @@ -0,0 +1,421 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include <EGL/egl.h> +#include "gl3stub.h" + +GLboolean gl3stubInit() { +#define FIND_PROC(s) s = (void*)eglGetProcAddress(#s); + FIND_PROC(glReadBuffer); + FIND_PROC(glDrawRangeElements); + FIND_PROC(glTexImage3D); + FIND_PROC(glTexSubImage3D); + FIND_PROC(glCopyTexSubImage3D); + FIND_PROC(glCompressedTexImage3D); + FIND_PROC(glCompressedTexSubImage3D); + FIND_PROC(glGenQueries); + FIND_PROC(glDeleteQueries); + FIND_PROC(glIsQuery); + FIND_PROC(glBeginQuery); + FIND_PROC(glEndQuery); + FIND_PROC(glGetQueryiv); + FIND_PROC(glGetQueryObjectuiv); + FIND_PROC(glUnmapBuffer); + FIND_PROC(glGetBufferPointerv); + FIND_PROC(glDrawBuffers); + FIND_PROC(glUniformMatrix2x3fv); + FIND_PROC(glUniformMatrix3x2fv); + FIND_PROC(glUniformMatrix2x4fv); + FIND_PROC(glUniformMatrix4x2fv); + FIND_PROC(glUniformMatrix3x4fv); + FIND_PROC(glUniformMatrix4x3fv); + FIND_PROC(glBlitFramebuffer); + FIND_PROC(glRenderbufferStorageMultisample); + FIND_PROC(glFramebufferTextureLayer); + FIND_PROC(glMapBufferRange); + FIND_PROC(glFlushMappedBufferRange); + FIND_PROC(glBindVertexArray); + FIND_PROC(glDeleteVertexArrays); + FIND_PROC(glGenVertexArrays); + FIND_PROC(glIsVertexArray); + FIND_PROC(glGetIntegeri_v); + FIND_PROC(glBeginTransformFeedback); + FIND_PROC(glEndTransformFeedback); + FIND_PROC(glBindBufferRange); + FIND_PROC(glBindBufferBase); + FIND_PROC(glTransformFeedbackVaryings); + FIND_PROC(glGetTransformFeedbackVarying); + FIND_PROC(glVertexAttribIPointer); + FIND_PROC(glGetVertexAttribIiv); + FIND_PROC(glGetVertexAttribIuiv); + FIND_PROC(glVertexAttribI4i); + FIND_PROC(glVertexAttribI4ui); + FIND_PROC(glVertexAttribI4iv); + FIND_PROC(glVertexAttribI4uiv); + FIND_PROC(glGetUniformuiv); + FIND_PROC(glGetFragDataLocation); + FIND_PROC(glUniform1ui); + FIND_PROC(glUniform2ui); + FIND_PROC(glUniform3ui); + FIND_PROC(glUniform4ui); + FIND_PROC(glUniform1uiv); + FIND_PROC(glUniform2uiv); + FIND_PROC(glUniform3uiv); + FIND_PROC(glUniform4uiv); + FIND_PROC(glClearBufferiv); + FIND_PROC(glClearBufferuiv); + FIND_PROC(glClearBufferfv); + FIND_PROC(glClearBufferfi); + FIND_PROC(glGetStringi); + FIND_PROC(glCopyBufferSubData); + FIND_PROC(glGetUniformIndices); + FIND_PROC(glGetActiveUniformsiv); + FIND_PROC(glGetUniformBlockIndex); + FIND_PROC(glGetActiveUniformBlockiv); + FIND_PROC(glGetActiveUniformBlockName); + FIND_PROC(glUniformBlockBinding); + FIND_PROC(glDrawArraysInstanced); + FIND_PROC(glDrawElementsInstanced); + FIND_PROC(glFenceSync); + FIND_PROC(glIsSync); + FIND_PROC(glDeleteSync); + FIND_PROC(glClientWaitSync); + FIND_PROC(glWaitSync); + FIND_PROC(glGetInteger64v); + FIND_PROC(glGetSynciv); + FIND_PROC(glGetInteger64i_v); + FIND_PROC(glGetBufferParameteri64v); + FIND_PROC(glGenSamplers); + FIND_PROC(glDeleteSamplers); + FIND_PROC(glIsSampler); + FIND_PROC(glBindSampler); + FIND_PROC(glSamplerParameteri); + FIND_PROC(glSamplerParameteriv); + FIND_PROC(glSamplerParameterf); + FIND_PROC(glSamplerParameterfv); + FIND_PROC(glGetSamplerParameteriv); + FIND_PROC(glGetSamplerParameterfv); + FIND_PROC(glVertexAttribDivisor); + FIND_PROC(glBindTransformFeedback); + FIND_PROC(glDeleteTransformFeedbacks); + FIND_PROC(glGenTransformFeedbacks); + FIND_PROC(glIsTransformFeedback); + FIND_PROC(glPauseTransformFeedback); + FIND_PROC(glResumeTransformFeedback); + FIND_PROC(glGetProgramBinary); + FIND_PROC(glProgramBinary); + FIND_PROC(glProgramParameteri); + FIND_PROC(glInvalidateFramebuffer); + FIND_PROC(glInvalidateSubFramebuffer); + FIND_PROC(glTexStorage2D); + FIND_PROC(glTexStorage3D); + FIND_PROC(glGetInternalformativ); +#undef FIND_PROC + + if (!glReadBuffer || !glDrawRangeElements || !glTexImage3D || + !glTexSubImage3D || !glCopyTexSubImage3D || !glCompressedTexImage3D || + !glCompressedTexSubImage3D || !glGenQueries || !glDeleteQueries || + !glIsQuery || !glBeginQuery || !glEndQuery || !glGetQueryiv || + !glGetQueryObjectuiv || !glUnmapBuffer || !glGetBufferPointerv || + !glDrawBuffers || !glUniformMatrix2x3fv || !glUniformMatrix3x2fv || + !glUniformMatrix2x4fv || !glUniformMatrix4x2fv || !glUniformMatrix3x4fv || + !glUniformMatrix4x3fv || !glBlitFramebuffer || + !glRenderbufferStorageMultisample || !glFramebufferTextureLayer || + !glMapBufferRange || !glFlushMappedBufferRange || !glBindVertexArray || + !glDeleteVertexArrays || !glGenVertexArrays || !glIsVertexArray || + !glGetIntegeri_v || !glBeginTransformFeedback || + !glEndTransformFeedback || !glBindBufferRange || !glBindBufferBase || + !glTransformFeedbackVaryings || !glGetTransformFeedbackVarying || + !glVertexAttribIPointer || !glGetVertexAttribIiv || + !glGetVertexAttribIuiv || !glVertexAttribI4i || !glVertexAttribI4ui || + !glVertexAttribI4iv || !glVertexAttribI4uiv || !glGetUniformuiv || + !glGetFragDataLocation || !glUniform1ui || !glUniform2ui || + !glUniform3ui || !glUniform4ui || !glUniform1uiv || !glUniform2uiv || + !glUniform3uiv || !glUniform4uiv || !glClearBufferiv || + !glClearBufferuiv || !glClearBufferfv || !glClearBufferfi || + !glGetStringi || !glCopyBufferSubData || !glGetUniformIndices || + !glGetActiveUniformsiv || !glGetUniformBlockIndex || + !glGetActiveUniformBlockiv || !glGetActiveUniformBlockName || + !glUniformBlockBinding || !glDrawArraysInstanced || + !glDrawElementsInstanced || !glFenceSync || !glIsSync || !glDeleteSync || + !glClientWaitSync || !glWaitSync || !glGetInteger64v || !glGetSynciv || + !glGetInteger64i_v || !glGetBufferParameteri64v || !glGenSamplers || + !glDeleteSamplers || !glIsSampler || !glBindSampler || + !glSamplerParameteri || !glSamplerParameteriv || !glSamplerParameterf || + !glSamplerParameterfv || !glGetSamplerParameteriv || + !glGetSamplerParameterfv || !glVertexAttribDivisor || + !glBindTransformFeedback || !glDeleteTransformFeedbacks || + !glGenTransformFeedbacks || !glIsTransformFeedback || + !glPauseTransformFeedback || !glResumeTransformFeedback || + !glGetProgramBinary || !glProgramBinary || !glProgramParameteri || + !glInvalidateFramebuffer || !glInvalidateSubFramebuffer || + !glTexStorage2D || !glTexStorage3D || !glGetInternalformativ) { + return GL_FALSE; + } + + return GL_TRUE; +} + +/* Function pointer definitions */ GL_APICALL void (*GL_APIENTRY glReadBuffer)( + GLenum mode); +GL_APICALL void (*GL_APIENTRY glDrawRangeElements)(GLenum mode, GLuint start, + GLuint end, GLsizei count, + GLenum type, + const GLvoid* indices); +GL_APICALL void (*GL_APIENTRY glTexImage3D)(GLenum target, GLint level, + GLint internalformat, GLsizei width, + GLsizei height, GLsizei depth, + GLint border, GLenum format, + GLenum type, const GLvoid* pixels); +GL_APICALL void (*GL_APIENTRY glTexSubImage3D)(GLenum target, GLint level, + GLint xoffset, GLint yoffset, + GLint zoffset, GLsizei width, + GLsizei height, GLsizei depth, + GLenum format, GLenum type, + const GLvoid* pixels); +GL_APICALL void (*GL_APIENTRY glCopyTexSubImage3D)(GLenum target, GLint level, + GLint xoffset, GLint yoffset, + GLint zoffset, GLint x, + GLint y, GLsizei width, + GLsizei height); +GL_APICALL void (*GL_APIENTRY glCompressedTexImage3D)( + GLenum target, GLint level, GLenum internalformat, GLsizei width, + GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, + const GLvoid* data); +GL_APICALL void (*GL_APIENTRY glCompressedTexSubImage3D)( + GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, + GLsizei width, GLsizei height, GLsizei depth, GLenum format, + GLsizei imageSize, const GLvoid* data); +GL_APICALL void (*GL_APIENTRY glGenQueries)(GLsizei n, GLuint* ids); +GL_APICALL void (*GL_APIENTRY glDeleteQueries)(GLsizei n, const GLuint* ids); +GL_APICALL GLboolean (*GL_APIENTRY glIsQuery)(GLuint id); +GL_APICALL void (*GL_APIENTRY glBeginQuery)(GLenum target, GLuint id); +GL_APICALL void (*GL_APIENTRY glEndQuery)(GLenum target); +GL_APICALL void (*GL_APIENTRY glGetQueryiv)(GLenum target, GLenum pname, + GLint* params); +GL_APICALL void (*GL_APIENTRY glGetQueryObjectuiv)(GLuint id, GLenum pname, + GLuint* params); +GL_APICALL GLboolean (*GL_APIENTRY glUnmapBuffer)(GLenum target); +GL_APICALL void (*GL_APIENTRY glGetBufferPointerv)(GLenum target, GLenum pname, + GLvoid** params); +GL_APICALL void (*GL_APIENTRY glDrawBuffers)(GLsizei n, const GLenum* bufs); +GL_APICALL void (*GL_APIENTRY glUniformMatrix2x3fv)(GLint location, + GLsizei count, + GLboolean transpose, + const GLfloat* value); +GL_APICALL void (*GL_APIENTRY glUniformMatrix3x2fv)(GLint location, + GLsizei count, + GLboolean transpose, + const GLfloat* value); +GL_APICALL void (*GL_APIENTRY glUniformMatrix2x4fv)(GLint location, + GLsizei count, + GLboolean transpose, + const GLfloat* value); +GL_APICALL void (*GL_APIENTRY glUniformMatrix4x2fv)(GLint location, + GLsizei count, + GLboolean transpose, + const GLfloat* value); +GL_APICALL void (*GL_APIENTRY glUniformMatrix3x4fv)(GLint location, + GLsizei count, + GLboolean transpose, + const GLfloat* value); +GL_APICALL void (*GL_APIENTRY glUniformMatrix4x3fv)(GLint location, + GLsizei count, + GLboolean transpose, + const GLfloat* value); +GL_APICALL void (*GL_APIENTRY glBlitFramebuffer)( + GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, + GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +GL_APICALL void (*GL_APIENTRY glRenderbufferStorageMultisample)( + GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, + GLsizei height); +GL_APICALL void (*GL_APIENTRY glFramebufferTextureLayer)( + GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +GL_APICALL GLvoid* (*GL_APIENTRY glMapBufferRange)(GLenum target, + GLintptr offset, + GLsizeiptr length, + GLbitfield access); +GL_APICALL void (*GL_APIENTRY glFlushMappedBufferRange)(GLenum target, + GLintptr offset, + GLsizeiptr length); +GL_APICALL void (*GL_APIENTRY glBindVertexArray)(GLuint array); +GL_APICALL void (*GL_APIENTRY glDeleteVertexArrays)(GLsizei n, + const GLuint* arrays); +GL_APICALL void (*GL_APIENTRY glGenVertexArrays)(GLsizei n, GLuint* arrays); +GL_APICALL GLboolean (*GL_APIENTRY glIsVertexArray)(GLuint array); +GL_APICALL void (*GL_APIENTRY glGetIntegeri_v)(GLenum target, GLuint index, + GLint* data); +GL_APICALL void (*GL_APIENTRY glBeginTransformFeedback)(GLenum primitiveMode); +GL_APICALL void (*GL_APIENTRY glEndTransformFeedback)(void); +GL_APICALL void (*GL_APIENTRY glBindBufferRange)(GLenum target, GLuint index, + GLuint buffer, GLintptr offset, + GLsizeiptr size); +GL_APICALL void (*GL_APIENTRY glBindBufferBase)(GLenum target, GLuint index, + GLuint buffer); +GL_APICALL void (*GL_APIENTRY glTransformFeedbackVaryings)( + GLuint program, GLsizei count, const GLchar* const* varyings, + GLenum bufferMode); +GL_APICALL void (*GL_APIENTRY glGetTransformFeedbackVarying)( + GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, + GLsizei* size, GLenum* type, GLchar* name); +GL_APICALL void (*GL_APIENTRY glVertexAttribIPointer)(GLuint index, GLint size, + GLenum type, + GLsizei stride, + const GLvoid* pointer); +GL_APICALL void (*GL_APIENTRY glGetVertexAttribIiv)(GLuint index, GLenum pname, + GLint* params); +GL_APICALL void (*GL_APIENTRY glGetVertexAttribIuiv)(GLuint index, GLenum pname, + GLuint* params); +GL_APICALL void (*GL_APIENTRY glVertexAttribI4i)(GLuint index, GLint x, GLint y, + GLint z, GLint w); +GL_APICALL void (*GL_APIENTRY glVertexAttribI4ui)(GLuint index, GLuint x, + GLuint y, GLuint z, GLuint w); +GL_APICALL void (*GL_APIENTRY glVertexAttribI4iv)(GLuint index, const GLint* v); +GL_APICALL void (*GL_APIENTRY glVertexAttribI4uiv)(GLuint index, + const GLuint* v); +GL_APICALL void (*GL_APIENTRY glGetUniformuiv)(GLuint program, GLint location, + GLuint* params); +GL_APICALL GLint (*GL_APIENTRY glGetFragDataLocation)(GLuint program, + const GLchar* name); +GL_APICALL void (*GL_APIENTRY glUniform1ui)(GLint location, GLuint v0); +GL_APICALL void (*GL_APIENTRY glUniform2ui)(GLint location, GLuint v0, + GLuint v1); +GL_APICALL void (*GL_APIENTRY glUniform3ui)(GLint location, GLuint v0, + GLuint v1, GLuint v2); +GL_APICALL void (*GL_APIENTRY glUniform4ui)(GLint location, GLuint v0, + GLuint v1, GLuint v2, GLuint v3); +GL_APICALL void (*GL_APIENTRY glUniform1uiv)(GLint location, GLsizei count, + const GLuint* value); +GL_APICALL void (*GL_APIENTRY glUniform2uiv)(GLint location, GLsizei count, + const GLuint* value); +GL_APICALL void (*GL_APIENTRY glUniform3uiv)(GLint location, GLsizei count, + const GLuint* value); +GL_APICALL void (*GL_APIENTRY glUniform4uiv)(GLint location, GLsizei count, + const GLuint* value); +GL_APICALL void (*GL_APIENTRY glClearBufferiv)(GLenum buffer, GLint drawbuffer, + const GLint* value); +GL_APICALL void (*GL_APIENTRY glClearBufferuiv)(GLenum buffer, GLint drawbuffer, + const GLuint* value); +GL_APICALL void (*GL_APIENTRY glClearBufferfv)(GLenum buffer, GLint drawbuffer, + const GLfloat* value); +GL_APICALL void (*GL_APIENTRY glClearBufferfi)(GLenum buffer, GLint drawbuffer, + GLfloat depth, GLint stencil); +GL_APICALL const GLubyte* (*GL_APIENTRY glGetStringi)(GLenum name, + GLuint index); +GL_APICALL void (*GL_APIENTRY glCopyBufferSubData)(GLenum readTarget, + GLenum writeTarget, + GLintptr readOffset, + GLintptr writeOffset, + GLsizeiptr size); +GL_APICALL void (*GL_APIENTRY glGetUniformIndices)( + GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, + GLuint* uniformIndices); +GL_APICALL void (*GL_APIENTRY glGetActiveUniformsiv)( + GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, + GLenum pname, GLint* params); +GL_APICALL GLuint (*GL_APIENTRY glGetUniformBlockIndex)( + GLuint program, const GLchar* uniformBlockName); +GL_APICALL void (*GL_APIENTRY glGetActiveUniformBlockiv)( + GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params); +GL_APICALL void (*GL_APIENTRY glGetActiveUniformBlockName)( + GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, + GLchar* uniformBlockName); +GL_APICALL void (*GL_APIENTRY glUniformBlockBinding)( + GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); +GL_APICALL void (*GL_APIENTRY glDrawArraysInstanced)(GLenum mode, GLint first, + GLsizei count, + GLsizei instanceCount); +GL_APICALL void (*GL_APIENTRY glDrawElementsInstanced)(GLenum mode, + GLsizei count, + GLenum type, + const GLvoid* indices, + GLsizei instanceCount); +GL_APICALL GLsync (*GL_APIENTRY glFenceSync)(GLenum condition, + GLbitfield flags); +GL_APICALL GLboolean (*GL_APIENTRY glIsSync)(GLsync sync); +GL_APICALL void (*GL_APIENTRY glDeleteSync)(GLsync sync); +GL_APICALL GLenum (*GL_APIENTRY glClientWaitSync)(GLsync sync, GLbitfield flags, + GLuint64 timeout); +GL_APICALL void (*GL_APIENTRY glWaitSync)(GLsync sync, GLbitfield flags, + GLuint64 timeout); +GL_APICALL void (*GL_APIENTRY glGetInteger64v)(GLenum pname, GLint64* params); +GL_APICALL void (*GL_APIENTRY glGetSynciv)(GLsync sync, GLenum pname, + GLsizei bufSize, GLsizei* length, + GLint* values); +GL_APICALL void (*GL_APIENTRY glGetInteger64i_v)(GLenum target, GLuint index, + GLint64* data); +GL_APICALL void (*GL_APIENTRY glGetBufferParameteri64v)(GLenum target, + GLenum pname, + GLint64* params); +GL_APICALL void (*GL_APIENTRY glGenSamplers)(GLsizei count, GLuint* samplers); +GL_APICALL void (*GL_APIENTRY glDeleteSamplers)(GLsizei count, + const GLuint* samplers); +GL_APICALL GLboolean (*GL_APIENTRY glIsSampler)(GLuint sampler); +GL_APICALL void (*GL_APIENTRY glBindSampler)(GLuint unit, GLuint sampler); +GL_APICALL void (*GL_APIENTRY glSamplerParameteri)(GLuint sampler, GLenum pname, + GLint param); +GL_APICALL void (*GL_APIENTRY glSamplerParameteriv)(GLuint sampler, + GLenum pname, + const GLint* param); +GL_APICALL void (*GL_APIENTRY glSamplerParameterf)(GLuint sampler, GLenum pname, + GLfloat param); +GL_APICALL void (*GL_APIENTRY glSamplerParameterfv)(GLuint sampler, + GLenum pname, + const GLfloat* param); +GL_APICALL void (*GL_APIENTRY glGetSamplerParameteriv)(GLuint sampler, + GLenum pname, + GLint* params); +GL_APICALL void (*GL_APIENTRY glGetSamplerParameterfv)(GLuint sampler, + GLenum pname, + GLfloat* params); +GL_APICALL void (*GL_APIENTRY glVertexAttribDivisor)(GLuint index, + GLuint divisor); +GL_APICALL void (*GL_APIENTRY glBindTransformFeedback)(GLenum target, + GLuint id); +GL_APICALL void (*GL_APIENTRY glDeleteTransformFeedbacks)(GLsizei n, + const GLuint* ids); +GL_APICALL void (*GL_APIENTRY glGenTransformFeedbacks)(GLsizei n, GLuint* ids); +GL_APICALL GLboolean (*GL_APIENTRY glIsTransformFeedback)(GLuint id); +GL_APICALL void (*GL_APIENTRY glPauseTransformFeedback)(void); +GL_APICALL void (*GL_APIENTRY glResumeTransformFeedback)(void); +GL_APICALL void (*GL_APIENTRY glGetProgramBinary)(GLuint program, + GLsizei bufSize, + GLsizei* length, + GLenum* binaryFormat, + GLvoid* binary); +GL_APICALL void (*GL_APIENTRY glProgramBinary)(GLuint program, + GLenum binaryFormat, + const GLvoid* binary, + GLsizei length); +GL_APICALL void (*GL_APIENTRY glProgramParameteri)(GLuint program, GLenum pname, + GLint value); +GL_APICALL void (*GL_APIENTRY glInvalidateFramebuffer)( + GLenum target, GLsizei numAttachments, const GLenum* attachments); +GL_APICALL void (*GL_APIENTRY glInvalidateSubFramebuffer)( + GLenum target, GLsizei numAttachments, const GLenum* attachments, GLint x, + GLint y, GLsizei width, GLsizei height); +GL_APICALL void (*GL_APIENTRY glTexStorage2D)(GLenum target, GLsizei levels, + GLenum internalformat, + GLsizei width, GLsizei height); +GL_APICALL void (*GL_APIENTRY glTexStorage3D)(GLenum target, GLsizei levels, + GLenum internalformat, + GLsizei width, GLsizei height, + GLsizei depth); +GL_APICALL void (*GL_APIENTRY glGetInternalformativ)(GLenum target, + GLenum internalformat, + GLenum pname, + GLsizei bufSize, + GLint* params); diff --git a/NativeApp/Android/ndk_helper/src/gl3stub.cpp b/NativeApp/Android/ndk_helper/src/gl3stub.cpp new file mode 100644 index 0000000..cb3575b --- /dev/null +++ b/NativeApp/Android/ndk_helper/src/gl3stub.cpp @@ -0,0 +1,421 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include <EGL/egl.h> +#include "gl3stub.h" + +GLboolean gl3stubInit() { +#define FIND_PROC(s) s = (decltype(s))eglGetProcAddress(#s); + FIND_PROC(glReadBuffer); + FIND_PROC(glDrawRangeElements); + FIND_PROC(glTexImage3D); + FIND_PROC(glTexSubImage3D); + FIND_PROC(glCopyTexSubImage3D); + FIND_PROC(glCompressedTexImage3D); + FIND_PROC(glCompressedTexSubImage3D); + FIND_PROC(glGenQueries); + FIND_PROC(glDeleteQueries); + FIND_PROC(glIsQuery); + FIND_PROC(glBeginQuery); + FIND_PROC(glEndQuery); + FIND_PROC(glGetQueryiv); + FIND_PROC(glGetQueryObjectuiv); + FIND_PROC(glUnmapBuffer); + FIND_PROC(glGetBufferPointerv); + FIND_PROC(glDrawBuffers); + FIND_PROC(glUniformMatrix2x3fv); + FIND_PROC(glUniformMatrix3x2fv); + FIND_PROC(glUniformMatrix2x4fv); + FIND_PROC(glUniformMatrix4x2fv); + FIND_PROC(glUniformMatrix3x4fv); + FIND_PROC(glUniformMatrix4x3fv); + FIND_PROC(glBlitFramebuffer); + FIND_PROC(glRenderbufferStorageMultisample); + FIND_PROC(glFramebufferTextureLayer); + FIND_PROC(glMapBufferRange); + FIND_PROC(glFlushMappedBufferRange); + FIND_PROC(glBindVertexArray); + FIND_PROC(glDeleteVertexArrays); + FIND_PROC(glGenVertexArrays); + FIND_PROC(glIsVertexArray); + FIND_PROC(glGetIntegeri_v); + FIND_PROC(glBeginTransformFeedback); + FIND_PROC(glEndTransformFeedback); + FIND_PROC(glBindBufferRange); + FIND_PROC(glBindBufferBase); + FIND_PROC(glTransformFeedbackVaryings); + FIND_PROC(glGetTransformFeedbackVarying); + FIND_PROC(glVertexAttribIPointer); + FIND_PROC(glGetVertexAttribIiv); + FIND_PROC(glGetVertexAttribIuiv); + FIND_PROC(glVertexAttribI4i); + FIND_PROC(glVertexAttribI4ui); + FIND_PROC(glVertexAttribI4iv); + FIND_PROC(glVertexAttribI4uiv); + FIND_PROC(glGetUniformuiv); + FIND_PROC(glGetFragDataLocation); + FIND_PROC(glUniform1ui); + FIND_PROC(glUniform2ui); + FIND_PROC(glUniform3ui); + FIND_PROC(glUniform4ui); + FIND_PROC(glUniform1uiv); + FIND_PROC(glUniform2uiv); + FIND_PROC(glUniform3uiv); + FIND_PROC(glUniform4uiv); + FIND_PROC(glClearBufferiv); + FIND_PROC(glClearBufferuiv); + FIND_PROC(glClearBufferfv); + FIND_PROC(glClearBufferfi); + FIND_PROC(glGetStringi); + FIND_PROC(glCopyBufferSubData); + FIND_PROC(glGetUniformIndices); + FIND_PROC(glGetActiveUniformsiv); + FIND_PROC(glGetUniformBlockIndex); + FIND_PROC(glGetActiveUniformBlockiv); + FIND_PROC(glGetActiveUniformBlockName); + FIND_PROC(glUniformBlockBinding); + FIND_PROC(glDrawArraysInstanced); + FIND_PROC(glDrawElementsInstanced); + FIND_PROC(glFenceSync); + FIND_PROC(glIsSync); + FIND_PROC(glDeleteSync); + FIND_PROC(glClientWaitSync); + FIND_PROC(glWaitSync); + FIND_PROC(glGetInteger64v); + FIND_PROC(glGetSynciv); + FIND_PROC(glGetInteger64i_v); + FIND_PROC(glGetBufferParameteri64v); + FIND_PROC(glGenSamplers); + FIND_PROC(glDeleteSamplers); + FIND_PROC(glIsSampler); + FIND_PROC(glBindSampler); + FIND_PROC(glSamplerParameteri); + FIND_PROC(glSamplerParameteriv); + FIND_PROC(glSamplerParameterf); + FIND_PROC(glSamplerParameterfv); + FIND_PROC(glGetSamplerParameteriv); + FIND_PROC(glGetSamplerParameterfv); + FIND_PROC(glVertexAttribDivisor); + FIND_PROC(glBindTransformFeedback); + FIND_PROC(glDeleteTransformFeedbacks); + FIND_PROC(glGenTransformFeedbacks); + FIND_PROC(glIsTransformFeedback); + FIND_PROC(glPauseTransformFeedback); + FIND_PROC(glResumeTransformFeedback); + FIND_PROC(glGetProgramBinary); + FIND_PROC(glProgramBinary); + FIND_PROC(glProgramParameteri); + FIND_PROC(glInvalidateFramebuffer); + FIND_PROC(glInvalidateSubFramebuffer); + FIND_PROC(glTexStorage2D); + FIND_PROC(glTexStorage3D); + FIND_PROC(glGetInternalformativ); +#undef FIND_PROC + + if (!glReadBuffer || !glDrawRangeElements || !glTexImage3D || + !glTexSubImage3D || !glCopyTexSubImage3D || !glCompressedTexImage3D || + !glCompressedTexSubImage3D || !glGenQueries || !glDeleteQueries || + !glIsQuery || !glBeginQuery || !glEndQuery || !glGetQueryiv || + !glGetQueryObjectuiv || !glUnmapBuffer || !glGetBufferPointerv || + !glDrawBuffers || !glUniformMatrix2x3fv || !glUniformMatrix3x2fv || + !glUniformMatrix2x4fv || !glUniformMatrix4x2fv || !glUniformMatrix3x4fv || + !glUniformMatrix4x3fv || !glBlitFramebuffer || + !glRenderbufferStorageMultisample || !glFramebufferTextureLayer || + !glMapBufferRange || !glFlushMappedBufferRange || !glBindVertexArray || + !glDeleteVertexArrays || !glGenVertexArrays || !glIsVertexArray || + !glGetIntegeri_v || !glBeginTransformFeedback || + !glEndTransformFeedback || !glBindBufferRange || !glBindBufferBase || + !glTransformFeedbackVaryings || !glGetTransformFeedbackVarying || + !glVertexAttribIPointer || !glGetVertexAttribIiv || + !glGetVertexAttribIuiv || !glVertexAttribI4i || !glVertexAttribI4ui || + !glVertexAttribI4iv || !glVertexAttribI4uiv || !glGetUniformuiv || + !glGetFragDataLocation || !glUniform1ui || !glUniform2ui || + !glUniform3ui || !glUniform4ui || !glUniform1uiv || !glUniform2uiv || + !glUniform3uiv || !glUniform4uiv || !glClearBufferiv || + !glClearBufferuiv || !glClearBufferfv || !glClearBufferfi || + !glGetStringi || !glCopyBufferSubData || !glGetUniformIndices || + !glGetActiveUniformsiv || !glGetUniformBlockIndex || + !glGetActiveUniformBlockiv || !glGetActiveUniformBlockName || + !glUniformBlockBinding || !glDrawArraysInstanced || + !glDrawElementsInstanced || !glFenceSync || !glIsSync || !glDeleteSync || + !glClientWaitSync || !glWaitSync || !glGetInteger64v || !glGetSynciv || + !glGetInteger64i_v || !glGetBufferParameteri64v || !glGenSamplers || + !glDeleteSamplers || !glIsSampler || !glBindSampler || + !glSamplerParameteri || !glSamplerParameteriv || !glSamplerParameterf || + !glSamplerParameterfv || !glGetSamplerParameteriv || + !glGetSamplerParameterfv || !glVertexAttribDivisor || + !glBindTransformFeedback || !glDeleteTransformFeedbacks || + !glGenTransformFeedbacks || !glIsTransformFeedback || + !glPauseTransformFeedback || !glResumeTransformFeedback || + !glGetProgramBinary || !glProgramBinary || !glProgramParameteri || + !glInvalidateFramebuffer || !glInvalidateSubFramebuffer || + !glTexStorage2D || !glTexStorage3D || !glGetInternalformativ) { + return GL_FALSE; + } + + return GL_TRUE; +} + +/* Function pointer definitions */ GL_APICALL void (*GL_APIENTRY glReadBuffer)( + GLenum mode); +GL_APICALL void (*GL_APIENTRY glDrawRangeElements)(GLenum mode, GLuint start, + GLuint end, GLsizei count, + GLenum type, + const GLvoid* indices); +GL_APICALL void (*GL_APIENTRY glTexImage3D)(GLenum target, GLint level, + GLint internalformat, GLsizei width, + GLsizei height, GLsizei depth, + GLint border, GLenum format, + GLenum type, const GLvoid* pixels); +GL_APICALL void (*GL_APIENTRY glTexSubImage3D)(GLenum target, GLint level, + GLint xoffset, GLint yoffset, + GLint zoffset, GLsizei width, + GLsizei height, GLsizei depth, + GLenum format, GLenum type, + const GLvoid* pixels); +GL_APICALL void (*GL_APIENTRY glCopyTexSubImage3D)(GLenum target, GLint level, + GLint xoffset, GLint yoffset, + GLint zoffset, GLint x, + GLint y, GLsizei width, + GLsizei height); +GL_APICALL void (*GL_APIENTRY glCompressedTexImage3D)( + GLenum target, GLint level, GLenum internalformat, GLsizei width, + GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, + const GLvoid* data); +GL_APICALL void (*GL_APIENTRY glCompressedTexSubImage3D)( + GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, + GLsizei width, GLsizei height, GLsizei depth, GLenum format, + GLsizei imageSize, const GLvoid* data); +GL_APICALL void (*GL_APIENTRY glGenQueries)(GLsizei n, GLuint* ids); +GL_APICALL void (*GL_APIENTRY glDeleteQueries)(GLsizei n, const GLuint* ids); +GL_APICALL GLboolean (*GL_APIENTRY glIsQuery)(GLuint id); +GL_APICALL void (*GL_APIENTRY glBeginQuery)(GLenum target, GLuint id); +GL_APICALL void (*GL_APIENTRY glEndQuery)(GLenum target); +GL_APICALL void (*GL_APIENTRY glGetQueryiv)(GLenum target, GLenum pname, + GLint* params); +GL_APICALL void (*GL_APIENTRY glGetQueryObjectuiv)(GLuint id, GLenum pname, + GLuint* params); +GL_APICALL GLboolean (*GL_APIENTRY glUnmapBuffer)(GLenum target); +GL_APICALL void (*GL_APIENTRY glGetBufferPointerv)(GLenum target, GLenum pname, + GLvoid** params); +GL_APICALL void (*GL_APIENTRY glDrawBuffers)(GLsizei n, const GLenum* bufs); +GL_APICALL void (*GL_APIENTRY glUniformMatrix2x3fv)(GLint location, + GLsizei count, + GLboolean transpose, + const GLfloat* value); +GL_APICALL void (*GL_APIENTRY glUniformMatrix3x2fv)(GLint location, + GLsizei count, + GLboolean transpose, + const GLfloat* value); +GL_APICALL void (*GL_APIENTRY glUniformMatrix2x4fv)(GLint location, + GLsizei count, + GLboolean transpose, + const GLfloat* value); +GL_APICALL void (*GL_APIENTRY glUniformMatrix4x2fv)(GLint location, + GLsizei count, + GLboolean transpose, + const GLfloat* value); +GL_APICALL void (*GL_APIENTRY glUniformMatrix3x4fv)(GLint location, + GLsizei count, + GLboolean transpose, + const GLfloat* value); +GL_APICALL void (*GL_APIENTRY glUniformMatrix4x3fv)(GLint location, + GLsizei count, + GLboolean transpose, + const GLfloat* value); +GL_APICALL void (*GL_APIENTRY glBlitFramebuffer)( + GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, + GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +GL_APICALL void (*GL_APIENTRY glRenderbufferStorageMultisample)( + GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, + GLsizei height); +GL_APICALL void (*GL_APIENTRY glFramebufferTextureLayer)( + GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +GL_APICALL GLvoid* (*GL_APIENTRY glMapBufferRange)(GLenum target, + GLintptr offset, + GLsizeiptr length, + GLbitfield access); +GL_APICALL void (*GL_APIENTRY glFlushMappedBufferRange)(GLenum target, + GLintptr offset, + GLsizeiptr length); +GL_APICALL void (*GL_APIENTRY glBindVertexArray)(GLuint array); +GL_APICALL void (*GL_APIENTRY glDeleteVertexArrays)(GLsizei n, + const GLuint* arrays); +GL_APICALL void (*GL_APIENTRY glGenVertexArrays)(GLsizei n, GLuint* arrays); +GL_APICALL GLboolean (*GL_APIENTRY glIsVertexArray)(GLuint array); +GL_APICALL void (*GL_APIENTRY glGetIntegeri_v)(GLenum target, GLuint index, + GLint* data); +GL_APICALL void (*GL_APIENTRY glBeginTransformFeedback)(GLenum primitiveMode); +GL_APICALL void (*GL_APIENTRY glEndTransformFeedback)(void); +GL_APICALL void (*GL_APIENTRY glBindBufferRange)(GLenum target, GLuint index, + GLuint buffer, GLintptr offset, + GLsizeiptr size); +GL_APICALL void (*GL_APIENTRY glBindBufferBase)(GLenum target, GLuint index, + GLuint buffer); +GL_APICALL void (*GL_APIENTRY glTransformFeedbackVaryings)( + GLuint program, GLsizei count, const GLchar* const* varyings, + GLenum bufferMode); +GL_APICALL void (*GL_APIENTRY glGetTransformFeedbackVarying)( + GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, + GLsizei* size, GLenum* type, GLchar* name); +GL_APICALL void (*GL_APIENTRY glVertexAttribIPointer)(GLuint index, GLint size, + GLenum type, + GLsizei stride, + const GLvoid* pointer); +GL_APICALL void (*GL_APIENTRY glGetVertexAttribIiv)(GLuint index, GLenum pname, + GLint* params); +GL_APICALL void (*GL_APIENTRY glGetVertexAttribIuiv)(GLuint index, GLenum pname, + GLuint* params); +GL_APICALL void (*GL_APIENTRY glVertexAttribI4i)(GLuint index, GLint x, GLint y, + GLint z, GLint w); +GL_APICALL void (*GL_APIENTRY glVertexAttribI4ui)(GLuint index, GLuint x, + GLuint y, GLuint z, GLuint w); +GL_APICALL void (*GL_APIENTRY glVertexAttribI4iv)(GLuint index, const GLint* v); +GL_APICALL void (*GL_APIENTRY glVertexAttribI4uiv)(GLuint index, + const GLuint* v); +GL_APICALL void (*GL_APIENTRY glGetUniformuiv)(GLuint program, GLint location, + GLuint* params); +GL_APICALL GLint (*GL_APIENTRY glGetFragDataLocation)(GLuint program, + const GLchar* name); +GL_APICALL void (*GL_APIENTRY glUniform1ui)(GLint location, GLuint v0); +GL_APICALL void (*GL_APIENTRY glUniform2ui)(GLint location, GLuint v0, + GLuint v1); +GL_APICALL void (*GL_APIENTRY glUniform3ui)(GLint location, GLuint v0, + GLuint v1, GLuint v2); +GL_APICALL void (*GL_APIENTRY glUniform4ui)(GLint location, GLuint v0, + GLuint v1, GLuint v2, GLuint v3); +GL_APICALL void (*GL_APIENTRY glUniform1uiv)(GLint location, GLsizei count, + const GLuint* value); +GL_APICALL void (*GL_APIENTRY glUniform2uiv)(GLint location, GLsizei count, + const GLuint* value); +GL_APICALL void (*GL_APIENTRY glUniform3uiv)(GLint location, GLsizei count, + const GLuint* value); +GL_APICALL void (*GL_APIENTRY glUniform4uiv)(GLint location, GLsizei count, + const GLuint* value); +GL_APICALL void (*GL_APIENTRY glClearBufferiv)(GLenum buffer, GLint drawbuffer, + const GLint* value); +GL_APICALL void (*GL_APIENTRY glClearBufferuiv)(GLenum buffer, GLint drawbuffer, + const GLuint* value); +GL_APICALL void (*GL_APIENTRY glClearBufferfv)(GLenum buffer, GLint drawbuffer, + const GLfloat* value); +GL_APICALL void (*GL_APIENTRY glClearBufferfi)(GLenum buffer, GLint drawbuffer, + GLfloat depth, GLint stencil); +GL_APICALL const GLubyte* (*GL_APIENTRY glGetStringi)(GLenum name, + GLuint index); +GL_APICALL void (*GL_APIENTRY glCopyBufferSubData)(GLenum readTarget, + GLenum writeTarget, + GLintptr readOffset, + GLintptr writeOffset, + GLsizeiptr size); +GL_APICALL void (*GL_APIENTRY glGetUniformIndices)( + GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, + GLuint* uniformIndices); +GL_APICALL void (*GL_APIENTRY glGetActiveUniformsiv)( + GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, + GLenum pname, GLint* params); +GL_APICALL GLuint (*GL_APIENTRY glGetUniformBlockIndex)( + GLuint program, const GLchar* uniformBlockName); +GL_APICALL void (*GL_APIENTRY glGetActiveUniformBlockiv)( + GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params); +GL_APICALL void (*GL_APIENTRY glGetActiveUniformBlockName)( + GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, + GLchar* uniformBlockName); +GL_APICALL void (*GL_APIENTRY glUniformBlockBinding)( + GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); +GL_APICALL void (*GL_APIENTRY glDrawArraysInstanced)(GLenum mode, GLint first, + GLsizei count, + GLsizei instanceCount); +GL_APICALL void (*GL_APIENTRY glDrawElementsInstanced)(GLenum mode, + GLsizei count, + GLenum type, + const GLvoid* indices, + GLsizei instanceCount); +GL_APICALL GLsync (*GL_APIENTRY glFenceSync)(GLenum condition, + GLbitfield flags); +GL_APICALL GLboolean (*GL_APIENTRY glIsSync)(GLsync sync); +GL_APICALL void (*GL_APIENTRY glDeleteSync)(GLsync sync); +GL_APICALL GLenum (*GL_APIENTRY glClientWaitSync)(GLsync sync, GLbitfield flags, + GLuint64 timeout); +GL_APICALL void (*GL_APIENTRY glWaitSync)(GLsync sync, GLbitfield flags, + GLuint64 timeout); +GL_APICALL void (*GL_APIENTRY glGetInteger64v)(GLenum pname, GLint64* params); +GL_APICALL void (*GL_APIENTRY glGetSynciv)(GLsync sync, GLenum pname, + GLsizei bufSize, GLsizei* length, + GLint* values); +GL_APICALL void (*GL_APIENTRY glGetInteger64i_v)(GLenum target, GLuint index, + GLint64* data); +GL_APICALL void (*GL_APIENTRY glGetBufferParameteri64v)(GLenum target, + GLenum pname, + GLint64* params); +GL_APICALL void (*GL_APIENTRY glGenSamplers)(GLsizei count, GLuint* samplers); +GL_APICALL void (*GL_APIENTRY glDeleteSamplers)(GLsizei count, + const GLuint* samplers); +GL_APICALL GLboolean (*GL_APIENTRY glIsSampler)(GLuint sampler); +GL_APICALL void (*GL_APIENTRY glBindSampler)(GLuint unit, GLuint sampler); +GL_APICALL void (*GL_APIENTRY glSamplerParameteri)(GLuint sampler, GLenum pname, + GLint param); +GL_APICALL void (*GL_APIENTRY glSamplerParameteriv)(GLuint sampler, + GLenum pname, + const GLint* param); +GL_APICALL void (*GL_APIENTRY glSamplerParameterf)(GLuint sampler, GLenum pname, + GLfloat param); +GL_APICALL void (*GL_APIENTRY glSamplerParameterfv)(GLuint sampler, + GLenum pname, + const GLfloat* param); +GL_APICALL void (*GL_APIENTRY glGetSamplerParameteriv)(GLuint sampler, + GLenum pname, + GLint* params); +GL_APICALL void (*GL_APIENTRY glGetSamplerParameterfv)(GLuint sampler, + GLenum pname, + GLfloat* params); +GL_APICALL void (*GL_APIENTRY glVertexAttribDivisor)(GLuint index, + GLuint divisor); +GL_APICALL void (*GL_APIENTRY glBindTransformFeedback)(GLenum target, + GLuint id); +GL_APICALL void (*GL_APIENTRY glDeleteTransformFeedbacks)(GLsizei n, + const GLuint* ids); +GL_APICALL void (*GL_APIENTRY glGenTransformFeedbacks)(GLsizei n, GLuint* ids); +GL_APICALL GLboolean (*GL_APIENTRY glIsTransformFeedback)(GLuint id); +GL_APICALL void (*GL_APIENTRY glPauseTransformFeedback)(void); +GL_APICALL void (*GL_APIENTRY glResumeTransformFeedback)(void); +GL_APICALL void (*GL_APIENTRY glGetProgramBinary)(GLuint program, + GLsizei bufSize, + GLsizei* length, + GLenum* binaryFormat, + GLvoid* binary); +GL_APICALL void (*GL_APIENTRY glProgramBinary)(GLuint program, + GLenum binaryFormat, + const GLvoid* binary, + GLsizei length); +GL_APICALL void (*GL_APIENTRY glProgramParameteri)(GLuint program, GLenum pname, + GLint value); +GL_APICALL void (*GL_APIENTRY glInvalidateFramebuffer)( + GLenum target, GLsizei numAttachments, const GLenum* attachments); +GL_APICALL void (*GL_APIENTRY glInvalidateSubFramebuffer)( + GLenum target, GLsizei numAttachments, const GLenum* attachments, GLint x, + GLint y, GLsizei width, GLsizei height); +GL_APICALL void (*GL_APIENTRY glTexStorage2D)(GLenum target, GLsizei levels, + GLenum internalformat, + GLsizei width, GLsizei height); +GL_APICALL void (*GL_APIENTRY glTexStorage3D)(GLenum target, GLsizei levels, + GLenum internalformat, + GLsizei width, GLsizei height, + GLsizei depth); +GL_APICALL void (*GL_APIENTRY glGetInternalformativ)(GLenum target, + GLenum internalformat, + GLenum pname, + GLsizei bufSize, + GLint* params); diff --git a/NativeApp/Android/ndk_helper/src/interpolator.cpp b/NativeApp/Android/ndk_helper/src/interpolator.cpp new file mode 100644 index 0000000..f729914 --- /dev/null +++ b/NativeApp/Android/ndk_helper/src/interpolator.cpp @@ -0,0 +1,153 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "interpolator.h" +#include <math.h> +#include "interpolator.h" + +namespace ndk_helper { + +//------------------------------------------------- +// Ctor +//------------------------------------------------- +Interpolator::Interpolator() { list_params_.clear(); } + +//------------------------------------------------- +// Dtor +//------------------------------------------------- +Interpolator::~Interpolator() { list_params_.clear(); } + +void Interpolator::Clear() { list_params_.clear(); } + +Interpolator& Interpolator::Set(const float start, const float dest, + const INTERPOLATOR_TYPE type, + const double duration) { + // init the parameters for the interpolation process + start_time_ = PerfMonitor::GetCurrentTime(); + dest_time_ = start_time_ + duration; + type_ = type; + + start_value_ = start; + dest_value_ = dest; + return *this; +} + +Interpolator& Interpolator::Add(const float dest, const INTERPOLATOR_TYPE type, + const double duration) { + InterpolatorParams param; + param.dest_value_ = dest; + param.type_ = type; + param.duration_ = duration; + list_params_.push_back(param); + return *this; +} + +bool Interpolator::Update(const double current_time, float& p) { + bool bContinue; + if (current_time >= dest_time_) { + p = dest_value_; + if (list_params_.size()) { + InterpolatorParams& item = list_params_.front(); + Set(dest_value_, item.dest_value_, item.type_, item.duration_); + list_params_.pop_front(); + + bContinue = true; + } else { + bContinue = false; + } + } else { + float t = (float)(current_time - start_time_); + float d = (float)(dest_time_ - start_time_); + float b = start_value_; + float c = dest_value_ - start_value_; + p = GetFormula(type_, t, b, d, c); + + bContinue = true; + } + return bContinue; +} + +float Interpolator::GetFormula(const INTERPOLATOR_TYPE type, const float t, + const float b, const float d, const float c) { + float t1; + switch (type) { + case INTERPOLATOR_TYPE_LINEAR: + // simple linear interpolation - no easing + return (c * t / d + b); + + case INTERPOLATOR_TYPE_EASEINQUAD: + // quadratic (t^2) easing in - accelerating from zero velocity + t1 = t / d; + return (c * t1 * t1 + b); + + case INTERPOLATOR_TYPE_EASEOUTQUAD: + // quadratic (t^2) easing out - decelerating to zero velocity + t1 = t / d; + return (-c * t1 * (t1 - 2) + b); + + case INTERPOLATOR_TYPE_EASEINOUTQUAD: + // quadratic easing in/out - acceleration until halfway, then deceleration + t1 = t / d / 2; + if (t1 < 1) + return (c / 2 * t1 * t1 + b); + else { + t1 = t1 - 1; + return (-c / 2 * (t1 * (t1 - 2) - 1) + b); + } + case INTERPOLATOR_TYPE_EASEINCUBIC: + // cubic easing in - accelerating from zero velocity + t1 = t / d; + return (c * t1 * t1 * t1 + b); + + case INTERPOLATOR_TYPE_EASEOUTCUBIC: + // cubic easing in - accelerating from zero velocity + t1 = t / d - 1; + return (c * (t1 * t1 * t1 + 1) + b); + + case INTERPOLATOR_TYPE_EASEINOUTCUBIC: + // cubic easing in - accelerating from zero velocity + t1 = t / d / 2; + + if (t1 < 1) + return (c / 2 * t1 * t1 * t1 + b); + else { + t1 -= 2; + return (c / 2 * (t1 * t1 * t1 + 2) + b); + } + case INTERPOLATOR_TYPE_EASEINQUART: + // quartic easing in - accelerating from zero velocity + t1 = t / d; + return (c * t1 * t1 * t1 * t1 + b); + + case INTERPOLATOR_TYPE_EASEINEXPO: + // exponential (2^t) easing in - accelerating from zero velocity + if (t == 0) + return b; + else + return (c * powf(2, (10 * (t / d - 1))) + b); + + case INTERPOLATOR_TYPE_EASEOUTEXPO: + // exponential (2^t) easing out - decelerating to zero velocity + if (t == d) + return (b + c); + else + return (c * (-powf(2, -10 * t / d) + 1) + b); + default: + return 0; + } +} + +} // namespace ndkHelper diff --git a/NativeApp/Android/ndk_helper/src/java/com/android/helper/NDKHelper.java b/NativeApp/Android/ndk_helper/src/java/com/android/helper/NDKHelper.java new file mode 100644 index 0000000..8c9055b --- /dev/null +++ b/NativeApp/Android/ndk_helper/src/java/com/android/helper/NDKHelper.java @@ -0,0 +1,360 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Must be changed with #define HELPER_CLASS_NAME "com/android/helper/NDKHelper" in AndroidMain.cpp +package com.android.helper; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.nio.ByteBuffer; + +import javax.microedition.khronos.opengles.GL10; + +import android.R.bool; +import android.opengl.GLES30; + +import android.annotation.TargetApi; +import android.app.Activity; +import android.app.NativeActivity; +import android.content.Context; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.content.pm.PackageManager.NameNotFoundException; +import android.graphics.Bitmap; +import android.graphics.Bitmap.CompressFormat; +import android.graphics.BitmapFactory; +import android.graphics.Matrix; +import android.media.AudioManager; +import android.media.AudioTrack; +import android.opengl.GLUtils; +import android.os.Build; +import android.util.Log; +import android.view.View; +import android.view.View.MeasureSpec; + +@TargetApi(Build.VERSION_CODES.GINGERBREAD) +public class NDKHelper { + + public NDKHelper(NativeActivity act) { + activity = act; + } + + public void loadLibrary(String soname) { + if (soname.isEmpty() == false) { + System.loadLibrary(soname); + loadedSO = true; + } + } + + public static Boolean checkSOLoaded() { + if (loadedSO == false) { + Log.e("NDKHelper", + "--------------------------------------------\n" + + ".so has not been loaded. To use JUI helper, please initialize with \n" + + "NDKHelper::Init( ANativeActivity* activity, const char* helper_class_name, const char* native_soname);\n" + + "--------------------------------------------\n"); + return false; + } else + return true; + } + + private static boolean loadedSO = false; + NativeActivity activity; + + + + // + // Load Bitmap + // Java helper is useful decoding PNG, TIFF etc rather than linking libPng + // etc separately + // + private int nextPOT(int i) { + int pot = 1; + while (pot < i) + pot <<= 1; + return pot; + } + + private Bitmap scaleBitmap(Bitmap bitmapToScale, float newWidth, + float newHeight) { + if (bitmapToScale == null) + return null; + // get the original width and height + int width = bitmapToScale.getWidth(); + int height = bitmapToScale.getHeight(); + // create a matrix for the manipulation + Matrix matrix = new Matrix(); + + // resize the bit map + matrix.postScale(newWidth / width, newHeight / height); + + // recreate the new Bitmap and set it back + return Bitmap.createBitmap(bitmapToScale, 0, 0, + bitmapToScale.getWidth(), bitmapToScale.getHeight(), matrix, + true); + } + + public class TextureInformation { + boolean ret; + boolean alphaChannel; + int originalWidth; + int originalHeight; + Object image; + } + + public Object loadTexture(String path) { + Bitmap bitmap = null; + TextureInformation info = new TextureInformation(); + try { + String str = path; + if (!path.startsWith("/")) { + str = "/" + path; + } + + File file = new File(activity.getExternalFilesDir(null), str); + if (file.canRead()) { + bitmap = BitmapFactory.decodeStream(new FileInputStream(file)); + } else { + bitmap = BitmapFactory.decodeStream(activity.getResources() + .getAssets().open(path)); + } + // Matrix matrix = new Matrix(); + // // resize the bit map + // matrix.postScale(-1F, 1F); + // + // // recreate the new Bitmap and set it back + // bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), + // bitmap.getHeight(), matrix, true); + + } catch (Exception e) { + Log.w("NDKHelper", "Coundn't load a file:" + path); + info.ret = false; + return info; + } + + if (bitmap != null) { + GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); + } + info.ret = true; + info.alphaChannel = bitmap.hasAlpha(); + info.originalWidth = getBitmapWidth(bitmap); + info.originalHeight = getBitmapHeight(bitmap); + + return info; + } + + public Object loadCubemapTexture(String path, int face, int miplevel, boolean sRGB) { + Bitmap bitmap = null; + TextureInformation info = new TextureInformation(); + try { + String str = path; + if (!path.startsWith("/")) { + str = "/" + path; + } + + File file = new File(activity.getExternalFilesDir(null), str); + if (file.canRead()) { + bitmap = BitmapFactory.decodeStream(new FileInputStream(file)); + } else { + bitmap = BitmapFactory.decodeStream(activity.getResources() + .getAssets().open(path)); + } + } catch (Exception e) { + Log.w("NDKHelper", "Coundn't load a file:" + path); + info.ret = false; + return info; + } + + if (bitmap != null) { + if (sRGB) + { +// GLUtils.texImage2D(face, miplevel, bitmap, 0); +// GLUtils.texImage2D(face, miplevel, +// GLUtils.getInternalFormat(bitmap), bitmap, 0); +// int i = GLUtils.getInternalFormat(bitmap); +// if( i == GL10.GL_RGBA) +// { +// GLUtils.texImage2D(face, miplevel, +// GLES30.GL_SRGB, bitmap, 0); +// } + //Leave them for now + GLUtils.texImage2D(face, miplevel, bitmap, 0); + } + else + GLUtils.texImage2D(face, miplevel, bitmap, 0); + } + info.ret = true; + info.alphaChannel = bitmap.hasAlpha(); + info.originalWidth = getBitmapWidth(bitmap); + info.originalHeight = getBitmapHeight(bitmap); + + return info; + + } + + public Object loadImage(String path) { + Bitmap bitmap = null; + TextureInformation info = new TextureInformation(); + try { + String str = path; + if (!path.startsWith("/")) { + str = "/" + path; + } + + File file = new File(activity.getExternalFilesDir(null), str); + if (file.canRead()) { + bitmap = BitmapFactory.decodeStream(new FileInputStream(file)); + } else { + bitmap = BitmapFactory.decodeStream(activity.getResources() + .getAssets().open(path)); + } + } catch (Exception e) { + Log.w("NDKHelper", "Coundn't load a file:" + path); + info.ret = false; + return info; + } + + if (bitmap != null) { + GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); + } + info.ret = true; + info.alphaChannel = bitmap.hasAlpha(); + info.originalWidth = getBitmapWidth(bitmap); + info.originalHeight = getBitmapHeight(bitmap); + + int iBytes = bitmap.getWidth() * bitmap.getHeight() * 4; + ByteBuffer buffer = ByteBuffer.allocateDirect(iBytes); + + bitmap.copyPixelsToBuffer(buffer); + info.image = buffer; + return info; + } + + public Bitmap openBitmap(String path, boolean iScalePOT) { + Bitmap bitmap = null; + try { + bitmap = BitmapFactory.decodeStream(activity.getResources() + .getAssets().open(path)); + if (iScalePOT) { + int originalWidth = getBitmapWidth(bitmap); + int originalHeight = getBitmapHeight(bitmap); + int width = nextPOT(originalWidth); + int height = nextPOT(originalHeight); + if (originalWidth != width || originalHeight != height) { + // Scale it + bitmap = scaleBitmap(bitmap, width, height); + } + } + + } catch (Exception e) { + Log.w("NDKHelper", "Coundn't load a file:" + path); + } + + return bitmap; + } + + public int getBitmapWidth(Bitmap bmp) { + return bmp.getWidth(); + } + + public int getBitmapHeight(Bitmap bmp) { + return bmp.getHeight(); + } + + public void getBitmapPixels(Bitmap bmp, int[] pixels) { + int w = bmp.getWidth(); + int h = bmp.getHeight(); + bmp.getPixels(pixels, 0, w, 0, 0, w, h); + } + + public void closeBitmap(Bitmap bmp) { + bmp.recycle(); + } + + public String getNativeLibraryDirectory(Context appContext) { + ApplicationInfo ai = activity.getApplicationInfo(); + + Log.w("NDKHelper", "ai.nativeLibraryDir:" + ai.nativeLibraryDir); + + if ((ai.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0 + || (ai.flags & ApplicationInfo.FLAG_SYSTEM) == 0) { + return ai.nativeLibraryDir; + } + return "/system/lib/"; + } + + public String getApplicationName() { + final PackageManager pm = activity.getPackageManager(); + ApplicationInfo ai; + try { + ai = pm.getApplicationInfo(activity.getPackageName(), 0); + } catch (final NameNotFoundException e) { + ai = null; + } + String applicationName = (String) (ai != null ? pm + .getApplicationLabel(ai) : "(unknown)"); + return applicationName; + } + + public String getStringResource(String resourceName) + { + int id = activity.getResources().getIdentifier(resourceName, "string", activity.getPackageName()); + String value = id == 0 ? "" : (String)activity.getResources().getText(id); + return value; + } + + // + // Audio related helpers + // + @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) + public int getNativeAudioBufferSize() { + int SDK_INT = android.os.Build.VERSION.SDK_INT; + if (SDK_INT >= 17) { + AudioManager am = (AudioManager) activity + .getSystemService(Context.AUDIO_SERVICE); + String framesPerBuffer = am + .getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER); + return Integer.parseInt(framesPerBuffer); + } else { + return 0; + } + } + + public int getNativeAudioSampleRate() { + return AudioTrack.getNativeOutputSampleRate(AudioManager.STREAM_SYSTEM); + } + + /* + * Helper to execute function in UIThread + */ + public void runOnUIThread(final long p) { + if (checkSOLoaded()) { + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + RunOnUiThreadHandler(p); + } + }); + } + return; + } + + /* + * Native code helper for RunOnUiThread + */ + native public void RunOnUiThreadHandler(long pointer); +}
\ No newline at end of file diff --git a/NativeApp/Android/ndk_helper/src/perfMonitor.cpp b/NativeApp/Android/ndk_helper/src/perfMonitor.cpp new file mode 100644 index 0000000..b38cffd --- /dev/null +++ b/NativeApp/Android/ndk_helper/src/perfMonitor.cpp @@ -0,0 +1,61 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "perfMonitor.h" + +namespace ndk_helper { + +PerfMonitor::PerfMonitor() + : current_FPS_(0), + tv_last_sec_(0), + last_tick_(0.f), + tickindex_(0), + ticksum_(0) { + for (int32_t i = 0; i < kNumSamples; ++i) ticklist_[i] = 0; +} + +PerfMonitor::~PerfMonitor() {} + +double PerfMonitor::UpdateTick(double currentTick) { + ticksum_ -= ticklist_[tickindex_]; + ticksum_ += currentTick; + ticklist_[tickindex_] = currentTick; + tickindex_ = (tickindex_ + 1) % kNumSamples; + + return ((double)ticksum_ / kNumSamples); +} + +bool PerfMonitor::Update(float &fFPS) { + struct timeval Time; + gettimeofday(&Time, NULL); + + double time = Time.tv_sec + Time.tv_usec * 1.0 / 1000000.0; + double tick = time - last_tick_; + double d = UpdateTick(tick); + last_tick_ = time; + + if (Time.tv_sec - tv_last_sec_ >= 1) { + current_FPS_ = 1.f / d; + tv_last_sec_ = Time.tv_sec; + fFPS = current_FPS_; + return true; + } else { + fFPS = current_FPS_; + return false; + } +} + +} // namespace ndkHelper diff --git a/NativeApp/Android/ndk_helper/src/sensorManager.cpp b/NativeApp/Android/ndk_helper/src/sensorManager.cpp new file mode 100644 index 0000000..90487d0 --- /dev/null +++ b/NativeApp/Android/ndk_helper/src/sensorManager.cpp @@ -0,0 +1,106 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include <math.h> +#include "sensorManager.h" + +//-------------------------------------------------------------------------------- +// sensorManager.cpp +//-------------------------------------------------------------------------------- +namespace ndk_helper { + +//-------------------------------------------------------------------------------- +// includes +//-------------------------------------------------------------------------------- + +//------------------------------------------------------------------------- +// Sensor handlers +//------------------------------------------------------------------------- +SensorManager::SensorManager() + : sensorManager_(nullptr), + accelerometerSensor_(nullptr), + sensorEventQueue_(nullptr) {} + +SensorManager::~SensorManager() {} + +void SensorManager::Init(android_app *app) { + sensorManager_ = AcquireASensorManagerInstance(app); + accelerometerSensor_ = ASensorManager_getDefaultSensor( + sensorManager_, ASENSOR_TYPE_ACCELEROMETER); + sensorEventQueue_ = ASensorManager_createEventQueue( + sensorManager_, app->looper, LOOPER_ID_USER, NULL, NULL); +} + +void SensorManager::Resume() { + // When the app gains focus, start monitoring the accelerometer. + if (accelerometerSensor_ != NULL) { + ASensorEventQueue_enableSensor(sensorEventQueue_, accelerometerSensor_); + // We'd like to get 60 events per second (in us). + ASensorEventQueue_setEventRate(sensorEventQueue_, accelerometerSensor_, + (1000L / 60) * 1000); + } +} + +void SensorManager::Suspend() { + // When the app loses focus, stop monitoring the accelerometer. + // This is to avoid consuming battery while not being used. + if (accelerometerSensor_ != NULL) { + ASensorEventQueue_disableSensor(sensorEventQueue_, accelerometerSensor_); + } +} + +#include <dlfcn.h> +ASensorManager* AcquireASensorManagerInstance(android_app* app) { + + if(!app) + return nullptr; + + typedef ASensorManager *(*PF_GETINSTANCEFORPACKAGE)(const char *name); + void* androidHandle = dlopen("libandroid.so", RTLD_NOW); + PF_GETINSTANCEFORPACKAGE getInstanceForPackageFunc = (PF_GETINSTANCEFORPACKAGE) + dlsym(androidHandle, "ASensorManager_getInstanceForPackage"); + if (getInstanceForPackageFunc) { + JNIEnv* env = nullptr; + app->activity->vm->AttachCurrentThread(&env, NULL); + + jclass android_content_Context = env->GetObjectClass(app->activity->clazz); + jmethodID midGetPackageName = env->GetMethodID(android_content_Context, + "getPackageName", + "()Ljava/lang/String;"); + jstring packageName= (jstring)env->CallObjectMethod(app->activity->clazz, + midGetPackageName); + + const char *nativePackageName = env->GetStringUTFChars(packageName, 0); + ASensorManager* mgr = getInstanceForPackageFunc(nativePackageName); + env->ReleaseStringUTFChars(packageName, nativePackageName); + app->activity->vm->DetachCurrentThread(); + if (mgr) { + dlclose(androidHandle); + return mgr; + } + } + + typedef ASensorManager *(*PF_GETINSTANCE)(); + PF_GETINSTANCE getInstanceFunc = (PF_GETINSTANCE) + dlsym(androidHandle, "ASensorManager_getInstance"); + // by all means at this point, ASensorManager_getInstance should be available + assert(getInstanceFunc); + dlclose(androidHandle); + + return getInstanceFunc(); +} + +} // namespace ndkHelper diff --git a/NativeApp/Android/ndk_helper/src/shader.cpp b/NativeApp/Android/ndk_helper/src/shader.cpp new file mode 100644 index 0000000..af7a155 --- /dev/null +++ b/NativeApp/Android/ndk_helper/src/shader.cpp @@ -0,0 +1,166 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include <cstdlib> +#include <EGL/egl.h> +#include <GLES2/gl2.h> + +#include "shader.h" +#include "JNIHelper.h" + +namespace ndk_helper { + +#define DEBUG (1) + +bool shader::CompileShader( + GLuint *shader, const GLenum type, const char *str_file_name, + const std::map<std::string, std::string> &map_parameters) { + std::vector<uint8_t> data; + if (!JNIHelper::GetInstance()->ReadFile(str_file_name, &data)) { + LOGI("Can not open a file:%s", str_file_name); + return false; + } + + const char REPLACEMENT_TAG = '*'; + // Fill-in parameters + std::string str(data.begin(), data.end()); + std::string str_replacement_map(data.size(), ' '); + + std::map<std::string, std::string>::const_iterator it = + map_parameters.begin(); + std::map<std::string, std::string>::const_iterator itEnd = + map_parameters.end(); + while (it != itEnd) { + size_t pos = 0; + while ((pos = str.find(it->first, pos)) != std::string::npos) { + // Check if the sub string is already touched + + size_t replaced_pos = str_replacement_map.find(REPLACEMENT_TAG, pos); + if (replaced_pos == std::string::npos || replaced_pos > pos) { + str.replace(pos, it->first.length(), it->second); + str_replacement_map.replace(pos, it->first.length(), it->first.length(), + REPLACEMENT_TAG); + pos += it->second.length(); + } else { + // The replacement target has been touched by other tag, skipping them + pos += it->second.length(); + } + } + it++; + } + + LOGI("Patched Shdader:\n%s", str.c_str()); + + std::vector<uint8_t> v(str.begin(), str.end()); + str.clear(); + return shader::CompileShader(shader, type, v); +} + +bool shader::CompileShader(GLuint *shader, const GLenum type, + const GLchar *source, const int32_t iSize) { + if (source == NULL || iSize <= 0) return false; + + *shader = glCreateShader(type); + glShaderSource(*shader, 1, &source, &iSize); // Not specifying 3rd parameter + // (size) could be troublesome.. + + glCompileShader(*shader); + +#if defined(DEBUG) + GLint logLength; + glGetShaderiv(*shader, GL_INFO_LOG_LENGTH, &logLength); + if (logLength > 0) { + GLchar *log = (GLchar *)malloc(logLength); + glGetShaderInfoLog(*shader, logLength, &logLength, log); + LOGI("Shader compile log:\n%s", log); + free(log); + } +#endif + + GLint status; + glGetShaderiv(*shader, GL_COMPILE_STATUS, &status); + if (status == 0) { + glDeleteShader(*shader); + return false; + } + + return true; +} + +bool shader::CompileShader(GLuint *shader, const GLenum type, + std::vector<uint8_t> &data) { + if (!data.size()) return false; + + const GLchar *source = (GLchar *)&data[0]; + int32_t iSize = data.size(); + return shader::CompileShader(shader, type, source, iSize); +} + +bool shader::CompileShader(GLuint *shader, const GLenum type, + const char *strFileName) { + std::vector<uint8_t> data; + bool b = JNIHelper::GetInstance()->ReadFile(strFileName, &data); + if (!b) { + LOGI("Can not open a file:%s", strFileName); + return false; + } + + return shader::CompileShader(shader, type, data); +} + +bool shader::LinkProgram(const GLuint prog) { + GLint status; + + glLinkProgram(prog); + +#if defined(DEBUG) + GLint logLength; + glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logLength); + if (logLength > 0) { + GLchar *log = (GLchar *)malloc(logLength); + glGetProgramInfoLog(prog, logLength, &logLength, log); + LOGI("Program link log:\n%s", log); + free(log); + } +#endif + + glGetProgramiv(prog, GL_LINK_STATUS, &status); + if (status == 0) { + LOGI("Program link failed\n"); + return false; + } + + return true; +} + +bool shader::ValidateProgram(const GLuint prog) { + GLint logLength, status; + + glValidateProgram(prog); + glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logLength); + if (logLength > 0) { + GLchar *log = (GLchar *)malloc(logLength); + glGetProgramInfoLog(prog, logLength, &logLength, log); + LOGI("Program validate log:\n%s", log); + free(log); + } + + glGetProgramiv(prog, GL_VALIDATE_STATUS, &status); + if (status == 0) return false; + + return true; +} + +} // namespace ndkHelper diff --git a/NativeApp/Android/ndk_helper/src/tapCamera.cpp b/NativeApp/Android/ndk_helper/src/tapCamera.cpp new file mode 100644 index 0000000..e753ab1 --- /dev/null +++ b/NativeApp/Android/ndk_helper/src/tapCamera.cpp @@ -0,0 +1,324 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//---------------------------------------------------------- +// tapCamera.cpp +// Camera control with tap +// +//---------------------------------------------------------- +#include <fstream> +#include "tapCamera.h" + +namespace ndk_helper { + +const float TRANSFORM_FACTOR = 15.f; +const float TRANSFORM_FACTORZ = 10.f; + +const float MOMENTUM_FACTOR_DECREASE = 0.85f; +const float MOMENTUM_FACTOR_DECREASE_SHIFT = 0.9f; +const float MOMENTUM_FACTOR = 0.8f; +const float MOMENTUM_FACTOR_THRESHOLD = 0.001f; + +//---------------------------------------------------------- +// Ctor +//---------------------------------------------------------- +TapCamera::TapCamera() + : ball_radius_(0.75f), + dragging_(false), + pinching_(false), + pinch_start_distance_SQ_(0.f), + camera_rotation_(0.f), + camera_rotation_start_(0.f), + camera_rotation_now_(0.f), + momentum_(false), + momemtum_steps_(0.f), + flip_z_(0.f) { + // Init offset + InitParameters(); + + vec_flip_ = Vec2(1.f, -1.f); + flip_z_ = -1.f; + vec_pinch_transform_factor_ = Vec3(1.f, 1.f, 1.f); + + vec_ball_center_ = Vec2(0, 0); + vec_ball_now_ = Vec2(0, 0); + vec_ball_down_ = Vec2(0, 0); + + vec_pinch_start_ = Vec2(0, 0); + vec_pinch_start_center_ = Vec2(0, 0); + + vec_flip_ = Vec2(0, 0); +} + +void TapCamera::InitParameters() { + // Init parameters + vec_offset_ = Vec3(); + vec_offset_now_ = Vec3(); + + quat_ball_rot_ = Quaternion(); + quat_ball_now_ = Quaternion(); + quat_ball_now_.ToMatrix(mat_rotation_); + camera_rotation_ = 0.f; + + vec_drag_delta_ = Vec2(); + vec_offset_delta_ = Vec3(); + + momentum_ = false; +} + +//---------------------------------------------------------- +// Dtor +//---------------------------------------------------------- +TapCamera::~TapCamera() {} + +void TapCamera::Update() { + if (momentum_) { + float momenttum_steps = momemtum_steps_; + + // Momentum rotation + Vec2 v = vec_drag_delta_; + BeginDrag(Vec2()); // NOTE:This call reset _VDragDelta + Drag(v * vec_flip_); + + // Momentum shift + vec_offset_ += vec_offset_delta_; + + BallUpdate(); + EndDrag(); + + // Decrease deltas + vec_drag_delta_ = v * MOMENTUM_FACTOR_DECREASE; + vec_offset_delta_ = vec_offset_delta_ * MOMENTUM_FACTOR_DECREASE_SHIFT; + + // Count steps + momemtum_steps_ = momenttum_steps * MOMENTUM_FACTOR_DECREASE; + if (momemtum_steps_ < MOMENTUM_FACTOR_THRESHOLD) { + momentum_ = false; + } + } else { + vec_drag_delta_ *= MOMENTUM_FACTOR; + vec_offset_delta_ = vec_offset_delta_ * MOMENTUM_FACTOR; + BallUpdate(); + } + + Vec3 vec = vec_offset_ + vec_offset_now_; + Vec3 vec_tmp(TRANSFORM_FACTOR, -TRANSFORM_FACTOR, TRANSFORM_FACTORZ); + + vec *= vec_tmp * vec_pinch_transform_factor_; + + mat_transform_ = Mat4::Translation(vec); +} + +void TapCamera::Update(const double time) { + if (momentum_) { + const float MOMENTAM_UNIT = 0.0166f; + // Activate every 16.6msec + if (time - time_stamp_ >= MOMENTAM_UNIT) { + float momenttum_steps = momemtum_steps_; + + // Momentum rotation + Vec2 v = vec_drag_delta_; + BeginDrag(Vec2()); // NOTE:This call reset _VDragDelta + Drag(v * vec_flip_); + + // Momentum shift + vec_offset_ += vec_offset_delta_; + + BallUpdate(); + EndDrag(); + + // Decrease deltas + vec_drag_delta_ = v * MOMENTUM_FACTOR_DECREASE; + vec_offset_delta_ = vec_offset_delta_ * MOMENTUM_FACTOR_DECREASE_SHIFT; + + // Count steps + momemtum_steps_ = momenttum_steps * MOMENTUM_FACTOR_DECREASE; + if (momemtum_steps_ < MOMENTUM_FACTOR_THRESHOLD) { + momentum_ = false; + } + time_stamp_ = time; + } + } else { + vec_drag_delta_ *= MOMENTUM_FACTOR; + vec_offset_delta_ = vec_offset_delta_ * MOMENTUM_FACTOR; + BallUpdate(); + time_stamp_ = time; + } + + Vec3 vec = vec_offset_ + vec_offset_now_; + Vec3 vec_tmp(TRANSFORM_FACTOR, -TRANSFORM_FACTOR, TRANSFORM_FACTORZ); + + vec *= vec_tmp * vec_pinch_transform_factor_; + + mat_transform_ = Mat4::Translation(vec); +} +Mat4& TapCamera::GetRotationMatrix() { return mat_rotation_; } + +Mat4& TapCamera::GetTransformMatrix() { return mat_transform_; } + +void TapCamera::Reset(const bool bAnimate) { + InitParameters(); + Update(); +} + +//---------------------------------------------------------- +// Drag control +//---------------------------------------------------------- +void TapCamera::BeginDrag(const Vec2& v) { + if (dragging_) EndDrag(); + + if (pinching_) EndPinch(); + + Vec2 vec = v * vec_flip_; + vec_ball_now_ = vec; + vec_ball_down_ = vec_ball_now_; + + dragging_ = true; + momentum_ = false; + vec_last_input_ = vec; + vec_drag_delta_ = Vec2(); +} + +void TapCamera::EndDrag() { + quat_ball_down_ = quat_ball_now_; + quat_ball_rot_ = Quaternion(); + + dragging_ = false; + momentum_ = true; + momemtum_steps_ = 1.0f; +} + +void TapCamera::Drag(const Vec2& v) { + if (!dragging_) return; + + Vec2 vec = v * vec_flip_; + vec_ball_now_ = vec; + + vec_drag_delta_ = vec_drag_delta_ * MOMENTUM_FACTOR + (vec - vec_last_input_); + vec_last_input_ = vec; +} + +//---------------------------------------------------------- +// Pinch controll +//---------------------------------------------------------- +void TapCamera::BeginPinch(const Vec2& v1, const Vec2& v2) { + if (dragging_) EndDrag(); + + if (pinching_) EndPinch(); + + BeginDrag(Vec2()); + + vec_pinch_start_center_ = (v1 + v2) / 2.f; + + Vec2 vec = v1 - v2; + float x_diff; + float y_diff; + vec.Value(x_diff, y_diff); + + pinch_start_distance_SQ_ = x_diff * x_diff + y_diff * y_diff; + camera_rotation_start_ = atan2f(y_diff, x_diff); + camera_rotation_now_ = 0; + + pinching_ = true; + momentum_ = false; + + // Init momentum factors + vec_offset_delta_ = Vec3(); +} + +void TapCamera::EndPinch() { + pinching_ = false; + momentum_ = true; + momemtum_steps_ = 1.f; + vec_offset_ += vec_offset_now_; + camera_rotation_ += camera_rotation_now_; + vec_offset_now_ = Vec3(); + + camera_rotation_now_ = 0; + + EndDrag(); +} + +void TapCamera::Pinch(const Vec2& v1, const Vec2& v2) { + if (!pinching_) return; + + // Update momentum factor + vec_offset_last_ = vec_offset_now_; + + float x_diff, y_diff; + Vec2 vec = v1 - v2; + vec.Value(x_diff, y_diff); + + float fDistanceSQ = x_diff * x_diff + y_diff * y_diff; + + float f = pinch_start_distance_SQ_ / fDistanceSQ; + if (f < 1.f) + f = -1.f / f + 1.0f; + else + f = f - 1.f; + if (std::isnan(f)) f = 0.f; + + vec = (v1 + v2) / 2.f - vec_pinch_start_center_; + vec_offset_now_ = Vec3(vec, flip_z_ * f); + + // Update momentum factor + vec_offset_delta_ = vec_offset_delta_ * MOMENTUM_FACTOR + + (vec_offset_now_ - vec_offset_last_); + + // + // Update ration quaternion + float fRotation = atan2f(y_diff, x_diff); + camera_rotation_now_ = fRotation - camera_rotation_start_; + + // Trackball rotation + quat_ball_rot_ = Quaternion(0.f, 0.f, sinf(-camera_rotation_now_ * 0.5f), + cosf(-camera_rotation_now_ * 0.5f)); +} + +//---------------------------------------------------------- +// Trackball controll +//---------------------------------------------------------- +void TapCamera::BallUpdate() { + if (dragging_) { + Vec3 vec_from = PointOnSphere(vec_ball_down_); + Vec3 vec_to = PointOnSphere(vec_ball_now_); + + Vec3 vec = vec_from.Cross(vec_to); + float w = vec_from.Dot(vec_to); + + Quaternion qDrag = Quaternion(vec, w); + qDrag = qDrag * quat_ball_down_; + quat_ball_now_ = quat_ball_rot_ * qDrag; + } + quat_ball_now_.ToMatrix(mat_rotation_); +} + +Vec3 TapCamera::PointOnSphere(Vec2& point) { + Vec3 ball_mouse; + float mag; + Vec2 vec = (point - vec_ball_center_) / ball_radius_; + mag = vec.Dot(vec); + if (mag > 1.f) { + float scale = 1.f / sqrtf(mag); + vec *= scale; + ball_mouse = Vec3(vec, 0.f); + } else { + ball_mouse = Vec3(vec, sqrtf(1.f - mag)); + } + return ball_mouse; +} + +} // namespace ndkHelper diff --git a/NativeApp/Android/ndk_helper/src/vecmath.cpp b/NativeApp/Android/ndk_helper/src/vecmath.cpp new file mode 100644 index 0000000..1a06432 --- /dev/null +++ b/NativeApp/Android/ndk_helper/src/vecmath.cpp @@ -0,0 +1,406 @@ +/* + * Copy_right 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * y_ou may_ not use this file ex_cept in compliance with the License. + * You may_ obtain a copy_ of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by_ applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either ex_press or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//-------------------------------------------------------------------------------- +// vecmath.cpp +//-------------------------------------------------------------------------------- +#include "vecmath.h" + +namespace ndk_helper { + +//-------------------------------------------------------------------------------- +// vec3 +//-------------------------------------------------------------------------------- +Vec3::Vec3(const Vec4& vec) { + x_ = vec.x_; + y_ = vec.y_; + z_ = vec.z_; +} + +//-------------------------------------------------------------------------------- +// vec4 +//-------------------------------------------------------------------------------- +Vec4 Vec4::operator*(const Mat4& rhs) const { + Vec4 out; + out.x_ = x_ * rhs.f_[0] + y_ * rhs.f_[1] + z_ * rhs.f_[2] + w_ * rhs.f_[3]; + out.y_ = x_ * rhs.f_[4] + y_ * rhs.f_[5] + z_ * rhs.f_[6] + w_ * rhs.f_[7]; + out.z_ = x_ * rhs.f_[8] + y_ * rhs.f_[9] + z_ * rhs.f_[10] + w_ * rhs.f_[11]; + out.w_ = + x_ * rhs.f_[12] + y_ * rhs.f_[13] + z_ * rhs.f_[14] + w_ * rhs.f_[15]; + return out; +} + +//-------------------------------------------------------------------------------- +// mat4 +//-------------------------------------------------------------------------------- +Mat4::Mat4() { + for (int32_t i = 0; i < 16; ++i) f_[i] = 0.f; + // column major identity matrix + f_[0] = f_[5] = f_[10] = f_[15] = 1.0f; +} + +Mat4::Mat4(const float* mIn) { + for (int32_t i = 0; i < 16; ++i) f_[i] = mIn[i]; +} + +Mat4 Mat4::operator*(const Mat4& rhs) const { + Mat4 ret; + ret.f_[0] = f_[0] * rhs.f_[0] + f_[4] * rhs.f_[1] + f_[8] * rhs.f_[2] + + f_[12] * rhs.f_[3]; + ret.f_[1] = f_[1] * rhs.f_[0] + f_[5] * rhs.f_[1] + f_[9] * rhs.f_[2] + + f_[13] * rhs.f_[3]; + ret.f_[2] = f_[2] * rhs.f_[0] + f_[6] * rhs.f_[1] + f_[10] * rhs.f_[2] + + f_[14] * rhs.f_[3]; + ret.f_[3] = f_[3] * rhs.f_[0] + f_[7] * rhs.f_[1] + f_[11] * rhs.f_[2] + + f_[15] * rhs.f_[3]; + + ret.f_[4] = f_[0] * rhs.f_[4] + f_[4] * rhs.f_[5] + f_[8] * rhs.f_[6] + + f_[12] * rhs.f_[7]; + ret.f_[5] = f_[1] * rhs.f_[4] + f_[5] * rhs.f_[5] + f_[9] * rhs.f_[6] + + f_[13] * rhs.f_[7]; + ret.f_[6] = f_[2] * rhs.f_[4] + f_[6] * rhs.f_[5] + f_[10] * rhs.f_[6] + + f_[14] * rhs.f_[7]; + ret.f_[7] = f_[3] * rhs.f_[4] + f_[7] * rhs.f_[5] + f_[11] * rhs.f_[6] + + f_[15] * rhs.f_[7]; + + ret.f_[8] = f_[0] * rhs.f_[8] + f_[4] * rhs.f_[9] + f_[8] * rhs.f_[10] + + f_[12] * rhs.f_[11]; + ret.f_[9] = f_[1] * rhs.f_[8] + f_[5] * rhs.f_[9] + f_[9] * rhs.f_[10] + + f_[13] * rhs.f_[11]; + ret.f_[10] = f_[2] * rhs.f_[8] + f_[6] * rhs.f_[9] + f_[10] * rhs.f_[10] + + f_[14] * rhs.f_[11]; + ret.f_[11] = f_[3] * rhs.f_[8] + f_[7] * rhs.f_[9] + f_[11] * rhs.f_[10] + + f_[15] * rhs.f_[11]; + + ret.f_[12] = f_[0] * rhs.f_[12] + f_[4] * rhs.f_[13] + f_[8] * rhs.f_[14] + + f_[12] * rhs.f_[15]; + ret.f_[13] = f_[1] * rhs.f_[12] + f_[5] * rhs.f_[13] + f_[9] * rhs.f_[14] + + f_[13] * rhs.f_[15]; + ret.f_[14] = f_[2] * rhs.f_[12] + f_[6] * rhs.f_[13] + f_[10] * rhs.f_[14] + + f_[14] * rhs.f_[15]; + ret.f_[15] = f_[3] * rhs.f_[12] + f_[7] * rhs.f_[13] + f_[11] * rhs.f_[14] + + f_[15] * rhs.f_[15]; + + return ret; +} + +Vec4 Mat4::operator*(const Vec4& rhs) const { + Vec4 ret; + ret.x_ = rhs.x_ * f_[0] + rhs.y_ * f_[4] + rhs.z_ * f_[8] + rhs.w_ * f_[12]; + ret.y_ = rhs.x_ * f_[1] + rhs.y_ * f_[5] + rhs.z_ * f_[9] + rhs.w_ * f_[13]; + ret.z_ = rhs.x_ * f_[2] + rhs.y_ * f_[6] + rhs.z_ * f_[10] + rhs.w_ * f_[14]; + ret.w_ = rhs.x_ * f_[3] + rhs.y_ * f_[7] + rhs.z_ * f_[11] + rhs.w_ * f_[15]; + return ret; +} + +Mat4 Mat4::Inverse() { + Mat4 ret; + float det_1; + float pos = 0; + float neg = 0; + float temp; + + temp = f_[0] * f_[5] * f_[10]; + if (temp >= 0) + pos += temp; + else + neg += temp; + temp = f_[4] * f_[9] * f_[2]; + if (temp >= 0) + pos += temp; + else + neg += temp; + temp = f_[8] * f_[1] * f_[6]; + if (temp >= 0) + pos += temp; + else + neg += temp; + temp = -f_[8] * f_[5] * f_[2]; + if (temp >= 0) + pos += temp; + else + neg += temp; + temp = -f_[4] * f_[1] * f_[10]; + if (temp >= 0) + pos += temp; + else + neg += temp; + temp = -f_[0] * f_[9] * f_[6]; + if (temp >= 0) + pos += temp; + else + neg += temp; + det_1 = pos + neg; + + if (det_1 == 0.0) { + // Error + } else { + det_1 = 1.0f / det_1; + ret.f_[0] = (f_[5] * f_[10] - f_[9] * f_[6]) * det_1; + ret.f_[1] = -(f_[1] * f_[10] - f_[9] * f_[2]) * det_1; + ret.f_[2] = (f_[1] * f_[6] - f_[5] * f_[2]) * det_1; + ret.f_[4] = -(f_[4] * f_[10] - f_[8] * f_[6]) * det_1; + ret.f_[5] = (f_[0] * f_[10] - f_[8] * f_[2]) * det_1; + ret.f_[6] = -(f_[0] * f_[6] - f_[4] * f_[2]) * det_1; + ret.f_[8] = (f_[4] * f_[9] - f_[8] * f_[5]) * det_1; + ret.f_[9] = -(f_[0] * f_[9] - f_[8] * f_[1]) * det_1; + ret.f_[10] = (f_[0] * f_[5] - f_[4] * f_[1]) * det_1; + + /* Calculate -C * inverse(A) */ + ret.f_[12] = + -(f_[12] * ret.f_[0] + f_[13] * ret.f_[4] + f_[14] * ret.f_[8]); + ret.f_[13] = + -(f_[12] * ret.f_[1] + f_[13] * ret.f_[5] + f_[14] * ret.f_[9]); + ret.f_[14] = + -(f_[12] * ret.f_[2] + f_[13] * ret.f_[6] + f_[14] * ret.f_[10]); + + ret.f_[3] = 0.0f; + ret.f_[7] = 0.0f; + ret.f_[11] = 0.0f; + ret.f_[15] = 1.0f; + } + + *this = ret; + return *this; +} + +//-------------------------------------------------------------------------------- +// Misc +//-------------------------------------------------------------------------------- +Mat4 Mat4::RotationX(const float fAngle) { + Mat4 ret; + float fCosine, fSine; + + fCosine = cosf(fAngle); + fSine = sinf(fAngle); + + ret.f_[0] = 1.0f; + ret.f_[4] = 0.0f; + ret.f_[8] = 0.0f; + ret.f_[12] = 0.0f; + ret.f_[1] = 0.0f; + ret.f_[5] = fCosine; + ret.f_[9] = fSine; + ret.f_[13] = 0.0f; + ret.f_[2] = 0.0f; + ret.f_[6] = -fSine; + ret.f_[10] = fCosine; + ret.f_[14] = 0.0f; + ret.f_[3] = 0.0f; + ret.f_[7] = 0.0f; + ret.f_[11] = 0.0f; + ret.f_[15] = 1.0f; + return ret; +} + +Mat4 Mat4::RotationY(const float fAngle) { + Mat4 ret; + float fCosine, fSine; + + fCosine = cosf(fAngle); + fSine = sinf(fAngle); + + ret.f_[0] = fCosine; + ret.f_[4] = 0.0f; + ret.f_[8] = -fSine; + ret.f_[12] = 0.0f; + ret.f_[1] = 0.0f; + ret.f_[5] = 1.0f; + ret.f_[9] = 0.0f; + ret.f_[13] = 0.0f; + ret.f_[2] = fSine; + ret.f_[6] = 0.0f; + ret.f_[10] = fCosine; + ret.f_[14] = 0.0f; + ret.f_[3] = 0.0f; + ret.f_[7] = 0.0f; + ret.f_[11] = 0.0f; + ret.f_[15] = 1.0f; + return ret; +} + +Mat4 Mat4::RotationZ(const float fAngle) { + Mat4 ret; + float fCosine, fSine; + + fCosine = cosf(fAngle); + fSine = sinf(fAngle); + + ret.f_[0] = fCosine; + ret.f_[4] = fSine; + ret.f_[8] = 0.0f; + ret.f_[12] = 0.0f; + ret.f_[1] = -fSine; + ret.f_[5] = fCosine; + ret.f_[9] = 0.0f; + ret.f_[13] = 0.0f; + ret.f_[2] = 0.0f; + ret.f_[6] = 0.0f; + ret.f_[10] = 1.0f; + ret.f_[14] = 0.0f; + ret.f_[3] = 0.0f; + ret.f_[7] = 0.0f; + ret.f_[11] = 0.0f; + ret.f_[15] = 1.0f; + return ret; +} + +Mat4 Mat4::Scale(const float scaleX, const float scaleY, const float scaleZ) { + Mat4 ret; + ret.f_[0] = scaleX; + ret.f_[5] = scaleY; + ret.f_[10] = scaleZ; + ret.f_[1] = ret.f_[2] = ret.f_[3] = ret.f_[4] = ret.f_[6] = ret.f_[7] = + ret.f_[8] = ret.f_[9] = ret.f_[11] = ret.f_[12] = ret.f_[13] = + ret.f_[14] = 0.f; + ret.f_[15] = 1.0f; + return ret; +} + +Mat4 Mat4::Translation(const float fX, const float fY, const float fZ) { + Mat4 ret; + ret.f_[0] = 1.0f; + ret.f_[4] = 0.0f; + ret.f_[8] = 0.0f; + ret.f_[12] = fX; + ret.f_[1] = 0.0f; + ret.f_[5] = 1.0f; + ret.f_[9] = 0.0f; + ret.f_[13] = fY; + ret.f_[2] = 0.0f; + ret.f_[6] = 0.0f; + ret.f_[10] = 1.0f; + ret.f_[14] = fZ; + ret.f_[3] = 0.0f; + ret.f_[7] = 0.0f; + ret.f_[11] = 0.0f; + ret.f_[15] = 1.0f; + return ret; +} + +Mat4 Mat4::Translation(const Vec3 vec) { + Mat4 ret; + ret.f_[0] = 1.0f; + ret.f_[4] = 0.0f; + ret.f_[8] = 0.0f; + ret.f_[12] = vec.x_; + ret.f_[1] = 0.0f; + ret.f_[5] = 1.0f; + ret.f_[9] = 0.0f; + ret.f_[13] = vec.y_; + ret.f_[2] = 0.0f; + ret.f_[6] = 0.0f; + ret.f_[10] = 1.0f; + ret.f_[14] = vec.z_; + ret.f_[3] = 0.0f; + ret.f_[7] = 0.0f; + ret.f_[11] = 0.0f; + ret.f_[15] = 1.0f; + return ret; +} + +Mat4 Mat4::Perspective(float width, float height, float nearPlane, + float farPlane) { + float n2 = 2.0f * nearPlane; + float rcpnmf = 1.f / (nearPlane - farPlane); + + Mat4 result; + result.f_[0] = n2 / width; + result.f_[4] = 0; + result.f_[8] = 0; + result.f_[12] = 0; + result.f_[1] = 0; + result.f_[5] = n2 / height; + result.f_[9] = 0; + result.f_[13] = 0; + result.f_[2] = 0; + result.f_[6] = 0; + result.f_[10] = (farPlane + nearPlane) * rcpnmf; + result.f_[14] = farPlane * rcpnmf * n2; + result.f_[3] = 0; + result.f_[7] = 0; + result.f_[11] = -1.0; + result.f_[15] = 0; + + return result; +} + +Mat4 Mat4::Ortho2D(float left, float top, float right, float bottom) { + const float zNear = -1.0f; + const float zFar = 1.0f; + const float inv_z = 1.0f / (zFar - zNear); + const float inv_y = 1.0f / (-top + bottom); + const float inv_x = 1.0f / (right - left); + + Mat4 result; + result.f_[0] = 2.0f * inv_x; + result.f_[1] = 0.0f; + result.f_[2] = 0.0f; + result.f_[3] = 0.0f; + + result.f_[4] = 0.0f; + result.f_[5] = 2.0 * inv_y; + result.f_[6] = 0.0f; + result.f_[7] = 0.0f; + + result.f_[8] = 0.0f; + result.f_[9] = 0.0f; + result.f_[10] = -2.0f * inv_z; + result.f_[11] = 0.0f; + + result.f_[12] = -(right + left) * inv_x; + result.f_[13] = (top + bottom) * inv_y; + result.f_[14] = -(zFar + zNear) * inv_z; + result.f_[15] = 1.0f; + return result; +} + +Mat4 Mat4::LookAt(const Vec3& vec_eye, const Vec3& vec_at, const Vec3& vec_up) { + Vec3 vec_forward, vec_up_norm, vec_side; + Mat4 result; + + vec_forward.x_ = vec_eye.x_ - vec_at.x_; + vec_forward.y_ = vec_eye.y_ - vec_at.y_; + vec_forward.z_ = vec_eye.z_ - vec_at.z_; + + vec_forward.Normalize(); + vec_up_norm = vec_up; + vec_up_norm.Normalize(); + vec_side = vec_up_norm.Cross(vec_forward); + vec_up_norm = vec_forward.Cross(vec_side); + + result.f_[0] = vec_side.x_; + result.f_[4] = vec_side.y_; + result.f_[8] = vec_side.z_; + result.f_[12] = 0; + result.f_[1] = vec_up_norm.x_; + result.f_[5] = vec_up_norm.y_; + result.f_[9] = vec_up_norm.z_; + result.f_[13] = 0; + result.f_[2] = vec_forward.x_; + result.f_[6] = vec_forward.y_; + result.f_[10] = vec_forward.z_; + result.f_[14] = 0; + result.f_[3] = 0; + result.f_[7] = 0; + result.f_[11] = 0; + result.f_[15] = 1.0; + + result.PostTranslate(-vec_eye.x_, -vec_eye.y_, -vec_eye.z_); + return result; +} + +} // namespace ndkHelper diff --git a/NativeApp/Android/src/main/AndroidManifest.xml b/NativeApp/Android/src/main/AndroidManifest.xml new file mode 100644 index 0000000..467f1c7 --- /dev/null +++ b/NativeApp/Android/src/main/AndroidManifest.xml @@ -0,0 +1,2 @@ +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.diligentengine.android.common" /> diff --git a/NativeApp/Android/src/main/java/com/diligentengine/android/common/DiligentApplicationBase.java b/NativeApp/Android/src/main/java/com/diligentengine/android/common/DiligentApplicationBase.java new file mode 100644 index 0000000..2342e46 --- /dev/null +++ b/NativeApp/Android/src/main/java/com/diligentengine/android/common/DiligentApplicationBase.java @@ -0,0 +1,40 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.diligentengine.android.common; + +import android.app.Application; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.content.pm.PackageManager.NameNotFoundException; +import android.util.Log; +import android.widget.Toast; + +public class DiligentApplicationBase extends Application { + public void onCreate(){ + Log.w("native-activity", "onCreate"); + + final PackageManager pm = getApplicationContext().getPackageManager(); + ApplicationInfo ai; + try { + ai = pm.getApplicationInfo( this.getPackageName(), 0); + } catch (final NameNotFoundException e) { + ai = null; + } + final String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)"); + Toast.makeText(this, applicationName, Toast.LENGTH_SHORT).show(); + } +} diff --git a/NativeApp/Android/src/main/java/com/diligentengine/android/common/NativeActivityBase.java b/NativeApp/Android/src/main/java/com/diligentengine/android/common/NativeActivityBase.java new file mode 100644 index 0000000..396aa7a --- /dev/null +++ b/NativeApp/Android/src/main/java/com/diligentengine/android/common/NativeActivityBase.java @@ -0,0 +1,156 @@ +/* + * Copyright 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.diligentengine.android.common; + +import android.app.NativeActivity; +import android.os.Bundle; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup.MarginLayoutParams; +import android.view.WindowManager.LayoutParams; +import android.widget.LinearLayout; +import android.widget.PopupWindow; +import android.widget.TextView; +import android.util.Log; + +public class NativeActivityBase extends NativeActivity { + + static + { + try{ + System.loadLibrary("GraphicsEngineOpenGL"); + Log.i("native-activity", "Loaded GraphicsEngineOpenGL library.\n"); + } catch (UnsatisfiedLinkError e) { + Log.e("native-activity", "Failed to load GraphicsEngineOpenGL library.\n" + e); + } + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + //Hide toolbar + int SDK_INT = android.os.Build.VERSION.SDK_INT; + if(SDK_INT >= 19) + { + setImmersiveSticky(); + + View decorView = getWindow().getDecorView(); + decorView.setOnSystemUiVisibilityChangeListener + (new View.OnSystemUiVisibilityChangeListener() { + @Override + public void onSystemUiVisibilityChange(int visibility) { + setImmersiveSticky(); + } + }); + } + + } + + protected void onResume() { + super.onResume(); + + //Hide toolbar + int SDK_INT = android.os.Build.VERSION.SDK_INT; + if(SDK_INT >= 11 && SDK_INT < 14) + { + getWindow().getDecorView().setSystemUiVisibility(View.STATUS_BAR_HIDDEN); + } + else if(SDK_INT >= 14 && SDK_INT < 19) + { + getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LOW_PROFILE); + } + else if(SDK_INT >= 19) + { + setImmersiveSticky(); + } + + } + // Our popup window, you will call it from your C/C++ code later + + void setImmersiveSticky() { + View decorView = getWindow().getDecorView(); + decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN + | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); + } + + NativeActivityBase _activity; + PopupWindow _popupWindow; + TextView _label; + + public void showUI() + { + if( _popupWindow != null ) + return; + + _activity = this; + + this.runOnUiThread(new Runnable() { + @Override + public void run() { + LayoutInflater layoutInflater + = (LayoutInflater)getBaseContext() + .getSystemService(LAYOUT_INFLATER_SERVICE); + View popupView = layoutInflater.inflate(R.layout.widgets, null); + _popupWindow = new PopupWindow( + popupView, + LayoutParams.WRAP_CONTENT, + LayoutParams.WRAP_CONTENT); + + LinearLayout mainLayout = new LinearLayout(_activity); + MarginLayoutParams params = new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); + params.setMargins(0, 0, 0, 0); + _activity.setContentView(mainLayout, params); + + // Show our UI over NativeActivity window + _popupWindow.showAtLocation(mainLayout, Gravity.TOP | Gravity.LEFT, 10, 10); + _popupWindow.update(); + + _label = (TextView)popupView.findViewById(R.id.textViewFPS); + + }}); + } + + protected void onPause() + { + super.onPause(); + if (_popupWindow != null) { + _popupWindow.dismiss(); + _popupWindow = null; + } + } + + public void updateFPS(final float fFPS) + { + if( _label == null ) + return; + + _activity = this; + this.runOnUiThread(new Runnable() { + @Override + public void run() { + _label.setText(String.format("%2.2f FPS", fFPS)); + + }}); + } +} + + diff --git a/NativeApp/Android/src/main/res/layout/widgets.xml b/NativeApp/Android/src/main/res/layout/widgets.xml new file mode 100644 index 0000000..b6e86e6 --- /dev/null +++ b/NativeApp/Android/src/main/res/layout/widgets.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:gravity="top" + android:orientation="vertical" > + + <TextView + android:id="@+id/textViewFPS" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:gravity="end" + android:text="@string/fps" + android:textAppearance="?android:attr/textAppearanceMedium" + android:textColor="@android:color/white" /> + +</LinearLayout>
\ No newline at end of file diff --git a/NativeApp/Android/src/main/res/mipmap-hdpi/ic_launcher.png b/NativeApp/Android/src/main/res/mipmap-hdpi/ic_launcher.png Binary files differnew file mode 100644 index 0000000..5a261ea --- /dev/null +++ b/NativeApp/Android/src/main/res/mipmap-hdpi/ic_launcher.png diff --git a/NativeApp/Android/src/main/res/mipmap-mdpi/ic_launcher.png b/NativeApp/Android/src/main/res/mipmap-mdpi/ic_launcher.png Binary files differnew file mode 100644 index 0000000..74263d9 --- /dev/null +++ b/NativeApp/Android/src/main/res/mipmap-mdpi/ic_launcher.png diff --git a/NativeApp/Android/src/main/res/mipmap-xhdpi/ic_launcher.png b/NativeApp/Android/src/main/res/mipmap-xhdpi/ic_launcher.png Binary files differnew file mode 100644 index 0000000..da6a331 --- /dev/null +++ b/NativeApp/Android/src/main/res/mipmap-xhdpi/ic_launcher.png diff --git a/NativeApp/Android/src/main/res/mipmap-xxhdpi/ic_launcher.png b/NativeApp/Android/src/main/res/mipmap-xxhdpi/ic_launcher.png Binary files differnew file mode 100644 index 0000000..e587387 --- /dev/null +++ b/NativeApp/Android/src/main/res/mipmap-xxhdpi/ic_launcher.png diff --git a/NativeApp/Android/src/main/res/values-v11/styles.xml b/NativeApp/Android/src/main/res/values-v11/styles.xml new file mode 100644 index 0000000..541752f --- /dev/null +++ b/NativeApp/Android/src/main/res/values-v11/styles.xml @@ -0,0 +1,11 @@ +<resources> + + <!-- + Base application theme for API 11+. This theme completely replaces + AppBaseTheme from res/values/styles.xml on API 11+ devices. + --> + <style name="AppBaseTheme" parent="android:Theme.Holo.Light"> + <!-- API 11 theme customizations can go here. --> + </style> + +</resources>
\ No newline at end of file diff --git a/NativeApp/Android/src/main/res/values-v14/styles.xml b/NativeApp/Android/src/main/res/values-v14/styles.xml new file mode 100644 index 0000000..f20e015 --- /dev/null +++ b/NativeApp/Android/src/main/res/values-v14/styles.xml @@ -0,0 +1,12 @@ +<resources> + + <!-- + Base application theme for API 14+. This theme completely replaces + AppBaseTheme from BOTH res/values/styles.xml and + res/values-v11/styles.xml on API 14+ devices. + --> + <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar"> + <!-- API 14 theme customizations can go here. --> + </style> + +</resources>
\ No newline at end of file diff --git a/NativeApp/Android/src/main/res/values/strings.xml b/NativeApp/Android/src/main/res/values/strings.xml new file mode 100644 index 0000000..a06980b --- /dev/null +++ b/NativeApp/Android/src/main/res/values/strings.xml @@ -0,0 +1,5 @@ +<resources> + + <string name="fps">0.0 FPS</string> + +</resources>
\ No newline at end of file diff --git a/NativeApp/Android/src/main/res/values/styles.xml b/NativeApp/Android/src/main/res/values/styles.xml new file mode 100644 index 0000000..4a10ca4 --- /dev/null +++ b/NativeApp/Android/src/main/res/values/styles.xml @@ -0,0 +1,20 @@ +<resources> + + <!-- + Base application theme, dependent on API level. This theme is replaced + by AppBaseTheme from res/values-vXX/styles.xml on newer devices. + --> + <style name="AppBaseTheme" parent="android:Theme.Light"> + <!-- + Theme customizations available in newer API levels can go in + res/values-vXX/styles.xml, while customizations related to + backward-compatibility can go here. + --> + </style> + + <!-- Application theme. --> + <style name="AppTheme" parent="AppBaseTheme"> + <!-- All customizations that are NOT specific to a particular API-level can go here. --> + </style> + +</resources>
\ No newline at end of file diff --git a/NativeApp/Apple/Data/OSX/Base.lproj/Main.storyboard b/NativeApp/Apple/Data/OSX/Base.lproj/Main.storyboard new file mode 100644 index 0000000..9b6ac71 --- /dev/null +++ b/NativeApp/Apple/Data/OSX/Base.lproj/Main.storyboard @@ -0,0 +1,215 @@ +<?xml version="1.0" encoding="UTF-8"?> +<document type="com.apple.InterfaceBuilder3.Cocoa.Storyboard.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" initialViewController="B8D-0N-5wS"> + <dependencies> + <deployment identifier="macosx"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14460.31"/> + <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> + </dependencies> + <scenes> + <!--Application--> + <scene sceneID="JPo-4y-FX3"> + <objects> + <application id="hnw-xV-0zn" sceneMemberID="viewController"> + <menu key="mainMenu" title="Main Menu" systemMenu="main" id="AYu-sK-qS6"> + <items> + <menuItem title="Application" id="1Xt-HY-uBw"> + <modifierMask key="keyEquivalentModifierMask"/> + <menu key="submenu" title="Application" systemMenu="apple" id="uQy-DD-JDr"> + <items> + <menuItem title="About" id="5kV-Vb-QxS" userLabel="About"> + <modifierMask key="keyEquivalentModifierMask"/> + <connections> + <action selector="orderFrontStandardAboutPanel:" target="Ady-hI-5gd" id="Exp-CZ-Vem"/> + </connections> + </menuItem> + <menuItem isSeparatorItem="YES" id="VOq-y0-SEH"/> + <menuItem title="Preferences…" keyEquivalent="," id="BOF-NM-1cW"/> + <menuItem isSeparatorItem="YES" id="wFC-TO-SCJ"/> + <menuItem title="Services" id="NMo-om-nkz"> + <modifierMask key="keyEquivalentModifierMask"/> + <menu key="submenu" title="Services" systemMenu="services" id="hz9-B4-Xy5"/> + </menuItem> + <menuItem isSeparatorItem="YES" id="4je-JR-u6R"/> + <menuItem title="Hide" keyEquivalent="h" id="Olw-nP-bQN" userLabel="Hide"> + <connections> + <action selector="hide:" target="Ady-hI-5gd" id="PnN-Uc-m68"/> + </connections> + </menuItem> + <menuItem title="Hide Others" keyEquivalent="h" id="Vdr-fp-XzO"> + <modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/> + <connections> + <action selector="hideOtherApplications:" target="Ady-hI-5gd" id="VT4-aY-XCT"/> + </connections> + </menuItem> + <menuItem title="Show All" id="Kd2-mp-pUS"> + <modifierMask key="keyEquivalentModifierMask"/> + <connections> + <action selector="unhideAllApplications:" target="Ady-hI-5gd" id="Dhg-Le-xox"/> + </connections> + </menuItem> + <menuItem isSeparatorItem="YES" id="kCx-OE-vgT"/> + <menuItem title="Quit" keyEquivalent="q" id="4sb-4s-VLi" userLabel="Quit"> + <connections> + <action selector="terminate:" target="Ady-hI-5gd" id="Te7-pn-YzF"/> + </connections> + </menuItem> + </items> + </menu> + </menuItem> + <menuItem title="View" id="H8h-7b-M4v"> + <modifierMask key="keyEquivalentModifierMask"/> + <menu key="submenu" title="View" id="HyV-fh-RgO"> + <items> + <menuItem title="Show Toolbar" keyEquivalent="t" id="snW-S8-Cw5"> + <modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/> + <connections> + <action selector="toggleToolbarShown:" target="Ady-hI-5gd" id="BXY-wc-z0C"/> + </connections> + </menuItem> + <menuItem title="Customize Toolbar…" id="1UK-8n-QPP"> + <modifierMask key="keyEquivalentModifierMask"/> + <connections> + <action selector="runToolbarCustomizationPalette:" target="Ady-hI-5gd" id="pQI-g3-MTW"/> + </connections> + </menuItem> + </items> + </menu> + </menuItem> + <menuItem title="Window" id="aUF-d1-5bR"> + <modifierMask key="keyEquivalentModifierMask"/> + <menu key="submenu" title="Window" systemMenu="window" id="Td7-aD-5lo"> + <items> + <menuItem title="Minimize" keyEquivalent="m" id="OY7-WF-poV"> + <connections> + <action selector="performMiniaturize:" target="Ady-hI-5gd" id="VwT-WD-YPe"/> + </connections> + </menuItem> + <menuItem title="Zoom" id="R4o-n2-Eq4"> + <modifierMask key="keyEquivalentModifierMask"/> + <connections> + <action selector="performZoom:" target="Ady-hI-5gd" id="DIl-cC-cCs"/> + </connections> + </menuItem> + <menuItem isSeparatorItem="YES" id="eu3-7i-yIM"/> + <menuItem title="Bring All to Front" id="LE2-aR-0XJ"> + <modifierMask key="keyEquivalentModifierMask"/> + <connections> + <action selector="arrangeInFront:" target="Ady-hI-5gd" id="DRN-fu-gQh"/> + </connections> + </menuItem> + </items> + </menu> + </menuItem> + <menuItem title="Help" id="wpr-3q-Mcd"> + <modifierMask key="keyEquivalentModifierMask"/> + <menu key="submenu" title="Help" systemMenu="help" id="F2S-fz-NVQ"> + <items> + <menuItem title="Help" keyEquivalent="?" id="FKE-Sm-Kum" userLabel="Sample Help"> + <connections> + <action selector="showHelp:" target="Ady-hI-5gd" id="y7X-2Q-9no"/> + </connections> + </menuItem> + </items> + </menu> + </menuItem> + </items> + </menu> + <connections> + <outlet property="delegate" destination="Voe-Tx-rLC" id="PrD-fu-P6m"/> + </connections> + </application> + <customObject id="Voe-Tx-rLC" customClass="AppDelegate"/> + <customObject id="Ady-hI-5gd" userLabel="First Responder" customClass="NSResponder" sceneMemberID="firstResponder"/> + </objects> + <point key="canvasLocation" x="75" y="0.0"/> + </scene> + <!--Window Controller--> + <scene sceneID="R2V-B0-nI4"> + <objects> + <windowController id="B8D-0N-5wS" customClass="WindowController" sceneMemberID="viewController"> + <window key="window" title="Diligent Engine" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" visibleAtLaunch="NO" animationBehavior="default" id="IQv-IB-iLA"> + <windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/> + <windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/> + <rect key="contentRect" x="196" y="240" width="480" height="270"/> + <rect key="screenRect" x="0.0" y="0.0" width="1680" height="1027"/> + <value key="minSize" type="size" width="10" height="20"/> + <connections> + <outlet property="delegate" destination="B8D-0N-5wS" id="owC-aB-m7U"/> + </connections> + </window> + <connections> + <segue destination="lYj-9Z-eqp" kind="relationship" relationship="window.shadowedContentViewController" id="aXj-gz-HUq"/> + </connections> + </windowController> + <customObject id="Oky-zY-oP4" userLabel="First Responder" customClass="NSResponder" sceneMemberID="firstResponder"/> + </objects> + <point key="canvasLocation" x="75" y="250"/> + </scene> + <!--View Controller--> + <scene sceneID="hIz-AP-VOD"> + <objects> + <viewController storyboardIdentifier="GLViewControllerID" id="XfG-lQ-9wD" customClass="ViewController" sceneMemberID="viewController"> + <view key="view" id="m2S-Jp-Qdl" userLabel="GL View" customClass="GLView"> + <rect key="frame" x="0.0" y="0.0" width="800" height="600"/> + <autoresizingMask key="autoresizingMask"/> + </view> + </viewController> + <customObject id="rPt-NT-nkU" userLabel="First Responder" customClass="NSResponder" sceneMemberID="firstResponder"/> + </objects> + <point key="canvasLocation" x="75" y="655"/> + </scene> + <!--View Controller--> + <scene sceneID="JAO-pz-Td3"> + <objects> + <viewController storyboardIdentifier="MetalViewControllerID" id="VWH-wR-9QD" customClass="ViewController" sceneMemberID="viewController"> + <view key="view" id="0v6-SX-xCX" customClass="MetalView"> + <rect key="frame" x="0.0" y="0.0" width="800" height="600"/> + <autoresizingMask key="autoresizingMask"/> + </view> + </viewController> + <customObject id="CmR-bq-0b7" userLabel="First Responder" customClass="NSResponder" sceneMemberID="firstResponder"/> + </objects> + </scene> + <!--Mode Selection View Controller--> + <scene sceneID="rTr-Qo-t8b"> + <objects> + <viewController id="lYj-9Z-eqp" customClass="ModeSelectionViewController" sceneMemberID="viewController"> + <view key="view" autoresizesSubviews="NO" id="SPq-vc-rSb"> + <rect key="frame" x="0.0" y="0.0" width="350" height="255"/> + <autoresizingMask key="autoresizingMask"/> + <subviews> + <button fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="zEs-tf-G2z" userLabel="OpenGL"> + <rect key="frame" x="59" y="143" width="233" height="82"/> + <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> + <buttonCell key="cell" type="square" bezelStyle="shadowlessSquare" image="opengl-logo" imagePosition="only" alignment="center" borderStyle="border" imageScaling="proportionallyUpOrDown" inset="2" id="I5f-XW-9L1"> + <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> + <font key="font" metaFont="system"/> + <connections> + <action selector="goOpenGL:" target="lYj-9Z-eqp" id="Sg7-XX-Ktg"/> + </connections> + </buttonCell> + </button> + <button fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="mhf-V7-TKz" userLabel="Vulkan"> + <rect key="frame" x="59" y="32" width="233" height="82"/> + <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> + <buttonCell key="cell" type="square" bezelStyle="shadowlessSquare" image="vulkan-logo" imagePosition="only" alignment="center" borderStyle="border" imageScaling="proportionallyUpOrDown" inset="2" id="PWi-41-bCy"> + <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> + <font key="font" metaFont="system"/> + </buttonCell> + <connections> + <action selector="goVulkan:" target="lYj-9Z-eqp" id="Vj9-0Y-bjn"/> + </connections> + </button> + </subviews> + </view> + </viewController> + <customObject id="IGK-9x-tXY" userLabel="First Responder" customClass="NSResponder" sceneMemberID="firstResponder"/> + </objects> + <point key="canvasLocation" x="171" y="1214"/> + </scene> + </scenes> + <resources> + <image name="opengl-logo" width="900" height="375"/> + <image name="vulkan-logo" width="975" height="375"/> + </resources> +</document> diff --git a/NativeApp/Apple/Data/OSX/Images.xcassets/AppIcon.appiconset/dg.icns b/NativeApp/Apple/Data/OSX/Images.xcassets/AppIcon.appiconset/dg.icns Binary files differnew file mode 100644 index 0000000..fddfdff --- /dev/null +++ b/NativeApp/Apple/Data/OSX/Images.xcassets/AppIcon.appiconset/dg.icns diff --git a/NativeApp/Apple/Data/OSX/Images.xcassets/opengl-logo.png b/NativeApp/Apple/Data/OSX/Images.xcassets/opengl-logo.png Binary files differnew file mode 100644 index 0000000..5d4a211 --- /dev/null +++ b/NativeApp/Apple/Data/OSX/Images.xcassets/opengl-logo.png diff --git a/NativeApp/Apple/Data/OSX/Images.xcassets/vulkan-logo.png b/NativeApp/Apple/Data/OSX/Images.xcassets/vulkan-logo.png Binary files differnew file mode 100644 index 0000000..8a15b9e --- /dev/null +++ b/NativeApp/Apple/Data/OSX/Images.xcassets/vulkan-logo.png diff --git a/NativeApp/Apple/Data/OSX/Info.plist b/NativeApp/Apple/Data/OSX/Info.plist new file mode 100644 index 0000000..c482b4a --- /dev/null +++ b/NativeApp/Apple/Data/OSX/Info.plist @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>CFBundleDevelopmentRegion</key> + <string>en</string> + <key>CFBundleExecutable</key> + <string>$(EXECUTABLE_NAME)</string> + <key>CFBundleIconFile</key> + <string>dg.icns</string> + <key>CFBundleIdentifier</key> + <string></string> + <key>CFBundleInfoDictionaryVersion</key> + <string>6.0</string> + <key>CFBundleName</key> + <string>$(PRODUCT_NAME)</string> + <key>CFBundlePackageType</key> + <string>APPL</string> + <key>CFBundleShortVersionString</key> + <string>2.4</string> + <key>CFBundleSignature</key> + <string>????</string> + <key>LSMinimumSystemVersion</key> + <string>$(MACOSX_DEPLOYMENT_TARGET)</string> + <key>NSMainStoryboardFile</key> + <string>Main</string> + <key>NSPrincipalClass</key> + <string>NSApplication</string> +</dict> +</plist> diff --git a/NativeApp/Apple/Data/iOS/Base.lproj/LaunchScreen.xib b/NativeApp/Apple/Data/iOS/Base.lproj/LaunchScreen.xib new file mode 100644 index 0000000..42589b0 --- /dev/null +++ b/NativeApp/Apple/Data/iOS/Base.lproj/LaunchScreen.xib @@ -0,0 +1,45 @@ +<?xml version="1.0" encoding="UTF-8"?> +<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" colorMatched="YES"> + <device id="retina5_9" orientation="portrait"> + <adaptation id="fullscreen"/> + </device> + <dependencies> + <deployment identifier="iOS"/> + <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/> + <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> + </dependencies> + <objects> + <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/> + <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/> + <view contentMode="scaleToFill" id="iN0-l3-epB"> + <rect key="frame" x="0.0" y="0.0" width="480" height="480"/> + <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> + <subviews> + <label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" misplaced="YES" text=" Copyright © 2015-2019 Diligent Graphics." textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" minimumFontSize="9" translatesAutoresizingMaskIntoConstraints="NO" id="8ie-xW-0ye"> + <rect key="frame" x="20" y="439" width="441" height="21"/> + <fontDescription key="fontDescription" type="system" pointSize="17"/> + <color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> + <nil key="highlightedColor"/> + </label> + <label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" misplaced="YES" text="Diligent Engine" textAlignment="center" lineBreakMode="middleTruncation" baselineAdjustment="alignBaselines" minimumFontSize="18" translatesAutoresizingMaskIntoConstraints="NO" id="kId-c2-rCX"> + <rect key="frame" x="20" y="140" width="441" height="43"/> + <fontDescription key="fontDescription" type="boldSystem" pointSize="36"/> + <color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> + <nil key="highlightedColor"/> + </label> + </subviews> + <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> + <constraints> + <constraint firstItem="kId-c2-rCX" firstAttribute="centerY" secondItem="iN0-l3-epB" secondAttribute="bottom" multiplier="1/3" constant="1" id="5cJ-9S-tgC"/> + <constraint firstAttribute="centerX" secondItem="kId-c2-rCX" secondAttribute="centerX" id="Koa-jz-hwk"/> + <constraint firstAttribute="bottom" secondItem="8ie-xW-0ye" secondAttribute="bottom" constant="20" id="Kzo-t9-V3l"/> + <constraint firstItem="8ie-xW-0ye" firstAttribute="leading" secondItem="iN0-l3-epB" secondAttribute="leading" constant="20" symbolic="YES" id="MfP-vx-nX0"/> + <constraint firstAttribute="centerX" secondItem="8ie-xW-0ye" secondAttribute="centerX" id="ZEH-qu-HZ9"/> + <constraint firstItem="kId-c2-rCX" firstAttribute="leading" secondItem="iN0-l3-epB" secondAttribute="leading" constant="20" symbolic="YES" id="fvb-Df-36g"/> + </constraints> + <nil key="simulatedStatusBarMetrics"/> + <freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/> + <point key="canvasLocation" x="548" y="455"/> + </view> + </objects> +</document> diff --git a/NativeApp/Apple/Data/iOS/Base.lproj/Main.storyboard b/NativeApp/Apple/Data/iOS/Base.lproj/Main.storyboard new file mode 100644 index 0000000..78a30e4 --- /dev/null +++ b/NativeApp/Apple/Data/iOS/Base.lproj/Main.storyboard @@ -0,0 +1,89 @@ +<?xml version="1.0" encoding="UTF-8"?> +<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="XIi-06-RrN"> + <device id="retina5_9" orientation="portrait"> + <adaptation id="fullscreen"/> + </device> + <dependencies> + <deployment identifier="iOS"/> + <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/> + <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> + </dependencies> + <scenes> + <!--Mode Selection View Controller--> + <scene sceneID="zOR-Fi-Gze"> + <objects> + <viewController id="XIi-06-RrN" customClass="ModeSelectionViewController" sceneMemberID="viewController"> + <layoutGuides> + <viewControllerLayoutGuide type="top" id="xws-yS-Cpz"/> + <viewControllerLayoutGuide type="bottom" id="eBA-xl-v26"/> + </layoutGuides> + <view key="view" contentMode="scaleToFill" id="bQn-Ig-dl7" customClass="BaseView"> + <rect key="frame" x="0.0" y="0.0" width="375" height="812"/> + <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> + <subviews> + <button opaque="NO" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="Exn-mx-E3B" userLabel="Vulkan"> + <rect key="frame" x="37" y="543" width="302" height="120"/> + <autoresizingMask key="autoresizingMask" flexibleMinX="YES" flexibleMaxX="YES" flexibleMinY="YES" flexibleMaxY="YES"/> + <state key="normal" title="Button" image="vulkan-logo.png"/> + <connections> + <action selector="goVulkan:" destination="XIi-06-RrN" eventType="touchUpInside" id="jsv-Uc-EF5"/> + </connections> + </button> + <button opaque="NO" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="CtC-44-7bh" userLabel="OpenGLES"> + <rect key="frame" x="43" y="198" width="289" height="119"/> + <autoresizingMask key="autoresizingMask" flexibleMinX="YES" flexibleMaxX="YES" flexibleMinY="YES" flexibleMaxY="YES"/> + <state key="normal" title="Button" image="opengles-logo.png"/> + <connections> + <action selector="goOpenGLES:" destination="XIi-06-RrN" eventType="touchUpInside" id="Mad-GE-H0I"/> + </connections> + </button> + </subviews> + <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/> + </view> + </viewController> + <placeholder placeholderIdentifier="IBFirstResponder" id="voS-RJ-rQF" userLabel="First Responder" sceneMemberID="firstResponder"/> + </objects> + <point key="canvasLocation" x="-1458.4000000000001" y="73.891625615763544"/> + </scene> + <!--Metal View Controller--> + <scene sceneID="sxp-To-dZO"> + <objects> + <viewController storyboardIdentifier="MetalViewControllerID" id="2n5-tG-bFt" userLabel="Metal View Controller" sceneMemberID="viewController"> + <layoutGuides> + <viewControllerLayoutGuide type="top" id="X8x-0E-yac"/> + <viewControllerLayoutGuide type="bottom" id="6Gz-x2-Owi"/> + </layoutGuides> + <view key="view" contentMode="scaleToFill" id="fUr-Le-qAJ" customClass="MetalView"> + <rect key="frame" x="0.0" y="0.0" width="375" height="812"/> + <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> + <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/> + </view> + </viewController> + <placeholder placeholderIdentifier="IBFirstResponder" id="xSS-Vf-fsO" userLabel="First Responder" sceneMemberID="firstResponder"/> + </objects> + <point key="canvasLocation" x="-570" y="74"/> + </scene> + <!--EAGL View Controller--> + <scene sceneID="tne-QT-ifu"> + <objects> + <viewController storyboardIdentifier="EAGLViewControllerID" title="EAGL View Controller" id="BYZ-38-t0r" sceneMemberID="viewController"> + <layoutGuides> + <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/> + <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/> + </layoutGuides> + <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC" userLabel="EAGL View" customClass="EAGLView"> + <rect key="frame" x="0.0" y="0.0" width="375" height="812"/> + <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> + <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> + </view> + </viewController> + <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/> + </objects> + <point key="canvasLocation" x="214" y="74"/> + </scene> + </scenes> + <resources> + <image name="opengles-logo.png" width="1500" height="500"/> + <image name="vulkan-logo.png" width="1300" height="500"/> + </resources> +</document> diff --git a/NativeApp/Apple/Data/iOS/Images.xcassets/AppIcon.appiconset/dg-icon.png b/NativeApp/Apple/Data/iOS/Images.xcassets/AppIcon.appiconset/dg-icon.png Binary files differnew file mode 100644 index 0000000..c3f0b5e --- /dev/null +++ b/NativeApp/Apple/Data/iOS/Images.xcassets/AppIcon.appiconset/dg-icon.png diff --git a/NativeApp/Apple/Data/iOS/Images.xcassets/opengles-logo.png b/NativeApp/Apple/Data/iOS/Images.xcassets/opengles-logo.png Binary files differnew file mode 100644 index 0000000..88b6983 --- /dev/null +++ b/NativeApp/Apple/Data/iOS/Images.xcassets/opengles-logo.png diff --git a/NativeApp/Apple/Data/iOS/Images.xcassets/vulkan-logo.png b/NativeApp/Apple/Data/iOS/Images.xcassets/vulkan-logo.png Binary files differnew file mode 100644 index 0000000..8a15b9e --- /dev/null +++ b/NativeApp/Apple/Data/iOS/Images.xcassets/vulkan-logo.png diff --git a/NativeApp/Apple/Data/iOS/info.plist b/NativeApp/Apple/Data/iOS/info.plist new file mode 100644 index 0000000..47629ab --- /dev/null +++ b/NativeApp/Apple/Data/iOS/info.plist @@ -0,0 +1,49 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>CFBundleDevelopmentRegion</key> + <string>en</string> + <key>CFBundleExecutable</key> + <string>$(EXECUTABLE_NAME)</string> + <key>CFBundleIdentifier</key> + <string>com.diligentengine.sampleapp</string> + <key>CFBundleInfoDictionaryVersion</key> + <string>6.0</string> + <key>CFBundleName</key> + <string>$(PRODUCT_NAME)</string> + <key>CFBundlePackageType</key> + <string>APPL</string> + <key>CFBundleShortVersionString</key> + <string>2.4</string> + <key>CFBundleVersion</key> + <string>2.4</string> + <key>CFBundleSignature</key> + <string>????</string> + <key>CFBundleIconFile</key> + <string>dg-icon.png</string> + <key>LSRequiresIPhoneOS</key> + <true/> + <key>UILaunchStoryboardName</key> + <string>LaunchScreen</string> + <key>UIMainStoryboardFile</key> + <string>Main</string> + <key>UIRequiredDeviceCapabilities</key> + <array> + <string>armv7</string> + </array> + <key>UISupportedInterfaceOrientations</key> + <array> + <string>UIInterfaceOrientationPortrait</string> + <string>UIInterfaceOrientationLandscapeLeft</string> + <string>UIInterfaceOrientationLandscapeRight</string> + </array> + <key>UISupportedInterfaceOrientations~ipad</key> + <array> + <string>UIInterfaceOrientationPortrait</string> + <string>UIInterfaceOrientationPortraitUpsideDown</string> + <string>UIInterfaceOrientationLandscapeLeft</string> + <string>UIInterfaceOrientationLandscapeRight</string> + </array> +</dict> +</plist> diff --git a/NativeApp/Apple/LICENSE.txt b/NativeApp/Apple/LICENSE.txt new file mode 100644 index 0000000..73f0303 --- /dev/null +++ b/NativeApp/Apple/LICENSE.txt @@ -0,0 +1,42 @@ +Sample code project: GLEssentials +Version: 3.0 + +IMPORTANT: This Apple software is supplied to you by Apple +Inc. ("Apple") in consideration of your agreement to the following +terms, and your use, installation, modification or redistribution of +this Apple software constitutes acceptance of these terms. If you do +not agree with these terms, please do not use, install, modify or +redistribute this Apple software. + +In consideration of your agreement to abide by the following terms, and +subject to these terms, Apple grants you a personal, non-exclusive +license, under Apple's copyrights in this original Apple software (the +"Apple Software"), to use, reproduce, modify and redistribute the Apple +Software, with or without modifications, in source and/or binary forms; +provided that if you redistribute the Apple Software in its entirety and +without modifications, you must retain this notice and the following +text and disclaimers in all such redistributions of the Apple Software. +Neither the name, trademarks, service marks or logos of Apple Inc. may +be used to endorse or promote products derived from the Apple Software +without specific prior written permission from Apple. Except as +expressly stated in this notice, no other rights or licenses, express or +implied, are granted by Apple herein, including but not limited to any +patent rights that may be infringed by your derivative works or by other +works in which the Apple Software may be incorporated. + +The Apple Software is provided by Apple on an "AS IS" basis. APPLE +MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION +THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND +OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. + +IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL +OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, +MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED +AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), +STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +Copyright (C) 2015 Apple Inc. All Rights Reserved. diff --git a/NativeApp/Apple/Source/Classes/OSX/AppDelegate.h b/NativeApp/Apple/Source/Classes/OSX/AppDelegate.h new file mode 100644 index 0000000..d38403c --- /dev/null +++ b/NativeApp/Apple/Source/Classes/OSX/AppDelegate.h @@ -0,0 +1,15 @@ +/* + Copyright (C) 2015 Apple Inc. All Rights Reserved. + See LICENSE.txt for this sample’s licensing information + + Abstract: + The Application Delegate. + */ + +#import <Cocoa/Cocoa.h> + +@interface AppDelegate : NSObject <NSApplicationDelegate> + + +@end + diff --git a/NativeApp/Apple/Source/Classes/OSX/AppDelegate.m b/NativeApp/Apple/Source/Classes/OSX/AppDelegate.m new file mode 100644 index 0000000..fd52cc4 --- /dev/null +++ b/NativeApp/Apple/Source/Classes/OSX/AppDelegate.m @@ -0,0 +1,30 @@ +/* + Copyright (C) 2015 Apple Inc. All Rights Reserved. + See LICENSE.txt for this sample’s licensing information + + Abstract: + The Application Delegate. + */ + +#import "AppDelegate.h" + +@interface AppDelegate () + +@end + +@implementation AppDelegate + +- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { + NSWindow* mainWindow = [[NSApplication sharedApplication]mainWindow]; + [mainWindow setAcceptsMouseMovedEvents:YES]; +} + +- (void)applicationWillTerminate:(NSNotification *)aNotification { + // Insert code here to tear down your application +} + +- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication { + return YES; +} + +@end diff --git a/NativeApp/Apple/Source/Classes/OSX/FullscreenWindow.h b/NativeApp/Apple/Source/Classes/OSX/FullscreenWindow.h new file mode 100644 index 0000000..2a61a51 --- /dev/null +++ b/NativeApp/Apple/Source/Classes/OSX/FullscreenWindow.h @@ -0,0 +1,15 @@ +/* + Copyright (C) 2015 Apple Inc. All Rights Reserved. + See LICENSE.txt for this sample’s licensing information + + Abstract: + Fullscreen window class. + All logic here could have been done in the window controller except that, by default, borderless windows cannot be made key and input cannot go to them. + Therefore, this class exists to override canBecomeKeyWindow allowing this borderless window to accept inputs. + This class is not part of the NIB and entirely managed in code by the window controller. + */ +#import <Cocoa/Cocoa.h> + +@interface FullscreenWindow : NSWindow + +@end diff --git a/NativeApp/Apple/Source/Classes/OSX/FullscreenWindow.m b/NativeApp/Apple/Source/Classes/OSX/FullscreenWindow.m new file mode 100644 index 0000000..69c9063 --- /dev/null +++ b/NativeApp/Apple/Source/Classes/OSX/FullscreenWindow.m @@ -0,0 +1,52 @@ +/* + Copyright (C) 2015 Apple Inc. All Rights Reserved. + See LICENSE.txt for this sample’s licensing information + + Abstract: + Fullscreen window class. + All logic here could have been done in the window controller except that, by default, borderless windows cannot be made key and input cannot go to them. + Therefore, this class exists to override canBecomeKeyWindow allowing this borderless window to accept inputs. + This class is not part of the NIB and entirely managed in code by the window controller. + */ + +#import "FullscreenWindow.h" + +@implementation FullscreenWindow + +-(instancetype)init +{ + // Create a screen-sized window on the display you want to take over + NSRect screenRect = [[NSScreen mainScreen] frame]; + + // Initialize the window making it size of the screen and borderless + self = [super initWithContentRect:screenRect + styleMask:NSWindowStyleMaskBorderless + backing:NSBackingStoreBuffered + defer:YES]; + + // Set the window level to be above the menu bar to cover everything else + [self setLevel:NSMainMenuWindowLevel+1]; + + // Set opaque + [self setOpaque:YES]; + + // Hide this when user switches to another window (or app) + [self setHidesOnDeactivate:YES]; + + return self; +} + +-(BOOL)canBecomeKeyWindow +{ + // Return yes so that this borderless window can receive input + return YES; +} + +- (void)keyDown:(NSEvent *)event +{ + // Implement keyDown since controller will not get [ESC] key event which + // the controller uses to kill fullscreen + [[self windowController] keyDown:event]; +} + +@end diff --git a/NativeApp/Apple/Source/Classes/OSX/GLView.h b/NativeApp/Apple/Source/Classes/OSX/GLView.h new file mode 100644 index 0000000..666305a --- /dev/null +++ b/NativeApp/Apple/Source/Classes/OSX/GLView.h @@ -0,0 +1,15 @@ +/* + Copyright (C) 2015 Apple Inc. All Rights Reserved. + See LICENSE.txt for this sample’s licensing information + + Abstract: + OpenGL view subclass. + */ + + +#import <Cocoa/Cocoa.h> +#import "ViewBase.h" + +@interface GLView : ViewBase + +@end diff --git a/NativeApp/Apple/Source/Classes/OSX/GLView.m b/NativeApp/Apple/Source/Classes/OSX/GLView.m new file mode 100644 index 0000000..2e91b35 --- /dev/null +++ b/NativeApp/Apple/Source/Classes/OSX/GLView.m @@ -0,0 +1,211 @@ +/* + Copyright (C) 2015 Apple Inc. All Rights Reserved. + See LICENSE.txt for this sample’s licensing information + + Abstract: + OpenGL view subclass. + */ + +#include <memory> + +#import "GLView.h" + +@interface GLView () +{ + NSRect _viewRectPixels; +} +@end + +@implementation GLView + + +- (CVReturn) getFrameForTime:(const CVTimeStamp*)outputTime +{ + // There is no autorelease pool when this method is called + // because it will be called from a background thread. + // It's important to create one or app can leak objects. + @autoreleasepool { + [self drawView]; + } + return kCVReturnSuccess; +} + +// This is the renderer output callback function +static CVReturn MyDisplayLinkCallback(CVDisplayLinkRef displayLink, + const CVTimeStamp* now, + const CVTimeStamp* outputTime, + CVOptionFlags flagsIn, + CVOptionFlags* flagsOut, + void* displayLinkContext) +{ + CVReturn result = [(__bridge GLView*)displayLinkContext getFrameForTime:outputTime]; + return result; +} + +// Prepares the receiver for service after it has been loaded +// from an Interface Builder archive, or nib file. +- (void) awakeFromNib +{ + [super awakeFromNib]; + + NSOpenGLPixelFormatAttribute attrs[] = + { + NSOpenGLPFADoubleBuffer, + NSOpenGLPFADepthSize, 24, + NSOpenGLPFAOpenGLProfile, + NSOpenGLProfileVersion4_1Core, + 0 + }; + + NSOpenGLPixelFormat *pf = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs]; + + if (!pf) + { + NSLog(@"No OpenGL pixel format"); + } + + NSOpenGLContext* context = [[NSOpenGLContext alloc] initWithFormat:pf shareContext:nil]; + +#if defined(DEBUG) + // When we're using a CoreProfile context, crash if we call a legacy OpenGL function + // This will make it much more obvious where and when such a function call is made so + // that we can remove such calls. + // Without this we'd simply get GL_INVALID_OPERATION error for calling legacy functions + // but it would be more difficult to see where that function was called. + CGLEnable([context CGLContextObj], kCGLCECrashOnRemovedFunctions); +#endif + + [self setPixelFormat:pf]; + + [self setOpenGLContext:context]; + + // Opt-In to Retina resolution + [self setWantsBestResolutionOpenGLSurface:YES]; +} + +- (void) prepareOpenGL +{ + [super prepareOpenGL]; + + // Application must be initialized befor display link is started + [self initGL]; + + CVDisplayLinkRef displayLink; + // Create a display link capable of being used with all active displays + CVDisplayLinkCreateWithActiveCGDisplays(&displayLink); + [self setDisplayLink:displayLink]; + + // Set the renderer output callback function + CVDisplayLinkSetOutputCallback(displayLink, &MyDisplayLinkCallback, (__bridge void*)self); + + // Set the display link for the current renderer + CGLContextObj cglContext = [[self openGLContext] CGLContextObj]; + CGLPixelFormatObj cglPixelFormat = [[self pixelFormat] CGLPixelFormatObj]; + CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(displayLink, cglContext, cglPixelFormat); + + // Activate the display link + CVDisplayLinkStart(displayLink); +} + +- (void) initGL +{ + // The reshape function may have changed the thread to which our OpenGL + // context is attached before prepareOpenGL and initGL are called. So call + // makeCurrentContext to ensure that our OpenGL context current to this + // thread (i.e. makeCurrentContext directs all OpenGL calls on this thread + // to [self openGLContext]) + [[self openGLContext] makeCurrentContext]; + + // Synchronize buffer swaps with vertical refresh rate + GLint swapInt = 1; + [[self openGLContext] setValues:&swapInt forParameter:NSOpenGLCPSwapInterval]; + + // Init the application. + [self initApp:nil]; +} + +- (void)reshape +{ + [super reshape]; + + // We draw on a secondary thread through the display link. However, when + // resizing the view, -drawRect is called on the main thread. + // Add a mutex around to avoid the threads accessing the context + // simultaneously when resizing. + CGLLockContext([[self openGLContext] CGLContextObj]); + + // Get the view size in Points + NSRect viewRectPoints = [self bounds]; + + // Rendering at retina resolutions will reduce aliasing, but at the potential + // cost of framerate and battery life due to the GPU needing to render more + // pixels. + + // Any calculations the renderer does which use pixel dimentions, must be + // in "retina" space. [NSView convertRectToBacking] converts point sizes + // to pixel sizes. Thus the renderer gets the size in pixels, not points, + // so that it can set it's viewport and perform and other pixel based + // calculations appropriately. + // viewRectPixels will be larger than viewRectPoints for retina displays. + // viewRectPixels will be the same as viewRectPoints for non-retina displays + _viewRectPixels = [self convertRectToBacking:viewRectPoints]; + + // Set the new dimensions in our renderer + auto* theApp = [self lockApp]; + if(theApp) + { + theApp->WindowResize(_viewRectPixels.size.width, _viewRectPixels.size.height); + } + [self unlockApp]; + + CGLUnlockContext([[self openGLContext] CGLContextObj]); +} + + +- (void)renewGState +{ + // Called whenever graphics state updated (such as window resize) + + // OpenGL rendering is not synchronous with other rendering on the OSX. + // Therefore, call disableScreenUpdatesUntilFlush so the window server + // doesn't render non-OpenGL content in the window asynchronously from + // OpenGL content, which could cause flickering. (non-OpenGL content + // includes the title bar and drawing done by the app with other APIs) + [[self window] disableScreenUpdatesUntilFlush]; + + [super renewGState]; +} + +- (void) drawRect: (NSRect) theRect +{ + // Called during resize operations + + // Avoid flickering during resize by drawing + [self drawView]; +} + +- (void) drawView +{ + auto* glContext = [self openGLContext]; + + [glContext makeCurrentContext]; + + // We draw on a secondary thread through the display link + // When resizing the view, -reshape is called automatically on the main + // thread. Add a mutex around to avoid the threads accessing the context + // simultaneously when resizing + CGLLockContext([glContext CGLContextObj]); + + auto* theApp = [self lockApp]; + if(theApp) + { + theApp->Update(); + theApp->Render(); + } + [self unlockApp]; + + CGLFlushDrawable([glContext CGLContextObj]); + CGLUnlockContext([glContext CGLContextObj]); +} + +@end diff --git a/NativeApp/Apple/Source/Classes/OSX/MetalView.h b/NativeApp/Apple/Source/Classes/OSX/MetalView.h new file mode 100644 index 0000000..d9b6a7a --- /dev/null +++ b/NativeApp/Apple/Source/Classes/OSX/MetalView.h @@ -0,0 +1,30 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#import <AppKit/AppKit.h> + +#include "ViewBase.h" + +@interface MetalView : ViewBase + +@end diff --git a/NativeApp/Apple/Source/Classes/OSX/MetalView.m b/NativeApp/Apple/Source/Classes/OSX/MetalView.m new file mode 100644 index 0000000..5d4a7dd --- /dev/null +++ b/NativeApp/Apple/Source/Classes/OSX/MetalView.m @@ -0,0 +1,139 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#import <QuartzCore/CAMetalLayer.h> +#import "MetalView.h" + +@implementation MetalView +{ +} + +- (void) awakeFromNib +{ + [super awakeFromNib]; + + // Back the view with a layer created by the makeBackingLayer method. + self.wantsLayer = YES; + + [self initApp:self]; + + CVDisplayLinkRef displayLink; + CVDisplayLinkCreateWithActiveCGDisplays(&displayLink); + [self setDisplayLink:displayLink]; + CVDisplayLinkSetOutputCallback(displayLink, &DisplayLinkCallback, (__bridge void*)self); + CVDisplayLinkStart(displayLink); + + [self setPostsBoundsChangedNotifications:YES]; + [self setPostsFrameChangedNotifications:YES]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(boundsDidChange:) name:NSViewBoundsDidChangeNotification object:self]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(boundsDidChange:) name:NSViewFrameDidChangeNotification object:self]; +} + +// Indicates that the view wants to draw using the backing +// layer instead of using drawRect:. +-(BOOL) wantsUpdateLayer +{ + return YES; +} + +// Returns a Metal-compatible layer. ++(Class) layerClass +{ + return [CAMetalLayer class]; +} + +// If the wantsLayer property is set to YES, this method will +// be invoked to return a layer instance. +-(CALayer*) makeBackingLayer +{ + CALayer* layer = [self.class.layerClass layer]; + CGSize viewScale = [self convertSizeToBacking: CGSizeMake(1.0, 1.0)]; + layer.contentsScale = MIN(viewScale.width, viewScale.height); + return layer; +} + +-(void)render +{ + auto* theApp = [self lockApp]; + if (theApp) + { + theApp->Update(); + theApp->Render(); + theApp->Present(); + } + [self unlockApp]; +} + + +- (CVReturn) getFrameForTime:(const CVTimeStamp*)outputTime +{ + // There is no autorelease pool when this method is called + // because it will be called from a background thread. + // It's important to create one or app can leak objects. + @autoreleasepool { + [self render]; + } + return kCVReturnSuccess; +} + +// Rendering loop callback function for use with a CVDisplayLink. +static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, + const CVTimeStamp* now, + const CVTimeStamp* outputTime, + CVOptionFlags flagsIn, + CVOptionFlags* flagsOut, + void* target) +{ + MetalView* view = (__bridge MetalView*)target; + CVReturn result = [view getFrameForTime:outputTime]; + return result; +} + +-(void)boundsDidChange:(NSNotification *)notification +{ + // It is not clear what the proper way to handle window resize is. + // Cube demo from MoltenVK ignores any window resize notifications and + // recreates the swap chain if Present or AcquireNextImage fails, causing + // jagged transitions. + + // According to this thread, there is no solution for flickering during + // resize in Metal: + // https://forums.developer.apple.com/thread/77901 + + // Calling WindowResize() causes flickering. + // Even if [self render] is called ater WindowResize() + // Similar results when using Metal kit view + // Calling [self render] alone produces jagged transitions but no flickering. + // Calling nothing causes the app to crash during resize. + + NSRect viewRectPoints = [self bounds]; + NSRect viewRectPixels = [self convertRectToBacking:viewRectPoints]; + auto* theApp = [self lockApp]; + if (theApp) + { + theApp->WindowResize(viewRectPixels.size.width, viewRectPixels.size.height); + } + [self unlockApp]; +} + +@end diff --git a/NativeApp/Apple/Source/Classes/OSX/ModeSelectionViewController.h b/NativeApp/Apple/Source/Classes/OSX/ModeSelectionViewController.h new file mode 100644 index 0000000..895123b --- /dev/null +++ b/NativeApp/Apple/Source/Classes/OSX/ModeSelectionViewController.h @@ -0,0 +1,30 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + + +#import <AppKit/AppKit.h> + +@interface ModeSelectionViewController : NSViewController +{ +} +@end diff --git a/NativeApp/Apple/Source/Classes/OSX/ModeSelectionViewController.mm b/NativeApp/Apple/Source/Classes/OSX/ModeSelectionViewController.mm new file mode 100644 index 0000000..3bd4dbe --- /dev/null +++ b/NativeApp/Apple/Source/Classes/OSX/ModeSelectionViewController.mm @@ -0,0 +1,83 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#import "ModeSelectionViewController.h" +#import "GLView.h" +#import "MetalView.h" +#import "ViewController.h" + + +@implementation ModeSelectionViewController +{ +} + +- (void) setWindowTitle:(NSString*) title +{ + NSWindow* mainWindow = [[NSApplication sharedApplication]mainWindow]; + [mainWindow setTitle:title]; +} + +- (void) terminateApp:(NSString*) error +{ + NSAlert *alert = [[NSAlert alloc] init]; + [alert addButtonWithTitle:@"OK"]; + [alert setMessageText:@"Failed to start the application"]; + [alert setInformativeText:error]; + [alert setAlertStyle:NSAlertStyleCritical]; + [alert runModal]; + [NSApp terminate:self]; +} + +- (IBAction)goOpenGL:(id)sender +{ + ViewController* glViewController = [self.storyboard instantiateControllerWithIdentifier:@"GLViewControllerID"]; + self.view.window.contentViewController = glViewController; + + GLView* glView = (GLView*)[glViewController view]; + NSString* error = [glView getError]; + if(error != nil) + { + [self terminateApp:error]; + } + + NSString* name = [glView getAppName]; + [self setWindowTitle:name]; +} + +- (IBAction)goVulkan:(id)sender +{ + ViewController* metalViewController = [self.storyboard instantiateControllerWithIdentifier:@"MetalViewControllerID"]; + self.view.window.contentViewController = metalViewController; + + MetalView* mtlView = (MetalView*)[metalViewController view]; + NSString* error = [mtlView getError]; + if(error != nil) + { + [self terminateApp:error]; + } + + NSString* name = [mtlView getAppName]; + [self setWindowTitle:name]; +} + +@end diff --git a/NativeApp/Apple/Source/Classes/OSX/ViewBase.h b/NativeApp/Apple/Source/Classes/OSX/ViewBase.h new file mode 100644 index 0000000..d3084dd --- /dev/null +++ b/NativeApp/Apple/Source/Classes/OSX/ViewBase.h @@ -0,0 +1,43 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#include "NativeAppBase.h" + +#import <AppKit/AppKit.h> +#import <QuartzCore/CVDisplayLink.h> +#import <Cocoa/Cocoa.h> + +@interface ViewBase : NSOpenGLView + +@property CVDisplayLinkRef displayLink; + +-(void)initApp:(NSView*) view; +-(void)destroyApp; +-(NSString*)getError; +-(Diligent::NativeAppBase*)lockApp; +-(void)unlockApp; +-(void)stopDisplayLink; +-(void)startDisplayLink; +-(NSString*)getAppName; + +@end diff --git a/NativeApp/Apple/Source/Classes/OSX/ViewBase.m b/NativeApp/Apple/Source/Classes/OSX/ViewBase.m new file mode 100644 index 0000000..b73a5eb --- /dev/null +++ b/NativeApp/Apple/Source/Classes/OSX/ViewBase.m @@ -0,0 +1,147 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#include <memory> +#include <string> + +#import "ViewBase.h" + +@implementation ViewBase +{ + std::unique_ptr<Diligent::NativeAppBase> _theApp; + std::string _error; + NSRecursiveLock* appLock; +} + +@synthesize displayLink; + +// Prepares the receiver for service after it has been loaded +// from an Interface Builder archive, or nib file. +- (void) awakeFromNib +{ + [super awakeFromNib]; + + _theApp.reset(Diligent::CreateApplication()); + + // [self window] is nil here + auto* mainWindow = [[NSApplication sharedApplication] mainWindow]; + // Register to be notified when the main window closes so we can stop the displaylink + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(windowWillClose:) + name:NSWindowWillCloseNotification + object:mainWindow]; + mainWindow.minSize = NSSize{320, 240}; +} + +-(void)initApp:(NSView*) view +{ + // Init the application. + try + { + _theApp->Initialize(view); + } + catch(std::runtime_error &err) + { + _error = err.what(); + _theApp.reset(); + } +} + +-(Diligent::NativeAppBase*)lockApp +{ + [appLock lock]; + return _theApp.get(); +} + +-(void)unlockApp +{ + [appLock unlock]; +} + +- (BOOL)acceptsFirstResponder +{ + return YES; // To make keyboard events work +} + +-(void)destroyApp +{ + // Stop the display link BEFORE releasing anything in the view + // otherwise the display link thread may call into the view and crash + // when it encounters something that has been released + if (displayLink) + { + CVDisplayLinkStop(displayLink); + } + + [appLock lock]; + _theApp.reset(); + [appLock unlock]; +} + +-(void) dealloc +{ + [self destroyApp]; + + CVDisplayLinkRelease(displayLink); + + [appLock release]; + + [super dealloc]; +} + +-(NSString*)getError +{ + return _error.empty() ? nil : [NSString stringWithFormat:@"%s", _error.c_str()]; +} + + +- (void)stopDisplayLink +{ + if (displayLink) + { + CVDisplayLinkStop(displayLink); + } +} + +- (void)startDisplayLink +{ + if (displayLink) + { + CVDisplayLinkStart(displayLink); + } +} + +- (void) windowWillClose:(NSNotification*)notification +{ + [self destroyApp]; +} + +-(NSString*)getAppName +{ + auto* theApp = [self lockApp]; + auto Title = [NSString stringWithFormat:@"%s", theApp ? theApp->GetAppTitle() : ""]; + [self unlockApp]; + return Title; +} + +@end diff --git a/NativeApp/Apple/Source/Classes/OSX/ViewController.h b/NativeApp/Apple/Source/Classes/OSX/ViewController.h new file mode 100644 index 0000000..a8e4685 --- /dev/null +++ b/NativeApp/Apple/Source/Classes/OSX/ViewController.h @@ -0,0 +1,30 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + + +#import <AppKit/AppKit.h> +#include "NativeAppBase.h" + +@interface ViewController : NSViewController + +@end diff --git a/NativeApp/Apple/Source/Classes/OSX/ViewController.mm b/NativeApp/Apple/Source/Classes/OSX/ViewController.mm new file mode 100644 index 0000000..1a6611c --- /dev/null +++ b/NativeApp/Apple/Source/Classes/OSX/ViewController.mm @@ -0,0 +1,116 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#import "ViewController.h" +#import "ViewBase.h" + +@implementation ViewController + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + // Add a tracking area in order to receive mouse events whenever the mouse is within the bounds of our view + NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect + options:NSTrackingMouseMoved | NSTrackingInVisibleRect | NSTrackingActiveAlways + owner:self + userInfo:nil]; + [self.view addTrackingArea:trackingArea]; +} + +- (void)handleEvent : (NSEvent *)theEvent { + auto* view = (ViewBase*)self.view; + auto* theApp = [view lockApp]; + if(theApp){ + theApp->HandleOSXEvent(theEvent, view); + } + [view unlockApp]; +} + + +- (void)mouseDown:(NSEvent *)theEvent { + [self handleEvent:theEvent]; +} + +- (void)mouseUp:(NSEvent *)theEvent { + [self handleEvent:theEvent]; +} + +- (void)rightMouseDown:(NSEvent *)theEvent { + [self handleEvent:theEvent]; +} + +- (void)rightMouseUp:(NSEvent *)theEvent { + [self handleEvent:theEvent]; +} + +- (void)mouseMoved:(NSEvent *)theEvent { + [self handleEvent:theEvent]; +} + +- (void)mouseDragged:(NSEvent *)theEvent { + [self handleEvent:theEvent]; +} + +- (void)rightMouseDragged:(NSEvent *)theEvent { + [self handleEvent:theEvent]; +} + +- (void)keyEvent:(NSEvent *)theEvent isKeyPressed:(bool)keyPressed +{ + [self handleEvent:theEvent]; +} + +- (void)keyDown:(NSEvent *)theEvent +{ + [self handleEvent:theEvent]; + + [super keyDown:theEvent]; +} + +- (void)keyUp:(NSEvent *)theEvent +{ + [self handleEvent:theEvent]; + + [super keyUp:theEvent]; +} + +// Informs the receiver that the user has pressed or released a +// modifier key (Shift, Control, and so on) +- (void)flagsChanged:(NSEvent *)event +{ + [self handleEvent:event]; + + [super flagsChanged:event]; +} + +- (void)scrollWheel:(NSEvent *)event +{ + [self handleEvent:event]; +} + +- (BOOL)acceptsFirstResponder { + return YES; +} + +@end diff --git a/NativeApp/Apple/Source/Classes/OSX/WindowController.h b/NativeApp/Apple/Source/Classes/OSX/WindowController.h new file mode 100644 index 0000000..1d9203b --- /dev/null +++ b/NativeApp/Apple/Source/Classes/OSX/WindowController.h @@ -0,0 +1,14 @@ +/* + Copyright (C) 2015 Apple Inc. All Rights Reserved. + See LICENSE.txt for this sample’s licensing information + + Abstract: + Window controller subclass. + */ + + +#import <Cocoa/Cocoa.h> + +@interface WindowController : NSWindowController + +@end diff --git a/NativeApp/Apple/Source/Classes/OSX/WindowController.m b/NativeApp/Apple/Source/Classes/OSX/WindowController.m new file mode 100644 index 0000000..e3f7923 --- /dev/null +++ b/NativeApp/Apple/Source/Classes/OSX/WindowController.m @@ -0,0 +1,181 @@ +/* + Copyright (C) 2015 Apple Inc. All Rights Reserved. + See LICENSE.txt for this sample’s licensing information + + Abstract: + Window controller subclass. + */ + +#import "WindowController.h" +#import "FullscreenWindow.h" +#import "ViewBase.h" + +@interface WindowController () + +// Fullscreen window +@property(strong) FullscreenWindow *fullscreenWindow; + +// Non-Fullscreen window (also the initial window) +@property(strong) NSWindow* standardWindow; + +@end + +@implementation WindowController +{ + bool CommandKeyPressed; +} + +- (instancetype)initWithWindow:(NSWindow *)window +{ + self = [super initWithWindow:window]; + + if (self) + { + // Initialize to nil since it indicates app is not fullscreen + _fullscreenWindow = nil; + } + + CommandKeyPressed = false; + + return self; +} + +- (void) goFullscreen +{ + // If app is already fullscreen... + if([self fullscreenWindow]) + { + //...don't do anything + return; + } + + ViewBase* view = (ViewBase*)self.window.contentView; + + // We must stop the display link while + // switching the windows to make sure + // that render commands are not issued + // from another thread + [view stopDisplayLink]; + + // Allocate a new fullscreen window + [self setFullscreenWindow: [[FullscreenWindow alloc] init]]; + + [[self fullscreenWindow] setAcceptsMouseMovedEvents:YES]; + + // Resize the view to screensize + NSRect viewRect = [[self fullscreenWindow] frame]; + + // Set the view to the size of the fullscreen window + [self.window.contentView setFrameSize: viewRect.size]; + + // Set the view in the fullscreen window + [[self fullscreenWindow] setContentView:self.window.contentView]; + + [self setStandardWindow:[self window]]; + + // Hide non-fullscreen window so it doesn't show up when switching out + // of this app (i.e. with CMD-TAB) + [[self standardWindow] orderOut:self]; + + // Set controller to the fullscreen window so that all input will go to + // this controller (self) + [self setWindow:[self fullscreenWindow]]; + + // Show the window and make it the key window for input + [[self fullscreenWindow] makeKeyAndOrderFront:self]; + + // Restore display link + [view startDisplayLink]; +} + +- (void) goWindow +{ + // If controller doesn't have a full screen window... + if([self fullscreenWindow] == nil) + { + //...app is already windowed so don't do anything + return; + } + + ViewBase* view = (ViewBase*)self.window.contentView; + + // We must stop the display link while + // switching the windows to make sure + // that render commands are not issued + // from another thread + [view stopDisplayLink]; + + // Get the rectangle of the original window + NSRect viewRect = [[self standardWindow] frame]; + + // Set the view rect to the new size + [self.window.contentView setFrame:viewRect]; + + // Hide fullscreen window + [[self fullscreenWindow] orderOut:self]; + + // Set controller to the standard window so that all input will go to + // this controller (self) + [self setWindow:[self standardWindow]]; + + // Set the content of the orginal window to the view + [[self window] setContentView: [self fullscreenWindow].contentView]; + + // Show the window and make it the key window for input + [[self window] makeKeyAndOrderFront:self]; + + // Ensure we set fullscreen Window to nil so our checks for + // windowed vs. fullscreen mode elsewhere are correct + [self setFullscreenWindow: nil]; + + // Restore display link + [view startDisplayLink]; +} + + +- (void) keyDown:(NSEvent *)event +{ + unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0]; + + switch (c) + { + // Handle [ESC] key + case 27: + if([self fullscreenWindow] != nil) + { + [self goWindow]; + } + return; + + // Have Command+f or Command+Enter toggle fullscreen + case 13: + case 'f': + if (CommandKeyPressed) + { + if([self fullscreenWindow] == nil) + { + [self goFullscreen]; + } + else + { + [self goWindow]; + } + } + return; + } + + // Allow other character to be handled (or not and beep) + //[super keyDown:event]; +} + +// Informs the receiver that the user has pressed or released a +// modifier key (Shift, Control, and so on) +- (void)flagsChanged:(NSEvent *)event +{ + auto modifierFlags = [event modifierFlags]; + CommandKeyPressed = modifierFlags & NSEventModifierFlagCommand; + + [super flagsChanged:event]; +} + +@end diff --git a/NativeApp/Apple/Source/Classes/iOS/AppDelegate.h b/NativeApp/Apple/Source/Classes/iOS/AppDelegate.h new file mode 100644 index 0000000..3839faa --- /dev/null +++ b/NativeApp/Apple/Source/Classes/iOS/AppDelegate.h @@ -0,0 +1,18 @@ +/* + Copyright (C) 2015 Apple Inc. All Rights Reserved. + See LICENSE.txt for this sample’s licensing information + + Abstract: + The application delegate + */ + + +#import <UIKit/UIKit.h> + +@interface AppDelegate : NSObject <UIApplicationDelegate> { +} + +@property (nonatomic, retain) UIWindow *window; + +@end + diff --git a/NativeApp/Apple/Source/Classes/iOS/AppDelegate.m b/NativeApp/Apple/Source/Classes/iOS/AppDelegate.m new file mode 100644 index 0000000..5e1745c --- /dev/null +++ b/NativeApp/Apple/Source/Classes/iOS/AppDelegate.m @@ -0,0 +1,89 @@ +/* + Copyright (C) 2015 Apple Inc. All Rights Reserved. + See LICENSE.txt for this sample’s licensing information + + Abstract: + The application delegate +*/ + +#import "AppDelegate.h" +#import "BaseView.h" + +@implementation AppDelegate + +#pragma mark - +#pragma mark Application lifecycle + +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions +{ + // Override point for customization after application launch. + + [self.window makeKeyAndVisible]; + + [(BaseView*)self.window.rootViewController.view startAnimation]; + + return YES; +} + + +- (void)applicationWillResignActive:(UIApplication *)application +{ + /* + Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + 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. + */ + + [(BaseView*)self.window.rootViewController.view stopAnimation]; +} + + +- (void)applicationDidEnterBackground:(UIApplication *)application { + /* + Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + If your application supports background execution, called instead of applicationWillTerminate: when the user quits. + */ + + [(BaseView*)self.window.rootViewController.view stopAnimation]; +} + + +- (void)applicationWillEnterForeground:(UIApplication *)application { + /* + Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background. + */ + + [(BaseView*)self.window.rootViewController.view startAnimation]; +} + + +- (void)applicationDidBecomeActive:(UIApplication *)application +{ + /* + 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. + */ + + [(BaseView*)self.window.rootViewController.view startAnimation]; +} + + +- (void)applicationWillTerminate:(UIApplication *)application { + /* + Called when the application is about to terminate. + See also applicationDidEnterBackground:. + */ + + [(BaseView*)self.window.rootViewController.view stopAnimation]; + [(BaseView*)self.window.rootViewController.view terminate]; +} + + +#pragma mark - +#pragma mark Memory management + +- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { + /* + Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. + */ +} + +@end diff --git a/NativeApp/Apple/Source/Classes/iOS/AppViewBase.h b/NativeApp/Apple/Source/Classes/iOS/AppViewBase.h new file mode 100644 index 0000000..e6273e9 --- /dev/null +++ b/NativeApp/Apple/Source/Classes/iOS/AppViewBase.h @@ -0,0 +1,16 @@ + +#import <UIKit/UIKit.h> +#import "BaseView.h" + +@interface AppViewBase : BaseView + +@property (nonatomic) NSInteger animationFrameInterval; + +- (void) initApp:(int)deviceType; +- (void) startAnimation; +- (void) stopAnimation; +- (void) terminate; +- (void) render; +- (NSString*)getError; + +@end diff --git a/NativeApp/Apple/Source/Classes/iOS/AppViewBase.m b/NativeApp/Apple/Source/Classes/iOS/AppViewBase.m new file mode 100644 index 0000000..e7d4c57 --- /dev/null +++ b/NativeApp/Apple/Source/Classes/iOS/AppViewBase.m @@ -0,0 +1,166 @@ + +#import "AppViewBase.h" + +#include "NativeAppBase.h" +#include <memory> +#include <string> + +@interface AppViewBase () +{ + std::unique_ptr<Diligent::NativeAppBase> _theApp; + NSInteger _animationFrameInterval; + CADisplayLink* _displayLink; + std::string _error; +} +@end + +@implementation AppViewBase + +- (void) initApp:(int)deviceType; +{ + try + { + _theApp.reset(Diligent::CreateApplication()); + // Init our renderer. + _theApp->Initialize(deviceType, (__bridge void*)self.layer); + } + catch(std::runtime_error &err) + { + _error = err.what(); + _theApp.reset(); + } + + [super stopAnimation]; + _animationFrameInterval = 1; + _displayLink = nil; +} + +- (void) render +{ + if(_theApp) + { + _theApp->Update(); + _theApp->Render(); + _theApp->Present(); + } +} + +- (void) layoutSubviews +{ + auto bounds = [self.layer bounds]; + auto scale = [self.layer contentsScale]; + + if(_theApp) + { + _theApp->WindowResize(bounds.size.width * scale, bounds.size.height * scale); + } +} + +- (NSInteger) animationFrameInterval +{ + return _animationFrameInterval; +} + +- (void) setAnimationFrameInterval:(NSInteger)frameInterval +{ + // Frame interval defines how many display frames must pass between each time the + // display link fires. The display link will only fire 30 times a second when the + // frame internal is two on a display that refreshes 60 times a second. The default + // frame interval setting of one will fire 60 times a second when the display refreshes + // at 60 times a second. A frame interval setting of less than one results in undefined + // behavior. + if (frameInterval >= 1) + { + _animationFrameInterval = frameInterval; + + if (self.animating) + { + [self stopAnimation]; + [self startAnimation]; + } + } +} + +- (void) startAnimation +{ + if (!self.animating) + { + // Create the display link and set the callback to our drawView method + _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(drawView:)]; + + // Set it to our _animationFrameInterval + [_displayLink setFrameInterval:_animationFrameInterval]; + + // Have the display link run on the default runn loop (and the main thread) + [_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + + [super startAnimation]; + } +} + +- (void)stopAnimation +{ + if (self.animating) + { + [_displayLink invalidate]; + _displayLink = nil; + [super stopAnimation]; + } +} + +- (void)terminate +{ + _theApp.reset(); + [super terminate]; +} + +- (NSString*)getError +{ + return _error.empty() ? nil : [NSString stringWithFormat:@"%s", _error.c_str()]; +} + +- (void)touchesBegan:(NSSet<UITouch *> *)touches + withEvent:(UIEvent *)event; +{ + UITouch *firstTouch = touches.allObjects[0]; + CGPoint location = [firstTouch locationInView:self]; + if(_theApp) + { + _theApp->OnTouchBegan(location.x, location.y); + } +} + +- (void)touchesMoved:(NSSet<UITouch *> *)touches + withEvent:(UIEvent *)event; +{ + UITouch *firstTouch = touches.allObjects[0]; + CGPoint location = [firstTouch locationInView:self]; + if(_theApp) + { + _theApp->OnTouchMoved(location.x, location.y); + } +} + +- (void)touchesEnded:(NSSet<UITouch *> *)touches + withEvent:(UIEvent *)event; +{ + UITouch *firstTouch = touches.allObjects[0]; + CGPoint location = [firstTouch locationInView:self]; + if(_theApp) + { + _theApp->OnTouchEnded(location.x, location.y); + } +} + +- (void)touchesCancelled:(NSSet<UITouch *> *)touches + withEvent:(UIEvent *)event; +{ + UITouch *firstTouch = touches.allObjects[0]; + CGPoint location = [firstTouch locationInView:self]; + if(_theApp) + { + _theApp->OnTouchEnded(location.x, location.y); + } +} + +@end diff --git a/NativeApp/Apple/Source/Classes/iOS/BaseView.h b/NativeApp/Apple/Source/Classes/iOS/BaseView.h new file mode 100644 index 0000000..9e8b99e --- /dev/null +++ b/NativeApp/Apple/Source/Classes/iOS/BaseView.h @@ -0,0 +1,12 @@ + +#import <UIKit/UIKit.h> + +@interface BaseView : UIView + +@property (readonly, nonatomic, getter=isAnimating) BOOL animating; + +- (void) startAnimation; +- (void) stopAnimation; +- (void) terminate; + +@end diff --git a/NativeApp/Apple/Source/Classes/iOS/BaseView.m b/NativeApp/Apple/Source/Classes/iOS/BaseView.m new file mode 100644 index 0000000..c87e5cd --- /dev/null +++ b/NativeApp/Apple/Source/Classes/iOS/BaseView.m @@ -0,0 +1,21 @@ + +#import "BaseView.h" + +@implementation BaseView + +- (void) startAnimation +{ + _animating = TRUE; +} + +- (void)stopAnimation +{ + _animating = FALSE; +} + +- (void) terminate +{ + +} + +@end diff --git a/NativeApp/Apple/Source/Classes/iOS/EAGLView.h b/NativeApp/Apple/Source/Classes/iOS/EAGLView.h new file mode 100644 index 0000000..e5ba68a --- /dev/null +++ b/NativeApp/Apple/Source/Classes/iOS/EAGLView.h @@ -0,0 +1,18 @@ +/* + Copyright (C) 2015 Apple Inc. All Rights Reserved. + See LICENSE.txt for this sample’s licensing information + + Abstract: + The EAGLView class is a UIView subclass that renders OpenGL scene. +*/ + +#import "AppViewBase.h" + +// This class wraps the CAEAGLLayer from CoreAnimation into a convenient UIView subclass. +// The view content is basically an EAGL surface you render your OpenGL scene into. +// Note that setting the view non-opaque will only work if the EAGL surface has an alpha channel. +@interface EAGLView : AppViewBase + +- (void) drawView:(id)sender; + +@end diff --git a/NativeApp/Apple/Source/Classes/iOS/EAGLView.m b/NativeApp/Apple/Source/Classes/iOS/EAGLView.m new file mode 100644 index 0000000..ff02820 --- /dev/null +++ b/NativeApp/Apple/Source/Classes/iOS/EAGLView.m @@ -0,0 +1,74 @@ +/* + Copyright (C) 2015 Apple Inc. All Rights Reserved. + See LICENSE.txt for this sample’s licensing information + + Abstract: + The EAGLView class is a UIView subclass that renders OpenGL scene. +*/ + +#import "EAGLView.h" + +#include "DeviceCaps.h" + +@interface EAGLView () +{ + EAGLContext* _context; +} +@end + +@implementation EAGLView + +// Must return the CAEAGLLayer class so that CA allocates an EAGLLayer backing for this view ++ (Class) layerClass +{ + return [CAEAGLLayer class]; +} + +// The GL view is stored in the storyboard file. When it's unarchived it's sent -initWithCoder: +- (instancetype) initWithCoder:(NSCoder*)coder +{ + if ((self = [super initWithCoder:coder])) + { + // Get the layer + CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer; + + eaglLayer.opaque = TRUE; + eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys: + [NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil]; + + _context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3]; + + if (!_context || ![EAGLContext setCurrentContext:_context]) + { + return nil; + } + + [self initApp:(int)Diligent::DeviceType::OpenGLES]; + } + + return self; +} + +- (void) drawView:(id)sender +{ + [EAGLContext setCurrentContext:_context]; + + // There is no autorelease pool when this method is called + // because it will be called from a background thread. + // It's important to create one or app can leak objects. + @autoreleasepool + { + [self render]; + } +} + +- (void) dealloc +{ + [self terminate]; + + // tear down context + if ([EAGLContext currentContext] == _context) + [EAGLContext setCurrentContext:nil]; +} + +@end diff --git a/NativeApp/Apple/Source/Classes/iOS/MetalView.h b/NativeApp/Apple/Source/Classes/iOS/MetalView.h new file mode 100644 index 0000000..a485b27 --- /dev/null +++ b/NativeApp/Apple/Source/Classes/iOS/MetalView.h @@ -0,0 +1,7 @@ +#import "AppViewBase.h" + +@interface MetalView : AppViewBase + +- (void) drawView:(id)sender; + +@end diff --git a/NativeApp/Apple/Source/Classes/iOS/MetalView.m b/NativeApp/Apple/Source/Classes/iOS/MetalView.m new file mode 100644 index 0000000..67c2a27 --- /dev/null +++ b/NativeApp/Apple/Source/Classes/iOS/MetalView.m @@ -0,0 +1,44 @@ +#import "MetalView.h" + +#if VULKAN_SUPPORTED +#import <QuartzCore/CAMetalLayer.h> +#endif + +#include "DeviceCaps.h" + +@implementation MetalView + +#if VULKAN_SUPPORTED ++ (Class) layerClass +{ + return [CAMetalLayer class]; +} +#endif + +- (instancetype) initWithCoder:(NSCoder*)coder +{ + if ((self = [super initWithCoder:coder])) + { + [self initApp:(int)Diligent::DeviceType::Vulkan]; + } + + return self; +} + +- (void) drawView:(id)sender +{ + // There is no autorelease pool when this method is called + // because it will be called from a background thread. + // It's important to create one or app can leak objects. + @autoreleasepool + { + [self render]; + } +} + +- (void) dealloc +{ + [self terminate]; +} + +@end diff --git a/NativeApp/Apple/Source/Classes/iOS/ModeSelectionViewController.h b/NativeApp/Apple/Source/Classes/iOS/ModeSelectionViewController.h new file mode 100644 index 0000000..4a08d7d --- /dev/null +++ b/NativeApp/Apple/Source/Classes/iOS/ModeSelectionViewController.h @@ -0,0 +1,29 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#import <UIKit/UIKit.h> + +@interface ModeSelectionViewController : UIViewController +{ +} +@end diff --git a/NativeApp/Apple/Source/Classes/iOS/ModeSelectionViewController.mm b/NativeApp/Apple/Source/Classes/iOS/ModeSelectionViewController.mm new file mode 100644 index 0000000..8958c10 --- /dev/null +++ b/NativeApp/Apple/Source/Classes/iOS/ModeSelectionViewController.mm @@ -0,0 +1,64 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#import "ModeSelectionViewController.h" +#import "BaseView.h" +#import "AppViewBase.h" + +@implementation ModeSelectionViewController +{ +} + +-(void)selectViewController:(NSString*)controllerID +{ + auto animating = ((BaseView*)self.view).animating; + + UIViewController* viewController = [self.storyboard instantiateViewControllerWithIdentifier:controllerID]; + self.view.window.rootViewController = viewController; + + NSString *error = [(AppViewBase*)viewController.view getError]; + if(error != nil) + { + UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failed to start the application" message:error delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Whatever", nil]; + [alert show]; + } + + if(animating) + { + [(BaseView*)viewController.view startAnimation]; + } +} + +- (IBAction)goOpenGLES:(id)sender +{ + [self selectViewController:@"EAGLViewControllerID"]; +} + +- (IBAction)goVulkan:(id)sender +{ +#if VULKAN_SUPPORTED + [self selectViewController:@"MetalViewControllerID"]; +#endif +} + +@end diff --git a/NativeApp/Apple/Source/main.m b/NativeApp/Apple/Source/main.m new file mode 100644 index 0000000..7134864 --- /dev/null +++ b/NativeApp/Apple/Source/main.m @@ -0,0 +1,25 @@ +/* + Copyright (C) 2015 Apple Inc. All Rights Reserved. + See LICENSE.txt for this sample’s licensing information + + Abstract: + Standard AppKit entry point. + */ + +#if PLATFORM_IOS +#import <UIKit/UIKit.h> +#import "AppDelegate.h" +#else // OS X +#import <Cocoa/Cocoa.h> +#endif + +int main(int argc, char * argv[]) { + +#if PLATFORM_IOS + @autoreleasepool { + return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); + } +#else + return NSApplicationMain(argc, (const char**)argv); +#endif +} diff --git a/NativeApp/CMakeLists.txt b/NativeApp/CMakeLists.txt new file mode 100644 index 0000000..3e75406 --- /dev/null +++ b/NativeApp/CMakeLists.txt @@ -0,0 +1,402 @@ +cmake_minimum_required (VERSION 3.6) + +if(PLATFORM_ANDROID) + add_subdirectory(Android) +elseif(PLATFORM_LINUX) + add_subdirectory(Linux) +endif() + + +project(NativeAppBase) + +if(PLATFORM_WIN32) + + set(SOURCE + src/Win32/WinMain.cpp + ) + set(INCLUDE + include/Win32/Win32AppBase.h + ) + + function(add_win32_app TARGET_NAME SOURCE INCLUDE ASSETS) + add_executable(${TARGET_NAME} WIN32 ${SOURCE} ${INCLUDE} ${ASSETS}) + + if (CMAKE_CXX_COMPILER_ID MATCHES "GNU") + # libmingw32 must be included BEFORE NativeAppBase that contains the definition of WinMain. + # otherwise WinMain will be stripped out of NativeAppBase and will be unresolved. + target_link_libraries(${TARGET_NAME} + PRIVATE + mingw32 + ) + endif() + endfunction() + + function(add_target_platform_app TARGET_NAME SOURCE INCLUDE ASSETS) + add_win32_app("${TARGET_NAME}" "${SOURCE}" "${INCLUDE}" "${ASSETS}") + endfunction() + +elseif(PLATFORM_UNIVERSAL_WINDOWS) + + set(SOURCE + src/UWP/dummy.cpp + ) + set(INCLUDE + include/UWP/UWPAppBase.h + ) + + # Windows Runtime types cannot be included into static libraries + # https://social.msdn.microsoft.com/Forums/en-US/269db513-64ef-4817-a025-43954f614eb3/lnk4264-why-are-static-libraries-not-recommended-when-authoring-windows-runtime-types?forum=winappswithnativecode + # So as a workaround, we will include all source files into the target app project + function(add_uwp_app TARGET_NAME SOURCE INCLUDE ASSETS) + get_target_property(NATIVE_APP_SOURCE_DIR NativeAppBase SOURCE_DIR) + + set(UWP_SOURCE + ${NATIVE_APP_SOURCE_DIR}/src/UWP/Common/DeviceResources.cpp + ${NATIVE_APP_SOURCE_DIR}/src/UWP/App.cpp + ${NATIVE_APP_SOURCE_DIR}/src/UWP/UWPAppBase.cpp + ) + + set(UWP_INCLUDE + ${NATIVE_APP_SOURCE_DIR}/src/UWP/Common/DeviceResources.h + ${NATIVE_APP_SOURCE_DIR}/src/UWP/Common/DirectXHelper.h + ${NATIVE_APP_SOURCE_DIR}/src/UWP/App.h + ${NATIVE_APP_SOURCE_DIR}/include/UWP/UWPAppBase.h + ${NATIVE_APP_SOURCE_DIR}/src/UWP/Common/StepTimer.h + ) + + add_executable(${TARGET_NAME} WIN32 ${SOURCE} ${INCLUDE} ${ASSETS} ${UWP_SOURCE} ${UWP_INCLUDE}) + set_source_files_properties(${ASSETS} PROPERTIES VS_DEPLOYMENT_CONTENT 1) + + target_include_directories(${TARGET_NAME} + PUBLIC + ${NATIVE_APP_SOURCE_DIR}/Src/UWP + ) + + source_group("UWP Common\\src" FILES ${UWP_SOURCE}) + source_group("UWP Common\\include" FILES ${UWP_INCLUDE}) + + endfunction(add_uwp_app) + + function(add_target_platform_app TARGET_NAME SOURCE INCLUDE ASSETS) + add_uwp_app("${TARGET_NAME}" "${SOURCE}" "${INCLUDE}" "${ASSETS}") + endfunction() + + +elseif(PLATFORM_ANDROID) + + set(SOURCE + src/Android/AndroidAppBase.cpp + ) + set(INCLUDE + include/Android/AndroidAppBase.h + ) + function(add_android_app TARGET_NAME SOURCE INCLUDE ASSETS) + get_target_property(NATIVE_APP_SOURCE_DIR NativeAppBase SOURCE_DIR) + set(ANDROID_SOURCE + ${NATIVE_APP_SOURCE_DIR}/src/Android/AndroidMain.cpp + ) + add_library(${TARGET_NAME} SHARED ${SOURCE} ${ANDROID_SOURCE} ${INCLUDE} ${ASSETS}) + target_link_libraries(${TARGET_NAME} + PRIVATE + android + native_app_glue + ) + # Export ANativeActivity_onCreate(), + # Refer to: https://github.com/android-ndk/ndk/issues/381. + set_target_properties(${TARGET_NAME} + PROPERTIES + LINK_FLAGS "-u ANativeActivity_onCreate" + ) + #target_include_directories(${TARGET_NAME} + #PRIVATE + # ${ANDROID_NDK}/sources/android/cpufeatures + #) + source_group("Android" FILES ${ANDROID_SOURCE}) + endfunction() + + function(add_target_platform_app TARGET_NAME SOURCE INCLUDE ASSETS) + add_android_app("${TARGET_NAME}" "${SOURCE}" "${INCLUDE}" "${ASSETS}") + endfunction() + +elseif(PLATFORM_LINUX) + + set(SOURCE + src/Linux/LinuxMain.cpp + ) + set(INCLUDE + include/Linux/LinuxAppBase.h + ) + function(add_linux_app TARGET_NAME SOURCE INCLUDE ASSETS) + add_executable(${TARGET_NAME} ${SOURCE} ${INCLUDE} ${ASSETS}) + endfunction() + + function(add_target_platform_app TARGET_NAME SOURCE INCLUDE ASSETS) + add_linux_app("${TARGET_NAME}" "${SOURCE}" "${INCLUDE}" "${ASSETS}") + endfunction() + + +elseif(PLATFORM_MACOS) + + set(SOURCE + src/MacOS/MacOSAppBase.cpp + ) + set(INCLUDE + include/MacOS/MacOSAppBase.h + ) + + function(add_macos_app TARGET_NAME SOURCE INCLUDE ASSETS) + get_target_property(NATIVE_APP_SOURCE_DIR NativeAppBase SOURCE_DIR) + + set(APPLE_SOURCE + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/main.m + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/OSX/WindowController.m + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/OSX/AppDelegate.m + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/OSX/FullscreenWindow.m + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/OSX/GLView.m + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/OSX/MetalView.m + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/OSX/ViewBase.m + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/OSX/ViewController.mm + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/OSX/ModeSelectionViewController.mm + ) + set_source_files_properties(${APPLE_SOURCE} PROPERTIES + COMPILE_FLAGS "-x objective-c++" + ) + + set(APPLE_INCLUDE + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/OSX/WindowController.h + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/OSX/AppDelegate.h + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/OSX/FullscreenWindow.h + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/OSX/GLView.h + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/OSX/MetalView.h + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/OSX/ViewBase.h + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/OSX/ViewController.h + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/OSX/ModeSelectionViewController.h + ) + + set(APPLE_RESOURCES + ${NATIVE_APP_SOURCE_DIR}/Apple/Data/OSX/Base.lproj/Main.storyboard + ${NATIVE_APP_SOURCE_DIR}/Apple/Data/OSX/Images.xcassets/AppIcon.appiconset/dg.icns + ${NATIVE_APP_SOURCE_DIR}/Apple/Data/OSX/Images.xcassets/opengl-logo.png + ${NATIVE_APP_SOURCE_DIR}/Apple/Data/OSX/Images.xcassets/vulkan-logo.png + ) + + set(APPLE_INFO_PLIST + ${NATIVE_APP_SOURCE_DIR}/Apple/Data/OSX/Info.plist + ) + + set(APPLE_INCLUDE_DIRS + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/OSX + ) + + add_executable(${TARGET_NAME} MACOSX_BUNDLE ${SOURCE} ${APPLE_SOURCE} ${INCLUDE} ${APPLE_INCLUDE} ${ASSETS} ${APPLE_RESOURCES}) + set_target_properties(${TARGET_NAME} PROPERTIES + MACOSX_BUNDLE_GUI_IDENTIFIER "com.diligentengine.samples.${TARGET_NAME}" + MACOSX_BUNDLE_INFO_PLIST "${APPLE_INFO_PLIST}" + RESOURCE "${APPLE_RESOURCES}" + ) + source_group("MacOS" FILES ${APPLE_SOURCE}) + source_group("MacOS" FILES ${APPLE_INCLUDE}) + source_group("Resources" FILES ${APPLE_RESOURCES}) + target_include_directories(${TARGET_NAME} PRIVATE ${APPLE_INCLUDE_DIRS}) + + find_package(OpenGL REQUIRED) + + find_library(CORE_VIDEO CoreVideo) + if (NOT CORE_VIDEO) + message(FATAL_ERROR "CoreVideo is not found") + endif() + + find_library(METAL_FRAMEWORK Metal) + if (NOT METAL_FRAMEWORK) + message(FATAL_ERROR "Metal framework is not found") + endif() + + find_library(CORE_ANIMATION QuartzCore) + if (NOT CORE_ANIMATION) + message(FATAL_ERROR "QuartzCore (CoreAnimation) is not found") + endif() + + target_link_libraries(${TARGET_NAME} PRIVATE ${OPENGL_LIBRARY} ${CORE_VIDEO} ${METAL_FRAMEWORK} ${CORE_ANIMATION}) + + endfunction() + + function(add_target_platform_app TARGET_NAME SOURCE INCLUDE ASSETS) + add_macos_app("${TARGET_NAME}" "${SOURCE}" "${INCLUDE}" "${ASSETS}") + endfunction() + +elseif(PLATFORM_IOS) + + set(SOURCE + src/IOS/IOSAppBase.cpp + ) + set(INCLUDE + include/IOS/IOSAppBase.h + ) + + function(add_ios_app TARGET_NAME SOURCE INCLUDE ASSETS) + get_target_property(NATIVE_APP_SOURCE_DIR NativeAppBase SOURCE_DIR) + + set(APPLE_SOURCE + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/main.m + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/iOS/AppDelegate.m + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/iOS/BaseView.m + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/iOS/EAGLView.m + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/iOS/AppViewBase.m + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/iOS/ModeSelectionViewController.mm + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/iOS/MetalView.m + ) + + set_source_files_properties(${APPLE_SOURCE} PROPERTIES + COMPILE_FLAGS "-x objective-c++" + ) + + set(APPLE_INCLUDE + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/iOS/AppDelegate.h + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/iOS/BaseView.h + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/iOS/EAGLView.h + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/iOS/AppViewBase.h + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/iOS/ModeSelectionViewController.h + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/iOS/MetalView.h + ) + + set(APPLE_RESOURCES + ${NATIVE_APP_SOURCE_DIR}/Apple/Data/iOS/Base.lproj/Main.storyboard + ${NATIVE_APP_SOURCE_DIR}/Apple/Data/iOS/Base.lproj/LaunchScreen.xib + ${NATIVE_APP_SOURCE_DIR}/Apple/Data/iOS/Images.xcassets/AppIcon.appiconset/dg-icon.png + ${NATIVE_APP_SOURCE_DIR}/Apple/Data/iOS/Images.xcassets/opengles-logo.png + ${NATIVE_APP_SOURCE_DIR}/Apple/Data/iOS/Images.xcassets/vulkan-logo.png + ) + + set(APPLE_INFO_PLIST + ${NATIVE_APP_SOURCE_DIR}/Apple/Data/iOS/info.plist + ) + + set(APPLE_INCLUDE_DIRS + ${NATIVE_APP_SOURCE_DIR}/Apple/Source/Classes/iOS + ) + + add_executable(${TARGET_NAME} MACOSX_BUNDLE ${SOURCE} ${APPLE_SOURCE} ${INCLUDE} ${APPLE_INCLUDE} ${ASSETS} ${APPLE_RESOURCES}) + set_target_properties(${TARGET_NAME} PROPERTIES + MACOSX_BUNDLE_GUI_IDENTIFIER "com.diligentengine.samples.${TARGET_NAME}" + MACOSX_BUNDLE_INFO_PLIST "${APPLE_INFO_PLIST}" + RESOURCE "${APPLE_RESOURCES}" + XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "iPhone Developer" + # XCODE_ATTRIBUTE_DEVELOPMENT_TEAM "Dev Team" + BUILD_RPATH "@executable_path" + ) + source_group("iOS" FILES ${APPLE_SOURCE}) + source_group("iOS" FILES ${APPLE_INCLUDE}) + source_group("Resources" FILES ${APPLE_RESOURCES}) + target_include_directories(${TARGET_NAME} PRIVATE ${APPLE_INCLUDE_DIRS}) + + find_library(OPENGLES OpenGLES) + if (NOT OPENGLES) + message(FATAL_ERROR "OpenGLES is not found") + endif() + + find_library(UIKIT UIKit) + if (NOT UIKIT) + message(FATAL_ERROR "UIKIT is not found") + endif() + + find_library(CORE_ANIMATION QuartzCore) + if (NOT CORE_ANIMATION) + message(FATAL_ERROR "QuartzCore (CoreAnimation) is not found") + endif() + + target_link_libraries(${TARGET_NAME} PRIVATE ${OPENGLES} ${UIKIT} ${CORE_ANIMATION}) + endfunction() + + function(add_target_platform_app TARGET_NAME SOURCE INCLUDE ASSETS) + add_ios_app("${TARGET_NAME}" "${SOURCE}" "${INCLUDE}" "${ASSETS}") + endfunction() + +else() + message(FATAL_ERROR "Unknown platform") +endif() + +list(APPEND INCLUDE + include/AppBase.h + include/NativeAppBase.h +) + + +add_library(NativeAppBase STATIC ${SOURCE} ${INCLUDE}) +set_common_target_properties(NativeAppBase) + +target_include_directories(NativeAppBase +PUBLIC + include +) + + +if(MSVC) + target_compile_options(NativeAppBase PRIVATE -DUNICODE) + + if(PLATFORM_UNIVERSAL_WINDOWS) + # Disable w4189: local variable is initialized but not referenced + # Disable w4063: case is not a valid value for switch of enum + # Consume the windows runtime extensions (/ZW) + target_compile_options(NativeAppBase INTERFACE /wd4189 /wd4063) + endif() +endif() + +target_link_libraries(NativeAppBase +PRIVATE + Diligent-BuildSettings + Diligent-Common +) + +if(PLATFORM_WIN32) + + target_include_directories(NativeAppBase + PUBLIC + include/Win32 + ) + +elseif(PLATFORM_UNIVERSAL_WINDOWS) + + target_include_directories(NativeAppBase + PUBLIC + include/UWP + src/UWP + ) + +elseif(PLATFORM_ANDROID) + target_link_libraries(NativeAppBase PUBLIC NDKHelper native_app_glue PRIVATE android) + target_include_directories(NativeAppBase + PUBLIC + include/Android + ) +elseif(PLATFORM_LINUX) + target_link_libraries(NativeAppBase + PRIVATE + X11 + ) + target_include_directories(NativeAppBase + PUBLIC + include/Linux + ) + if(VULKAN_SUPPORTED) + target_link_libraries(NativeAppBase + PRIVATE + xcb + ) + endif() +elseif(PLATFORM_MACOS) + target_include_directories(NativeAppBase PUBLIC + src/MacOS + include/MacOS + ) +elseif(PLATFORM_IOS) + target_include_directories(NativeAppBase PUBLIC + include/IOS + ) +endif() + +source_group("src" FILES ${SOURCE}) +source_group("include" FILES ${INCLUDE}) + +set_target_properties(NativeAppBase PROPERTIES + FOLDER DiligentTools +) diff --git a/NativeApp/Linux/CMakeLists.txt b/NativeApp/Linux/CMakeLists.txt new file mode 100644 index 0000000..9c072c5 --- /dev/null +++ b/NativeApp/Linux/CMakeLists.txt @@ -0,0 +1,29 @@ +cmake_minimum_required (VERSION 3.6) + +project(XCBKeySyms C) + +set(INTERFACE + xcb_keysyms/xcb_keysyms.h +) + +set(SOURCE + xcb_keysyms/xcb_keysyms.c +) + +add_library(XCBKeySyms STATIC ${SOURCE} ${INTERFACE}) +set_common_target_properties(XCBKeySyms) + +target_include_directories(XCBKeySyms PUBLIC .) + +source_group("source" FILES ${SOURCE}) +source_group("interface" FILES ${INTERFACE}) + +target_link_libraries(XCBKeySyms +PRIVATE + Diligent-BuildSettings +) + +set_target_properties(XCBKeySyms PROPERTIES + FOLDER Common +) + diff --git a/NativeApp/Linux/xcb_keysyms/xcb_keysyms.c b/NativeApp/Linux/xcb_keysyms/xcb_keysyms.c new file mode 100644 index 0000000..419c58b --- /dev/null +++ b/NativeApp/Linux/xcb_keysyms/xcb_keysyms.c @@ -0,0 +1,505 @@ +/* + * Copyright © 2008 Ian Osgood <iano@quirkster.com> + * Copyright © 2008 Jamey Sharp <jamey@minilop.net> + * Copyright © 2008 Josh Triplett <josh@freedesktop.org> + * Copyright © 2008 Ulrich Eckhardt <doomster@knuut.de> + * + * 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 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. + * + * Except as contained in this notice, the names of the authors or + * their institutions shall not be used in advertising or otherwise to + * promote the sale, use or other dealings in this Software without + * prior written authorization from the authors. + */ + +#include <stdlib.h> + +#include <xcb/xcb.h> +#define XK_MISCELLANY +#define XK_XKB_KEYS +#define XK_LATIN1 +#define XK_LATIN2 +#define XK_LATIN3 +#define XK_LATIN4 +#define XK_CYRILLIC +#define XK_GREEK +#define XK_ARMENIAN +#include <X11/keysymdef.h> + +#include "xcb_keysyms.h" + +/* Private declaration */ +enum tag_t { + TAG_COOKIE, + TAG_VALUE +}; + +struct _XCBKeySymbols +{ + xcb_connection_t *c; + enum tag_t tag; + union { + xcb_get_keyboard_mapping_cookie_t cookie; + xcb_get_keyboard_mapping_reply_t *reply; + } u; +}; + +static void xcb_convert_case(xcb_keysym_t sym, + xcb_keysym_t *lower, + xcb_keysym_t *upper); + +static void xcb_key_symbols_get_reply (xcb_key_symbols_t *syms, + xcb_generic_error_t **e); + +/* public implementation */ + +xcb_key_symbols_t * +xcb_key_symbols_alloc (xcb_connection_t *c) +{ + xcb_key_symbols_t *syms; + xcb_keycode_t min_keycode; + xcb_keycode_t max_keycode; + + if (!c || xcb_connection_has_error(c)) + return NULL; + + syms = malloc (sizeof (xcb_key_symbols_t)); + if (!syms) + return NULL; + + syms->c = c; + syms->tag = TAG_COOKIE; + + min_keycode = xcb_get_setup (c)->min_keycode; + max_keycode = xcb_get_setup (c)->max_keycode; + + syms->u.cookie = xcb_get_keyboard_mapping(c, + min_keycode, + max_keycode - min_keycode + 1); + + return syms; +} + +void +xcb_key_symbols_free (xcb_key_symbols_t *syms) +{ + if (syms) + { + if (syms->tag == TAG_VALUE) + free (syms->u.reply); + free (syms); + syms = NULL; + } +} + +/* Use of the 'col' parameter: + +A list of KeySyms is associated with each KeyCode. The list is intended +to convey the set of symbols on the corresponding key. If the list +(ignoring trailing NoSymbol entries) is a single KeySym ``K'', then the +list is treated as if it were the list ``K NoSymbol K NoSymbol''. If the +list (ignoring trailing NoSymbol entries) is a pair of KeySyms ``K1 +K2'', then the list is treated as if it were the list ``K1 K2 K1 K2''. +If the list (ignoring trailing NoSymbol entries) is a triple of KeySyms +``K1 K2 K3'', then the list is treated as if it were the list ``K1 K2 K3 +NoSymbol''. When an explicit ``void'' element is desired in the list, +the value VoidSymbol can be used. + +The first four elements of the list are split into two groups of +KeySyms. Group 1 contains the first and second KeySyms; Group 2 contains +the third and fourth KeySyms. Within each group, if the second element +of the group is NoSymbol , then the group should be treated as if the +second element were the same as the first element, except when the first +element is an alphabetic KeySym ``K'' for which both lowercase and +uppercase forms are defined. In that case, the group should be treated +as if the first element were the lowercase form of ``K'' and the second +element were the uppercase form of ``K.'' + +The standard rules for obtaining a KeySym from a KeyPress event make use +of only the Group 1 and Group 2 KeySyms; no interpretation of other +KeySyms in the list is given. Which group to use is determined by the +modifier state. Switching between groups is controlled by the KeySym +named MODE SWITCH, by attaching that KeySym to some KeyCode and +attaching that KeyCode to any one of the modifiers Mod1 through Mod5. +This modifier is called the group modifier. For any KeyCode, Group 1 is +used when the group modifier is off, and Group 2 is used when the group +modifier is on. + +The Lock modifier is interpreted as CapsLock when the KeySym named +XK_Caps_Lock is attached to some KeyCode and that KeyCode is attached to +the Lock modifier. The Lock modifier is interpreted as ShiftLock when +the KeySym named XK_Shift_Lock is attached to some KeyCode and that +KeyCode is attached to the Lock modifier. If the Lock modifier could be +interpreted as both CapsLock and ShiftLock, the CapsLock interpretation +is used. + +The operation of keypad keys is controlled by the KeySym named +XK_Num_Lock, by attaching that KeySym to some KeyCode and attaching that +KeyCode to any one of the modifiers Mod1 through Mod5 . This modifier is +called the numlock modifier. The standard KeySyms with the prefix +``XK_KP_'' in their name are called keypad KeySyms; these are KeySyms +with numeric value in the hexadecimal range 0xFF80 to 0xFFBD inclusive. +In addition, vendor-specific KeySyms in the hexadecimal range 0x11000000 +to 0x1100FFFF are also keypad KeySyms. + +Within a group, the choice of KeySym is determined by applying the first +rule that is satisfied from the following list: + +* The numlock modifier is on and the second KeySym is a keypad KeySym. In + this case, if the Shift modifier is on, or if the Lock modifier is on + and is interpreted as ShiftLock, then the first KeySym is used, + otherwise the second KeySym is used. + +* The Shift and Lock modifiers are both off. In this case, the first + KeySym is used. + +* The Shift modifier is off, and the Lock modifier is on and is + interpreted as CapsLock. In this case, the first KeySym is used, but + if that KeySym is lowercase alphabetic, then the corresponding + uppercase KeySym is used instead. + +* The Shift modifier is on, and the Lock modifier is on and is + interpreted as CapsLock. In this case, the second KeySym is used, but + if that KeySym is lowercase alphabetic, then the corresponding + uppercase KeySym is used instead. + +* The Shift modifier is on, or the Lock modifier is on and is + interpreted as ShiftLock, or both. In this case, the second KeySym is + used. + +*/ + +xcb_keysym_t xcb_key_symbols_get_keysym (xcb_key_symbols_t *syms, + xcb_keycode_t keycode, + int col) +{ + xcb_keysym_t *keysyms; + xcb_keysym_t keysym_null = { XCB_NO_SYMBOL }; + xcb_keysym_t lsym; + xcb_keysym_t usym; + xcb_keycode_t min_keycode; + xcb_keycode_t max_keycode; + int per; + + if (!syms || xcb_connection_has_error(syms->c)) + return keysym_null; + + xcb_key_symbols_get_reply (syms, NULL); + + if (!syms->u.reply) + return keysym_null; + + keysyms = xcb_get_keyboard_mapping_keysyms (syms->u.reply); + min_keycode = xcb_get_setup (syms->c)->min_keycode; + max_keycode = xcb_get_setup (syms->c)->max_keycode; + + per = syms->u.reply->keysyms_per_keycode; + if ((col < 0) || ((col >= per) && (col > 3)) || + (keycode < min_keycode) || + (keycode > max_keycode)) + return keysym_null; + + keysyms = &keysyms[(keycode - min_keycode) * per]; + if (col < 4) + { + if (col > 1) + { + while ((per > 2) && (keysyms[per - 1] == XCB_NO_SYMBOL)) + per--; + if (per < 3) + col -= 2; + } + if ((per <= (col|1)) || (keysyms[col|1] == XCB_NO_SYMBOL)) + { + xcb_convert_case(keysyms[col&~1], &lsym, &usym); + if (!(col & 1)) + return lsym; + else if (usym == lsym) + return keysym_null; + else + return usym; + } + } + return keysyms[col]; +} + +xcb_keycode_t * +xcb_key_symbols_get_keycode(xcb_key_symbols_t *syms, + xcb_keysym_t keysym) +{ + xcb_keysym_t ks; + int j, nresult = 0; + xcb_keycode_t i, min, max, *result = NULL, *result_np = NULL; + + if(syms && !xcb_connection_has_error(syms->c)) + { + xcb_key_symbols_get_reply (syms, NULL); + min = xcb_get_setup(syms->c)->min_keycode; + max = xcb_get_setup(syms->c)->max_keycode; + + if (!syms->u.reply) + return NULL; + + for(i = min; i && i <= max; i++) + for(j = 0; j < syms->u.reply->keysyms_per_keycode; j++) + { + ks = xcb_key_symbols_get_keysym(syms, i, j); + if(ks == keysym) + { + nresult++; + result_np = realloc(result, + sizeof(xcb_keycode_t) * (nresult + 1)); + + if(result_np == NULL) + { + free(result); + return NULL; + } + + result = result_np; + result[nresult - 1] = i; + result[nresult] = XCB_NO_SYMBOL; + break; + } + } + } + + return result; +} + +xcb_keysym_t +xcb_key_press_lookup_keysym (xcb_key_symbols_t *syms, + xcb_key_press_event_t *event, + int col) +{ + return xcb_key_symbols_get_keysym (syms, event->detail, col); +} + +xcb_keysym_t +xcb_key_release_lookup_keysym (xcb_key_symbols_t *syms, + xcb_key_release_event_t *event, + int col) +{ + return xcb_key_symbols_get_keysym (syms, event->detail, col); +} + +int +xcb_refresh_keyboard_mapping (xcb_key_symbols_t *syms, + xcb_mapping_notify_event_t *event) +{ + if (event->request == XCB_MAPPING_KEYBOARD && syms && !xcb_connection_has_error(syms->c)) { + if (syms->tag == TAG_VALUE) { + xcb_keycode_t min_keycode; + xcb_keycode_t max_keycode; + + if (syms->u.reply) { + free (syms->u.reply); + syms->u.reply = NULL; + } + syms->tag = TAG_COOKIE; + min_keycode = xcb_get_setup (syms->c)->min_keycode; + max_keycode = xcb_get_setup (syms->c)->max_keycode; + + syms->u.cookie = xcb_get_keyboard_mapping(syms->c, + min_keycode, + max_keycode - min_keycode + 1); + + } + return 1; + } + return 0; +} + + +/* Tests for classes of symbols */ + +int +xcb_is_keypad_key (xcb_keysym_t keysym) +{ + return ((keysym >= XK_KP_Space) && (keysym <= XK_KP_Equal)); +} + +int +xcb_is_private_keypad_key (xcb_keysym_t keysym) +{ + return ((keysym >= 0x11000000) && (keysym <= 0x1100FFFF)); +} + +int +xcb_is_cursor_key (xcb_keysym_t keysym) +{ + return ((keysym >= XK_Home) && (keysym <= XK_Select)); +} + +int +xcb_is_pf_key (xcb_keysym_t keysym) +{ + return ((keysym >= XK_KP_F1) && (keysym <= XK_KP_F4)); +} + +int +xcb_is_function_key (xcb_keysym_t keysym) +{ + return ((keysym >= XK_F1) && (keysym <= XK_F35)); +} + +int +xcb_is_misc_function_key (xcb_keysym_t keysym) +{ + return ((keysym >= XK_Select) && (keysym <= XK_Break)); +} + +int +xcb_is_modifier_key (xcb_keysym_t keysym) +{ + return (((keysym >= XK_Shift_L) && (keysym <= XK_Hyper_R)) || + ((keysym >= XK_ISO_Lock) && (keysym <= XK_ISO_Level5_Lock)) || + (keysym == XK_Mode_switch) || + (keysym == XK_Num_Lock)); +} + +/* private functions */ + +void +xcb_convert_case(xcb_keysym_t sym, + xcb_keysym_t *lower, + xcb_keysym_t *upper) +{ + *lower = sym; + *upper = sym; + + switch(sym >> 8) + { + case 0: /* Latin 1 */ + if ((sym >= XK_A) && (sym <= XK_Z)) + *lower += (XK_a - XK_A); + else if ((sym >= XK_a) && (sym <= XK_z)) + *upper -= (XK_a - XK_A); + else if ((sym >= XK_Agrave) && (sym <= XK_Odiaeresis)) + *lower += (XK_agrave - XK_Agrave); + else if ((sym >= XK_agrave) && (sym <= XK_odiaeresis)) + *upper -= (XK_agrave - XK_Agrave); + else if ((sym >= XK_Ooblique) && (sym <= XK_Thorn)) + *lower += (XK_oslash - XK_Ooblique); + else if ((sym >= XK_oslash) && (sym <= XK_thorn)) + *upper -= (XK_oslash - XK_Ooblique); + break; + case 1: /* Latin 2 */ + /* Assume the KeySym is a legal value (ignore discontinuities) */ + if (sym == XK_Aogonek) + *lower = XK_aogonek; + else if (sym >= XK_Lstroke && sym <= XK_Sacute) + *lower += (XK_lstroke - XK_Lstroke); + else if (sym >= XK_Scaron && sym <= XK_Zacute) + *lower += (XK_scaron - XK_Scaron); + else if (sym >= XK_Zcaron && sym <= XK_Zabovedot) + *lower += (XK_zcaron - XK_Zcaron); + else if (sym == XK_aogonek) + *upper = XK_Aogonek; + else if (sym >= XK_lstroke && sym <= XK_sacute) + *upper -= (XK_lstroke - XK_Lstroke); + else if (sym >= XK_scaron && sym <= XK_zacute) + *upper -= (XK_scaron - XK_Scaron); + else if (sym >= XK_zcaron && sym <= XK_zabovedot) + *upper -= (XK_zcaron - XK_Zcaron); + else if (sym >= XK_Racute && sym <= XK_Tcedilla) + *lower += (XK_racute - XK_Racute); + else if (sym >= XK_racute && sym <= XK_tcedilla) + *upper -= (XK_racute - XK_Racute); + break; + case 2: /* Latin 3 */ + /* Assume the KeySym is a legal value (ignore discontinuities) */ + if (sym >= XK_Hstroke && sym <= XK_Hcircumflex) + *lower += (XK_hstroke - XK_Hstroke); + else if (sym >= XK_Gbreve && sym <= XK_Jcircumflex) + *lower += (XK_gbreve - XK_Gbreve); + else if (sym >= XK_hstroke && sym <= XK_hcircumflex) + *upper -= (XK_hstroke - XK_Hstroke); + else if (sym >= XK_gbreve && sym <= XK_jcircumflex) + *upper -= (XK_gbreve - XK_Gbreve); + else if (sym >= XK_Cabovedot && sym <= XK_Scircumflex) + *lower += (XK_cabovedot - XK_Cabovedot); + else if (sym >= XK_cabovedot && sym <= XK_scircumflex) + *upper -= (XK_cabovedot - XK_Cabovedot); + break; + case 3: /* Latin 4 */ + /* Assume the KeySym is a legal value (ignore discontinuities) */ + if (sym >= XK_Rcedilla && sym <= XK_Tslash) + *lower += (XK_rcedilla - XK_Rcedilla); + else if (sym >= XK_rcedilla && sym <= XK_tslash) + *upper -= (XK_rcedilla - XK_Rcedilla); + else if (sym == XK_ENG) + *lower = XK_eng; + else if (sym == XK_eng) + *upper = XK_ENG; + else if (sym >= XK_Amacron && sym <= XK_Umacron) + *lower += (XK_amacron - XK_Amacron); + else if (sym >= XK_amacron && sym <= XK_umacron) + *upper -= (XK_amacron - XK_Amacron); + break; + case 6: /* Cyrillic */ + /* Assume the KeySym is a legal value (ignore discontinuities) */ + if (sym >= XK_Serbian_DJE && sym <= XK_Serbian_DZE) + *lower -= (XK_Serbian_DJE - XK_Serbian_dje); + else if (sym >= XK_Serbian_dje && sym <= XK_Serbian_dze) + *upper += (XK_Serbian_DJE - XK_Serbian_dje); + else if (sym >= XK_Cyrillic_YU && sym <= XK_Cyrillic_HARDSIGN) + *lower -= (XK_Cyrillic_YU - XK_Cyrillic_yu); + else if (sym >= XK_Cyrillic_yu && sym <= XK_Cyrillic_hardsign) + *upper += (XK_Cyrillic_YU - XK_Cyrillic_yu); + break; + case 7: /* Greek */ + /* Assume the KeySym is a legal value (ignore discontinuities) */ + if (sym >= XK_Greek_ALPHAaccent && sym <= XK_Greek_OMEGAaccent) + *lower += (XK_Greek_alphaaccent - XK_Greek_ALPHAaccent); + else if (sym >= XK_Greek_alphaaccent && sym <= XK_Greek_omegaaccent && + sym != XK_Greek_iotaaccentdieresis && + sym != XK_Greek_upsilonaccentdieresis) + *upper -= (XK_Greek_alphaaccent - XK_Greek_ALPHAaccent); + else if (sym >= XK_Greek_ALPHA && sym <= XK_Greek_OMEGA) + *lower += (XK_Greek_alpha - XK_Greek_ALPHA); + else if (sym >= XK_Greek_alpha && sym <= XK_Greek_omega && + sym != XK_Greek_finalsmallsigma) + *upper -= (XK_Greek_alpha - XK_Greek_ALPHA); + break; + case 0x14: /* Armenian */ + if (sym >= XK_Armenian_AYB && sym <= XK_Armenian_fe) { + *lower = sym | 1; + *upper = sym & ~1; + } + break; + } +} + +void +xcb_key_symbols_get_reply (xcb_key_symbols_t *syms, + xcb_generic_error_t **e) +{ + if (!syms) + return; + + if (syms->tag == TAG_COOKIE) + { + syms->tag = TAG_VALUE; + syms->u.reply = xcb_get_keyboard_mapping_reply(syms->c, + syms->u.cookie, + e); + } +} diff --git a/NativeApp/Linux/xcb_keysyms/xcb_keysyms.h b/NativeApp/Linux/xcb_keysyms/xcb_keysyms.h new file mode 100644 index 0000000..9d34a50 --- /dev/null +++ b/NativeApp/Linux/xcb_keysyms/xcb_keysyms.h @@ -0,0 +1,71 @@ +#ifndef __XCB_KEYSYMS_H__ +#define __XCB_KEYSYMS_H__ + +#include <xcb/xcb.h> + + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef struct _XCBKeySymbols xcb_key_symbols_t; + +xcb_key_symbols_t *xcb_key_symbols_alloc (xcb_connection_t *c); + +void xcb_key_symbols_free (xcb_key_symbols_t *syms); + +xcb_keysym_t xcb_key_symbols_get_keysym (xcb_key_symbols_t *syms, + xcb_keycode_t keycode, + int col); + +/** + * @brief Get the keycodes attached to a keysyms. + * There can be several value, so what is returned is an array of keycode + * terminated by XCB_NO_SYMBOL. You are responsible to free it. + * Be aware that this function can be slow. It will convert all + * combinations of all available keycodes to keysyms to find the ones that + * match. + * @param syms Key symbols. + * @param keysym The keysym to look for. + * @return A XCB_NO_SYMBOL terminated array of keycode, or NULL if nothing is found. + */ +xcb_keycode_t * xcb_key_symbols_get_keycode(xcb_key_symbols_t *syms, + xcb_keysym_t keysym); + +xcb_keysym_t xcb_key_press_lookup_keysym (xcb_key_symbols_t *syms, + xcb_key_press_event_t *event, + int col); + +xcb_keysym_t xcb_key_release_lookup_keysym (xcb_key_symbols_t *syms, + xcb_key_release_event_t *event, + int col); + +int xcb_refresh_keyboard_mapping (xcb_key_symbols_t *syms, + xcb_mapping_notify_event_t *event); + +/* TODO: need XLookupString equivalent */ + +/* Tests for classes of symbols */ + +int xcb_is_keypad_key (xcb_keysym_t keysym); + +int xcb_is_private_keypad_key (xcb_keysym_t keysym); + +int xcb_is_cursor_key (xcb_keysym_t keysym); + +int xcb_is_pf_key (xcb_keysym_t keysym); + +int xcb_is_function_key (xcb_keysym_t keysym); + +int xcb_is_misc_function_key (xcb_keysym_t keysym); + +int xcb_is_modifier_key (xcb_keysym_t keysym); + + +#ifdef __cplusplus +} +#endif + + +#endif /* __XCB_KEYSYMS_H__ */ diff --git a/NativeApp/include/Android/AndroidAppBase.h b/NativeApp/include/Android/AndroidAppBase.h new file mode 100644 index 0000000..607c8b6 --- /dev/null +++ b/NativeApp/include/Android/AndroidAppBase.h @@ -0,0 +1,112 @@ +/* Copyright 2015-2018 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +#include <memory> + +#include <android_native_app_glue.h> +#include "AppBase.h" + +#include "NDKHelper.h" + +struct android_app; + +namespace Diligent +{ + +class AndroidAppBase : public AppBase +{ +public: + int InitDisplay(); + void SetState(android_app* state, const char* native_activity_class_name); + void InitSensors(); + void ProcessSensors( int32_t id ); + void DrawFrame(); + bool IsReady(); + virtual void TrimMemory() = 0; + virtual void TermDisplay() = 0; + static int32_t HandleInput(android_app* app, AInputEvent* event); + static void HandleCmd(android_app* app, int32_t cmd); + bool CheckWindowSizeChanged() + { + auto new_window_width_ = ANativeWindow_getWidth(app_->window); + auto new_window_height_ = ANativeWindow_getHeight(app_->window); + if(new_window_width_ != window_width_ || new_window_height_ != window_height_) + { + window_width_ = new_window_width_; + window_height_ = new_window_height_; + return true; + } + else + return false; + } + +protected: + virtual void Initialize() + { + CheckWindowSizeChanged(); + } + + virtual int Resume(ANativeWindow* window) = 0; + + virtual int32_t HandleInput(AInputEvent* event ){return 0;} + + virtual void LoadResources() + { + //renderer_.Init(); + //renderer_.Bind( &tap_camera_ ); + } + + virtual void UnloadResources() + { + //renderer_.Unload(); + } + + ndk_helper::DoubletapDetector doubletap_detector_; + ndk_helper::PinchDetector pinch_detector_; + ndk_helper::DragDetector drag_detector_; + ndk_helper::PerfMonitor monitor_; + + //ndk_helper::TapCamera tap_camera_; + android_app* app_ = nullptr; + std::string native_activity_class_name_; + +private: + void UpdatePosition( AInputEvent* event, int32_t iIndex, float& fX, float& fY ); + void SuspendSensors(); + void ResumeSensors(); + void ShowUI(); + void UpdateFPS( float fFPS ); + + bool initialized_resources_ = false; + bool has_focus_ = false; + int32_t window_width_ = 0; + int32_t window_height_ = 0; + + ASensorManager* sensor_manager_ = nullptr; + const ASensor* accelerometer_sensor_ = nullptr; + ASensorEventQueue* sensor_event_queue_ = nullptr; +}; + +} diff --git a/NativeApp/include/AppBase.h b/NativeApp/include/AppBase.h new file mode 100644 index 0000000..d3de11c --- /dev/null +++ b/NativeApp/include/AppBase.h @@ -0,0 +1,47 @@ +/* Copyright 2019 Diligent Graphics LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +namespace Diligent +{ + +class AppBase +{ +public: + virtual ~AppBase() {} + + virtual void ProcessCommandLine(const char* CmdLine) = 0; + virtual const char* GetAppTitle()const = 0; + virtual void Update(double CurrTime, double ElapsedTime) {}; + virtual void Render() = 0; + virtual void Present() = 0; + virtual void WindowResize(int width, int height) = 0; + virtual void GetDesiredInitialWindowSize(int& width, int& height) + { + width = 0; + height = 0; + } +}; + +} diff --git a/NativeApp/include/IOS/IOSAppBase.h b/NativeApp/include/IOS/IOSAppBase.h new file mode 100644 index 0000000..847052a --- /dev/null +++ b/NativeApp/include/IOS/IOSAppBase.h @@ -0,0 +1,47 @@ +/* Copyright 2015-2018 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +#include "AppBase.h" +#include "Timer.h" + +namespace Diligent +{ + +class IOSAppBase : public AppBase +{ +public: + using AppBase::Update; + void Update(); + virtual void Initialize(int deviceType, void* layer) = 0; + virtual void OnTouchBegan(float x, float y){} + virtual void OnTouchMoved(float x, float y){} + virtual void OnTouchEnded(float x, float y){} + +protected: + Timer timer; + double PrevTime = 0.0; +}; + +} diff --git a/NativeApp/include/Linux/LinuxAppBase.h b/NativeApp/include/Linux/LinuxAppBase.h new file mode 100644 index 0000000..e4c6a3e --- /dev/null +++ b/NativeApp/include/Linux/LinuxAppBase.h @@ -0,0 +1,62 @@ +/* Copyright 2015-2018 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + + +#include <GL/glx.h> +#include <GL/gl.h> + +// Undef symbols defined by XLib +#ifdef Bool +# undef Bool +#endif +#ifdef True +# undef True +#endif +#ifdef False +# undef False +#endif + +#if VULKAN_SUPPORTED +#include <xcb/xcb.h> +#endif + +#include "AppBase.h" + +namespace Diligent +{ + +class LinuxAppBase : public AppBase +{ +public: + virtual void OnGLContextCreated(Display* display, Window window) = 0; + virtual int HandleXEvent(XEvent* xev){} + +#if VULKAN_SUPPORTED + virtual bool InitVulkan(xcb_connection_t* connection, uint32_t window) = 0; + virtual void HandleXCBEvent(xcb_generic_event_t* event){} +#endif +}; + +} diff --git a/NativeApp/include/MacOS/MacOSAppBase.h b/NativeApp/include/MacOS/MacOSAppBase.h new file mode 100644 index 0000000..923fcec --- /dev/null +++ b/NativeApp/include/MacOS/MacOSAppBase.h @@ -0,0 +1,45 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +#include "AppBase.h" +#include "Timer.h" + +namespace Diligent +{ + +class MacOSAppBase : public AppBase +{ +public: + using AppBase::Update; + void Update(); + virtual void Initialize(void* view) = 0; + virtual void HandleOSXEvent(void* event, void* view){}; + +protected: + Timer timer; + double PrevTime = 0.0; +}; + +} diff --git a/NativeApp/include/NativeAppBase.h b/NativeApp/include/NativeAppBase.h new file mode 100644 index 0000000..c475e0c --- /dev/null +++ b/NativeApp/include/NativeAppBase.h @@ -0,0 +1,81 @@ +/* Copyright 2019 Diligent Graphics LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ +#pragma once + +#if PLATFORM_WIN32 + + #include "Win32AppBase.h" + namespace Diligent + { + using NativeAppBase = Win32AppBase; + } + +#elif PLATFORM_UNIVERSAL_WINDOWS + + #include "UWPAppBase.h" + namespace Diligent + { + using NativeAppBase = UWPAppBase; + } + +#elif PLATFORM_LINUX + + #include "LinuxAppBase.h" + namespace Diligent + { + using NativeAppBase = LinuxAppBase; + } + +#elif PLATFORM_ANDROID + + #include "AndroidAppBase.h" + namespace Diligent + { + using NativeAppBase = AndroidAppBase; + } + +#elif PLATFORM_MACOS + + #include "MacOSAppBase.h" + namespace Diligent + { + using NativeAppBase = MacOSAppBase; + } + +#elif PLATFORM_IOS + + #include "IOSAppBase.h" + namespace Diligent + { + using NativeAppBase = IOSAppBase; + } +#else + +# error Usnupported paltform + +#endif + +namespace Diligent +{ + extern NativeAppBase* CreateApplication(); +}
\ No newline at end of file diff --git a/NativeApp/include/UWP/UWPAppBase.h b/NativeApp/include/UWP/UWPAppBase.h new file mode 100644 index 0000000..cc0c71e --- /dev/null +++ b/NativeApp/include/UWP/UWPAppBase.h @@ -0,0 +1,76 @@ +/* Copyright 2015-2018 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + + +#pragma once + +#include <memory> + +#define NOMINIMAX +#include <wrl.h> +#include <wrl/client.h> + +#include "AppBase.h" +#include "Common/StepTimer.h" +#include "Common/DeviceResources.h" + +namespace Diligent +{ + +class UWPAppBase : public AppBase +{ +public: + UWPAppBase(); + + virtual void OnSetWindow(Windows::UI::Core::CoreWindow^ window) {} + virtual void OnWindowSizeChanged() = 0; + + using AppBase::Update; + virtual void Update(); + + // Notifies the app that it is being suspended. + virtual void OnSuspending() {} + + // Notifes the app that it is no longer suspended. + virtual void OnResuming() {} + + // Notifies renderers that device resources need to be released. + virtual void OnDeviceRemoved() {} + + bool IsFrameReady()const { return m_bFrameReady; } + + virtual std::shared_ptr<DX::DeviceResources> InitDeviceResources() = 0; + + virtual void InitWindowSizeDependentResources() = 0; + + virtual void CreateRenderers() = 0; + +protected: + std::shared_ptr<DX::DeviceResources> m_DeviceResources; + + // Rendering loop timer. + DX::StepTimer m_timer; + bool m_bFrameReady = false; +}; + +} diff --git a/NativeApp/include/Win32/Win32AppBase.h b/NativeApp/include/Win32/Win32AppBase.h new file mode 100644 index 0000000..8242ac7 --- /dev/null +++ b/NativeApp/include/Win32/Win32AppBase.h @@ -0,0 +1,52 @@ +/* Copyright 2019 Diligent Graphics LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +#ifndef NOMINMAX +# define NOMINMAX +#endif +#include <Windows.h> + +#include "AppBase.h" + +namespace Diligent +{ + +class Win32AppBase : public AppBase +{ +public: + virtual void OnWindowCreated(HWND hWnd, + LONG WindowWidth, + LONG WindowHeight) = 0; + + virtual LRESULT HandleWin32Message(HWND hWnd, + UINT message, + WPARAM wParam, + LPARAM lParam) + { + return 0; + } +}; + +} diff --git a/NativeApp/src/Android/AndroidAppBase.cpp b/NativeApp/src/Android/AndroidAppBase.cpp new file mode 100644 index 0000000..f3e341c --- /dev/null +++ b/NativeApp/src/Android/AndroidAppBase.cpp @@ -0,0 +1,266 @@ +/* Copyright 2015-2018 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#include "AndroidAppBase.h" +#include "Timer.h" + +#include <android/sensor.h> +//#include <android/log.h> +//#include <android_native_app_glue.h> +#include <android/native_window_jni.h> +//#include <cpu-features.h> + +namespace Diligent +{ + +int AndroidAppBase::InitDisplay() +{ + if( !initialized_resources_ ) + { + Initialize(); + + LoadResources(); + initialized_resources_ = true; + } + else + { + // initialize OpenGL ES and EGL + if( EGL_SUCCESS != Resume( app_->window ) ) + { + UnloadResources(); + LoadResources(); + } + } + + ShowUI(); + + //tap_camera_.SetFlip( 1.f, -1.f, -1.f ); + //tap_camera_.SetPinchTransformFactor( 2.f, 2.f, 8.f ); + + return 0; +} + +void AndroidAppBase::InitSensors() +{ + sensor_manager_ = ASensorManager_getInstance(); + accelerometer_sensor_ = ASensorManager_getDefaultSensor( sensor_manager_, ASENSOR_TYPE_ACCELEROMETER ); + sensor_event_queue_ = ASensorManager_createEventQueue( sensor_manager_, app_->looper, LOOPER_ID_USER, NULL, NULL ); +} + +// +// Just the current frame in the display. +// +void AndroidAppBase::DrawFrame() +{ + // APP_CMD_CONFIG_CHANGED event is generated seveal frames + // before the screen is actually resized. The only robust way + // to detect window resize is to check it very frame + if(CheckWindowSizeChanged()) + WindowResize(0,0); + + float fFPS; + if( monitor_.Update( fFPS ) ) + { + UpdateFPS( fFPS ); + } + + static Diligent::Timer Timer; + static double PrevTime = Timer.GetElapsedTime(); + auto CurrTime = Timer.GetElapsedTime(); + auto ElapsedTime = CurrTime - PrevTime; + PrevTime = CurrTime; + + Update(CurrTime, ElapsedTime); + + Render(); + + Present(); + //if( EGL_SUCCESS != pRenderDevice_->Present() ) + //{ + // UnloadResources(); + // LoadResources(); + //} +} + + +// +// Process the next input event. +// +int32_t AndroidAppBase::HandleInput( android_app* app, AInputEvent* event ) +{ + AndroidAppBase* eng = (AndroidAppBase*)app->userData; + return eng->HandleInput( event ); +} + +// +// Process the next main command. +// +void AndroidAppBase::HandleCmd( struct android_app* app, int32_t cmd ) +{ + AndroidAppBase* eng = (AndroidAppBase*)app->userData; + switch( cmd ) + { + case APP_CMD_SAVE_STATE: + break; + + case APP_CMD_INIT_WINDOW: + // The window is being shown, get it ready. + if( app->window != NULL ) + { + eng->InitDisplay(); + eng->DrawFrame(); + } + break; + + case APP_CMD_CONFIG_CHANGED: + case APP_CMD_WINDOW_RESIZED: + // This does not work as the screen resizes few frames + // after the event has been received + // eng->WindowResize(0,0); + break; + + case APP_CMD_TERM_WINDOW: + // The window is being hidden or closed, clean it up. + eng->TermDisplay(); + eng->has_focus_ = false; + break; + + case APP_CMD_STOP: + break; + + case APP_CMD_GAINED_FOCUS: + eng->ResumeSensors(); + //Start animation + eng->has_focus_ = true; + break; + + case APP_CMD_LOST_FOCUS: + eng->SuspendSensors(); + // Also stop animating. + eng->has_focus_ = false; + eng->DrawFrame(); + break; + + case APP_CMD_LOW_MEMORY: + //Free up GL resources + eng->TrimMemory(); + break; + } +} + +//------------------------------------------------------------------------- +//Sensor handlers +//------------------------------------------------------------------------- +void AndroidAppBase::ProcessSensors( int32_t id ) +{ + // If a sensor has data, process it now. + if( id == LOOPER_ID_USER ) + { + if( accelerometer_sensor_ != NULL ) + { + ASensorEvent event; + while( ASensorEventQueue_getEvents( sensor_event_queue_, &event, 1 ) > 0 ) + { + } + } + } +} + +void AndroidAppBase::ResumeSensors() +{ + // When our app gains focus, we start monitoring the accelerometer. + if( accelerometer_sensor_ != NULL ) + { + ASensorEventQueue_enableSensor( sensor_event_queue_, accelerometer_sensor_ ); + // We'd like to get 60 events per second (in us). + ASensorEventQueue_setEventRate( sensor_event_queue_, accelerometer_sensor_, + (1000L / 60) * 1000 ); + } +} + +void AndroidAppBase::SuspendSensors() +{ + // When our app loses focus, we stop monitoring the accelerometer. + // This is to avoid consuming battery while not being used. + if( accelerometer_sensor_ != NULL ) + { + ASensorEventQueue_disableSensor( sensor_event_queue_, accelerometer_sensor_ ); + } +} + +//------------------------------------------------------------------------- +//Misc +//------------------------------------------------------------------------- +void AndroidAppBase::SetState( android_app* state, const char* native_activity_class_name ) +{ + app_ = state; + native_activity_class_name_ = native_activity_class_name; + doubletap_detector_.SetConfiguration( app_->config ); + drag_detector_.SetConfiguration( app_->config ); + pinch_detector_.SetConfiguration( app_->config ); +} + +bool AndroidAppBase::IsReady() +{ + if( has_focus_ ) + return true; + + return false; +} + +//void Engine::TransformPosition( ndk_helper::Vec2& vec ) +//{ +// vec = ndk_helper::Vec2( 2.0f, 2.0f ) * vec +// / ndk_helper::Vec2( pDeviceContext_->GetMainBackBufferDesc().Width, pDeviceContext_->GetMainBackBufferDesc().Height ) +// - ndk_helper::Vec2( 1.f, 1.f ); +//} + +void AndroidAppBase::ShowUI() +{ + JNIEnv *jni; + app_->activity->vm->AttachCurrentThread( &jni, NULL ); + + //Default class retrieval + jclass clazz = jni->GetObjectClass( app_->activity->clazz ); + jmethodID methodID = jni->GetMethodID( clazz, "showUI", "()V" ); + jni->CallVoidMethod( app_->activity->clazz, methodID ); + + app_->activity->vm->DetachCurrentThread(); + return; +} + +void AndroidAppBase::UpdateFPS( float fFPS ) +{ + JNIEnv *jni; + app_->activity->vm->AttachCurrentThread( &jni, NULL ); + + //Default class retrieval + jclass clazz = jni->GetObjectClass( app_->activity->clazz ); + jmethodID methodID = jni->GetMethodID( clazz, "updateFPS", "(F)V" ); + jni->CallVoidMethod( app_->activity->clazz, methodID, fFPS ); + + app_->activity->vm->DetachCurrentThread(); + return; +} + +} diff --git a/NativeApp/src/Android/AndroidMain.cpp b/NativeApp/src/Android/AndroidMain.cpp new file mode 100644 index 0000000..6e65b8a --- /dev/null +++ b/NativeApp/src/Android/AndroidMain.cpp @@ -0,0 +1,93 @@ + /* Copyright 2015-2018 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#include <memory> +#include <jni.h> +#include <errno.h> + +#include "PlatformDefinitions.h" +#include "NativeAppBase.h" + + +#define HELPER_CLASS_NAME "com/android/helper/NDKHelper" //Class name of helper function +#define NATIVEACTIVITY_CLASS_NAME "android/app/NativeActivity" + +using namespace Diligent; + +// This is the main entry point of a native application that is using +// android_native_app_glue. It runs in its own thread, with its own +// event loop for receiving input events and doing other things. +void android_main( android_app* state ) +{ + std::unique_ptr<AndroidAppBase> theApp(CreateApplication()); + theApp->SetState( state, NATIVEACTIVITY_CLASS_NAME ); + + //Init helper functions + ndk_helper::JNIHelper::Init( state->activity, HELPER_CLASS_NAME ); + + state->userData = theApp.get(); + state->onAppCmd = AndroidAppBase::HandleCmd; + state->onInputEvent = AndroidAppBase::HandleInput; + +#ifdef USE_NDK_PROFILER + monstartup( "libEngineSandbox.so" ); +#endif + + // Prepare to monitor accelerometer + theApp->InitSensors(); + + // loop waiting for stuff to do. + while( 1 ) + { + // Read all pending events. + int id; + int events; + android_poll_source* source; + + // If not animating, we will block forever waiting for events. + // If animating, we loop until all events are read, then continue + // to draw the next frame of animation. + while( (id = ALooper_pollAll( theApp->IsReady() ? 0 : -1, NULL, &events, (void**)&source )) >= 0 ) + { + // Process this event. + if( source != NULL ) + source->process( state, source ); + + theApp->ProcessSensors( id ); + + // Check if we are exiting. + if( state->destroyRequested != 0 ) + { + theApp->TermDisplay(); + return; + } + } + + if( theApp->IsReady() ) + { + // Drawing is throttled to the screen update rate, so there + // is no need to do timing here. + theApp->DrawFrame(); + } + } +} diff --git a/NativeApp/src/IOS/IOSAppBase.cpp b/NativeApp/src/IOS/IOSAppBase.cpp new file mode 100644 index 0000000..d4defb8 --- /dev/null +++ b/NativeApp/src/IOS/IOSAppBase.cpp @@ -0,0 +1,38 @@ +/* Copyright 2015-2018 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#include "IOSAppBase.h" + +namespace Diligent +{ + +void IOSAppBase::Update() +{ + // Render the scene + auto CurrTime = timer.GetElapsedTime(); + auto ElapsedTime = CurrTime - PrevTime; + PrevTime = CurrTime; + Update(CurrTime, ElapsedTime); +} + +} diff --git a/NativeApp/src/Linux/LinuxMain.cpp b/NativeApp/src/Linux/LinuxMain.cpp new file mode 100644 index 0000000..c8cf197 --- /dev/null +++ b/NativeApp/src/Linux/LinuxMain.cpp @@ -0,0 +1,526 @@ +/* Copyright 2015-2018 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#include <memory> +#include <iomanip> + +#include "PlatformDefinitions.h" +#include "NativeAppBase.h" +#include "StringTools.h" +#include "Timer.h" +#include "Errors.h" + + +#ifndef GLX_CONTEXT_MAJOR_VERSION_ARB +# define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091 +#endif + +#ifndef GLX_CONTEXT_MINOR_VERSION_ARB +# define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092 +#endif + +#ifndef GLX_CONTEXT_FLAGS_ARB +# define GLX_CONTEXT_FLAGS_ARB 0x2094 +#endif + +#ifndef GLX_CONTEXT_DEBUG_BIT_ARB +# define GLX_CONTEXT_DEBUG_BIT_ARB 0x0001 +#endif + +typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, int, const int*); + +static constexpr uint16_t WindowWidth = 1024; +static constexpr uint16_t WindowHeight = 768; +static constexpr uint16_t MinWindowWidth = 320; +static constexpr uint16_t MinWindowHeight = 240; + +using namespace Diligent; + +namespace +{ + +class WindowTitleHelper +{ +public: + WindowTitleHelper(std::string _Title) : + Title(std::move(_Title)) + {} + + std::string GetTitleWithFPS(double ElapsedTime) + { + double filterScale = 0.2; + FilteredFrameTime = FilteredFrameTime * (1.0 - filterScale) + filterScale * ElapsedTime; + std::stringstream TitleWithFpsSS; + TitleWithFpsSS << Title; + TitleWithFpsSS << " - " << std::fixed << std::setprecision(1) << FilteredFrameTime * 1000; + TitleWithFpsSS << " ms (" << 1.0 / FilteredFrameTime << " fps)"; + return TitleWithFpsSS.str(); + } + +private: + const std::string Title; + double FilteredFrameTime = 0.0; +}; + +} + +#if VULKAN_SUPPORTED + +// https://code.woboq.org/qt5/include/xcb/xcb_icccm.h.html +enum XCB_SIZE_HINT +{ + XCB_SIZE_HINT_US_POSITION = 1 << 0, + XCB_SIZE_HINT_US_SIZE = 1 << 1, + XCB_SIZE_HINT_P_POSITION = 1 << 2, + XCB_SIZE_HINT_P_SIZE = 1 << 3, + XCB_SIZE_HINT_P_MIN_SIZE = 1 << 4, + XCB_SIZE_HINT_P_MAX_SIZE = 1 << 5, + XCB_SIZE_HINT_P_RESIZE_INC = 1 << 6, + XCB_SIZE_HINT_P_ASPECT = 1 << 7, + XCB_SIZE_HINT_BASE_SIZE = 1 << 8, + XCB_SIZE_HINT_P_WIN_GRAVITY = 1 << 9 +}; + +struct xcb_size_hints_t +{ + uint32_t flags; /** User specified flags */ + int32_t x, y; /** User-specified position */ + int32_t width, height; /** User-specified size */ + int32_t min_width, min_height; /** Program-specified minimum size */ + int32_t max_width, max_height; /** Program-specified maximum size */ + int32_t width_inc, height_inc; /** Program-specified resize increments */ + int32_t min_aspect_num, min_aspect_den; /** Program-specified minimum aspect ratios */ + int32_t max_aspect_num, max_aspect_den; /** Program-specified maximum aspect ratios */ + int32_t base_width, base_height; /** Program-specified base size */ + uint32_t win_gravity; /** Program-specified window gravity */ +}; + +struct XCBInfo +{ + xcb_connection_t* connection = nullptr; + uint32_t window = 0; + uint16_t width = 0; + uint16_t height = 0; + xcb_intern_atom_reply_t* atom_wm_delete_window = nullptr; +}; + +XCBInfo InitXCBConnectionAndWindow(const std::string& Title) +{ + XCBInfo info; + + int scr = 0; + info.connection = xcb_connect(nullptr, &scr); + if (info.connection == nullptr || xcb_connection_has_error(info.connection)) + { + std::cerr << "Unable to make an XCB connection\n"; + exit(-1); + } + + const xcb_setup_t* setup = xcb_get_setup(info.connection); + xcb_screen_iterator_t iter = xcb_setup_roots_iterator(setup); + while (scr-- > 0) + xcb_screen_next(&iter); + + auto screen = iter.data; + + info.width = WindowWidth; + info.height = WindowHeight; + + uint32_t value_mask, value_list[32]; + + info.window = xcb_generate_id(info.connection); + + value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK; + value_list[0] = screen->black_pixel; + value_list[1] = + XCB_EVENT_MASK_KEY_RELEASE | + XCB_EVENT_MASK_KEY_PRESS | + XCB_EVENT_MASK_EXPOSURE | + XCB_EVENT_MASK_STRUCTURE_NOTIFY | + XCB_EVENT_MASK_POINTER_MOTION | + XCB_EVENT_MASK_BUTTON_PRESS | + XCB_EVENT_MASK_BUTTON_RELEASE; + + xcb_create_window(info.connection, XCB_COPY_FROM_PARENT, info.window, screen->root, 0, 0, info.width, info.height, 0, + XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list); + + // Magic code that will send notification when window is destroyed + xcb_intern_atom_cookie_t cookie = xcb_intern_atom(info.connection, 1, 12, "WM_PROTOCOLS"); + xcb_intern_atom_reply_t* reply = xcb_intern_atom_reply(info.connection, cookie, 0); + + xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(info.connection, 0, 16, "WM_DELETE_WINDOW"); + info.atom_wm_delete_window = xcb_intern_atom_reply(info.connection, cookie2, 0); + + xcb_change_property(info.connection, XCB_PROP_MODE_REPLACE, info.window, (*reply).atom, 4, 32, 1, + &(*info.atom_wm_delete_window).atom); + free(reply); + + xcb_change_property(info.connection, XCB_PROP_MODE_REPLACE, info.window, XCB_ATOM_WM_NAME, XCB_ATOM_STRING, + 8, Title.length(), Title.c_str() ); + + // https://stackoverflow.com/a/27771295 + xcb_size_hints_t hints = {}; + hints.flags = XCB_SIZE_HINT_P_MIN_SIZE; + hints.min_width = MinWindowWidth; + hints.min_height = MinWindowHeight; + xcb_change_property(info.connection, XCB_PROP_MODE_REPLACE, info.window, XCB_ATOM_WM_NORMAL_HINTS, XCB_ATOM_WM_SIZE_HINTS, + 32, sizeof(xcb_size_hints_t), &hints); + + xcb_map_window(info.connection, info.window); + + // Force the x/y coordinates to 100,100 results are identical in consecutive + // runs + const uint32_t coords[] = {100, 100}; + xcb_configure_window(info.connection, info.window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords); + xcb_flush(info.connection); + + xcb_generic_event_t *e; + while ((e = xcb_wait_for_event(info.connection))) + { + if ((e->response_type & ~0x80) == XCB_EXPOSE) break; + } + return info; +} + +void DestroyXCBConnectionAndWindow(XCBInfo &info) +{ + xcb_destroy_window(info.connection, info.window); + xcb_disconnect(info.connection); +} + +int xcb_main() +{ + std::unique_ptr<NativeAppBase> TheApp(CreateApplication()); + + std::string Title = TheApp->GetAppTitle(); + auto xcbInfo = InitXCBConnectionAndWindow(Title); + if(!TheApp->InitVulkan(xcbInfo.connection, xcbInfo.window)) + return -1; + + xcb_flush(xcbInfo.connection); + + Timer timer; + auto PrevTime = timer.GetElapsedTime(); + Title = TheApp->GetAppTitle(); + WindowTitleHelper TitleHelper(Title); + + while (true) + { + xcb_generic_event_t* event = nullptr; + bool Quit = false; + while ((event = xcb_poll_for_event(xcbInfo.connection)) != nullptr) + { + TheApp->HandleXCBEvent(event); + switch (event->response_type & 0x7f) + { + case XCB_CLIENT_MESSAGE: + if ((*(xcb_client_message_event_t*)event).data.data32[0] == + (*xcbInfo.atom_wm_delete_window).atom) + { + Quit = true; + } + break; + + case XCB_KEY_RELEASE: + { + const auto* keyEvent = reinterpret_cast<const xcb_key_release_event_t*>(event); + switch (keyEvent->detail) + { + #define KEY_ESCAPE 0x9 + case KEY_ESCAPE: + Quit = true; + break; + } + } + break; + + case XCB_DESTROY_NOTIFY: + Quit = true; + break; + + case XCB_CONFIGURE_NOTIFY: + { + const auto* cfgEvent = reinterpret_cast<const xcb_configure_notify_event_t*>(event); + if ((cfgEvent->width != xcbInfo.width) || (cfgEvent->height != xcbInfo.height)) + { + xcbInfo.width = cfgEvent->width; + xcbInfo.height = cfgEvent->height; + if ((xcbInfo.width > 0) && (xcbInfo.height > 0)) + { + TheApp->WindowResize(xcbInfo.width, xcbInfo.height); + } + } + } + break; + + default: + break; + } + free(event); + } + + if (Quit) + break; + + // Render the scene + auto CurrTime = timer.GetElapsedTime(); + auto ElapsedTime = CurrTime - PrevTime; + PrevTime = CurrTime; + + TheApp->Update(CurrTime, ElapsedTime); + + TheApp->Render(); + + TheApp->Present(); + + auto TitleWithFPS = TitleHelper.GetTitleWithFPS(ElapsedTime); + xcb_change_property(xcbInfo.connection, XCB_PROP_MODE_REPLACE, xcbInfo.window, XCB_ATOM_WM_NAME, XCB_ATOM_STRING, + 8, TitleWithFPS.length(), TitleWithFPS.c_str() ); + xcb_flush(xcbInfo.connection); + } + + TheApp.reset(); + DestroyXCBConnectionAndWindow(xcbInfo); + + return 0; +} + +#endif + + +int x_main() +{ + std::unique_ptr<NativeAppBase> TheApp(CreateApplication()); + Display *display = XOpenDisplay(0); + + static int visual_attribs[] = + { + GLX_RENDER_TYPE, GLX_RGBA_BIT, + GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, + GLX_DOUBLEBUFFER, true, + + // The largest available total RGBA color buffer size (sum of GLX_RED_SIZE, + // GLX_GREEN_SIZE, GLX_BLUE_SIZE, and GLX_ALPHA_SIZE) of at least the minimum + // size specified for each color component is preferred. + GLX_RED_SIZE, 8, + GLX_GREEN_SIZE, 8, + GLX_BLUE_SIZE, 8, + GLX_ALPHA_SIZE, 8, + + // The largest available depth buffer of at least GLX_DEPTH_SIZE size is preferred + GLX_DEPTH_SIZE, 24, + + //GLX_SAMPLE_BUFFERS, 1, + GLX_SAMPLES, 1, + None + }; + + int fbcount = 0; + GLXFBConfig *fbc = glXChooseFBConfig(display, DefaultScreen(display), visual_attribs, &fbcount); + if (!fbc) + { + LOG_ERROR_MESSAGE("Failed to retrieve a framebuffer config"); + return -1; + } + + XVisualInfo *vi = glXGetVisualFromFBConfig(display, fbc[0]); + + XSetWindowAttributes swa; + swa.colormap = XCreateColormap(display, RootWindow(display, vi->screen), vi->visual, AllocNone); + swa.border_pixel = 0; + swa.event_mask = + StructureNotifyMask | + ExposureMask | + KeyPressMask | + KeyReleaseMask | + ButtonPressMask | + ButtonReleaseMask | + PointerMotionMask; + + Window win = XCreateWindow(display, RootWindow(display, vi->screen), 0, 0, WindowWidth, WindowHeight, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel|CWColormap|CWEventMask, &swa); + if (!win) + { + LOG_ERROR_MESSAGE("Failed to create window."); + return -1; + } + + { + auto SizeHints = XAllocSizeHints(); + SizeHints->flags = PMinSize; + SizeHints->min_width = MinWindowWidth; + SizeHints->min_height = MinWindowHeight; + XSetWMNormalHints(display, win, SizeHints); + XFree(SizeHints); + } + + XMapWindow(display, win); + + glXCreateContextAttribsARBProc glXCreateContextAttribsARB = nullptr; + { + // Create an oldstyle context first, to get the correct function pointer for glXCreateContextAttribsARB + GLXContext ctx_old = glXCreateContext(display, vi, 0, GL_TRUE); + glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB"); + glXMakeCurrent(display, None, NULL); + glXDestroyContext(display, ctx_old); + } + + if (glXCreateContextAttribsARB == nullptr) + { + LOG_ERROR("glXCreateContextAttribsARB entry point not found. Aborting."); + return -1; + } + + int Flags = GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB; +#ifdef _DEBUG + Flags |= GLX_CONTEXT_DEBUG_BIT_ARB; +#endif + + int major_version = 4; + int minor_version = 3; + static int context_attribs[] = + { + GLX_CONTEXT_MAJOR_VERSION_ARB, major_version, + GLX_CONTEXT_MINOR_VERSION_ARB, minor_version, + GLX_CONTEXT_FLAGS_ARB, Flags, + None + }; + + constexpr int True = 1; + GLXContext ctx = glXCreateContextAttribsARB(display, fbc[0], NULL, True, context_attribs); + if (!ctx) + { + LOG_ERROR("Failed to create GL context."); + return -1; + } + XFree(fbc); + + + glXMakeCurrent(display, win, ctx); + TheApp->OnGLContextCreated(display, win); + std::string Title = TheApp->GetAppTitle(); + + Timer timer; + auto PrevTime = timer.GetElapsedTime(); + WindowTitleHelper TitleHelper(Title); + + while (true) + { + bool EscPressed = false; + XEvent xev; + // Handle all events in the queue + while(XCheckMaskEvent(display, 0xFFFFFFFF, &xev)) + { + TheApp->HandleXEvent(&xev); + switch(xev.type) + { + case KeyPress: + { + KeySym keysym; + char buffer[80]; + int num_char = XLookupString((XKeyEvent *)&xev, buffer, _countof(buffer), &keysym, 0); + EscPressed = (keysym==XK_Escape); + } + + case ConfigureNotify: + { + XConfigureEvent &xce = reinterpret_cast<XConfigureEvent &>(xev); + if(xce.width != 0 && xce.height != 0) + TheApp->WindowResize(xce.width, xce.height); + break; + } + } + } + + if(EscPressed) + break; + + // Render the scene + auto CurrTime = timer.GetElapsedTime(); + auto ElapsedTime = CurrTime - PrevTime; + PrevTime = CurrTime; + + TheApp->Update(CurrTime, ElapsedTime); + + TheApp->Render(); + + TheApp->Present(); + + auto TitleWithFPS = TitleHelper.GetTitleWithFPS(ElapsedTime); + XStoreName(display, win, TitleWithFPS.c_str()); + } + + TheApp.reset(); + + ctx = glXGetCurrentContext(); + glXMakeCurrent(display, None, NULL); + glXDestroyContext(display, ctx); + XDestroyWindow(display, win); + XCloseDisplay(display); +} + +int main (int argc, char ** argv) +{ + bool UseVulkan = false; + +#if VULKAN_SUPPORTED + UseVulkan = true; + if (argc > 1) + { + const auto* Key = "-mode "; + const auto* pos = strstr(argv[1], Key); + if (pos != nullptr) + { + pos += strlen(Key); + while(*pos != 0 && *pos == ' ')++pos; + if (strcasecmp(pos, "GL") == 0) + { + UseVulkan = false; + } + else if (strcasecmp(pos, "VK") == 0) + { + UseVulkan = true; + } + else + { + std::cerr << "Unknown device type. Only the following types are supported: GL, VK"; + return -1; + } + } + } + + if (UseVulkan) + { + auto ret = xcb_main(); + if (ret >= 0) + { + return ret; + } + else + { + LOG_ERROR_MESSAGE("Failed to initialize the engine in Vulkan mode. Attempting to use OpenGL"); + } + } +#endif + + return x_main(); +} diff --git a/NativeApp/src/MacOS/MacOSAppBase.cpp b/NativeApp/src/MacOS/MacOSAppBase.cpp new file mode 100644 index 0000000..f3d0313 --- /dev/null +++ b/NativeApp/src/MacOS/MacOSAppBase.cpp @@ -0,0 +1,38 @@ +/* Copyright 2015-2019 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#include "MacOSAppBase.h" + +namespace Diligent +{ + +void MacOSAppBase::Update() +{ + // Render the scene + auto CurrTime = timer.GetElapsedTime(); + auto ElapsedTime = CurrTime - PrevTime; + PrevTime = CurrTime; + Update(CurrTime, ElapsedTime); +} + +} diff --git a/NativeApp/src/UWP/App.cpp b/NativeApp/src/UWP/App.cpp new file mode 100644 index 0000000..0c928eb --- /dev/null +++ b/NativeApp/src/UWP/App.cpp @@ -0,0 +1,351 @@ +/* Copyright 2015-2016 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#define NOMINIMAX +#include <wrl.h> +#include <wrl/client.h> +#include <DirectXMath.h> +#include <agile.h> + +#if defined(_DEBUG) +# include <dxgidebug.h> +#endif + +#include "App.h" +#include "StringTools.h" + +#include <ppltasks.h> + +using namespace SampleApp; +using namespace Diligent; + +using namespace concurrency; +using namespace Windows::ApplicationModel; +using namespace Windows::ApplicationModel::Core; +using namespace Windows::ApplicationModel::Activation; +using namespace Windows::UI::Core; +using namespace Windows::UI::Input; +using namespace Windows::System; +using namespace Windows::Foundation; +using namespace Windows::Graphics::Display; + +using Microsoft::WRL::ComPtr; + + +ref class ApplicationSource sealed : IFrameworkViewSource +{ +public: + virtual IFrameworkView^ CreateView() + { + return ref new App(); + } +}; + + +// The main function is only used to initialize our IFrameworkView class. +[Platform::MTAThread] +int main(Platform::Array<Platform::String^>^) +{ + auto direct3DApplicationSource = ref new ApplicationSource(); + CoreApplication::Run(direct3DApplicationSource); + return 0; +} + +App::App() : + m_windowClosed(false), + m_windowVisible(true) +{ +} + + +// The first method called when the IFrameworkView is being created. +void App::Initialize(CoreApplicationView^ applicationView) +{ + // Register event handlers for app lifecycle. This example includes Activated, so that we + // can make the CoreWindow active and start rendering on the window. + applicationView->Activated += + ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &App::OnActivated); + + CoreApplication::Suspending += + ref new EventHandler<SuspendingEventArgs^>(this, &App::OnSuspending); + + CoreApplication::Resuming += + ref new EventHandler<Platform::Object^>(this, &App::OnResuming); +} + +// Called when the CoreWindow object is created (or re-created). +void App::SetWindow(CoreWindow^ window) +{ + window->SizeChanged += + ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &App::OnWindowSizeChanged); + + window->VisibilityChanged += + ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &App::OnVisibilityChanged); + + window->Closed += + ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &App::OnWindowClosed); + + window->KeyDown += + ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &App::OnKeyDown); + + window->KeyUp += + ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &App::OnKeyUp); + + DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView(); + + currentDisplayInformation->DpiChanged += + ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnDpiChanged); + + currentDisplayInformation->OrientationChanged += + ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnOrientationChanged); + + DisplayInformation::DisplayContentsInvalidated += + ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnDisplayContentsInvalidated); + + if (m_Main) + { + m_Main->OnSetWindow(window); + } +} + +// Initializes scene resources, or loads a previously saved app state. +void App::Load(Platform::String^ entryPoint) +{ + if (m_Main == nullptr) + { + m_Main.reset(CreateApplication()); + m_Main->OnSetWindow(CoreWindow::GetForCurrentThread()); + } +} + +// This method is called after the window becomes active. +void App::Run() +{ + while (!m_windowClosed) + { + if (m_windowVisible) + { + CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent); + + // Initialize device resources + GetDeviceResources(); + + //PIXBeginEvent(commandQueue, 0, L"Update"); + { + m_Main->Update(); + } + //PIXEndEvent(commandQueue); + + //PIXBeginEvent(commandQueue, 0, L"Render"); + { + m_Main->Render(); + if (m_Main->IsFrameReady()) + { + m_Main->Present(); + } + } + //PIXEndEvent(commandQueue); + } + else + { + CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending); + } + } +} + +// Required for IFrameworkView. +// Terminate events do not cause Uninitialize to be called. It will be called if your IFrameworkView +// class is torn down while the app is in the foreground. +void App::Uninitialize() +{ +} + +// Application lifecycle event handlers. + +void App::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args) +{ + if (args->Kind == ActivationKind::Launch) + { + LaunchActivatedEventArgs^ launchArgs = (LaunchActivatedEventArgs^)args; + auto CmdLine = Diligent::NarrowString(launchArgs->Arguments->Data()); + m_Main->ProcessCommandLine(CmdLine.c_str()); + } + + auto Title = Diligent::WidenString(m_Main->GetAppTitle()); + Windows::UI::ViewManagement::ApplicationView::GetForCurrentView()->Title = ref new Platform::String(Title.c_str()); + + // Run() won't start until the CoreWindow is activated. + CoreWindow::GetForCurrentThread()->Activate(); +} + +void App::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args) +{ + // Save app state asynchronously after requesting a deferral. Holding a deferral + // indicates that the application is busy performing suspending operations. Be + // aware that a deferral may not be held indefinitely. After about five seconds, + // the app will be forced to exit. + SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral(); + + create_task([this, deferral]() + { + m_Main->OnSuspending(); + deferral->Complete(); + }); +} + +void App::OnResuming(Platform::Object^ sender, Platform::Object^ args) +{ + // Restore any data or state that was unloaded on suspend. By default, data + // and state are persisted when resuming from suspend. Note that this event + // does not occur if the app was previously terminated. + + m_Main->OnResuming(); +} + +// Window event handlers. + +void App::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args) +{ + if (auto DeviceResources = GetDeviceResources()) + { + DeviceResources->SetLogicalSize(Size(sender->Bounds.Width, sender->Bounds.Height)); + m_Main->OnWindowSizeChanged(); + } +} + +void App::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args) +{ + m_windowVisible = args->Visible; +} + +void App::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args) +{ + m_windowClosed = true; +} + +// DisplayInformation event handlers. + +void App::OnDpiChanged(DisplayInformation^ sender, Object^ args) +{ + // Note: The value for LogicalDpi retrieved here may not match the effective DPI of the app + // if it is being scaled for high resolution devices. Once the DPI is set on DeviceResources, + // you should always retrieve it using the GetDpi method. + // See DeviceResources.cpp for more details. + if (auto DeviceResources = GetDeviceResources()) + { + DeviceResources->SetDpi(sender->LogicalDpi); + m_Main->OnWindowSizeChanged(); + } +} + +void App::OnOrientationChanged(DisplayInformation^ sender, Object^ args) +{ + if (auto DeviceResources = GetDeviceResources()) + { + DeviceResources->SetCurrentOrientation(sender->CurrentOrientation); + m_Main->OnWindowSizeChanged(); + } +} + +void App::OnDisplayContentsInvalidated(DisplayInformation^ sender, Object^ args) +{ + if (auto DeviceResources = GetDeviceResources()) + { + DeviceResources->ValidateDevice(); + } +} + +void App::OnKeyDown(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args) +{ + auto Key = args->VirtualKey; + switch(Key) + { + case VirtualKey::Escape: + CoreApplication::Exit(); + break; + + case VirtualKey::Enter: + if(m_bShiftPressed) + { + auto applicationView = Windows::UI::ViewManagement::ApplicationView::GetForCurrentView(); + if (applicationView->IsFullScreenMode) + { + applicationView->ExitFullScreenMode(); + } + else + { + applicationView->TryEnterFullScreenMode(); + } + } + break; + + case VirtualKey::Shift: + m_bShiftPressed = true; + break; + } +} + +void App::OnKeyUp(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args) +{ + auto Key = args->VirtualKey; + switch (Key) + { + case VirtualKey::Shift: + m_bShiftPressed = false; + break; + } +} + +std::shared_ptr<DX::DeviceResources> App::GetDeviceResources() +{ + if (m_deviceResources != nullptr && m_deviceResources->IsDeviceRemoved()) + { + // All references to the existing D3D device must be released before a new device + // can be created. + + m_deviceResources = nullptr; + m_Main->OnDeviceRemoved(); + +#if defined(_DEBUG) + ComPtr<IDXGIDebug1> dxgiDebug; + if (SUCCEEDED(DXGIGetDebugInterface1(0, IID_PPV_ARGS(&dxgiDebug)))) + { + dxgiDebug->ReportLiveObjects(DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_FLAGS(DXGI_DEBUG_RLO_SUMMARY | DXGI_DEBUG_RLO_IGNORE_INTERNAL)); + } +#endif + } + + if (m_deviceResources == nullptr) + { + m_deviceResources = m_Main->InitDeviceResources(); + if (m_deviceResources) + { + m_deviceResources->SetWindow(CoreWindow::GetForCurrentThread()); + auto Title = Diligent::WidenString(m_Main->GetAppTitle()); + Windows::UI::ViewManagement::ApplicationView::GetForCurrentView()->Title = ref new Platform::String(Title.c_str()); + m_Main->OnWindowSizeChanged(); + m_Main->CreateRenderers(); + } + } + return m_deviceResources; +} diff --git a/NativeApp/src/UWP/App.h b/NativeApp/src/UWP/App.h new file mode 100644 index 0000000..4f31f07 --- /dev/null +++ b/NativeApp/src/UWP/App.h @@ -0,0 +1,71 @@ +/* Copyright 2015-2016 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +#include "Common\DeviceResources.h" +#include "NativeAppBase.h" + +namespace SampleApp +{ + // Main entry point for our app. Connects the app with the Windows shell and handles application lifecycle events. + ref class App sealed : public Windows::ApplicationModel::Core::IFrameworkView + { + public: + App(); + + // IFrameworkView methods. + virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView); + virtual void SetWindow(Windows::UI::Core::CoreWindow^ window); + virtual void Load(Platform::String^ entryPoint); + virtual void Run(); + virtual void Uninitialize(); + + protected: + // Application lifecycle event handlers. + void OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args); + void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args); + void OnResuming(Platform::Object^ sender, Platform::Object^ args); + + // Window event handlers. + void OnWindowSizeChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ args); + void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args); + void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args); + + // DisplayInformation event handlers. + void OnDpiChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args); + void OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args); + void OnDisplayContentsInvalidated(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args); + + void OnKeyDown(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args); + void OnKeyUp(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args); + + private: + std::shared_ptr<DX::DeviceResources> GetDeviceResources(); + std::unique_ptr<Diligent::NativeAppBase> m_Main; + std::shared_ptr<DX::DeviceResources> m_deviceResources; + bool m_windowClosed = false; + bool m_windowVisible = false; + bool m_bShiftPressed = false; + }; +} diff --git a/NativeApp/src/UWP/Common/DeviceResources.cpp b/NativeApp/src/UWP/Common/DeviceResources.cpp new file mode 100644 index 0000000..c111a54 --- /dev/null +++ b/NativeApp/src/UWP/Common/DeviceResources.cpp @@ -0,0 +1,328 @@ + +#define NOMINIMAX +#include <wrl.h> +#include <wrl/client.h> +#include <DirectXMath.h> +#include <agile.h> + +#include <dxgi1_4.h> +#include <d3d12.h> +#include <d3d11.h> +#include <pix.h> + +#if defined(_DEBUG) +# include <dxgidebug.h> +#endif + +#include "DeviceResources.h" +#include "DirectXHelper.h" + + +using namespace DirectX; +using namespace Microsoft::WRL; +using namespace Windows::Foundation; +using namespace Windows::Graphics::Display; +using namespace Windows::UI::Core; +using namespace Windows::UI::Xaml::Controls; +using namespace Platform; + +namespace DisplayMetrics +{ + // High resolution displays can require a lot of GPU and battery power to render. + // High resolution phones, for example, may suffer from poor battery life if + // games attempt to render at 60 frames per second at full fidelity. + // The decision to render at full fidelity across all platforms and form factors + // should be deliberate. + static const bool SupportHighResolutions = false; + + // The default thresholds that define a "high resolution" display. If the thresholds + // are exceeded and SupportHighResolutions is false, the dimensions will be scaled + // by 50%. + static const float DpiThreshold = 192.0f; // 200% of standard desktop display. + static const float WidthThreshold = 1920.0f; // 1080p width. + static const float HeightThreshold = 1080.0f; // 1080p height. +}; + +// Constants used to calculate screen rotations. +namespace ScreenRotation +{ + // 0-degree Z-rotation + static const XMFLOAT4X4 Rotation0( + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + ); + + // 90-degree Z-rotation + static const XMFLOAT4X4 Rotation90( + 0.0f, 1.0f, 0.0f, 0.0f, + -1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + ); + + // 180-degree Z-rotation + static const XMFLOAT4X4 Rotation180( + -1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, -1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + ); + + // 270-degree Z-rotation + static const XMFLOAT4X4 Rotation270( + 0.0f, -1.0f, 0.0f, 0.0f, + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + ); +}; + +// Constructor for DeviceResources. +DX::DeviceResources::DeviceResources(ID3D11Device *d3d11Device, ID3D12Device *d3d12Device) : + m_d3dRenderTargetSize(), + m_outputSize(), + m_logicalSize(), + m_nativeOrientation(DisplayOrientations::None), + m_currentOrientation(DisplayOrientations::None), + m_dpi(-1.0f), + m_deviceRemoved(false), + m_d3d11Device(d3d11Device), + m_d3d12Device(d3d12Device) +{ +} + + +void DX::DeviceResources::SetSwapChainRotation(IDXGISwapChain3 *swapChain) +{ + // Set the proper orientation for the swap chain, and generate + // 3D matrix transformations for rendering to the rotated swap chain. + // The 3D matrix is specified explicitly to avoid rounding errors. + DXGI_MODE_ROTATION displayRotation = ComputeDisplayRotation(); + switch (displayRotation) + { + case DXGI_MODE_ROTATION_IDENTITY: + m_orientationTransform3D = ScreenRotation::Rotation0; + break; + + case DXGI_MODE_ROTATION_ROTATE90: + m_orientationTransform3D = ScreenRotation::Rotation270; + break; + + case DXGI_MODE_ROTATION_ROTATE180: + m_orientationTransform3D = ScreenRotation::Rotation180; + break; + + case DXGI_MODE_ROTATION_ROTATE270: + m_orientationTransform3D = ScreenRotation::Rotation90; + break; + + default: + throw ref new FailureException(); + } + + DX::ThrowIfFailed( + swapChain->SetRotation(displayRotation) + ); +} + +// Determine the dimensions of the render target and whether it will be scaled down. +void DX::DeviceResources::UpdateRenderTargetSize() +{ + m_effectiveDpi = m_dpi; + + // To improve battery life on high resolution devices, render to a smaller render target + // and allow the GPU to scale the output when it is presented. + if (!DisplayMetrics::SupportHighResolutions && m_dpi > DisplayMetrics::DpiThreshold) + { + float width = DX::ConvertDipsToPixels(m_logicalSize.Width, m_dpi); + float height = DX::ConvertDipsToPixels(m_logicalSize.Height, m_dpi); + + // When the device is in portrait orientation, height > width. Compare the + // larger dimension against the width threshold and the smaller dimension + // against the height threshold. + if (max(width, height) > DisplayMetrics::WidthThreshold && min(width, height) > DisplayMetrics::HeightThreshold) + { + // To scale the app we change the effective DPI. Logical size does not change. + m_effectiveDpi /= 2.0f; + } + } + + // Calculate the necessary render target size in pixels. + m_outputSize.Width = DX::ConvertDipsToPixels(m_logicalSize.Width, m_effectiveDpi); + m_outputSize.Height = DX::ConvertDipsToPixels(m_logicalSize.Height, m_effectiveDpi); + + // Prevent zero size DirectX content from being created. + m_outputSize.Width = max(m_outputSize.Width, 1); + m_outputSize.Height = max(m_outputSize.Height, 1); + + + // The width and height of the swap chain must be based on the window's + // natively-oriented width and height. If the window is not in the native + // orientation, the dimensions must be reversed. + DXGI_MODE_ROTATION displayRotation = ComputeDisplayRotation(); + + bool swapDimensions = displayRotation == DXGI_MODE_ROTATION_ROTATE90 || displayRotation == DXGI_MODE_ROTATION_ROTATE270; + auto fWidth = swapDimensions ? m_outputSize.Height : m_outputSize.Width; + auto fHeight = swapDimensions ? m_outputSize.Width : m_outputSize.Height; + + m_backBufferWidth = lround(fWidth); + m_backBufferHeight = lround(fHeight); +} + +// This method is called when the CoreWindow is created (or re-created). +void DX::DeviceResources::SetWindow(CoreWindow^ window) +{ + DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView(); + + m_window = window; + m_logicalSize = Windows::Foundation::Size(window->Bounds.Width, window->Bounds.Height); + m_nativeOrientation = currentDisplayInformation->NativeOrientation; + m_currentOrientation = currentDisplayInformation->CurrentOrientation; + m_dpi = currentDisplayInformation->LogicalDpi; + + //CreateWindowSizeDependentResources(); +} + +// This method is called in the event handler for the SizeChanged event. +void DX::DeviceResources::SetLogicalSize(Windows::Foundation::Size logicalSize) +{ + if (m_logicalSize != logicalSize) + { + m_logicalSize = logicalSize; + //CreateWindowSizeDependentResources(); + } +} + +// This method is called in the event handler for the DpiChanged event. +void DX::DeviceResources::SetDpi(float dpi) +{ + if (dpi != m_dpi) + { + m_dpi = dpi; + + // When the display DPI changes, the logical size of the window (measured in Dips) also changes and needs to be updated. + m_logicalSize = Windows::Foundation::Size(m_window->Bounds.Width, m_window->Bounds.Height); + + //CreateWindowSizeDependentResources(); + } +} + +// This method is called in the event handler for the OrientationChanged event. +void DX::DeviceResources::SetCurrentOrientation(DisplayOrientations currentOrientation) +{ + if (m_currentOrientation != currentOrientation) + { + m_currentOrientation = currentOrientation; + //CreateWindowSizeDependentResources(); + } +} + +// This method is called in the event handler for the DisplayContentsInvalidated event. +void DX::DeviceResources::ValidateDevice() +{ + // The D3D Device is no longer valid if the default adapter changed since the device + // was created or if the device has been removed. + + ComPtr<IDXGIDevice3> dxgiDevice; + if(m_d3d11Device) + DX::ThrowIfFailed(m_d3d11Device.As(&dxgiDevice)); + else if(m_d3d12Device) + DX::ThrowIfFailed(m_d3d12Device.As(&dxgiDevice)); + + ComPtr<IDXGIAdapter> deviceAdapter; + DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter)); + + ComPtr<IDXGIFactory2> deviceFactory; + DX::ThrowIfFailed(deviceAdapter->GetParent(IID_PPV_ARGS(&deviceFactory))); + + // First, get the LUID for the default adapter from when the device was created. + + DXGI_ADAPTER_DESC previousDesc; + { + ComPtr<IDXGIAdapter1> previousDefaultAdapter; + DX::ThrowIfFailed(deviceFactory->EnumAdapters1(0, &previousDefaultAdapter)); + + DX::ThrowIfFailed(previousDefaultAdapter->GetDesc(&previousDesc)); + } + + // Next, get the information for the current default adapter. + + DXGI_ADAPTER_DESC currentDesc; + { + ComPtr<IDXGIFactory4> currentDxgiFactory; + DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(¤tDxgiFactory))); + + ComPtr<IDXGIAdapter1> currentDefaultAdapter; + DX::ThrowIfFailed(currentDxgiFactory->EnumAdapters1(0, ¤tDefaultAdapter)); + + DX::ThrowIfFailed(currentDefaultAdapter->GetDesc(¤tDesc)); + } + + // If the adapter LUIDs don't match, or if the device reports that it has been removed, + // a new D3D device must be created. + + if (previousDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart || + previousDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart || + m_d3d11Device && FAILED(m_d3d11Device->GetDeviceRemovedReason()) || + m_d3d12Device && FAILED(m_d3d12Device->GetDeviceRemovedReason())) + { + m_deviceRemoved = true; + } +} + +// This method determines the rotation between the display device's native Orientation and the +// current display orientation. +DXGI_MODE_ROTATION DX::DeviceResources::ComputeDisplayRotation() +{ + DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED; + + // Note: NativeOrientation can only be Landscape or Portrait even though + // the DisplayOrientations enum has other values. + switch (m_nativeOrientation) + { + case DisplayOrientations::Landscape: + switch (m_currentOrientation) + { + case DisplayOrientations::Landscape: + rotation = DXGI_MODE_ROTATION_IDENTITY; + break; + + case DisplayOrientations::Portrait: + rotation = DXGI_MODE_ROTATION_ROTATE270; + break; + + case DisplayOrientations::LandscapeFlipped: + rotation = DXGI_MODE_ROTATION_ROTATE180; + break; + + case DisplayOrientations::PortraitFlipped: + rotation = DXGI_MODE_ROTATION_ROTATE90; + break; + } + break; + + case DisplayOrientations::Portrait: + switch (m_currentOrientation) + { + case DisplayOrientations::Landscape: + rotation = DXGI_MODE_ROTATION_ROTATE90; + break; + + case DisplayOrientations::Portrait: + rotation = DXGI_MODE_ROTATION_IDENTITY; + break; + + case DisplayOrientations::LandscapeFlipped: + rotation = DXGI_MODE_ROTATION_ROTATE270; + break; + + case DisplayOrientations::PortraitFlipped: + rotation = DXGI_MODE_ROTATION_ROTATE180; + break; + } + break; + } + return rotation; +} diff --git a/NativeApp/src/UWP/Common/DeviceResources.h b/NativeApp/src/UWP/Common/DeviceResources.h new file mode 100644 index 0000000..69fa00c --- /dev/null +++ b/NativeApp/src/UWP/Common/DeviceResources.h @@ -0,0 +1,72 @@ +#pragma once + +#include <dxgi1_4.h> +#include <d3d12.h> +#include <d3d11.h> +#include <DirectXMath.h> +#include <agile.h> + +namespace DX +{ + // Controls all the DirectX device resources. + class DeviceResources + { + public: + DeviceResources(ID3D11Device *d3d11Device, ID3D12Device *d3d12Device); + + void SetWindow(Windows::UI::Core::CoreWindow^ window); + void SetLogicalSize(Windows::Foundation::Size logicalSize); + void SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation); + void SetDpi(float dpi); + void ValidateDevice(); + void SetSwapChainRotation(IDXGISwapChain3 *swapChain); + + // The size of the render target, in pixels. + Windows::Foundation::Size GetOutputSize() const { return m_outputSize; } + + // The size of the render target, in dips. + Windows::Foundation::Size GetLogicalSize() const { return m_logicalSize; } + + float GetDpi() const { return m_effectiveDpi; } + bool IsDeviceRemoved() const { return m_deviceRemoved; } + + // D3D Accessors. + DirectX::XMFLOAT4X4 GetOrientationTransform3D() const { return m_orientationTransform3D; } + + void UpdateRenderTargetSize(); + UINT GetBackBufferWidth() {return m_backBufferWidth;} + UINT GetBackBufferHeight() {return m_backBufferHeight;} + + Windows::UI::Core::CoreWindow^ GetWindow(){return m_window.Get();} + + private: + + + DXGI_MODE_ROTATION ComputeDisplayRotation(); + + bool m_deviceRemoved; + + // Direct3D objects. + Microsoft::WRL::ComPtr<ID3D12Device> m_d3d12Device; + Microsoft::WRL::ComPtr<ID3D11Device> m_d3d11Device; + + // Cached reference to the Window. + Platform::Agile<Windows::UI::Core::CoreWindow> m_window; + + // Cached device properties. + Windows::Foundation::Size m_d3dRenderTargetSize; + Windows::Foundation::Size m_outputSize; + Windows::Foundation::Size m_logicalSize; + Windows::Graphics::Display::DisplayOrientations m_nativeOrientation; + Windows::Graphics::Display::DisplayOrientations m_currentOrientation; + float m_dpi; + UINT m_backBufferWidth = 0; + UINT m_backBufferHeight = 0; + + // This is the DPI that will be reported back to the app. It takes into account whether the app supports high resolution screens or not. + float m_effectiveDpi; + + // Transforms used for display orientation. + DirectX::XMFLOAT4X4 m_orientationTransform3D; + }; +} diff --git a/NativeApp/src/UWP/Common/DirectXHelper.h b/NativeApp/src/UWP/Common/DirectXHelper.h new file mode 100644 index 0000000..7bfe36f --- /dev/null +++ b/NativeApp/src/UWP/Common/DirectXHelper.h @@ -0,0 +1,58 @@ +#pragma once + +#include <ppltasks.h> // For create_task + +namespace DX +{ + inline void ThrowIfFailed(HRESULT hr) + { + if (FAILED(hr)) + { + // Set a breakpoint on this line to catch Win32 API errors. + throw Platform::Exception::CreateException(hr); + } + } + + // Function that reads from a binary file asynchronously. + inline Concurrency::task<std::vector<byte>> ReadDataAsync(const std::wstring& filename) + { + using namespace Windows::Storage; + using namespace Concurrency; + + auto folder = Windows::ApplicationModel::Package::Current->InstalledLocation; + + return create_task(folder->GetFileAsync(Platform::StringReference(filename.c_str()))).then([](StorageFile^ file) + { + return FileIO::ReadBufferAsync(file); + }).then([](Streams::IBuffer^ fileBuffer) -> std::vector<byte> + { + std::vector<byte> returnBuffer; + returnBuffer.resize(fileBuffer->Length); + Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(Platform::ArrayReference<byte>(returnBuffer.data(), fileBuffer->Length)); + return returnBuffer; + }); + } + + // Converts a length in device-independent pixels (DIPs) to a length in physical pixels. + inline float ConvertDipsToPixels(float dips, float dpi) + { + static const float dipsPerInch = 96.0f; + return floorf(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer. + } + + // Assign a name to the object to aid with debugging. +#if defined(_DEBUG) + inline void SetName(ID3D12Object* pObject, LPCWSTR name) + { + pObject->SetName(name); + } +#else + inline void SetName(ID3D12Object*, LPCWSTR) + { + } +#endif +} + +// Naming helper function for ComPtr<T>. +// Assigns the name of the variable as the name of the object. +#define NAME_D3D12_OBJECT(x) DX::SetName(x.Get(), L#x) diff --git a/NativeApp/src/UWP/Common/StepTimer.h b/NativeApp/src/UWP/Common/StepTimer.h new file mode 100644 index 0000000..c8addbc --- /dev/null +++ b/NativeApp/src/UWP/Common/StepTimer.h @@ -0,0 +1,183 @@ +#pragma once + +#include <wrl.h> + +namespace DX +{ + // Helper class for animation and simulation timing. + class StepTimer + { + public: + StepTimer() : + m_elapsedTicks(0), + m_totalTicks(0), + m_leftOverTicks(0), + m_frameCount(0), + m_framesPerSecond(0), + m_framesThisSecond(0), + m_qpcSecondCounter(0), + m_isFixedTimeStep(false), + m_targetElapsedTicks(TicksPerSecond / 60) + { + if (!QueryPerformanceFrequency(&m_qpcFrequency)) + { + throw ref new Platform::FailureException(); + } + + if (!QueryPerformanceCounter(&m_qpcLastTime)) + { + throw ref new Platform::FailureException(); + } + + // Initialize max delta to 1/10 of a second. + m_qpcMaxDelta = m_qpcFrequency.QuadPart / 10; + } + + // Get elapsed time since the previous Update call. + uint64 GetElapsedTicks() const { return m_elapsedTicks; } + double GetElapsedSeconds() const { return TicksToSeconds(m_elapsedTicks); } + + // Get total time since the start of the program. + uint64 GetTotalTicks() const { return m_totalTicks; } + double GetTotalSeconds() const { return TicksToSeconds(m_totalTicks); } + + // Get total number of updates since start of the program. + uint32 GetFrameCount() const { return m_frameCount; } + + // Get the current framerate. + uint32 GetFramesPerSecond() const { return m_framesPerSecond; } + + // Set whether to use fixed or variable timestep mode. + void SetFixedTimeStep(bool isFixedTimestep) { m_isFixedTimeStep = isFixedTimestep; } + + // Set how often to call Update when in fixed timestep mode. + void SetTargetElapsedTicks(uint64 targetElapsed) { m_targetElapsedTicks = targetElapsed; } + void SetTargetElapsedSeconds(double targetElapsed) { m_targetElapsedTicks = SecondsToTicks(targetElapsed); } + + // Integer format represents time using 10,000,000 ticks per second. + static const uint64 TicksPerSecond = 10000000; + + static double TicksToSeconds(uint64 ticks) { return static_cast<double>(ticks) / TicksPerSecond; } + static uint64 SecondsToTicks(double seconds) { return static_cast<uint64>(seconds * TicksPerSecond); } + + // After an intentional timing discontinuity (for instance a blocking IO operation) + // call this to avoid having the fixed timestep logic attempt a set of catch-up + // Update calls. + + void ResetElapsedTime() + { + if (!QueryPerformanceCounter(&m_qpcLastTime)) + { + throw ref new Platform::FailureException(); + } + + m_leftOverTicks = 0; + m_framesPerSecond = 0; + m_framesThisSecond = 0; + m_qpcSecondCounter = 0; + } + + // Update timer state, calling the specified Update function the appropriate number of times. + template<typename TUpdate> + void Tick(const TUpdate& update) + { + // Query the current time. + LARGE_INTEGER currentTime; + + if (!QueryPerformanceCounter(¤tTime)) + { + throw ref new Platform::FailureException(); + } + + uint64 timeDelta = currentTime.QuadPart - m_qpcLastTime.QuadPart; + + m_qpcLastTime = currentTime; + m_qpcSecondCounter += timeDelta; + + // Clamp excessively large time deltas (e.g. after paused in the debugger). + if (timeDelta > m_qpcMaxDelta) + { + timeDelta = m_qpcMaxDelta; + } + + // Convert QPC units into a canonical tick format. This cannot overflow due to the previous clamp. + timeDelta *= TicksPerSecond; + timeDelta /= m_qpcFrequency.QuadPart; + + uint32 lastFrameCount = m_frameCount; + + if (m_isFixedTimeStep) + { + // Fixed timestep update logic + + // If the app is running very close to the target elapsed time (within 1/4 of a millisecond) just clamp + // the clock to exactly match the target value. This prevents tiny and irrelevant errors + // from accumulating over time. Without this clamping, a game that requested a 60 fps + // fixed update, running with vsync enabled on a 59.94 NTSC display, would eventually + // accumulate enough tiny errors that it would drop a frame. It is better to just round + // small deviations down to zero to leave things running smoothly. + + if (abs(static_cast<int64>(timeDelta - m_targetElapsedTicks)) < TicksPerSecond / 4000) + { + timeDelta = m_targetElapsedTicks; + } + + m_leftOverTicks += timeDelta; + + while (m_leftOverTicks >= m_targetElapsedTicks) + { + m_elapsedTicks = m_targetElapsedTicks; + m_totalTicks += m_targetElapsedTicks; + m_leftOverTicks -= m_targetElapsedTicks; + m_frameCount++; + + update(); + } + } + else + { + // Variable timestep update logic. + m_elapsedTicks = timeDelta; + m_totalTicks += timeDelta; + m_leftOverTicks = 0; + m_frameCount++; + + update(); + } + + // Track the current framerate. + if (m_frameCount != lastFrameCount) + { + m_framesThisSecond++; + } + + if (m_qpcSecondCounter >= static_cast<uint64>(m_qpcFrequency.QuadPart)) + { + m_framesPerSecond = m_framesThisSecond; + m_framesThisSecond = 0; + m_qpcSecondCounter %= m_qpcFrequency.QuadPart; + } + } + + private: + // Source timing data uses QPC units. + LARGE_INTEGER m_qpcFrequency; + LARGE_INTEGER m_qpcLastTime; + uint64 m_qpcMaxDelta; + + // Derived timing data uses a canonical tick format. + uint64 m_elapsedTicks; + uint64 m_totalTicks; + uint64 m_leftOverTicks; + + // Members for tracking the framerate. + uint32 m_frameCount; + uint32 m_framesPerSecond; + uint32 m_framesThisSecond; + uint64 m_qpcSecondCounter; + + // Members for configuring fixed timestep mode. + bool m_isFixedTimeStep; + uint64 m_targetElapsedTicks; + }; +} diff --git a/NativeApp/src/UWP/UWPAppBase.cpp b/NativeApp/src/UWP/UWPAppBase.cpp new file mode 100644 index 0000000..346b2bd --- /dev/null +++ b/NativeApp/src/UWP/UWPAppBase.cpp @@ -0,0 +1,50 @@ +/* Copyright 2015-2018 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#include "UWPAppBase.h" + +namespace Diligent +{ + +UWPAppBase::UWPAppBase() +{ + // TODO: Change the timer settings if you want something other than the default variable timestep mode. + // e.g. for 60 FPS fixed timestep update logic, call: + /* + m_timer.SetFixedTimeStep(true); + m_timer.SetTargetElapsedSeconds(1.0 / 60); + */ +} + +void UWPAppBase::Update() +{ + // Update scene objects. + m_timer.Tick([&]() + { + auto CurrTime = m_timer.GetTotalSeconds(); + auto ElapsedTime = m_timer.GetElapsedSeconds(); + Update(CurrTime, ElapsedTime); + }); +} + +} diff --git a/NativeApp/src/UWP/dummy.cpp b/NativeApp/src/UWP/dummy.cpp new file mode 100644 index 0000000..5caae53 --- /dev/null +++ b/NativeApp/src/UWP/dummy.cpp @@ -0,0 +1,7 @@ +#include "AppBase.h" + +// This dummy file is only required for the NativeAppBase.lib to be created, +// which is required to avoid linker error + +// We cannot add real source to this library because Windows Runtime types cannot +// be included into static libraries
\ No newline at end of file diff --git a/NativeApp/src/Win32/WinMain.cpp b/NativeApp/src/Win32/WinMain.cpp new file mode 100644 index 0000000..8f63460 --- /dev/null +++ b/NativeApp/src/Win32/WinMain.cpp @@ -0,0 +1,168 @@ +/* Copyright 2019 Diligent Graphics LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#include <memory> +#include <iomanip> +#include <Windows.h> +#include <crtdbg.h> +#include "NativeAppBase.h" +#include "StringTools.h" +#include "Timer.h" + +using namespace Diligent; + +std::unique_ptr<NativeAppBase> g_pTheApp; + +LRESULT CALLBACK MessageProc(HWND, UINT, WPARAM, LPARAM); +// Main +int WINAPI WinMain(HINSTANCE instance, HINSTANCE, LPSTR, int cmdShow) +{ +#if defined(_DEBUG) || defined(DEBUG) + _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); +#endif + + g_pTheApp.reset( CreateApplication() ); + + const auto* cmdLine = GetCommandLineA(); + g_pTheApp->ProcessCommandLine(cmdLine); + + const auto* AppTitle = g_pTheApp->GetAppTitle(); + +#ifdef UNICODE + const auto* const WindowClassName = L"SampleApp"; +#else + const auto* const WindowClassName = "SampleApp"; +#endif + + // Register our window class + WNDCLASSEX wcex = { sizeof(WNDCLASSEX), CS_HREDRAW|CS_VREDRAW, MessageProc, + 0L, 0L, instance, NULL, NULL, NULL, NULL, WindowClassName, NULL }; + RegisterClassEx(&wcex); + + int DesiredWidth = 0; + int DesiredHeight = 0; + g_pTheApp->GetDesiredInitialWindowSize(DesiredWidth, DesiredHeight); + // Create a window + LONG WindowWidth = DesiredWidth > 0 ? DesiredWidth : 1280; + LONG WindowHeight = DesiredHeight > 0 ? DesiredHeight : 1024; + RECT rc = { 0, 0, WindowWidth, WindowHeight }; + AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE); + HWND wnd = CreateWindowA("SampleApp", AppTitle, + WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, + rc.right-rc.left, rc.bottom-rc.top, NULL, NULL, instance, NULL); + if (!wnd) + { + MessageBoxA(NULL, "Cannot create window", "Error", MB_OK|MB_ICONERROR); + return 0; + } + ShowWindow(wnd, cmdShow); + UpdateWindow(wnd); + + g_pTheApp->OnWindowCreated(wnd, WindowWidth, WindowHeight); + AppTitle = g_pTheApp->GetAppTitle(); + + Diligent::Timer Timer; + auto PrevTime = Timer.GetElapsedTime(); + double filteredFrameTime = 0.0; + + // Main message loop + MSG msg = {0}; + while (WM_QUIT != msg.message) + { + if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) + { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + else + { + auto CurrTime = Timer.GetElapsedTime(); + auto ElapsedTime = CurrTime - PrevTime; + PrevTime = CurrTime; + g_pTheApp->Update(CurrTime, ElapsedTime); + + g_pTheApp->Render(); + + g_pTheApp->Present(); + + double filterScale = 0.2; + filteredFrameTime = filteredFrameTime * (1.0 - filterScale) + filterScale * ElapsedTime; + std::stringstream fpsCounterSS; + fpsCounterSS << AppTitle << " - " << std::fixed << std::setprecision(1) << filteredFrameTime * 1000; + fpsCounterSS << " ms (" << 1.0 / filteredFrameTime << " fps)"; + SetWindowTextA(wnd, fpsCounterSS.str().c_str()); + } + } + + g_pTheApp.reset(); + + return (int)msg.wParam; +} + +// Called every time the NativeNativeAppBase receives a message +LRESULT CALLBACK MessageProc(HWND wnd, UINT message, WPARAM wParam, LPARAM lParam) +{ + if(g_pTheApp) + { + auto res = g_pTheApp->HandleWin32Message(wnd, message, wParam, lParam); + if (res != 0) + return res; + } + + switch (message) + { + case WM_PAINT: + { + PAINTSTRUCT ps; + BeginPaint(wnd, &ps); + EndPaint(wnd, &ps); + return 0; + } + case WM_SIZE: // Window size has been changed + if( g_pTheApp ) + { + g_pTheApp->WindowResize(LOWORD(lParam), HIWORD(lParam)); + } + return 0; + + case WM_CHAR: + if (wParam == VK_ESCAPE) + PostQuitMessage(0); + return 0; + + case WM_DESTROY: + PostQuitMessage(0); + return 0; + + case WM_GETMINMAXINFO: + { + LPMINMAXINFO lpMMI = (LPMINMAXINFO)lParam; + lpMMI->ptMinTrackSize.x = 320; + lpMMI->ptMinTrackSize.y = 240; + return 0; + } + + default: + return DefWindowProc(wnd, message, wParam, lParam); + } +} |
