summaryrefslogtreecommitdiffstats
path: root/dom/vr/XRInputSource.cpp
blob: 8cf2849d1c727024ac1d24c532a3729951239df1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/dom/XRInputSource.h"
#include "mozilla/dom/XRInputSourceEvent.h"
#include "XRNativeOriginViewer.h"
#include "XRNativeOriginTracker.h"
#include "XRInputSpace.h"
#include "VRDisplayClient.h"

#include "mozilla/dom/Gamepad.h"
#include "mozilla/dom/GamepadManager.h"

namespace mozilla::dom {

NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(XRInputSource, mParent, mTargetRaySpace,
                                      mGripSpace, mGamepad)

// Follow the controller profile ids from
// https://github.com/immersive-web/webxr-input-profiles.
nsTArray<nsString> GetInputSourceProfile(gfx::VRControllerType aType) {
  nsTArray<nsString> profile;
  nsString id;

  switch (aType) {
    case gfx::VRControllerType::HTCVive:
      id.AssignLiteral("htc-vive");
      profile.AppendElement(id);
      id.AssignLiteral("generic-trigger-squeeze-touchpad");
      profile.AppendElement(id);
      break;
    case gfx::VRControllerType::HTCViveCosmos:
      id.AssignLiteral("htc-vive-cosmos");
      profile.AppendElement(id);
      id.AssignLiteral("generic-trigger-squeeze-thumbstick");
      profile.AppendElement(id);
      break;
    case gfx::VRControllerType::HTCViveFocus:
      id.AssignLiteral("htc-vive-focus");
      profile.AppendElement(id);
      id.AssignLiteral("generic-trigger-touchpad");
      profile.AppendElement(id);
      break;
    case gfx::VRControllerType::HTCViveFocusPlus:
      id.AssignLiteral("htc-vive-focus-plus");
      profile.AppendElement(id);
      id.AssignLiteral("generic-trigger-squeeze-touchpad");
      profile.AppendElement(id);
      break;
    case gfx::VRControllerType::MSMR:
      id.AssignLiteral("microsoft-mixed-reality");
      profile.AppendElement(id);
      id.AssignLiteral("generic-trigger-squeeze-touchpad-thumbstick");
      profile.AppendElement(id);
      break;
    case gfx::VRControllerType::ValveIndex:
      id.AssignLiteral("valve-index");
      profile.AppendElement(id);
      id.AssignLiteral("generic-trigger-squeeze-touchpad-thumbstick");
      profile.AppendElement(id);
      break;
    case gfx::VRControllerType::OculusGo:
      id.AssignLiteral("oculus-go");
      profile.AppendElement(id);
      id.AssignLiteral("generic-trigger-touchpad");
      profile.AppendElement(id);
      break;
    case gfx::VRControllerType::OculusTouch:
      id.AssignLiteral("oculus-touch");
      profile.AppendElement(id);
      id.AssignLiteral("generic-trigger-squeeze-thumbstick");
      profile.AppendElement(id);
      break;
    case gfx::VRControllerType::OculusTouch2:
      id.AssignLiteral("oculus-touch-v2");
      profile.AppendElement(id);
      id.AssignLiteral("oculus-touch");
      profile.AppendElement(id);
      id.AssignLiteral("generic-trigger-squeeze-thumbstick");
      profile.AppendElement(id);
      break;
    case gfx::VRControllerType::OculusTouch3:
      id.AssignLiteral("oculus-touch-v3");
      profile.AppendElement(id);
      id.AssignLiteral("oculus-touch-v2");
      profile.AppendElement(id);
      id.AssignLiteral("oculus-touch");
      profile.AppendElement(id);
      id.AssignLiteral("generic-trigger-squeeze-thumbstick");
      profile.AppendElement(id);
      break;
    case gfx::VRControllerType::PicoGaze:
      id.AssignLiteral("pico-gaze");
      profile.AppendElement(id);
      id.AssignLiteral("generic-button");
      profile.AppendElement(id);
      break;
    case gfx::VRControllerType::PicoG2:
      id.AssignLiteral("pico-g2");
      profile.AppendElement(id);
      id.AssignLiteral("generic-trigger-touchpad");
      profile.AppendElement(id);
      break;
    case gfx::VRControllerType::PicoNeo2:
      id.AssignLiteral("pico-neo2");
      profile.AppendElement(id);
      id.AssignLiteral("generic-trigger-squeeze-thumbstick");
      profile.AppendElement(id);
      break;
    default:
      NS_WARNING("Unsupported XR input source profile.\n");
      break;
  }
  return profile;
}

XRInputSource::XRInputSource(nsISupports* aParent)
    : mParent(aParent),
      mGamepad(nullptr),
      mIndex(-1),
      mSelectAction(ActionState::ActionState_Released),
      mSqueezeAction(ActionState::ActionState_Released) {}

XRInputSource::~XRInputSource() {
  mTargetRaySpace = nullptr;
  mGripSpace = nullptr;
  mGamepad = nullptr;
}

JSObject* XRInputSource::WrapObject(JSContext* aCx,
                                    JS::Handle<JSObject*> aGivenProto) {
  return XRInputSource_Binding::Wrap(aCx, this, aGivenProto);
}

XRHandedness XRInputSource::Handedness() { return mHandedness; }

XRTargetRayMode XRInputSource::TargetRayMode() { return mTargetRayMode; }

XRSpace* XRInputSource::TargetRaySpace() { return mTargetRaySpace; }

XRSpace* XRInputSource::GetGripSpace() { return mGripSpace; }

void XRInputSource::GetProfiles(nsTArray<nsString>& aResult) {
  aResult = mProfiles.Clone();
}

Gamepad* XRInputSource::GetGamepad() { return mGamepad; }

void XRInputSource::Setup(XRSession* aSession, uint32_t aIndex) {
  MOZ_ASSERT(aSession);
  gfx::VRDisplayClient* displayClient = aSession->GetDisplayClient();
  if (!displayClient) {
    MOZ_ASSERT(displayClient);
    return;
  }
  const gfx::VRDisplayInfo& displayInfo = displayClient->GetDisplayInfo();
  const gfx::VRControllerState& controllerState =
      displayInfo.mControllerState[aIndex];
  MOZ_ASSERT(controllerState.controllerName[0] != '\0');

  mProfiles = GetInputSourceProfile(controllerState.type);
  mHandedness = XRHandedness::None;
  switch (controllerState.hand) {
    case GamepadHand::_empty:
      mHandedness = XRHandedness::None;
      break;
    case GamepadHand::Left:
      mHandedness = XRHandedness::Left;
      break;
    case GamepadHand::Right:
      mHandedness = XRHandedness::Right;
      break;
    default:
      MOZ_ASSERT(false && "Unknown GamepadHand type.");
      break;
  }

  RefPtr<XRNativeOrigin> nativeOriginTargetRay = nullptr;
  mTargetRayMode = XRTargetRayMode::Tracked_pointer;
  switch (controllerState.targetRayMode) {
    case gfx::TargetRayMode::Gaze:
      mTargetRayMode = XRTargetRayMode::Gaze;
      nativeOriginTargetRay = new XRNativeOriginViewer(displayClient);
      break;
    case gfx::TargetRayMode::TrackedPointer:
      mTargetRayMode = XRTargetRayMode::Tracked_pointer;
      // We use weak pointers of poses in XRNativeOriginTracker to sync their
      // data internally.
      nativeOriginTargetRay =
          new XRNativeOriginTracker(&controllerState.targetRayPose);
      break;
    case gfx::TargetRayMode::Screen:
      mTargetRayMode = XRTargetRayMode::Screen;
      break;
    default:
      MOZ_ASSERT(false && "Undefined TargetRayMode type.");
      break;
  }

  mTargetRaySpace = new XRInputSpace(aSession->GetParentObject(), aSession,
                                     nativeOriginTargetRay, aIndex);

  const uint32_t gamepadHandleValue =
      displayInfo.mDisplayID * gfx::kVRControllerMaxCount + aIndex;

  const GamepadHandle gamepadHandle{gamepadHandleValue, GamepadHandleKind::VR};

  mGamepad =
      new Gamepad(mParent, NS_ConvertASCIItoUTF16(""), -1, gamepadHandle,
                  GamepadMappingType::Xr_standard, controllerState.hand,
                  displayInfo.mDisplayID, controllerState.numButtons,
                  controllerState.numAxes, controllerState.numHaptics, 0, 0);
  mIndex = aIndex;

  if (!mGripSpace) {
    CreateGripSpace(aSession, controllerState);
  }
}

void XRInputSource::SetGamepadIsConnected(bool aConnected,
                                          XRSession* aSession) {
  mGamepad->SetConnected(aConnected);
  MOZ_ASSERT(aSession);

  if (!aConnected) {
    if (mSelectAction != ActionState::ActionState_Released) {
      DispatchEvent(u"selectend"_ns, aSession);
      mSelectAction = ActionState::ActionState_Released;
    }
    if (mSqueezeAction != ActionState::ActionState_Released) {
      DispatchEvent(u"squeezeend"_ns, aSession);
      mSqueezeAction = ActionState::ActionState_Released;
    }
  }
}

void XRInputSource::Update(XRSession* aSession) {
  MOZ_ASSERT(aSession && mIndex >= 0 && mGamepad);

  gfx::VRDisplayClient* displayClient = aSession->GetDisplayClient();
  if (!displayClient) {
    MOZ_ASSERT(displayClient);
    return;
  }
  const gfx::VRDisplayInfo& displayInfo = displayClient->GetDisplayInfo();
  const gfx::VRControllerState& controllerState =
      displayInfo.mControllerState[mIndex];
  MOZ_ASSERT(controllerState.controllerName[0] != '\0');

  // OculusVR and OpenVR controllers need to wait until
  // update functions to assign GamepadCapabilityFlags::Cap_GripSpacePosition
  // flag.
  if (!mGripSpace) {
    CreateGripSpace(aSession, controllerState);
  }

  // Update button values.
  nsTArray<RefPtr<GamepadButton>> buttons;
  mGamepad->GetButtons(buttons);
  for (uint32_t i = 0; i < buttons.Length(); ++i) {
    const bool pressed = controllerState.buttonPressed & (1ULL << i);
    const bool touched = controllerState.buttonTouched & (1ULL << i);

    if (buttons[i]->Pressed() != pressed || buttons[i]->Touched() != touched ||
        buttons[i]->Value() != controllerState.triggerValue[i]) {
      mGamepad->SetButton(i, pressed, touched, controllerState.triggerValue[i]);
    }
  }
  // Update axis values.
  nsTArray<double> axes;
  mGamepad->GetAxes(axes);
  for (uint32_t i = 0; i < axes.Length(); ++i) {
    if (axes[i] != controllerState.axisValue[i]) {
      mGamepad->SetAxis(i, controllerState.axisValue[i]);
    }
  }

  // We define 0.85f and 0.15f based on our current finding
  // for better experience, we can adjust these values if we need.
  const float completeThreshold = 0.90f;
  const float startThreshold = 0.85f;
  const float endThreshold = 0.15f;
  const uint32_t selectIndex = 0;
  const uint32_t squeezeIndex = 1;

  // Checking selectstart, select, selectend
  if (buttons.Length() > selectIndex) {
    if (controllerState.selectActionStartFrameId >
        controllerState.selectActionStopFrameId) {
      if (mSelectAction == ActionState::ActionState_Released &&
          controllerState.triggerValue[selectIndex] > endThreshold) {
        DispatchEvent(u"selectstart"_ns, aSession);
        mSelectAction = ActionState::ActionState_Pressing;
      } else if (mSelectAction == ActionState::ActionState_Pressing &&
                 controllerState.triggerValue[selectIndex] >
                     completeThreshold) {
        mSelectAction = ActionState::ActionState_Pressed;
      } else if (mSelectAction == ActionState::ActionState_Pressed &&
                 controllerState.triggerValue[selectIndex] < startThreshold) {
        DispatchEvent(u"select"_ns, aSession);
        mSelectAction = ActionState::ActionState_Releasing;
      } else if (mSelectAction <= ActionState::ActionState_Releasing &&
                 controllerState.triggerValue[selectIndex] < endThreshold) {
        // For a select btn which only has pressed and unpressed status.
        if (mSelectAction == ActionState::ActionState_Pressed) {
          DispatchEvent(u"select"_ns, aSession);
        }
        DispatchEvent(u"selectend"_ns, aSession);
        mSelectAction = ActionState::ActionState_Released;
      }
    } else if (mSelectAction <= ActionState::ActionState_Releasing) {
      // For a select btn which only has pressed and unpressed status.
      if (mSelectAction == ActionState::ActionState_Pressed) {
        DispatchEvent(u"select"_ns, aSession);
      }
      DispatchEvent(u"selectend"_ns, aSession);
      mSelectAction = ActionState::ActionState_Released;
    }
  }

  // Checking squeezestart, squeeze, squeezeend
  if (buttons.Length() > squeezeIndex) {
    if (controllerState.squeezeActionStartFrameId >
        controllerState.squeezeActionStopFrameId) {
      if (mSqueezeAction == ActionState::ActionState_Released &&
          controllerState.triggerValue[squeezeIndex] > endThreshold) {
        DispatchEvent(u"squeezestart"_ns, aSession);
        mSqueezeAction = ActionState::ActionState_Pressing;
      } else if (mSqueezeAction == ActionState::ActionState_Pressing &&
                 controllerState.triggerValue[squeezeIndex] >
                     completeThreshold) {
        mSqueezeAction = ActionState::ActionState_Pressed;
      } else if (mSqueezeAction == ActionState::ActionState_Pressed &&
                 controllerState.triggerValue[squeezeIndex] < startThreshold) {
        DispatchEvent(u"squeeze"_ns, aSession);
        mSqueezeAction = ActionState::ActionState_Releasing;
      } else if (mSqueezeAction <= ActionState::ActionState_Releasing &&
                 controllerState.triggerValue[squeezeIndex] < endThreshold) {
        // For a squeeze btn which only has pressed and unpressed status.
        if (mSqueezeAction == ActionState::ActionState_Pressed) {
          DispatchEvent(u"squeeze"_ns, aSession);
        }
        DispatchEvent(u"squeezeend"_ns, aSession);
        mSqueezeAction = ActionState::ActionState_Released;
      }
    } else if (mSqueezeAction <= ActionState::ActionState_Releasing) {
      // For a squeeze btn which only has pressed and unpressed status.
      if (mSqueezeAction == ActionState::ActionState_Pressed) {
        DispatchEvent(u"squeeze"_ns, aSession);
      }
      DispatchEvent(u"squeezeend"_ns, aSession);
      mSqueezeAction = ActionState::ActionState_Released;
    }
  }
}

int32_t XRInputSource::GetIndex() { return mIndex; }

void XRInputSource::DispatchEvent(const nsAString& aEvent,
                                  XRSession* aSession) {
  if (!GetParentObject() || !aSession) {
    return;
  }
  // Create a XRFrame for its callbacks
  RefPtr<XRFrame> frame = new XRFrame(GetParentObject(), aSession);
  frame->StartInputSourceEvent();

  XRInputSourceEventInit init;
  init.mBubbles = false;
  init.mCancelable = false;
  init.mFrame = frame;
  init.mInputSource = this;

  RefPtr<XRInputSourceEvent> event =
      XRInputSourceEvent::Constructor(aSession, aEvent, init);

  event->SetTrusted(true);
  aSession->DispatchEvent(*event);
  frame->EndInputSourceEvent();
}

void XRInputSource::CreateGripSpace(
    XRSession* aSession, const gfx::VRControllerState& controllerState) {
  MOZ_ASSERT(!mGripSpace);
  MOZ_ASSERT(aSession && mIndex >= 0 && mGamepad);
  if (mTargetRayMode == XRTargetRayMode::Tracked_pointer &&
      controllerState.flags & GamepadCapabilityFlags::Cap_GripSpacePosition) {
    RefPtr<XRNativeOrigin> nativeOriginGrip = nullptr;
    nativeOriginGrip = new XRNativeOriginTracker(&controllerState.pose);
    mGripSpace = new XRInputSpace(aSession->GetParentObject(), aSession,
                                  nativeOriginGrip, mIndex);
  } else {
    mGripSpace = nullptr;
  }
}

}  // namespace mozilla::dom