babylon.webVRCamera.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. declare var HMDVRDevice;
  2. declare var PositionSensorVRDevice;
  3. module BABYLON {
  4. export class WebVRCamera extends BABYLON.OculusCamera {
  5. public _hmdDevice = null;
  6. public _sensorDevice = null;
  7. public _cacheState = null;
  8. public _cacheQuaternion = new BABYLON.Quaternion();
  9. public _cacheRotation = BABYLON.Vector3.Zero();
  10. public _vrEnabled = false;
  11. constructor(name: string, position: Vector3, scene: Scene) {
  12. super(name, position, scene);
  13. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  14. }
  15. private _getWebVRDevices(devices: Array<any>): void {
  16. var size = devices.length;
  17. var i = 0;
  18. // Reset devices.
  19. this._sensorDevice = null;
  20. this._hmdDevice = null;
  21. // Search for a HmdDevice.
  22. while (i < size && this._hmdDevice === null) {
  23. if (devices[i] instanceof HMDVRDevice) {
  24. this._hmdDevice = devices[i];
  25. }
  26. i++;
  27. }
  28. i = 0;
  29. while (i < size && this._sensorDevice === null) {
  30. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  31. this._sensorDevice = devices[i];
  32. }
  33. i++;
  34. }
  35. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  36. }
  37. public _update(): void {
  38. if (this._vrEnabled) {
  39. this._cacheState = this._sensorDevice.getState();
  40. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  41. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  42. this.rotation.x = -this._cacheRotation.z;
  43. this.rotation.y = -this._cacheRotation.y;
  44. this.rotation.z = this._cacheRotation.x;
  45. }
  46. super._update();
  47. }
  48. public attachControl(element: HTMLElement, noPreventDefault?: boolean): void {
  49. super.attachControl(element, noPreventDefault);
  50. if (navigator.getVRDevices) {
  51. navigator.getVRDevices().then(this._getWebVRDevices);
  52. }
  53. else if (navigator.mozGetVRDevices) {
  54. navigator.mozGetVRDevices(this._getWebVRDevices);
  55. }
  56. }
  57. public detachControl(element: HTMLElement): void {
  58. super.detachControl(element);
  59. this._vrEnabled = false;
  60. }
  61. }
  62. }