Added VR libraries

This commit is contained in:
Chris Midkiff
2018-10-08 23:54:11 -04:00
parent d9eb2a9763
commit 7ce1036e39
1037 changed files with 195630 additions and 348 deletions

View File

@@ -0,0 +1,371 @@
// Copyright 2017 Google Inc. All rights reserved.
//
// 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.
using UnityEngine;
using UnityEngine.EventSystems;
using Gvr.Internal;
using System;
using System.Collections;
using System.Collections.Generic;
// Events to update the keyboard.
// These values depend on C API keyboard values
public enum GvrKeyboardEvent {
/// Unknown error.
GVR_KEYBOARD_ERROR_UNKNOWN = 0,
/// The keyboard service could not be connected. This is usually due to the
/// keyboard service not being installed.
GVR_KEYBOARD_ERROR_SERVICE_NOT_CONNECTED = 1,
/// No locale was found in the keyboard service.
GVR_KEYBOARD_ERROR_NO_LOCALES_FOUND = 2,
/// The keyboard SDK tried to load dynamically but failed. This is usually due
/// to the keyboard service not being installed or being out of date.
GVR_KEYBOARD_ERROR_SDK_LOAD_FAILED = 3,
/// Keyboard becomes visible.
GVR_KEYBOARD_SHOWN = 4,
/// Keyboard becomes hidden.
GVR_KEYBOARD_HIDDEN = 5,
/// Text has been updated.
GVR_KEYBOARD_TEXT_UPDATED = 6,
/// Text has been committed.
GVR_KEYBOARD_TEXT_COMMITTED = 7,
};
// These values depend on C API keyboard values.
public enum GvrKeyboardError {
UNKNOWN = 0,
SERVICE_NOT_CONNECTED = 1,
NO_LOCALES_FOUND = 2,
SDK_LOAD_FAILED = 3
};
// These values depend on C API keyboard values.
public enum GvrKeyboardInputMode {
DEFAULT = 0,
NUMERIC = 1
};
// Handles keyboard state management such as hiding and displaying
// the keyboard, directly modifying text and stereoscopic rendering.
[HelpURL("https://developers.google.com/vr/unity/reference/class/GvrKeyboard")]
public class GvrKeyboard : MonoBehaviour {
private static GvrKeyboard instance;
private static IKeyboardProvider keyboardProvider;
private KeyboardState keyboardState = new KeyboardState();
private IEnumerator keyboardUpdate;
// Keyboard delegate types.
public delegate void StandardCallback();
public delegate void EditTextCallback(string edit_text);
public delegate void ErrorCallback(GvrKeyboardError err);
public delegate void KeyboardCallback(IntPtr closure, GvrKeyboardEvent evt);
// Private data and callbacks.
private ErrorCallback errorCallback = null;
private StandardCallback showCallback = null;
private StandardCallback hideCallback = null;
private EditTextCallback updateCallback = null;
private EditTextCallback enterCallback = null;
#if UNITY_ANDROID
// Which eye is currently being rendered.
private bool isRight = false;
#endif // UNITY_ANDROID
private bool isKeyboardHidden = false;
private const float kExecuterWait = 0.01f;
private static List<GvrKeyboardEvent> threadSafeCallbacks =
new List<GvrKeyboardEvent>();
private static System.Object callbacksLock = new System.Object();
// Public parameters.
public GvrKeyboardDelegateBase keyboardDelegate = null;
public GvrKeyboardInputMode inputMode = GvrKeyboardInputMode.DEFAULT;
public bool useRecommended = true;
public float distance = 0;
public string EditorText {
get { return instance != null ? instance.keyboardState.editorText : string.Empty; }
set { keyboardProvider.EditorText = value; }
}
public GvrKeyboardInputMode Mode {
get { return instance != null ? instance.keyboardState.mode : GvrKeyboardInputMode.DEFAULT; }
}
public bool IsValid {
get { return instance != null ? instance.keyboardState.isValid : false; }
}
public bool IsReady {
get { return instance != null ? instance.keyboardState.isReady : false; }
}
public Matrix4x4 WorldMatrix {
get { return instance != null ? instance.keyboardState.worldMatrix : Matrix4x4.zero; }
}
void Awake() {
if (instance != null) {
Debug.LogError("More than one GvrKeyboard instance was found in your scene. "
+ "Ensure that there is only one GvrKeyboard.");
enabled = false;
return;
}
instance = this;
if (keyboardProvider == null) {
keyboardProvider = KeyboardProviderFactory.CreateKeyboardProvider(this);
}
}
void OnDestroy() {
instance = null;
threadSafeCallbacks.Clear();
}
// Use this for initialization.
void Start() {
if (keyboardDelegate != null) {
errorCallback = keyboardDelegate.OnKeyboardError;
showCallback = keyboardDelegate.OnKeyboardShow;
hideCallback = keyboardDelegate.OnKeyboardHide;
updateCallback = keyboardDelegate.OnKeyboardUpdate;
enterCallback = keyboardDelegate.OnKeyboardEnterPressed;
keyboardDelegate.KeyboardHidden += KeyboardDelegate_KeyboardHidden;
keyboardDelegate.KeyboardShown += KeyboardDelegate_KeyboardShown;
}
keyboardProvider.ReadState(keyboardState);
if (IsValid) {
if (keyboardProvider.Create(OnKeyboardCallback)) {
keyboardProvider.SetInputMode(inputMode);
}
} else {
Debug.LogError("Could not validate keyboard");
}
}
// Update per-frame data.
void Update() {
if (keyboardProvider == null) {
return;
}
keyboardProvider.ReadState(keyboardState);
if (IsReady) {
// Reset position of keyboard.
if (transform.hasChanged) {
Show();
transform.hasChanged = false;
}
keyboardProvider.UpdateData();
}
}
// Use this function for procedural rendering
// Gets called twice per frame, once for each eye.
// On each frame, left eye renders before right eye so
// we keep track of a boolean that toggles back and forth
// between each eye.
void OnRenderObject() {
if (keyboardProvider == null || !IsReady) {
return;
}
#if UNITY_ANDROID
Camera camera = Camera.current;
if (camera && camera == Camera.main) {
// Get current eye.
Camera.StereoscopicEye camEye = isRight ? Camera.StereoscopicEye.Right : Camera.StereoscopicEye.Left;
// Camera matrices.
Matrix4x4 proj = camera.GetStereoProjectionMatrix(camEye);
Matrix4x4 modelView = camera.GetStereoViewMatrix(camEye);
// Camera viewport.
Rect viewport = camera.pixelRect;
// Render keyboard.
keyboardProvider.Render((int) camEye, modelView, proj, viewport);
// Swap.
isRight = !isRight;
}
#endif // !UNITY_ANDROID
}
// Resets keyboard text.
public void ClearText() {
if (keyboardProvider != null) {
keyboardProvider.EditorText = string.Empty;
}
}
public void Show() {
if (keyboardProvider == null) {
return;
}
// Get user matrix.
Quaternion fixRot = new Quaternion(transform.rotation.x * -1, transform.rotation.y * -1,
transform.rotation.z, transform.rotation.w);
// Need to convert from left handed to right handed for the Keyboard coordinates.
Vector3 fixPos = new Vector3(transform.position.x, transform.position.y,
transform.position.z * -1);
Matrix4x4 modelMatrix = Matrix4x4.TRS(fixPos, fixRot, Vector3.one);
Matrix4x4 mat = Matrix4x4.identity;
Vector3 position = gameObject.transform.position;
if (position.x == 0 && position.y == 0 && position.z == 0 && !useRecommended) {
// Force use recommended to be true, otherwise keyboard won't show up.
keyboardProvider.Show(mat, true, distance, modelMatrix);
return;
}
// Matrix needs to be set only if we're not using the recommended one.
// Uses the values of the keyboard gameobject transform as reported by Unity. If this is
// the zero vector, parent it under another gameobject instead.
if (!useRecommended) {
mat = GetKeyboardObjectMatrix(position);
}
keyboardProvider.Show(mat, useRecommended, distance, modelMatrix);
}
public void Hide() {
if (keyboardProvider != null) {
keyboardProvider.Hide();
}
}
public void OnPointerClick(BaseEventData data) {
if (isKeyboardHidden) {
Show();
}
}
void OnEnable() {
keyboardUpdate = Executer();
StartCoroutine(keyboardUpdate);
}
void OnDisable() {
StopCoroutine(keyboardUpdate);
}
void OnApplicationPause(bool paused) {
if (null == keyboardProvider) return;
if (paused) {
keyboardProvider.OnPause();
} else {
keyboardProvider.OnResume();
}
}
IEnumerator Executer() {
while (true) {
yield return new WaitForSeconds(kExecuterWait);
while (threadSafeCallbacks.Count > 0) {
GvrKeyboardEvent keyboardEvent = threadSafeCallbacks[0];
PoolKeyboardCallbacks(keyboardEvent);
lock (callbacksLock) {
threadSafeCallbacks.RemoveAt(0);
}
}
}
}
private void PoolKeyboardCallbacks(GvrKeyboardEvent keyboardEvent) {
switch (keyboardEvent) {
case GvrKeyboardEvent.GVR_KEYBOARD_ERROR_UNKNOWN:
errorCallback(GvrKeyboardError.UNKNOWN);
break;
case GvrKeyboardEvent.GVR_KEYBOARD_ERROR_SERVICE_NOT_CONNECTED:
errorCallback(GvrKeyboardError.SERVICE_NOT_CONNECTED);
break;
case GvrKeyboardEvent.GVR_KEYBOARD_ERROR_NO_LOCALES_FOUND:
errorCallback(GvrKeyboardError.NO_LOCALES_FOUND);
break;
case GvrKeyboardEvent.GVR_KEYBOARD_ERROR_SDK_LOAD_FAILED:
errorCallback(GvrKeyboardError.SDK_LOAD_FAILED);
break;
case GvrKeyboardEvent.GVR_KEYBOARD_SHOWN:
showCallback();
break;
case GvrKeyboardEvent.GVR_KEYBOARD_HIDDEN:
hideCallback();
break;
case GvrKeyboardEvent.GVR_KEYBOARD_TEXT_UPDATED:
updateCallback(keyboardProvider.EditorText);
break;
case GvrKeyboardEvent.GVR_KEYBOARD_TEXT_COMMITTED:
enterCallback(keyboardProvider.EditorText);
break;
}
}
[AOT.MonoPInvokeCallback(typeof(GvrKeyboardEvent))]
private static void OnKeyboardCallback(IntPtr closure, GvrKeyboardEvent keyboardEvent) {
lock (callbacksLock) {
threadSafeCallbacks.Add(keyboardEvent);
}
}
private void KeyboardDelegate_KeyboardShown(object sender, System.EventArgs e) {
isKeyboardHidden = false;
}
private void KeyboardDelegate_KeyboardHidden(object sender, System.EventArgs e) {
isKeyboardHidden = true;
}
// Returns a matrix populated by the keyboard's gameobject position. If the position is not
// zero, but comes back as zero, parent this under another gameobject instead.
private Matrix4x4 GetKeyboardObjectMatrix(Vector3 position) {
// Set keyboard position based on this gameObject's position.
float angleX = Mathf.Atan2(position.y, position.x);
float kTanAngleX = Mathf.Tan(angleX);
float newPosX = kTanAngleX * position.x;
float angleY = Mathf.Atan2(position.x, position.y);
float kTanAngleY = Mathf.Tan(angleY);
float newPosY = kTanAngleY * position.y;
float angleZ = Mathf.Atan2(position.y, position.z);
float kTanAngleZ = Mathf.Tan(angleZ);
float newPosZ = kTanAngleZ * position.z;
Vector3 keyboardPosition = new Vector3(newPosX, newPosY, newPosZ);
Vector3 lookPosition = Camera.main.transform.position;
Quaternion rotation = Quaternion.LookRotation(lookPosition);
Matrix4x4 mat = new Matrix4x4();
mat.SetTRS(keyboardPosition, rotation, position);
// Set diagonal to identity if any of them are zero.
if (mat[0, 0] == 0) {
Vector4 row0 = mat.GetRow(0);
mat.SetRow(0, new Vector4(1, row0.y, row0.z, row0.w));
}
if (mat[1, 1] == 0) {
Vector4 row1 = mat.GetRow(1);
mat.SetRow(1, new Vector4(row1.x, 1, row1.z, row1.w));
}
if (mat[2, 2] == 0) {
Vector4 row2 = mat.GetRow(2);
mat.SetRow(2, new Vector4(row2.x, row2.y, 1, row2.w));
}
return mat;
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 573e2b04dc4734d68a2b6747421ce0bc
timeCreated: 1478820921
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,35 @@
// Copyright 2017 Google Inc. All rights reserved.
//
// 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.
using UnityEngine;
using System;
// This is an abstract class instead of an interface so that it can be exposed in Unity's
// editor. It inherits from MonoBehaviour so that it can be directly used as a game object.
public abstract class GvrKeyboardDelegateBase : MonoBehaviour {
public abstract void OnKeyboardShow();
public abstract void OnKeyboardHide();
public abstract void OnKeyboardUpdate(string edit_text);
public abstract void OnKeyboardEnterPressed(string edit_text);
public abstract void OnKeyboardError(GvrKeyboardError errorCode);
public abstract event EventHandler KeyboardHidden;
public abstract event EventHandler KeyboardShown;
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 3590c93395a39449ca11509317375cea
timeCreated: 1478820262
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,99 @@
// Copyright 2017 Google Inc. All rights reserved.
//
// 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.
using UnityEngine;
using System;
public class GvrKeyboardIntent {
#if UNITY_ANDROID && !UNITY_EDITOR
// The Play Store intent is requested via an Android Activity Fragment Java object.
private AndroidJavaObject keyboardFragment = null;
#endif // UNITY_ANDROID && !UNITY_EDITOR
// Constants used via JNI to access the keyboard fragment.
private const string FRAGMENT_CLASSNAME =
"com.google.gvr.keyboardsupport.KeyboardFragment";
private const string CALLBACK_CLASSNAME = FRAGMENT_CLASSNAME +
"$KeyboardCallback";
// Singleton instance.
private static GvrKeyboardIntent theInstance;
/// The singleton instance of the PermissionsRequester class,
/// lazily instantiated.
public static GvrKeyboardIntent Instance {
get {
if (theInstance == null) {
theInstance = new GvrKeyboardIntent();
if (!theInstance.InitializeFragment()) {
Debug.LogError("Cannot initialize fragment!");
theInstance = null;
}
}
return theInstance;
}
}
/// <summary>
/// Initializes the fragment via JNI.
/// </summary>
/// <returns>True if fragment was initialized.</returns>
protected bool InitializeFragment() {
#if !UNITY_ANDROID || UNITY_EDITOR
Debug.LogWarning("GvrKeyboardIntent requires the Android runtime environment");
return false;
#else
AndroidJavaClass ajc = new AndroidJavaClass(FRAGMENT_CLASSNAME);
if (ajc != null) {
// Get the KeyboardFragment object
keyboardFragment = ajc.CallStatic<AndroidJavaObject>("getInstance",
GvrActivityHelper.GetActivity());
}
return keyboardFragment != null &&
keyboardFragment.GetRawObject() != IntPtr.Zero;
#endif // !UNITY_ANDROID || UNITY_EDITOR
}
public void LaunchPlayStore() {
#if !UNITY_ANDROID || UNITY_EDITOR
Debug.LogError("GvrKeyboardIntent requires the Android runtime environment");
#else
KeyboardCallback cb = new KeyboardCallback();
keyboardFragment.Call("launchPlayStore", cb);
#endif // !UNITY_ANDROID || UNITY_EDITOR
}
/// <summary>
/// Keyboard callback implementation.
/// </summary>
/// <remarks>Instances of this class are passed to the java fragment and then
/// invoked once the request process is completed by the user.
/// </remarks>
class KeyboardCallback : AndroidJavaProxy {
internal KeyboardCallback() : base(CALLBACK_CLASSNAME) {
}
/// <summary>
/// Called when then flow is completed.
/// </summary>
void onPlayStoreResult() {
Application.Quit();
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 75e29b2b7f39fc5489e792b0f3338c79
timeCreated: 1494440249
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 4ef5f024c2ab92847a201d444256a76b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,48 @@
// Copyright 2017 Google Inc. All rights reserved.
//
// 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.
using UnityEngine;
namespace Gvr.Internal {
/// Internal interface that abstracts an implementation of a keyboard.
///
/// Each platform has a different concrete implementation of a Keyboard Provider.
/// For example, if running on the Unity Editor, we use an implementation that
/// emulates the keyboard behaviour. If running on a real Android device,
/// we use an implementation that uses the underlying Daydream keyboard API.
interface IKeyboardProvider {
/// Notifies the controller provider that the application has paused.
void OnPause();
/// Notifies the controller provider that the application has resumed.
void OnResume();
/// Reads the controller's current state and stores it in outState.
void ReadState(KeyboardState outState);
bool Create(GvrKeyboard.KeyboardCallback keyboardEvent);
void UpdateData();
void Render(int eye, Matrix4x4 modelview, Matrix4x4 projection, Rect viewport);
void Hide();
void Show(Matrix4x4 controllerMatrix, bool useRecommended, float distance, Matrix4x4 model);
void SetInputMode(GvrKeyboardInputMode mode);
string EditorText { get; set; }
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 1f16e78d5a8cbe946b9dbaad22815581
timeCreated: 1491935011
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,36 @@
// Copyright 2017 Google Inc. All rights reserved.
//
// 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.
using UnityEngine;
namespace Gvr.Internal {
/// Factory that provides a concrete implementation of IKeyboardProvider for the
/// current platform.
static class KeyboardProviderFactory {
static internal IKeyboardProvider CreateKeyboardProvider(GvrKeyboard owner)
{
// Use emulator in editor.
#if UNITY_EDITOR
return new EmulatorKeyboardProvider();
#elif UNITY_ANDROID
// Running on an Android device.
return new AndroidNativeKeyboardProvider();
#else
// Other platforms not supported, including iOS and Unity versions w/o the native integraiton.
Debug.LogWarning("GVR Keyboard not supported on " + Application.platform);
return new DummyKeyboardProvider();
#endif // UNITY_EDITOR
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 696c86fab86049947bd12e68a9b724cf
timeCreated: 1491935011
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5d26023142e798440b25a7a2004ba138
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,374 @@
// Copyright 2017 Google Inc. All rights reserved.
//
// 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.
// This is a Keyboard Subclass that runs on device only. It displays the
// full VR Keyboard.
using UnityEngine;
using System;
using System.Runtime.InteropServices;
#if UNITY_2017_2_OR_NEWER
using UnityEngine.XR;
#else
using UnityEngine.VR;
#endif // UNITY_2017_2_OR_NEWER
/// @cond
namespace Gvr.Internal {
public class AndroidNativeKeyboardProvider : IKeyboardProvider {
private IntPtr renderEventFunction;
#if UNITY_ANDROID && !UNITY_EDITOR
private float currentDistance = 0.0f;
#endif // UNITY_ANDROID && !UNITY_EDITOR
// Android method names.
private const string METHOD_NAME_GET_PACKAGE_MANAGER = "getPackageManager";
private const string METHOD_NAME_GET_PACKAGE_INFO = "getPackageInfo";
private const string PACKAGE_NAME_VRINPUTMETHOD = "com.google.android.vr.inputmethod";
private const string FIELD_NAME_VERSION_CODE = "versionCode";
// Min version for VrInputMethod.
private const int MIN_VERSION_VRINPUTMETHOD = 170509062;
// Library name.
private const string dllName = "gvr_keyboard_shim_unity";
// Enum gvr_trigger_state.
private const int TRIGGER_NONE = 0;
private const int TRIGGER_PRESSED = 1;
[StructLayout (LayoutKind.Sequential)]
private struct gvr_clock_time_point {
public long monotonic_system_time_nanos;
}
[StructLayout (LayoutKind.Sequential)]
private struct gvr_recti {
public int left;
public int right;
public int bottom;
public int top;
}
[DllImport (GvrActivityHelper.GVR_DLL_NAME)]
private static extern gvr_clock_time_point gvr_get_time_point_now();
[DllImport (dllName)]
private static extern GvrKeyboardInputMode gvr_keyboard_get_input_mode(IntPtr keyboard_context);
[DllImport (dllName)]
private static extern void gvr_keyboard_set_input_mode(IntPtr keyboard_context, GvrKeyboardInputMode mode);
#if UNITY_ANDROID
[DllImport(dllName)]
private static extern IntPtr gvr_keyboard_initialize(AndroidJavaObject app_context, AndroidJavaObject class_loader);
#endif
[DllImport (dllName)]
private static extern IntPtr gvr_keyboard_create(IntPtr closure, GvrKeyboard.KeyboardCallback callback);
// Gets a recommended world space matrix.
[DllImport (dllName)]
private static extern void gvr_keyboard_get_recommended_world_from_keyboard_matrix(float distance_from_eye,
IntPtr matrix);
// Sets the recommended world space matrix. The matrix may
// contain a combination of translation/rotation/scaling information.
[DllImport(dllName)]
private static extern void gvr_keyboard_set_world_from_keyboard_matrix(IntPtr keyboard_context, IntPtr matrix);
// Shows the keyboard
[DllImport (dllName)]
private static extern void gvr_keyboard_show(IntPtr keyboard_context);
// Updates the keyboard with the controller's button state.
[DllImport(dllName)]
private static extern void gvr_keyboard_update_button_state(IntPtr keyboard_context, int buttonIndex, bool pressed);
// Updates the controller ray on the keyboard.
[DllImport(dllName)]
private static extern bool gvr_keyboard_update_controller_ray(IntPtr keyboard_context, IntPtr vector3Start,
IntPtr vector3End, IntPtr vector3Hit);
// Updates the touch state of the controller.
[DllImport(dllName)]
private static extern void gvr_keyboard_update_controller_touch(IntPtr keyboard_context, bool touched, IntPtr vector2Pos);
// Returns the EditText with for the keyboard.
[DllImport (dllName)]
private static extern IntPtr gvr_keyboard_get_text(IntPtr keyboard_context);
// Sets the edit_text for the keyboard.
// @return 1 if the edit text could be set. 0 if it cannot be set.
[DllImport (dllName)]
private static extern int gvr_keyboard_set_text(IntPtr keyboard_context, IntPtr edit_text);
// Hides the keyboard.
[DllImport (dllName)]
private static extern void gvr_keyboard_hide(IntPtr keyboard_context);
// Destroys the keyboard. Resources related to the keyboard is released.
[DllImport (dllName)]
private static extern void gvr_keyboard_destroy(IntPtr keyboard_context);
// Called once per frame to set the time index.
[DllImport(dllName)]
private static extern void GvrKeyboardSetFrameData(IntPtr keyboard_context, gvr_clock_time_point t);
// Sets VR eye data in preparation for rendering a single eye's view.
[DllImport(dllName)]
private static extern void GvrKeyboardSetEyeData(int eye_type, Matrix4x4 modelview, Matrix4x4 projection, gvr_recti viewport);
[DllImport(dllName)]
private static extern IntPtr GetKeyboardRenderEventFunc();
// Private class data.
private IntPtr keyboard_context = IntPtr.Zero;
// Used in the GVR Unity C++ shim layer.
private const int advanceID = 0x5DAC793B;
private const int renderLeftID = 0x3CF97A3D;
private const int renderRightID = 0x3CF97A3E;
private const string KEYBOARD_JAVA_CLASS = "com.google.vr.keyboard.GvrKeyboardUnity";
private const long kPredictionTimeWithoutVsyncNanos = 50000000;
private const int kGvrControllerButtonClick = 1;
private GvrKeyboardInputMode mode = GvrKeyboardInputMode.DEFAULT;
private string editorText = string.Empty;
private Matrix4x4 worldMatrix;
private bool isValid = false;
private bool isReady = false;
public string EditorText {
get {
IntPtr text = gvr_keyboard_get_text(keyboard_context);
editorText = Marshal.PtrToStringAnsi(text);
return editorText;
}
set {
editorText = value;
IntPtr text = Marshal.StringToHGlobalAnsi(editorText);
gvr_keyboard_set_text(keyboard_context, text);
}
}
public void SetInputMode(GvrKeyboardInputMode mode) {
Debug.Log("Calling set input mode: " + mode);
gvr_keyboard_set_input_mode(keyboard_context, mode);
this.mode = mode;
}
public void OnPause() { }
public void OnResume() { }
public void ReadState(KeyboardState outState) {
outState.editorText = editorText;
outState.mode = mode;
outState.worldMatrix = worldMatrix;
outState.isValid = isValid;
outState.isReady = isReady;
}
// Initialization function.
public AndroidNativeKeyboardProvider() {
#if UNITY_ANDROID && !UNITY_EDITOR
// Running on Android device.
AndroidJavaObject activity = GvrActivityHelper.GetActivity();
if (activity == null) {
Debug.Log("Failed to get activity for keyboard.");
return;
}
AndroidJavaObject context = GvrActivityHelper.GetApplicationContext(activity);
if (context == null) {
Debug.Log("Failed to get context for keyboard.");
return;
}
AndroidJavaObject plugin = new AndroidJavaObject(KEYBOARD_JAVA_CLASS);
if (plugin != null) {
plugin.Call("initializeKeyboard", context);
isValid = true;
}
#endif // UNITY_ANDROID && !UNITY_EDITOR
renderEventFunction = GetKeyboardRenderEventFunc();
}
~AndroidNativeKeyboardProvider() {
if (keyboard_context != IntPtr.Zero)
gvr_keyboard_destroy(keyboard_context);
}
public bool Create(GvrKeyboard.KeyboardCallback keyboardEvent) {
if (!IsVrInputMethodAppMinVersion(keyboardEvent)) {
return false;
}
keyboard_context = gvr_keyboard_create(IntPtr.Zero, keyboardEvent);
isReady = keyboard_context != IntPtr.Zero;
return isReady;
}
public void Show(Matrix4x4 userMatrix, bool useRecommended, float distance, Matrix4x4 model) {
#if UNITY_ANDROID && !UNITY_EDITOR
currentDistance = distance;
#endif // UNITY_ANDROID && !UNITY_EDITOR
if (useRecommended) {
worldMatrix = getRecommendedMatrix(distance);
} else {
// Convert to GVR coordinates.
worldMatrix = Pose3D.FlipHandedness(userMatrix).transpose;
}
Matrix4x4 matToSet = worldMatrix * model.transpose;
IntPtr mat_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(matToSet));
Marshal.StructureToPtr(matToSet, mat_ptr, true);
gvr_keyboard_set_world_from_keyboard_matrix(keyboard_context, mat_ptr);
gvr_keyboard_show(keyboard_context);
Marshal.FreeHGlobal(mat_ptr);
}
public void UpdateData() {
#if UNITY_ANDROID && !UNITY_EDITOR
// Running on Android device.
// Update controller state.
GvrBasePointer pointer = GvrPointerInputModule.Pointer;
bool isPointerAvailable = pointer != null && pointer.IsAvailable;
if (isPointerAvailable) {
GvrControllerInputDevice controllerInputDevice = pointer.ControllerInputDevice;
if (controllerInputDevice != null && controllerInputDevice.State == GvrConnectionState.Connected) {
bool pressed = controllerInputDevice.GetButton(GvrControllerButton.TouchPadButton);
gvr_keyboard_update_button_state(keyboard_context, kGvrControllerButtonClick, pressed);
// Update touch state
Vector2 touch_pos = controllerInputDevice.TouchPos;
IntPtr touch_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(touch_pos));
Marshal.StructureToPtr(touch_pos, touch_ptr, true);
bool isTouching = controllerInputDevice.GetButton(GvrControllerButton.TouchPadTouch);
gvr_keyboard_update_controller_touch(keyboard_context, isTouching, touch_ptr);
GvrBasePointer.PointerRay pointerRay = pointer.GetRayForDistance(currentDistance);
Vector3 startPoint = pointerRay.ray.origin;
// Need to flip Z for native library
startPoint.z *= -1;
IntPtr start_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(startPoint));
Marshal.StructureToPtr(startPoint, start_ptr, true);
Vector3 endPoint = pointerRay.ray.GetPoint(pointerRay.distance);
// Need to flip Z for native library
endPoint.z *= -1;
IntPtr end_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(endPoint));
Marshal.StructureToPtr(endPoint, end_ptr, true);
Vector3 hit = Vector3.one;
IntPtr hit_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(Vector3.zero));
Marshal.StructureToPtr(Vector3.zero, hit_ptr, true);
gvr_keyboard_update_controller_ray(keyboard_context, start_ptr, end_ptr, hit_ptr);
hit = (Vector3)Marshal.PtrToStructure(hit_ptr, typeof(Vector3));
hit.z *= -1;
Marshal.FreeHGlobal(touch_ptr);
Marshal.FreeHGlobal(hit_ptr);
Marshal.FreeHGlobal(end_ptr);
Marshal.FreeHGlobal(start_ptr);
}
}
#endif // UNITY_ANDROID && !UNITY_EDITOR
// Get time stamp.
gvr_clock_time_point time = gvr_get_time_point_now();
time.monotonic_system_time_nanos += kPredictionTimeWithoutVsyncNanos;
// Update frame data.
GvrKeyboardSetFrameData(keyboard_context, time);
GL.IssuePluginEvent(renderEventFunction, advanceID);
}
public void Render(int eye, Matrix4x4 modelview, Matrix4x4 projection, Rect viewport) {
gvr_recti rect = new gvr_recti();
rect.left = (int)viewport.x;
rect.top = (int)viewport.y + (int)viewport.height;
rect.right = (int)viewport.x + (int)viewport.width;
rect.bottom = (int)viewport.y;
// For the modelview matrix, we need to convert it to a world-to-camera
// matrix for GVR keyboard, hence the inverse. We need to convert left
// handed to right handed, hence the multiply by flipZ.
// Unity projection matrices are already in a form GVR needs.
// Unity stores matrices row-major, so both get a final transpose to get
// them column-major for GVR.
GvrKeyboardSetEyeData(eye,
(Pose3D.FLIP_Z * modelview.inverse).transpose.inverse,
projection.transpose,
rect);
GL.IssuePluginEvent(renderEventFunction, eye == 0 ? renderLeftID : renderRightID);
}
public void Hide() {
gvr_keyboard_hide(keyboard_context);
}
// Return the recommended keyboard local to world space
// matrix given a distance value by the user. This value should
// be between 1 and 5 and will get clamped to that range.
private Matrix4x4 getRecommendedMatrix(float inputDistance) {
float distance = Mathf.Clamp(inputDistance, 1.0f, 5.0f);
Matrix4x4 result = new Matrix4x4();
IntPtr mat_ptr = Marshal.AllocHGlobal(Marshal.SizeOf (result));
Marshal.StructureToPtr(result, mat_ptr, true);
gvr_keyboard_get_recommended_world_from_keyboard_matrix(distance, mat_ptr);
result = (Matrix4x4) Marshal.PtrToStructure(mat_ptr, typeof(Matrix4x4));
Marshal.FreeHGlobal(mat_ptr);
return result;
}
// Returns true if the VrInputMethod APK is at least as high as MIN_VERSION_VRINPUTMETHOD.
private bool IsVrInputMethodAppMinVersion(GvrKeyboard.KeyboardCallback keyboardEvent) {
#if UNITY_ANDROID && !UNITY_EDITOR
// Running on Android device.
AndroidJavaObject activity = GvrActivityHelper.GetActivity();
if (activity == null) {
Debug.Log("Failed to get activity for keyboard.");
return false;
}
AndroidJavaObject packageManager = activity.Call<AndroidJavaObject>(METHOD_NAME_GET_PACKAGE_MANAGER);
if (packageManager == null) {
Debug.Log("Failed to get activity package manager");
return false;
}
AndroidJavaObject info = packageManager.Call<AndroidJavaObject>(METHOD_NAME_GET_PACKAGE_INFO, PACKAGE_NAME_VRINPUTMETHOD, 0);
if (info == null) {
Debug.Log("Failed to get package info for com.google.android.apps.vr.inputmethod");
return false;
}
int versionCode = info.Get<int>(FIELD_NAME_VERSION_CODE);
if (versionCode < MIN_VERSION_VRINPUTMETHOD) {
keyboardEvent(IntPtr.Zero, GvrKeyboardEvent.GVR_KEYBOARD_ERROR_SDK_LOAD_FAILED);
return false;
}
return true;
#else
return true;
#endif // UNITY_ANDROID && !UNITY_EDITOR
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 494e0fcfce3cb4d1c973863b3ad4e5d0
timeCreated: 1478821396
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,47 @@
// Copyright 2017 Google Inc. All rights reserved.
//
// 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.
using UnityEngine;
namespace Gvr.Internal {
class DummyKeyboardProvider : IKeyboardProvider {
private KeyboardState dummyState = new KeyboardState();
internal DummyKeyboardProvider() { }
public void ReadState(KeyboardState outState) {
outState.CopyFrom(dummyState);
}
public void OnPause() { }
public void OnResume() { }
public void UpdateData() { }
public void Render(int eye, Matrix4x4 modelview, Matrix4x4 projection, Rect viewport) { }
public void Hide() { }
public void Show(Matrix4x4 controllerMatrix, bool useRecommended, float distance,
Matrix4x4 model) { }
public bool Create(GvrKeyboard.KeyboardCallback keyboardEvent) { return true; }
public void SetInputMode(GvrKeyboardInputMode mode) { }
public string EditorText { get; set; }
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: b9fcd2a047ec9c440a2bfeace305c425
timeCreated: 1491941207
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,145 @@
// Copyright 2017 Google Inc. All rights reserved.
//
// 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.
// This is a version of the keyboard that runs directly in the Unity Editor.
// It is meant to simply be a placeholder so developers can test their games
// without having to use actual devices.
using UnityEngine;
using System;
/// @cond
namespace Gvr.Internal {
/// Keyboard subclass to run in the Unity editor
public class EmulatorKeyboardProvider : IKeyboardProvider {
private GameObject stub;
private bool showing;
GvrKeyboard.KeyboardCallback keyboardCallback;
private string editorText = string.Empty;
private GvrKeyboardInputMode mode = GvrKeyboardInputMode.DEFAULT;
private Matrix4x4 worldMatrix;
private bool isValid = false;
public string EditorText {
get { return editorText; }
set { editorText = value; }
}
public void SetInputMode(GvrKeyboardInputMode mode) {
this.mode = mode;
}
public EmulatorKeyboardProvider() {
Debug.Log("Creating stub keyboard");
// Set default data;
showing = false;
isValid = true;
}
public void OnPause() { }
public void OnResume() { }
public void ReadState(KeyboardState outState) {
outState.mode = mode;
outState.editorText = editorText;
outState.worldMatrix = worldMatrix;
outState.isValid = isValid;
outState.isReady = true;
}
public bool Create(GvrKeyboard.KeyboardCallback keyboardEvent) {
keyboardCallback = keyboardEvent;
if (!isValid) {
keyboardCallback(IntPtr.Zero, GvrKeyboardEvent.GVR_KEYBOARD_ERROR_SERVICE_NOT_CONNECTED);
}
return true;
}
public void Show(Matrix4x4 controllerMatrix, bool useRecommended, float distance, Matrix4x4 model) {
if (!showing && isValid) {
showing = true;
worldMatrix = controllerMatrix;
keyboardCallback(IntPtr.Zero, GvrKeyboardEvent.GVR_KEYBOARD_SHOWN);
}
}
public void UpdateData() {
// Can skip if keyboard not available
if (!showing)
{
return;
}
if (Input.GetKeyDown(KeyCode.KeypadEnter))
{
keyboardCallback(IntPtr.Zero, GvrKeyboardEvent.GVR_KEYBOARD_TEXT_COMMITTED);
return;
}
if (Input.GetKeyDown(KeyCode.Backspace))
{
if (editorText.Length > 0)
{
editorText = editorText.Substring(0, editorText.Length - 1);
SendUpdateNotification();
}
return;
}
if (Input.inputString.Length <= 0)
{
return;
}
switch (mode)
{
case GvrKeyboardInputMode.DEFAULT:
editorText += Input.inputString;
break;
case GvrKeyboardInputMode.NUMERIC:
foreach (char n in Input.inputString)
{
if (n >= '0' && n <= '9')
{
editorText += n;
}
}
break;
default:
break;
}
SendUpdateNotification();
}
public void Render(int eye, Matrix4x4 modelview, Matrix4x4 projection, Rect viewport) {}
public void Hide() {
if (showing) {
showing = false;
keyboardCallback(IntPtr.Zero, GvrKeyboardEvent.GVR_KEYBOARD_HIDDEN);
}
}
private void SendUpdateNotification() {
keyboardCallback(IntPtr.Zero, GvrKeyboardEvent.GVR_KEYBOARD_TEXT_UPDATED);
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: f73feeef531a54f2a8cf5b05a8c06e58
timeCreated: 1478821396
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,32 @@
// Copyright 2017 Google Inc. All rights reserved.
//
// 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.
using UnityEngine;
public class KeyboardState {
internal string editorText = string.Empty;
internal GvrKeyboardInputMode mode = GvrKeyboardInputMode.DEFAULT;
internal bool isValid = false;
internal bool isReady = false;
internal Matrix4x4 worldMatrix;
public void CopyFrom(KeyboardState other) {
editorText = other.editorText;
mode = other.mode;
isValid = other.isValid;
isReady = other.isReady;
worldMatrix = other.worldMatrix;
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 5baa0455970b442238015283920cc587
timeCreated: 1479086112
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: