-
Notifications
You must be signed in to change notification settings - Fork 117
/
XRInputSourceFacade.js
336 lines (298 loc) · 11.5 KB
/
XRInputSourceFacade.js
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
import { Group3DFacade, Object3DFacade } from 'troika-3d'
import { Facade, utils } from 'troika-core'
import { Matrix4, Ray } from 'three'
import CursorFacade from './CursorFacade'
import TargetRayFacade from './TargetRayFacade'
import GripFacade from './GripFacade'
import { BUTTON_DEFAULT_BACK, BUTTON_SQUEEZE, BUTTON_TRIGGER } from '../XRStandardGamepadMapping'
const SCENE_EVENTS = ['mousemove', 'mouseover', 'mouseout', 'mousedown', 'mouseup', 'click']
const XRSESSION_EVENTS = ['selectstart', 'selectend', 'squeezestart', 'squeezeend']
const CLICK_MAX_DUR = 300
const HAPTICS = { //TODO allow control
mouseover: {value: 0.3, duration: 10},
click: {value: 1, duration: 20}
}
const DEFAULT_CURSOR = {
facade: CursorFacade
}
const DEFAULT_TARGET_RAY = {
facade: TargetRayFacade
}
const DEFAULT_GRIP = {
facade: GripFacade
}
function toggleEvents (target, on, eventTypes, handler) {
if (target) {
eventTypes.forEach(type => {
target[`${on ? 'add' : 'remove'}EventListener`](type, handler)
})
}
}
const tempMat4 = new Matrix4()
/**
* Controls the behavior and visual representation of a single XRInputSource.
*
* | | Highlight | Cursor | Pointing Ray | Renderable Model |
* | ------------------| --------- | ------ | ------------ | ---------------- |
* | 'screen' | √ | X | X | X |
* | 'gaze' | √ | √ | X | X |
* | 'tracked-pointer' | √ | √ | √ | √ (if possible) |
*/
class XRInputSourceFacade extends Group3DFacade {
constructor (parent) {
super(parent)
this.isXRInputSource = true
// Required props
this.xrInputSource = null
this.xrSession = null
this.xrReferenceSpace = null
// Current frame state data, passed to all children:
this.targetRayPose = null
this.gripPose = null
this.rayIntersection = null
// Child object configs:
this.cursor = utils.assign(DEFAULT_CURSOR)
this.targetRay = utils.assign(DEFAULT_TARGET_RAY)
this.grip = utils.assign(DEFAULT_GRIP)
// Pointing - true for all inputs by default
this.isPointing = true
this.children = [
null, //cursor
null, //targetRay
null //grip
]
this._ray = new Ray()
this._onSessionEvent = this._onSessionEvent.bind(this)
this._onSceneRayEvent = this._onSceneRayEvent.bind(this)
this.addEventListener('xrframe', this._onXrFrame.bind(this))
// Listen to ray intersection related events at the scene level, so we can respond to intersection changes
toggleEvents(this.getSceneFacade(), true, SCENE_EVENTS, this._onSceneRayEvent)
}
afterUpdate () {
const {xrSession, _lastXrSession, xrInputSource, rayIntersection, children, isPointing, cursor, targetRay, grip, targetRayPose, gripPose} = this
if (xrSession !== _lastXrSession) {
this._lastXrSession = xrSession
toggleEvents(_lastXrSession, false, XRSESSION_EVENTS, this._onSessionEvent)
// Only listen for XRSession 'select' event if we won't be handling the xr-standard
// gamepad button tracking ourselves
if (!this._isXrStandardGamepad()) {
toggleEvents(xrSession, true, XRSESSION_EVENTS, this._onSessionEvent)
}
}
// Update child objects
let cursorCfg = null, targetRayCfg = null, gripCfg = null
if (xrInputSource.targetRayMode !== 'screen') {
cursorCfg = isPointing && cursor
if (cursorCfg) {
cursorCfg.key = 'cursor'
cursorCfg.targetRayPose = targetRayPose
cursorCfg.gripPose = gripPose
cursorCfg.rayIntersection = rayIntersection
cursorCfg.xrInputSource = xrInputSource
}
}
if (xrInputSource.targetRayMode === 'tracked-pointer') {
targetRayCfg = isPointing && targetRay
if (targetRayCfg) {
targetRayCfg.key = 'targetRay'
targetRayCfg.targetRayPose = targetRayPose
targetRayCfg.gripPose = gripPose
targetRayCfg.rayIntersection = rayIntersection
targetRayCfg.xrInputSource = xrInputSource
}
gripCfg = gripPose ? grip : null
if (gripCfg) {
gripCfg.key = 'grip'
gripCfg.targetRayPose = targetRayPose
gripCfg.gripPose = gripPose
gripCfg.rayIntersection = rayIntersection
gripCfg.xrInputSource = xrInputSource
}
}
children[0] = cursorCfg
children[1] = targetRayCfg
children[2] = gripCfg
super.afterUpdate()
}
_onXrFrame (time, xrFrame) {
const {xrInputSource, isPointing, _ray: ray} = this
const offsetReferenceSpace = this.getCameraFacade().offsetReferenceSpace
if (offsetReferenceSpace) {
// Update current poses
const {targetRaySpace, gripSpace} = xrInputSource
const targetRayPose = xrFrame.getPose(targetRaySpace, offsetReferenceSpace)
if (targetRayPose && isPointing) {
ray.origin.copy(targetRayPose.transform.position)
ray.direction.set(0, 0, -1).applyQuaternion(targetRayPose.transform.orientation)
this.notifyWorld('rayPointerMotion', ray)
}
this.targetRayPose = targetRayPose
this.gripPose = gripSpace ? xrFrame.getPose(gripSpace, offsetReferenceSpace) : null
}
// If this is a tracked-pointer with a gamepad, track its button/axis states
if (this._isXrStandardGamepad()) {
this._trackGamepadState(xrInputSource.gamepad)
}
this.afterUpdate()
}
_isXrStandardGamepad() {
const {gamepad} = this.xrInputSource
return gamepad && gamepad.mapping === 'xr-standard'
}
_trackGamepadState(gamepad) {
// Handle button presses
const buttons = gamepad.buttons
const pressedTimes = this._buttonPresses || (this._buttonPresses = [])
const now = Date.now()
const ray = this._ray //assumes already updated to current frame pose
for (let i = 0; i < buttons.length; i++) {
if (buttons[i].pressed !== !!pressedTimes[i]) {
if (this.isPointing) {
this.notifyWorld('rayPointerAction', {
ray,
type: buttons[i].pressed ? 'mousedown' : 'mouseup',
button: i
})
if (pressedTimes[i] && !buttons[i].pressed && now - pressedTimes[i] <= CLICK_MAX_DUR) {
this.notifyWorld('rayPointerAction', {
ray,
type: 'click',
button: i
})
}
}
pressedTimes[i] = buttons[i].pressed ? now : null
}
pressedTimes.length = buttons.length
}
// Handle axis inputs
const axes = gamepad.axes
for (let i = 0; i < axes.length; i += 2) {
// Map each pair of axes to wheel event deltaX/Y
// TODO investigate better mapping
const deltaX = (axes[i] || 0) * 10
const deltaY = (axes[i + 1] || 0) * 10
if (Math.hypot(deltaX, deltaY) > 0.1) {
if (this.isPointing) {
this.notifyWorld('rayPointerAction', {
ray,
type: 'wheel',
deltaX,
deltaY,
deltaMode: 0 //pixel mode
})
}
}
}
}
_onSessionEvent (e) {
if (e.inputSource === this.xrInputSource) {
// Redispatch select and squeeze events as standard pointer events to the world's event system.
// Note this is only used for non xr-standard gamepad inputs, otherwise it's handled in the
// gamepad button state tracking.
const button = /^squeeze/.test(e.type) ? BUTTON_SQUEEZE : BUTTON_TRIGGER
this.notifyWorld('rayPointerAction', {
ray: this._ray,
type: /start$/.test(e.type) ? 'mousedown' : 'mouseup',
button
})
// If this was an "end" event, then we'll also want to fire a click event after the mouseup.
// This is a workaround for the fact that WebXR fires 'select' then 'selectend', which doesn't
// match with standard DOM mouse events which go 'mouseup' then 'click', and can lead to
// unexpected behaviors in downstram code that assumes the standard order.
if (/end$/.test(e.type)) {
this.notifyWorld('rayPointerAction', {
ray: this._ray,
type: 'click',
button
})
}
}
}
_onSceneRayEvent (e) {
// Only handle events where this was the ray's source
if (e.nativeEvent.eventSource === this) {
const {gamepad} = this.xrInputSource
// Copy intersection info to local state and update subtree
this.rayIntersection = e.intersection
this.afterUpdate()
// If haptics available, trigger a pulse
if (gamepad) {
const isScene = e.target === e.currentTarget
const hapticPulse = e.type === 'click' ? HAPTICS.click
: (e.type === 'mouseover' && !isScene) ? HAPTICS.mouseover
: null
if (hapticPulse) {
const hapticActuator = gamepad.hapticActuators && gamepad.hapticActuators[0]
if (hapticActuator) {
hapticActuator.pulse(hapticPulse.value || 1, hapticPulse.duration || 100)
}
}
}
// For gamepad buttons and select/squeeze session events, dispatch custom xr-specific
// events to the raycasted target facade:
let defaultPrevented = e.defaultPrevented
const fireEvent = type => {
if (type) {
const customEvent = new Event(type, {bubbles: true})
customEvent.eventSource = this
e.target.dispatchEvent(customEvent)
defaultPrevented = defaultPrevented || customEvent.defaultPrevented
}
}
//TODO: fireEvent(RAY_TARGET_EVENTS.all[e.type]) //all buttons
fireEvent(RAY_TARGET_EVENTS[e.button] && RAY_TARGET_EVENTS[e.button][e.type]) //special select/squeeze
// Default gamepad button mapping to exit the XR session; authors can override this
// to use that button for other things by calling `preventDefault()`
if (!defaultPrevented && e.type === 'click' && e.button === BUTTON_DEFAULT_BACK) {
this.notifyWorld('endXRSession')
}
}
}
destructor () {
toggleEvents(this.xrSession, false, XRSESSION_EVENTS, this._onSessionEvent)
toggleEvents(this.getSceneFacade(), false, SCENE_EVENTS, this._onSceneRayEvent)
super.destructor()
}
}
// this.onXrFrame = null //timestamp, XRFrame
// this.onIntersectionEvent = null //???
// this.onSelectStart = null
// this.onSelect = null
// this.onSelectEnd = null
// this.onSqueezeStart = null
// this.onSqueeze = null
// this.onSqueezeEnd = null
// this.onButtonTouchStart = null
// this.onButtonPressStart = null
// this.onButtonPress = null
// this.onButtonPressEnd = null
// this.onButtonTouchEnd = null
// Define some custom xr-specific events that will be dispatched to the target Object3DFacade
// intersecting the ray at the time of a button action:
const RAY_TARGET_EVENTS = {
[BUTTON_TRIGGER]: {
mousedown: 'xrselectstart',
mouseup: 'xrselectend',
click: 'xrselect'
},
[BUTTON_SQUEEZE]: {
mousedown: 'xrsqueezestart',
mouseup: 'xrsqueezeend',
click: 'xrsqueeze'
},
// TODO decide on event names, and handle touching without press:
// all: {
// mousedown: 'xrbuttondown',
// mouseup: 'xrbuttonup',
// click: 'xrbuttonclick'
// }
}
// ...and add shortcut event handler properties on Object3DFacade for those events:
Facade.defineEventProperty(Object3DFacade, 'onXRSelectStart', 'xrselectstart')
Facade.defineEventProperty(Object3DFacade, 'onXRSelect', 'xrselect')
Facade.defineEventProperty(Object3DFacade, 'onXRSelectEnd', 'xrselectend')
Facade.defineEventProperty(Object3DFacade, 'onXRSqueezeStart', 'xrsqueezestart')
Facade.defineEventProperty(Object3DFacade, 'onXRSqueeze', 'xrsqueeze')
Facade.defineEventProperty(Object3DFacade, 'onXRSqueezeEnd', 'xrsqueezeend')
export default XRInputSourceFacade