@galacean/effects-plugin-orientation-transformer 2.3.0-alpha.2 → 2.3.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/alipay.mjs CHANGED
@@ -1,779 +1,2 @@
1
- import * as EFFECTS from '@galacean/effects/alipay';
2
- import { isArray, isIOSByUA, isMiniProgram, assertExist, AbstractPlugin, effectsClass, Behaviour, registerPlugin, VFXItem, logger } from '@galacean/effects/alipay';
3
- import { window, document } from '@galacean/appx-adapter/alipay';
4
-
5
- function _set_prototype_of(o, p) {
6
- _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
7
- o.__proto__ = p;
8
- return o;
9
- };
10
- return _set_prototype_of(o, p);
11
- }
12
-
13
- function _inherits(subClass, superClass) {
14
- if (typeof superClass !== "function" && superClass !== null) {
15
- throw new TypeError("Super expression must either be null or a function");
16
- }
17
- subClass.prototype = Object.create(superClass && superClass.prototype, {
18
- constructor: {
19
- value: subClass,
20
- writable: true,
21
- configurable: true
22
- }
23
- });
24
- if (superClass) _set_prototype_of(subClass, superClass);
25
- }
26
-
27
- var CompositionTransformerAcceler = /*#__PURE__*/ function() {
28
- function CompositionTransformerAcceler(composition) {
29
- this.composition = composition;
30
- this.targets = {};
31
- this.records = {};
32
- this.currentPos = {};
33
- this.currentRot = {};
34
- this.gammaRange = [
35
- -89,
36
- 89
37
- ];
38
- this.betaRange = [
39
- -89,
40
- 89
41
- ];
42
- }
43
- var _proto = CompositionTransformerAcceler.prototype;
44
- _proto.update = function update(param) {
45
- var x = param.x, y = param.y, beta = param.beta, gamma = param.gamma;
46
- this.currentEvent = {
47
- x: x,
48
- y: y,
49
- beta: beta,
50
- gamma: gamma
51
- };
52
- };
53
- _proto.updateOrientation = function updateOrientation() {
54
- var _this = this;
55
- var event = this.currentEvent;
56
- if (event) {
57
- Object.getOwnPropertyNames(this.targets).forEach(function(name) {
58
- _this.moveLayer(name, event);
59
- });
60
- }
61
- };
62
- _proto.initComposition = function initComposition() {
63
- var items = this.composition.items;
64
- for(var i = 0; i < items.length; i++){
65
- var item = items[i];
66
- var target = this.targets[item.name];
67
- if (target) {
68
- var position = item.transform.position.toArray();
69
- var rotation = item.transform.rotation.toArray();
70
- var currentPosition = this.currentPos[item.name];
71
- var currentRot = this.currentRot[item.name];
72
- this.records[item.name] = {
73
- item: item,
74
- position: position,
75
- rotation: rotation
76
- };
77
- if (currentPosition) {
78
- item.transform.setPosition(currentPosition[0], currentPosition[1], currentPosition[2]);
79
- }
80
- if (currentRot) {
81
- item.transform.setRotation(currentRot[0], currentRot[1], currentRot[2]);
82
- }
83
- }
84
- }
85
- };
86
- _proto.addTarget = function addTarget(target) {
87
- this.targets[target.name] = target;
88
- };
89
- _proto.removeTarget = function removeTarget(name) {
90
- delete this.targets[name];
91
- delete this.records[name];
92
- };
93
- _proto.moveLayer = function moveLayer(name, param) {
94
- var x = param.x, y = param.y, b = param.beta, g = param.gamma;
95
- var _this_records_name;
96
- var layer = (_this_records_name = this.records[name]) == null ? void 0 : _this_records_name.item;
97
- if (layer) {
98
- var initPosition = this.records[name].position;
99
- var initRotation = this.records[name].rotation;
100
- var target = this.targets[name];
101
- var beta = clamp(x, this.betaRange), gamma = clamp(y, this.gammaRange);
102
- if (target) {
103
- var _layer_transform, _layer_transform1;
104
- var position = [
105
- initPosition[0] + 1.2 * mapRange(normalize(beta, this.gammaRange[0], this.gammaRange[1]), target.xMin, target.xMax),
106
- initPosition[1] + 1.2 * mapRange(normalize(gamma, this.betaRange[0], this.betaRange[1]), target.yMin, target.yMax),
107
- initPosition[2]
108
- ];
109
- var br = normalize(clamp(g * 0.8, this.gammaRange), this.gammaRange[0], this.gammaRange[1]);
110
- var gr = normalize(clamp(b * 0.8, this.betaRange), this.betaRange[0], this.betaRange[1]);
111
- var rotation = [
112
- initRotation[0] + mapRange(gr, target.hMin, target.hMax),
113
- initRotation[1] + mapRange(br, target.vMin, target.vMax),
114
- initRotation[2]
115
- ];
116
- (_layer_transform = layer.transform).setPosition.apply(_layer_transform, [].concat(position));
117
- (_layer_transform1 = layer.transform).setRotation.apply(_layer_transform1, [].concat(rotation));
118
- this.currentPos[name] = position.slice();
119
- this.currentRot[name] = rotation.slice();
120
- }
121
- }
122
- };
123
- return CompositionTransformerAcceler;
124
- }();
125
- function clamp(x, range) {
126
- if (x < range[0]) {
127
- return range[0];
128
- } else if (x > range[1]) {
129
- return range[1];
130
- }
131
- return x;
132
- }
133
- function mapRange(t, min, max) {
134
- return min + (max - min) * t;
135
- }
136
- function normalize(a, min, max) {
137
- return (a - min) / (max - min);
138
- }
139
-
140
- function _extends() {
141
- _extends = Object.assign || function assign(target) {
142
- for(var i = 1; i < arguments.length; i++){
143
- var source = arguments[i];
144
- for(var key in source)if (Object.prototype.hasOwnProperty.call(source, key)) target[key] = source[key];
145
- }
146
- return target;
147
- };
148
- return _extends.apply(this, arguments);
149
- }
150
-
151
- /**
152
- * 角度限制
153
- * @internal
154
- * @param angleObj 角度数值对象
155
- * @param validRange 角度限制值
156
- */ function angleLimit(angleObj, validRange) {
157
- var flagAlpha = true;
158
- var flagBeta = true;
159
- var flagGamma = true;
160
- if (isArray(validRange.alpha) && validRange.alpha.length >= 2) {
161
- var referAlphaA = angleObj.alpha + validRange.alpha[0];
162
- var referAlphaB = angleObj.alpha + validRange.alpha[1];
163
- referAlphaA = referAlphaA < 0 ? referAlphaA + 360 : referAlphaA;
164
- referAlphaB = referAlphaB > 360 ? referAlphaB - 360 : referAlphaB;
165
- if (referAlphaA < referAlphaB) {
166
- flagAlpha = angleObj.alpha > referAlphaA && angleObj.alpha < referAlphaB;
167
- } else {
168
- flagAlpha = angleObj.alpha > referAlphaA || angleObj.alpha < referAlphaB;
169
- }
170
- }
171
- if (isArray(validRange.beta) && validRange.beta.length >= 2) {
172
- flagBeta = angleObj.beta >= validRange.beta[0] && angleObj.beta <= validRange.beta[1];
173
- }
174
- if (isArray(validRange.gamma) && validRange.gamma.length >= 2) {
175
- flagGamma = angleObj.gamma >= validRange.gamma[0] && angleObj.gamma <= validRange.gamma[1];
176
- }
177
- return flagAlpha && flagBeta && flagGamma;
178
- }
179
-
180
- /**
181
- * 稳定区间
182
- */ var STABLE_RANGE = 3;
183
- /**
184
- * 每次增幅的最大值
185
- */ var MAX_CHANGE = 5;
186
- /**
187
- * 每次增幅的最小值
188
- */ var MIN_CHANGE = 1;
189
- /**
190
- * 数据缓存队列的长度
191
- */ var VALUE_POOL_LENGTH = 5;
192
- /**
193
- * 滤波方法
194
- */ var Filtering = /*#__PURE__*/ function() {
195
- function Filtering(options) {
196
- if (options === void 0) options = {};
197
- this.options = options;
198
- this.lastValue = 0;
199
- this.valuePool = [];
200
- }
201
- var _proto = Filtering.prototype;
202
- /**
203
- * 0deg 左右保持一定的稳定区间 STABLE_RANGE
204
- * - 小于 STABLE_RANGE 的算 0
205
- * - 大于 STABLE_RANGE 的减去 STABLE_RANGE
206
- * @param value - 输入值
207
- * @returns
208
- */ _proto.stableFix = function stableFix(value) {
209
- var stableRange = this.options.stableRange || STABLE_RANGE;
210
- if (Math.abs(value) < stableRange) {
211
- return 0;
212
- }
213
- return value > stableRange ? value - stableRange : value + stableRange;
214
- };
215
- /**
216
- * 变幅限制
217
- * - 最大变化 MAX_CHANGE
218
- * - 最小变化 MIN_CHANGE
219
- * @param value
220
- * @returns
221
- */ _proto.changeLimit = function changeLimit(value) {
222
- var lastValue = this.lastValue;
223
- var result = value;
224
- if (Math.abs(value - lastValue) > MAX_CHANGE) {
225
- result = lastValue < value ? lastValue + MAX_CHANGE : lastValue - MAX_CHANGE;
226
- }
227
- if (Math.abs(value - lastValue) < MIN_CHANGE) {
228
- result = lastValue;
229
- }
230
- this.lastValue = result;
231
- return result;
232
- };
233
- _proto.linearRegressionMedian = function linearRegressionMedian(value) {
234
- // 在队列中装载数据,达到队列阀值长度时开始计算
235
- this.valuePool.push(value);
236
- var result;
237
- if (this.valuePool.length >= VALUE_POOL_LENGTH) {
238
- result = getLinearRegressionFixedVal(this.valuePool);
239
- this.valuePool.shift();
240
- } else {
241
- result = this.lastValue;
242
- }
243
- return result;
244
- };
245
- return Filtering;
246
- }();
247
- // 计算出线性回归参数
248
- function linearRegression(x, y) {
249
- var result = {};
250
- var n = y.length;
251
- var sumX = 0;
252
- var sumY = 0;
253
- var sumXY = 0;
254
- var sumXX = 0;
255
- var sumYY = 0;
256
- for(var i = 0; i < y.length; i++){
257
- sumX += x[i];
258
- sumY += y[i];
259
- sumXY += x[i] * y[i];
260
- sumXX += x[i] * x[i];
261
- sumYY += y[i] * y[i];
262
- }
263
- var avgX = sumX / n;
264
- var avgY = sumY / n;
265
- result["a"] = (sumXY - n * avgX * avgY) / (sumXX - n * avgX * avgX);
266
- result["b"] = avgY - result.a * avgX;
267
- result["miss"] = Math.pow((n * sumXY - sumX * sumY) / Math.sqrt((n * sumXX - sumX * sumX) * (n * sumYY - sumY * sumY)), 2);
268
- return result;
269
- }
270
- // 生成线性回归函数 F(x) = ax + b
271
- function createLinearRegressionFx(values) {
272
- var x = [];
273
- var y = [];
274
- values.forEach(function(item, index) {
275
- x.push(index); // 数据是连续的,所以直接取数组下标为 x
276
- y.push(item);
277
- });
278
- var key = linearRegression(x, y);
279
- return function(x) {
280
- return key.a * x + key.b;
281
- };
282
- }
283
- // 获取线性回归后的中位数
284
- function getLinearRegressionFixedVal(valuePool) {
285
- var fx = createLinearRegressionFx(valuePool);
286
- // 这个迭代修正很重要
287
- valuePool = valuePool.map(function(item, index) {
288
- return fx(index);
289
- });
290
- return fx(valuePool.length / 2);
291
- }
292
-
293
- var useJSBridge = isIOSByUA() && typeof window.AlipayJSBridge !== "undefined";
294
- var useWindVane = typeof window.WindVane !== "undefined";
295
- // 默认参数
296
- var defaultOptions = {
297
- X: true,
298
- Y: true,
299
- interval: Math.floor(1000 / 30),
300
- useRequestAnimationFrame: true,
301
- relativeBeta: false,
302
- relativeGamma: false,
303
- validRange: {
304
- alpha: [
305
- -60,
306
- 60
307
- ],
308
- beta: [
309
- -60,
310
- 180
311
- ],
312
- gamma: [
313
- -89,
314
- 89
315
- ]
316
- },
317
- stableRange: 3
318
- };
319
- var DeviceOrientation = /*#__PURE__*/ function() {
320
- function DeviceOrientation(options) {
321
- if (options === void 0) options = {};
322
- this.lastX = 0;
323
- this.lastY = 0;
324
- this.prevAcceler = {
325
- x: 0,
326
- y: 0,
327
- z: 0
328
- };
329
- this.stoped = false;
330
- // 模拟简单的 deep merge
331
- var validRange = _extends({}, defaultOptions.validRange, options.validRange);
332
- var mergeOptions = _extends({}, defaultOptions, options);
333
- mergeOptions.validRange = validRange;
334
- this.options = mergeOptions;
335
- var stableRange = this.options.stableRange;
336
- this.filterX = new Filtering({
337
- stableRange: stableRange
338
- });
339
- this.filterY = new Filtering({
340
- stableRange: stableRange
341
- });
342
- }
343
- var _proto = DeviceOrientation.prototype;
344
- _proto.watch = function watch(callback) {
345
- var _this = this;
346
- if (typeof callback !== "function") {
347
- return;
348
- }
349
- // 目前只能绑定一个方法,此处可以扩展成一个方法队列
350
- if (this.watchListener) {
351
- return;
352
- }
353
- var timefragment = 0; // 时间片计时
354
- var nowts = 0; // 当前时间
355
- // 初始化角度,作为单独一个用户的空间旋转的参照
356
- var referGamma = NaN, referBeta = NaN;
357
- var alpha;
358
- var beta;
359
- var gamma;
360
- var isInValidDegRange;
361
- var x; // 最终输出的 x
362
- var y; // 最终输出的 y
363
- var handleWatch = function(e) {
364
- if (_this.stoped) {
365
- return;
366
- }
367
- alpha = e.alpha || 0; // 垂直于屏幕的轴 0 ~ 360
368
- beta = e.beta || 0; // 横向 X 轴 -180 ~ 180
369
- gamma = e.gamma || 0; // 纵向 Y 轴 -90 ~ 90
370
- isInValidDegRange = angleLimit.call(_this, {
371
- alpha: alpha,
372
- beta: beta,
373
- gamma: gamma
374
- }, _this.options.validRange);
375
- if (isNaN(referGamma)) {
376
- referGamma = gamma;
377
- _this.filterX.lastValue = gamma;
378
- }
379
- if (isNaN(referBeta)) {
380
- referBeta = beta;
381
- _this.filterY.lastValue = beta;
382
- }
383
- if (isInValidDegRange) {
384
- // 最终结果值
385
- if (_this.options.X) {
386
- x = _this.options.relativeGamma ? gamma - referGamma : gamma;
387
- x = _this.filterX.stableFix(x);
388
- x = _this.filterX.changeLimit(x);
389
- x = _this.filterX.linearRegressionMedian(+x);
390
- } else {
391
- x = 0;
392
- }
393
- if (_this.options.Y) {
394
- y = _this.options.relativeBeta ? beta - referBeta : beta;
395
- y = _this.filterY.stableFix(y);
396
- y = _this.filterY.changeLimit(y);
397
- y = _this.filterY.linearRegressionMedian(+y);
398
- } else {
399
- y = 0;
400
- }
401
- if (_this.isValid(x, y)) {
402
- if (_this.options.useRequestAnimationFrame) {
403
- window.requestAnimationFrame(function() {
404
- callback(x, y, {
405
- alpha: alpha,
406
- beta: y - referBeta,
407
- gamma: x - referGamma
408
- });
409
- });
410
- } else {
411
- callback(x, y, {
412
- alpha: alpha,
413
- beta: y - referBeta,
414
- gamma: x - referGamma
415
- });
416
- }
417
- _this.lastX = x;
418
- _this.lastY = y;
419
- }
420
- }
421
- };
422
- // 针对不同平台绑定不同事件
423
- this.stoped = false;
424
- if (useWindVane) {
425
- switchWindVane(true, this.options.interval);
426
- this.watchListener = function(e) {
427
- if ("param" in e) {
428
- var _e_param = e.param, x = _e_param.x, y = _e_param.y, z = _e_param.z;
429
- // 即使手机没动,也会不停触发,所以这里加个判断,值相等则不调用回调
430
- if (x === _this.prevAcceler.x && y === _this.prevAcceler.y && z === _this.prevAcceler.z) {
431
- return;
432
- }
433
- _this.prevAcceler = {
434
- x: x,
435
- y: y,
436
- z: z
437
- };
438
- var evt = {
439
- alpha: +z * 180,
440
- beta: +y * -90,
441
- gamma: +x * 90
442
- };
443
- handleWatch(evt);
444
- }
445
- };
446
- document.addEventListener("motion.gyro", this.watchListener, false);
447
- } else if (useJSBridge && !isMiniProgram()) {
448
- switchIOSEvent(true, this.options.interval / 1000);
449
- this.watchListener = function(e) {
450
- if (e && "data" in e) {
451
- /*
452
- data:
453
- {
454
- data: {
455
- x: 0.0, // gamma -1 ~ 1
456
- y: 0.0, // beta -1 ~ 1
457
- z: 0.0, // alpha
458
- }
459
- }
460
- */ var _e_data = e.data, x = _e_data.x, y = _e_data.y, z = _e_data.z;
461
- var evt = {
462
- alpha: z * 180,
463
- beta: y * -90,
464
- gamma: x * 90
465
- };
466
- handleWatch(evt);
467
- }
468
- };
469
- document.addEventListener("accelerometerChange", this.watchListener, false);
470
- } else {
471
- this.watchListener = function(e) {
472
- nowts = new Date().getTime();
473
- // 控制时间片
474
- if (nowts - timefragment >= _this.options.interval) {
475
- timefragment = nowts;
476
- handleWatch(e);
477
- }
478
- };
479
- window.addEventListener("deviceorientation", this.watchListener, false);
480
- }
481
- };
482
- _proto.unWatch = function unWatch() {
483
- assertExist(this.watchListener);
484
- if (useWindVane) {
485
- switchWindVane(false);
486
- document.removeEventListener("motion.gyro", this.watchListener);
487
- } else if (useJSBridge) {
488
- switchIOSEvent(false);
489
- document.removeEventListener("accelerometerChange", this.watchListener);
490
- } else {
491
- window.removeEventListener("deviceorientation", this.watchListener);
492
- }
493
- this.stoped = true;
494
- this.watchListener = undefined;
495
- };
496
- _proto.pause = function pause() {
497
- this.stoped = true;
498
- if (useJSBridge) {
499
- switchIOSEvent(false);
500
- }
501
- };
502
- _proto.continue = function _continue() {
503
- this.stoped = false;
504
- if (useJSBridge) {
505
- switchIOSEvent(true, this.options.interval / 1000);
506
- }
507
- };
508
- _proto.isValid = function isValid(x, y) {
509
- // 判断是否和上次的值一样,检测有没有变
510
- return this.lastX !== x || this.lastY !== y;
511
- };
512
- return DeviceOrientation;
513
- }();
514
- // 开启/关闭 iOS 的陀螺仪监听
515
- function switchIOSEvent(open, interval) {
516
- window.AlipayJSBridge.call("watchShake", {
517
- monitorGyroscope: false,
518
- monitorAccelerometer: !!open,
519
- interval: !open ? 10 : parseFloat(interval.toFixed(3))
520
- }, function() {});
521
- }
522
- function switchWindVane(open, interval) {
523
- var params = {
524
- // 是开启还是关闭陀螺仪的监听
525
- on: open,
526
- // 陀螺仪事件的时间间隔
527
- frequency: interval
528
- };
529
- window.WindVane.call("WVMotion", "listenGyro", params, function(e) {
530
- console.info("Call WVMotion success.");
531
- }, function(e) {
532
- console.error("Call WVMotion failed: " + JSON.stringify(e) + ".");
533
- });
534
- }
535
-
536
- /**
537
- *
538
- */ var OrientationAdapterAcceler = /*#__PURE__*/ function() {
539
- function OrientationAdapterAcceler() {
540
- this.transformers = [];
541
- this.connected = false;
542
- this.accelerMotion = null;
543
- this.validRange = {
544
- alpha: [
545
- -60,
546
- 60
547
- ],
548
- beta: [
549
- -80,
550
- 80
551
- ],
552
- gamma: [
553
- -89,
554
- 89
555
- ]
556
- };
557
- }
558
- var _proto = OrientationAdapterAcceler.prototype;
559
- _proto.connect = function connect() {
560
- var _this = this;
561
- if (!this.connected) {
562
- this.accelerMotion = new DeviceOrientation({
563
- X: true,
564
- Y: true,
565
- interval: Math.floor(1000 / 60),
566
- useRequestAnimationFrame: true,
567
- relativeBeta: false,
568
- relativeGamma: false,
569
- validRange: this.validRange,
570
- stableRange: 3
571
- });
572
- this.accelerMotion.watch(function(x, y, param) {
573
- var beta = param.beta, gamma = param.gamma;
574
- var motion = {
575
- x: x,
576
- y: y,
577
- beta: beta,
578
- gamma: gamma
579
- };
580
- _this.dispatchMotion(motion);
581
- });
582
- }
583
- this.connected = true;
584
- };
585
- _proto.disconnect = function disconnect() {
586
- if (this.accelerMotion) {
587
- this.accelerMotion.unWatch();
588
- }
589
- this.connected = false;
590
- };
591
- /**
592
- *
593
- * @param motion
594
- */ _proto.dispatchMotion = function dispatchMotion(motion) {
595
- this.transformers.forEach(function(t) {
596
- return t.update(motion);
597
- });
598
- };
599
- _proto.addTransformer = function addTransformer(transformer) {
600
- if (!this.transformers.includes(transformer)) {
601
- this.transformers.push(transformer);
602
- }
603
- };
604
- _proto.removeTransformer = function removeTransformer(transformer) {
605
- var index = this.transformers.indexOf(transformer);
606
- if (index > -1) {
607
- this.transformers.splice(index, 1);
608
- }
609
- return this.transformers.length === 0;
610
- };
611
- return OrientationAdapterAcceler;
612
- }();
613
- var adapter;
614
- function getAccelerAdapter() {
615
- if (!adapter) {
616
- adapter = new OrientationAdapterAcceler();
617
- }
618
- return adapter;
619
- }
620
-
621
- var OrientationPluginLoader = /*#__PURE__*/ function(AbstractPlugin) {
622
- _inherits(OrientationPluginLoader, AbstractPlugin);
623
- function OrientationPluginLoader() {
624
- var _this;
625
- _this = AbstractPlugin.apply(this, arguments) || this;
626
- _this.order = 90;
627
- _this.adapter = null;
628
- _this.handleConnect = function() {
629
- if (!closeManually) {
630
- var _this_adapter;
631
- (_this_adapter = _this.adapter) == null ? void 0 : _this_adapter.connect();
632
- }
633
- };
634
- _this.handleDisconnect = function() {
635
- var _this_adapter;
636
- (_this_adapter = _this.adapter) == null ? void 0 : _this_adapter.disconnect();
637
- };
638
- return _this;
639
- }
640
- var _proto = OrientationPluginLoader.prototype;
641
- _proto.onCompositionConstructed = function onCompositionConstructed() {
642
- var _this_adapter;
643
- this.adapter = getAdapter();
644
- (_this_adapter = this.adapter) == null ? void 0 : _this_adapter.connect();
645
- this.bindAccelerDocumentEvent();
646
- };
647
- _proto.onCompositionReset = function onCompositionReset(composition) {
648
- var _this_adapter;
649
- var transformer = composition.loaderData.deviceTransformer = new CompositionTransformerAcceler(composition);
650
- (_this_adapter = this.adapter) == null ? void 0 : _this_adapter.addTransformer(transformer);
651
- };
652
- _proto.onCompositionUpdate = function onCompositionUpdate(composition) {
653
- var transformer = composition.loaderData.deviceTransformer;
654
- if (transformer) {
655
- transformer.updateOrientation();
656
- }
657
- };
658
- _proto.onCompositionDestroyed = function onCompositionDestroyed(composition) {
659
- var _this_adapter;
660
- var empty = (_this_adapter = this.adapter) == null ? void 0 : _this_adapter.removeTransformer(composition.loaderData.deviceTransformer);
661
- if (empty) {
662
- var _this_adapter1;
663
- (_this_adapter1 = this.adapter) == null ? void 0 : _this_adapter1.disconnect();
664
- }
665
- };
666
- _proto.bindAccelerDocumentEvent = function bindAccelerDocumentEvent() {
667
- this.unbindAccelerDocumentEvent(); // 保证全局只监听一份
668
- document.addEventListener("resume", this.handleConnect, false);
669
- document.addEventListener("pause", this.handleDisconnect, false);
670
- document.addEventListener("back", this.handleDisconnect, false);
671
- };
672
- _proto.unbindAccelerDocumentEvent = function unbindAccelerDocumentEvent() {
673
- document.removeEventListener("resume", this.handleConnect);
674
- document.removeEventListener("pause", this.handleDisconnect);
675
- document.removeEventListener("back", this.handleDisconnect);
676
- };
677
- _proto.dispose = function dispose() {
678
- getAdapter().disconnect();
679
- this.unbindAccelerDocumentEvent();
680
- };
681
- return OrientationPluginLoader;
682
- }(AbstractPlugin);
683
- // 是否是手动关闭,如果是,那么 resume 时不要恢复
684
- var closeManually = false;
685
- /**
686
- *
687
- * @returns
688
- */ function getAdapter() {
689
- // 运动感应类型(默认使用加速度,Native 环境使用陀螺仪)
690
- return getAccelerAdapter();
691
- }
692
- function closeDeviceMotion() {
693
- closeManually = true;
694
- getAdapter().disconnect();
695
- }
696
- function openDeviceMotion() {
697
- closeManually = false;
698
- getAdapter().connect();
699
- }
700
-
701
- function __decorate(decorators, target, key, desc) {
702
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
703
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
704
- else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
705
- return c > 3 && r && Object.defineProperty(target, key, r), r;
706
- }
707
- typeof SuppressedError === "function" ? SuppressedError : function _SuppressedError(error, suppressed, message) {
708
- var e = new Error(message);
709
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
710
- };
711
-
712
- var OrientationComponent = /*#__PURE__*/ function(Behaviour) {
713
- _inherits(OrientationComponent, Behaviour);
714
- function OrientationComponent() {
715
- return Behaviour.apply(this, arguments);
716
- }
717
- var _proto = OrientationComponent.prototype;
718
- _proto.fromData = function fromData(data) {
719
- Behaviour.prototype.fromData.call(this, data);
720
- var targets = data.options.targets;
721
- if (targets) {
722
- this.targets = targets.map(function(t) {
723
- return {
724
- name: t.name,
725
- xMin: +t.xMin || 0,
726
- yMin: +t.yMin || 0,
727
- xMax: +t.xMax || 0,
728
- yMax: +t.yMax || 0,
729
- vMin: +t.vMin || 0,
730
- hMin: +t.hMin || 0,
731
- vMax: +t.vMax || 0,
732
- hMax: +t.hMax || 0
733
- };
734
- });
735
- }
736
- };
737
- _proto.onStart = function onStart() {
738
- var _this_item_composition;
739
- var transformer = (_this_item_composition = this.item.composition) == null ? void 0 : _this_item_composition.loaderData.deviceTransformer;
740
- if (transformer) {
741
- var _this_targets;
742
- (_this_targets = this.targets) == null ? void 0 : _this_targets.forEach(function(target) {
743
- return transformer.addTarget(target);
744
- });
745
- transformer.initComposition();
746
- }
747
- };
748
- _proto.onUpdate = function onUpdate(dt) {
749
- var _this_item_composition;
750
- var transformer = (_this_item_composition = this.item.composition) == null ? void 0 : _this_item_composition.loaderData.deviceTransformer;
751
- if (transformer) {
752
- transformer.updateOrientation();
753
- }
754
- };
755
- _proto.onDestroy = function onDestroy() {
756
- var _this = this;
757
- var _this_targets;
758
- (_this_targets = this.targets) == null ? void 0 : _this_targets.forEach(function(target) {
759
- var _this_item_composition_loaderData_deviceTransformer, _this_item_composition;
760
- return (_this_item_composition = _this.item.composition) == null ? void 0 : (_this_item_composition_loaderData_deviceTransformer = _this_item_composition.loaderData.deviceTransformer) == null ? void 0 : _this_item_composition_loaderData_deviceTransformer.removeTarget(target.name);
761
- });
762
- };
763
- return OrientationComponent;
764
- }(Behaviour);
765
- OrientationComponent = __decorate([
766
- effectsClass("OrientationComponent")
767
- ], OrientationComponent);
768
-
769
- registerPlugin("orientation-transformer", OrientationPluginLoader, VFXItem);
770
- /**
771
- * 插件版本号
772
- */ var version = "2.3.0-alpha.2";
773
- logger.info("Plugin orientation transformer version: " + version + ".");
774
- if (version !== EFFECTS.version) {
775
- console.error("注意:请统一 Orientation Transformer 插件与 Player 版本,不统一的版本混用会有不可预知的后果!", "\nAttention: Please ensure the Orientation Transformer plugin is synchronized with the Player version. Mixing and matching incompatible versions may result in unpredictable consequences!");
776
- }
777
-
778
- export { OrientationAdapterAcceler, OrientationComponent, OrientationPluginLoader, closeDeviceMotion, getAdapter, openDeviceMotion, version };
1
+ import*as t from"@galacean/effects/alipay";import{isArray as e,isIOSByUA as n,isMiniProgram as a,assertExist as i,AbstractPlugin as r,effectsClass as o,Behaviour as s,registerPlugin as c,VFXItem as l,logger as h}from"@galacean/effects/alipay";import{window as u,document as f}from"@galacean/appx-adapter/alipay";function m(t,e){return m=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t},m(t,e)}function p(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&m(t,e)}var v=function(){function t(t){this.composition=t,this.targets={},this.records={},this.currentPos={},this.currentRot={},this.gammaRange=[-89,89],this.betaRange=[-89,89]}var e=t.prototype;return e.update=function(t){var e=t.x,n=t.y,a=t.beta,i=t.gamma;this.currentEvent={x:e,y:n,beta:a,gamma:i}},e.updateOrientation=function(){var t=this,e=this.currentEvent;e&&Object.getOwnPropertyNames(this.targets).forEach((function(n){t.moveLayer(n,e)}))},e.initComposition=function(){for(var t=this.composition.items,e=0;e<t.length;e++){var n=t[e];if(this.targets[n.name]){var a=n.transform.position.toArray(),i=n.transform.rotation.toArray(),r=this.currentPos[n.name],o=this.currentRot[n.name];this.records[n.name]={item:n,position:a,rotation:i},r&&n.transform.setPosition(r[0],r[1],r[2]),o&&n.transform.setRotation(o[0],o[1],o[2])}}},e.addTarget=function(t){this.targets[t.name]=t},e.removeTarget=function(t){delete this.targets[t],delete this.records[t]},e.moveLayer=function(t,e){var n,a=e.x,i=e.y,r=e.beta,o=e.gamma,s=null==(n=this.records[t])?void 0:n.item;if(s){var c=this.records[t].position,l=this.records[t].rotation,h=this.targets[t],u=d(a,this.betaRange),f=d(i,this.gammaRange);if(h){var m,p,v=[c[0]+1.2*g(y(u,this.gammaRange[0],this.gammaRange[1]),h.xMin,h.xMax),c[1]+1.2*g(y(f,this.betaRange[0],this.betaRange[1]),h.yMin,h.yMax),c[2]],b=y(d(.8*o,this.gammaRange),this.gammaRange[0],this.gammaRange[1]),M=y(d(.8*r,this.betaRange),this.betaRange[0],this.betaRange[1]),R=[l[0]+g(M,h.hMin,h.hMax),l[1]+g(b,h.vMin,h.vMax),l[2]];(m=s.transform).setPosition.apply(m,[].concat(v)),(p=s.transform).setRotation.apply(p,[].concat(R)),this.currentPos[t]=v.slice(),this.currentRot[t]=R.slice()}}},t}();function d(t,e){return t<e[0]?e[0]:t>e[1]?e[1]:t}function g(t,e,n){return e+(n-e)*t}function y(t,e,n){return(t-e)/(n-e)}function b(){return b=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},b.apply(this,arguments)}function M(t,n){var a=!0,i=!0,r=!0;if(e(n.alpha)&&n.alpha.length>=2){var o=t.alpha+n.alpha[0],s=t.alpha+n.alpha[1];a=(o=o<0?o+360:o)<(s=s>360?s-360:s)?t.alpha>o&&t.alpha<s:t.alpha>o||t.alpha<s}return e(n.beta)&&n.beta.length>=2&&(i=t.beta>=n.beta[0]&&t.beta<=n.beta[1]),e(n.gamma)&&n.gamma.length>=2&&(r=t.gamma>=n.gamma[0]&&t.gamma<=n.gamma[1]),a&&i&&r}var R=function(){function t(t){void 0===t&&(t={}),this.options=t,this.lastValue=0,this.valuePool=[]}var e=t.prototype;return e.stableFix=function(t){var e=this.options.stableRange||3;return Math.abs(t)<e?0:t>e?t-e:t+e},e.changeLimit=function(t){var e=this.lastValue,n=t;return Math.abs(t-e)>5&&(n=e<t?e+5:e-5),Math.abs(t-e)<1&&(n=e),this.lastValue=n,n},e.linearRegressionMedian=function(t){var e,n,a;return this.valuePool.push(t),this.valuePool.length>=5?(n=this.valuePool,a=function(t){var e=[],n=[];t.forEach((function(t,a){e.push(a),n.push(t)}));var a=function(t,e){for(var n={},a=e.length,i=0,r=0,o=0,s=0,c=0,l=0;l<e.length;l++)i+=t[l],r+=e[l],o+=t[l]*e[l],s+=t[l]*t[l],c+=e[l]*e[l];var h=i/a,u=r/a;return n.a=(o-a*h*u)/(s-a*h*h),n.b=u-n.a*h,n.miss=Math.pow((a*o-i*r)/Math.sqrt((a*s-i*i)*(a*c-r*r)),2),n}(e,n);return function(t){return a.a*t+a.b}}(n),n=n.map((function(t,e){return a(e)})),e=a(n.length/2),this.valuePool.shift()):e=this.lastValue,e},t}();var x=n()&&void 0!==u.AlipayJSBridge,w=void 0!==u.WindVane,L={X:!0,Y:!0,interval:Math.floor(1e3/30),useRequestAnimationFrame:!0,relativeBeta:!1,relativeGamma:!1,validRange:{alpha:[-60,60],beta:[-60,180],gamma:[-89,89]},stableRange:3},E=function(){function t(t){void 0===t&&(t={}),this.lastX=0,this.lastY=0,this.prevAcceler={x:0,y:0,z:0},this.stoped=!1;var e=b({},L.validRange,t.validRange),n=b({},L,t);n.validRange=e,this.options=n;var a=this.options.stableRange;this.filterX=new R({stableRange:a}),this.filterY=new R({stableRange:a})}var e=t.prototype;return e.watch=function(t){var e=this;if("function"==typeof t&&!this.watchListener){var n,i,r,o,s,c,l=0,h=0,m=NaN,p=NaN,v=function(a){e.stoped||(n=a.alpha||0,i=a.beta||0,r=a.gamma||0,o=M.call(e,{alpha:n,beta:i,gamma:r},e.options.validRange),isNaN(m)&&(m=r,e.filterX.lastValue=r),isNaN(p)&&(p=i,e.filterY.lastValue=i),o&&(e.options.X?(s=e.options.relativeGamma?r-m:r,s=e.filterX.stableFix(s),s=e.filterX.changeLimit(s),s=e.filterX.linearRegressionMedian(+s)):s=0,e.options.Y?(c=e.options.relativeBeta?i-p:i,c=e.filterY.stableFix(c),c=e.filterY.changeLimit(c),c=e.filterY.linearRegressionMedian(+c)):c=0,e.isValid(s,c)&&(e.options.useRequestAnimationFrame?u.requestAnimationFrame((function(){t(s,c,{alpha:n,beta:c-p,gamma:s-m})})):t(s,c,{alpha:n,beta:c-p,gamma:s-m}),e.lastX=s,e.lastY=c)))};this.stoped=!1,w?(A(!0,this.options.interval),this.watchListener=function(t){if("param"in t){var n=t.param,a=n.x,i=n.y,r=n.z;if(a===e.prevAcceler.x&&i===e.prevAcceler.y&&r===e.prevAcceler.z)return;e.prevAcceler={x:a,y:i,z:r},v({alpha:180*+r,beta:-90*+i,gamma:90*+a})}},f.addEventListener("motion.gyro",this.watchListener,!1)):x&&!a()?(D(!0,this.options.interval/1e3),this.watchListener=function(t){if(t&&"data"in t){var e=t.data,n=e.x,a=e.y,i=e.z;v({alpha:180*i,beta:-90*a,gamma:90*n})}},f.addEventListener("accelerometerChange",this.watchListener,!1)):(this.watchListener=function(t){(h=(new Date).getTime())-l>=e.options.interval&&(l=h,v(t))},u.addEventListener("deviceorientation",this.watchListener,!1))}},e.unWatch=function(){i(this.watchListener),w?(A(!1),f.removeEventListener("motion.gyro",this.watchListener)):x?(D(!1),f.removeEventListener("accelerometerChange",this.watchListener)):u.removeEventListener("deviceorientation",this.watchListener),this.stoped=!0,this.watchListener=void 0},e.pause=function(){this.stoped=!0,x&&D(!1)},e.continue=function(){this.stoped=!1,x&&D(!0,this.options.interval/1e3)},e.isValid=function(t,e){return this.lastX!==t||this.lastY!==e},t}();function D(t,e){u.AlipayJSBridge.call("watchShake",{monitorGyroscope:!1,monitorAccelerometer:!!t,interval:t?parseFloat(e.toFixed(3)):10},(function(){}))}function A(t,e){var n={on:t,frequency:e};u.WindVane.call("WVMotion","listenGyro",n,(function(t){console.info("Call WVMotion success.")}),(function(t){console.error("Call WVMotion failed: "+JSON.stringify(t)+".")}))}var O,P=function(){function t(){this.transformers=[],this.connected=!1,this.accelerMotion=null,this.validRange={alpha:[-60,60],beta:[-80,80],gamma:[-89,89]}}var e=t.prototype;return e.connect=function(){var t=this;this.connected||(this.accelerMotion=new E({X:!0,Y:!0,interval:Math.floor(1e3/60),useRequestAnimationFrame:!0,relativeBeta:!1,relativeGamma:!1,validRange:this.validRange,stableRange:3}),this.accelerMotion.watch((function(e,n,a){var i={x:e,y:n,beta:a.beta,gamma:a.gamma};t.dispatchMotion(i)}))),this.connected=!0},e.disconnect=function(){this.accelerMotion&&this.accelerMotion.unWatch(),this.connected=!1},e.dispatchMotion=function(t){this.transformers.forEach((function(e){return e.update(t)}))},e.addTransformer=function(t){this.transformers.includes(t)||this.transformers.push(t)},e.removeTransformer=function(t){var e=this.transformers.indexOf(t);return e>-1&&this.transformers.splice(e,1),0===this.transformers.length},t}();var T=function(t){function e(){var e;return(e=t.apply(this,arguments)||this).order=90,e.adapter=null,e.handleConnect=function(){var t;C||(null==(t=e.adapter)||t.connect())},e.handleDisconnect=function(){var t;null==(t=e.adapter)||t.disconnect()},e}p(e,t);var n=e.prototype;return n.onCompositionConstructed=function(){var t;this.adapter=V(),null==(t=this.adapter)||t.connect(),this.bindAccelerDocumentEvent()},n.onCompositionReset=function(t){var e,n=t.loaderData.deviceTransformer=new v(t);null==(e=this.adapter)||e.addTransformer(n)},n.onCompositionUpdate=function(t){var e=t.loaderData.deviceTransformer;e&&e.updateOrientation()},n.onCompositionDestroyed=function(t){var e,n;(null==(e=this.adapter)?void 0:e.removeTransformer(t.loaderData.deviceTransformer))&&(null==(n=this.adapter)||n.disconnect())},n.bindAccelerDocumentEvent=function(){this.unbindAccelerDocumentEvent(),f.addEventListener("resume",this.handleConnect,!1),f.addEventListener("pause",this.handleDisconnect,!1),f.addEventListener("back",this.handleDisconnect,!1)},n.unbindAccelerDocumentEvent=function(){f.removeEventListener("resume",this.handleConnect),f.removeEventListener("pause",this.handleDisconnect),f.removeEventListener("back",this.handleDisconnect)},n.dispose=function(){V().disconnect(),this.unbindAccelerDocumentEvent()},e}(r),C=!1;function V(){return O||(O=new P),O}function X(){C=!0,V().disconnect()}function Y(){C=!1,V().connect()}"function"==typeof SuppressedError&&SuppressedError;var N=function(t){function e(){return t.apply(this,arguments)}p(e,t);var n=e.prototype;return n.fromData=function(e){t.prototype.fromData.call(this,e);var n=e.options.targets;n&&(this.targets=n.map((function(t){return{name:t.name,xMin:+t.xMin||0,yMin:+t.yMin||0,xMax:+t.xMax||0,yMax:+t.yMax||0,vMin:+t.vMin||0,hMin:+t.hMin||0,vMax:+t.vMax||0,hMax:+t.hMax||0}})))},n.onStart=function(){var t,e,n=null==(t=this.item.composition)?void 0:t.loaderData.deviceTransformer;n&&(null==(e=this.targets)||e.forEach((function(t){return n.addTarget(t)})),n.initComposition())},n.onUpdate=function(t){var e,n=null==(e=this.item.composition)?void 0:e.loaderData.deviceTransformer;n&&n.updateOrientation()},n.onDestroy=function(){var t,e=this;null==(t=this.targets)||t.forEach((function(t){var n,a;return null==(a=e.item.composition)||null==(n=a.loaderData.deviceTransformer)?void 0:n.removeTarget(t.name)}))},e}(s);N=function(t,e,n,a){var i,r=arguments.length,o=r<3?e:null===a?a=Object.getOwnPropertyDescriptor(e,n):a;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,n,a);else for(var s=t.length-1;s>=0;s--)(i=t[s])&&(o=(r<3?i(o):r>3?i(e,n,o):i(e,n))||o);return r>3&&o&&Object.defineProperty(e,n,o),o}([o("OrientationComponent")],N),c("orientation-transformer",T,l);var F="2.3.0-beta.1";h.info("Plugin orientation transformer version: "+F+"."),F!==t.version&&console.error("注意:请统一 Orientation Transformer 插件与 Player 版本,不统一的版本混用会有不可预知的后果!","\nAttention: Please ensure the Orientation Transformer plugin is synchronized with the Player version. Mixing and matching incompatible versions may result in unpredictable consequences!");export{P as OrientationAdapterAcceler,N as OrientationComponent,T as OrientationPluginLoader,X as closeDeviceMotion,V as getAdapter,Y as openDeviceMotion,F as version};
779
2
  //# sourceMappingURL=alipay.mjs.map